leejunyoung5819 pdf-to-md
공개Convert text-based PDFs (including HWP equations) to UTF-8 Markdown with editable math notation
| 1 | #!/usr/bin/env python3 |
| 2 | """Convert a text-based PDF to UTF-8 Markdown with LaTeX math ($...$, $$...$$).""" |
| 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 | GREEK = dict(zip( |
| 38 | "αβγδεζηθικλμνξπρστυφχψωΓΔΘΛΞΠΣΥΦΨΩ", |
| 39 | ("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi pi rho sigma " |
| 40 | "tau upsilon phi chi psi omega Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega").split(), |
| 41 | )) |
| 42 | LATEX_SYMBOLS = { |
| 43 | **{c: "\\" + name for c, name in GREEK.items()}, |
| 44 | "×": r"\times", "÷": r"\div", "≠": r"\neq", "≤": r"\le", "≥": r"\ge", "±": r"\pm", |
| 45 | "∓": r"\mp", "→": r"\to", "←": r"\leftarrow", "↔": r"\leftrightarrow", |
| 46 | "⇒": r"\Rightarrow", "⇔": r"\Leftrightarrow", "∞": r"\infty", "∫": r"\int", |
| 47 | "∑": r"\sum", "∏": r"\prod", "√": r"\surd", "⋅": r"\cdot", "·": r"\cdot", "∙": r"\cdot", |
| 48 | "⋯": r"\cdots", "…": r"\ldots", "⋮": r"\vdots", "′": "'", "″": "''", "‴": "'''", |
| 49 | "∪": r"\cup", "∩": r"\cap", "∈": r"\in", "∉": r"\notin", "∋": r"\ni", "⊂": r"\subset", |
| 50 | "⊃": r"\supset", "⊆": r"\subseteq", "⊇": r"\supseteq", "∅": r"\varnothing", |
| 51 | "∀": r"\forall", "∃": r"\exists", "≈": r"\approx", "≒": r"\fallingdotseq", |
| 52 | "≡": r"\equiv", "∼": r"\sim", "∝": r"\propto", "∠": r"\angle", "△": r"\triangle", |
| 53 | "⊥": r"\perp", "∥": r"\parallel", "°": r"^{\circ}", "∴": r"\therefore", |
| 54 | "∵": r"\because", "∘": r"\circ", "−": "-", "{": r"\{", "}": r"\}", "%": r"\%", |
| 55 | "#": r"\#", "&": r"\&", "$": r"\$", "_": r"\_", "\\": r"\backslash", "~": r"\sim", |
| 56 | "^": r"\wedge", |
| 57 | } |
| 58 | # Korean (and other CJK) text inside a formula must be wrapped in \text{...}. |
| 59 | CJK_TEXT = re.compile(r"( ?)([ᄀ-ᇿ-㈀-㋿一-鿿가-힣]" |
| 60 | r"(?:[ ᄀ-ᇿ-㈀-㋿一-鿿가-힣]*" |
| 61 | r"[ᄀ-ᇿ-㈀-㋿一-鿿가-힣])?)") |
| 62 | # Line openings that begin a new paragraph: "<b>12.</b>", "3\.", "①", "ㄱ.", "(가)", "\* ". |
| 63 | BLOCK_START = re.compile(r"(?:<b>)?\d{1,2}\\?[.)]|[①-⑳]|[ㄱ-ㅎ]\.|\([가-힣]\)|\\\* ") |
| 64 | UNICODE_SCRIPTS = ( |
| 65 | ("^", dict(zip("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207a\u207b\u207c\u207d\u207e\u207f", "0123456789+-=()n"))), |
| 66 | ("_", dict(zip("\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208a\u208b\u208c\u208d\u208e", "0123456789+-=()"))), |
| 67 | ) |
| 68 | |
| 69 | |
| 70 | @dataclass(frozen=True) |
| 71 | class Glyph: |
| 72 | text: str |
| 73 | x0: float |
| 74 | x1: float |
| 75 | center: float |
| 76 | baseline: float |
| 77 | size: float |
| 78 | tags: frozenset[str] = frozenset() |
| 79 | math: bool = False |
| 80 | horizontal: bool = True |
| 81 | scope: int | None = None |
| 82 | script_reach: float = 0.0 |
| 83 | # `text` keeps a plain notation such as "(1)/(3)" that the layout |
| 84 | # heuristics match against; `latex` holds what is written to Markdown. |
| 85 | latex: str | None = None |
| 86 | |
| 87 | @property |
| 88 | def x(self): |
| 89 | return (self.x0 + self.x1) / 2 |
| 90 | |
| 91 | @property |
| 92 | def tex(self): |
| 93 | return self.latex if self.latex is not None else latex_symbol(self.text) |
| 94 | |
| 95 | |
| 96 | @dataclass(frozen=True) |
| 97 | class Rule: |
| 98 | x0: float |
| 99 | x1: float |
| 100 | y: float |
| 101 | glyph: Glyph | None = None |
| 102 | |
| 103 | |
| 104 | def font_styles(page): |
| 105 | from pdfminer.pdftypes import dict_value, resolve1 |
| 106 | |
| 107 | styles = {} |
| 108 | fonts = dict_value(page.page_obj.resources.get("Font", {})) |
| 109 | for reference in fonts.values(): |
| 110 | # A single broken font dictionary should not abort the whole page; |
| 111 | # named_styles() still provides a fallback from the font name. |
| 112 | try: |
| 113 | font = page.pdf.rsrcmgr.get_font(getattr(reference, "objid", None), dict_value(reference)) |
| 114 | descriptor = getattr(font, "descriptor", None) or {} |
| 115 | flags = int(resolve1(descriptor.get("Flags", 0)) or 0) |
| 116 | weight = resolve1(descriptor.get("FontWeight", 0)) |
| 117 | except Exception: |
| 118 | continue |
| 119 | tags = set() |
| 120 | if flags & 64 or font.italic_angle: |
| 121 | tags.add("em") |
| 122 | if flags & (1 << 18) or (isinstance(weight, (int, float)) and weight >= 600): |
| 123 | tags.add("b") |
| 124 | styles[font.fontname] = tags |
| 125 | return styles |
| 126 | |
| 127 | |
| 128 | @lru_cache(maxsize=256) |
| 129 | def named_styles(name): |
| 130 | if name.startswith("b'") or name.startswith('b"'): |
| 131 | try: |
| 132 | name = ast.literal_eval(name).decode("cp949") |
| 133 | except (ValueError, SyntaxError, UnicodeDecodeError): |
| 134 | pass |
| 135 | tags = set() |
| 136 | if re.search(r"italic|oblique|slanted|(?:[-,](?:bi|it|i))$|기울임", name, re.I): |
| 137 | tags.add("em") |
| 138 | # "DemiLight" (e.g. Noto Sans CJK) is a light weight, not a bold one. |
| 139 | if re.search(r"bold|demi(?!-?light)|black|heavy|(?:[-,](?:bd|bi|b))$|굵|견명조|견고딕", name, re.I): |
| 140 | tags.add("b") |
| 141 | return tags |
| 142 | |
| 143 | |
| 144 | def visible_characters(page): |
| 145 | from pdfplumber.utils import dedupe_chars |
| 146 | |
| 147 | if not any(r["fill"] and r["non_stroking_color"] in (1, (1,), (1, 1, 1)) |
| 148 | for r in page.rects): |
| 149 | return page.dedupe_chars(tolerance=0.85, extra_attrs=("fontname", "size")).chars |
| 150 | |
| 151 | # PDF editors sometimes paint an opaque panel over the original header. |
| 152 | # Walk backward so that the panel hides only characters drawn before it. |
| 153 | characters, masks = [], [] |
| 154 | objects = list(page.iter_layout_objects(page.layout._objs)) |
| 155 | for obj in reversed(objects): |
| 156 | if obj["object_type"] == "char": |
| 157 | x = (obj["x0"] + obj["x1"]) / 2 |
| 158 | y = (obj["top"] + obj["bottom"]) / 2 |
| 159 | if not any(x0 <= x <= x1 and top <= y <= bottom for x0, top, x1, bottom in masks): |
| 160 | characters.append(obj) |
| 161 | elif (obj["object_type"] == "rect" and obj["fill"] |
| 162 | and obj["width"] >= 24 and obj["height"] >= 12 |
| 163 | and obj["non_stroking_color"] in (1, (1,), (1, 1, 1))): |
| 164 | masks.append(bounds(obj)) |
| 165 | characters.reverse() |
| 166 | return dedupe_chars(characters, tolerance=0.85, extra_attrs=("fontname", "size")) |
| 167 | |
| 168 | |
| 169 | def page_glyphs(page, unknown): |
| 170 | styles = font_styles(page) |
| 171 | scope = 0 |
| 172 | was_math = False |
| 173 | for char in visible_characters(page): |
| 174 | font = char["fontname"] |
| 175 | text = char["text"] |
| 176 | if not text or char["size"] <= 0: |
| 177 | continue |
| 178 | tags = styles.get(font, set()) | named_styles(font) |
| 179 | a, b, c, d, x, y = char["matrix"] |
| 180 | horizontal = abs(b) <= abs(a) * 0.08 |
| 181 | if horizontal and d and 0.08 < abs(c / d) < 0.7: |
| 182 | tags.add("em") |
| 183 | is_math = "hyhwpeq" in font.lower() |
| 184 | if is_math: |
| 185 | # Math letters are often slanted on purpose; that is notation, not |
| 186 | # emphasis, and an <em> tag would split the inline code span. |
| 187 | tags.discard("em") |
| 188 | if is_math and not was_math: |
| 189 | scope += 1 |
| 190 | was_math = is_math |
| 191 | if is_math and len(text) == 1: |
| 192 | text = HWP_SYMBOLS.get(ord(text), text) |
| 193 | if (len(text) == 1 and "\ue000" <= text <= "\uf8ff" |
| 194 | and text != HWP_BAR and text not in HWP_BRACE): |
| 195 | unknown[ord(text)] += 1 |
| 196 | text = f"[U+{ord(text):04X}]" |
| 197 | if text.startswith("(cid:") or "\ufffd" in text: |
| 198 | unknown[0xFFFD] += 1 |
| 199 | center = (char["top"] + char["bottom"]) / 2 |
| 200 | baseline = page.point2coord((x, y))[1] if horizontal else center |
| 201 | yield Glyph(text, char["x0"], char["x1"], center, baseline, char["size"], |
| 202 | frozenset(tags), is_math, horizontal, scope if is_math else None) |
| 203 | |
| 204 | |
| 205 | def bounds(shape): |
| 206 | return shape["x0"], shape["top"], shape["x1"], shape["bottom"] |
| 207 | |
| 208 | |
| 209 | def path_is_closed(shape): |
| 210 | points = shape.get("pts") or [] |
| 211 | path = shape.get("path") or [] |
| 212 | return ((path and path[-1][0] == "h") |
| 213 | or (len(points) >= 4 and all(abs(a - b) <= 0.75 |
| 214 | for a, b in zip(points[0], points[-1])))) |
| 215 | |
| 216 | |
| 217 | def drawing_regions(page): |
| 218 | rules, verticals, boxes = [], [], [] |
| 219 | for shape in page.lines + page.rects + page.curves: |
| 220 | x0, top, x1, bottom = bounds(shape) |
| 221 | width, height = x1 - x0, bottom - top |
| 222 | if not (shape["stroke"] or shape["fill"]): |
| 223 | continue |
| 224 | if height <= 2 and width >= 2: |
| 225 | rules.append(Rule(x0, x1, (top + bottom) / 2)) |
| 226 | elif width <= 2 and height >= 2: |
| 227 | verticals.append((x0, top, x1, bottom)) |
| 228 | elif path_is_closed(shape) and width >= 4 and height >= 4: |
| 229 | color = shape["non_stroking_color"] |
| 230 | colored = isinstance(color, (tuple, list)) and len(color) == 3 and max(color) - min(color) > 0.12 |
| 231 | if shape["stroke"] or (shape["fill"] and colored): |
| 232 | boxes.append((x0, top, x1, bottom)) |
| 233 | |
| 234 | # Some generators draw each of the four sides as an independent path. |
| 235 | for upper in rules: |
| 236 | lefts = [v for v in verticals if abs(v[0] - upper.x0) <= 1.5 |
| 237 | and abs(v[1] - upper.y) <= 1.5 and v[3] - v[1] >= 4] |
| 238 | for left in lefts: |
| 239 | right = next((v for v in verticals if abs(v[2] - upper.x1) <= 1.5 |
| 240 | and abs(v[1] - left[1]) <= 1.5 and abs(v[3] - left[3]) <= 1.5), None) |
| 241 | if right and any(abs(lower.y - left[3]) <= 1.5 |
| 242 | and abs(lower.x0 - upper.x0) <= 1.5 |
| 243 | and abs(lower.x1 - upper.x1) <= 1.5 for lower in rules): |
| 244 | boxes.append((left[0], upper.y, right[2], left[3])) |
| 245 | boxes = [b for b in boxes if b[2] - b[0] < page.width * 0.88 |
| 246 | or b[3] - b[1] < page.height * 0.78] |
| 247 | return list(dict.fromkeys(rules)), list(dict.fromkeys(verticals)), list(dict.fromkeys(boxes)) |
| 248 | |
| 249 | |
| 250 | def annotation_regions(page): |
| 251 | from pdfminer.pdftypes import dict_value, resolve1 |
| 252 | from pdfminer.psparser import literal_name |
| 253 | |
| 254 | tags = { |
| 255 | "Underline": "u", "StrikeOut": "del", "Highlight": "mark", |
| 256 | "Square": "mark", "Circle": "mark", "Polygon": "mark", "Squiggly": "mark", |
| 257 | } |
| 258 | left, bottom, right, top = page.page_obj.mediabox |
| 259 | |
| 260 | def to_page(x, y): |
| 261 | if page.rotation == 90: |
| 262 | return page.point2coord((y - bottom, right - x)) |
| 263 | if page.rotation == 180: |
| 264 | return page.point2coord((right - x, top - y)) |
| 265 | if page.rotation == 270: |
| 266 | return page.point2coord((top - y, x - left)) |
| 267 | return page.point2coord((x - left, y - bottom)) |
| 268 | |
| 269 | for reference in resolve1(page.page_obj.annots) or []: |
| 270 | annotation = dict_value(reference) |
| 271 | subtype = resolve1(annotation.get("Subtype")) |
| 272 | tag = tags.get(literal_name(subtype)) if subtype else None |
| 273 | rect = resolve1(annotation.get("Rect")) or [] |
| 274 | if not tag or len(rect) != 4 or resolve1(annotation.get("F", 0)) & 3: |
| 275 | continue |
| 276 | quads = resolve1(annotation.get("QuadPoints")) or [] |
| 277 | if len(quads) >= 8 and len(quads) % 8 == 0: |
| 278 | groups = [quads[i:i+8] for i in range(0, len(quads), 8)] |
| 279 | else: |
| 280 | groups = [rect] |
| 281 | for group in groups: |
| 282 | xs, ys = zip(*(to_page(resolve1(x), resolve1(y)) for x, y in zip(group[::2], group[1::2]))) |
| 283 | yield (min(xs), min(ys), max(xs), max(ys)), tag |
| 284 | |
| 285 | |
| 286 | def apply_regions(glyphs, regions): |
| 287 | return [ |
| 288 | replace(g, tags=g.tags.union(tag for (x0, y0, x1, y1), tag in regions |
| 289 | if x0 <= g.x <= x1 and y0 <= g.center <= y1)) |
| 290 | for g in glyphs |
| 291 | ] |
| 292 | |
| 293 | |
| 294 | def line_decorations(glyphs, rules): |
| 295 | for rule in rules: |
| 296 | for tag, low, high in (("u", -0.04, 0.26), ("del", -0.58, -0.18)): |
| 297 | hits = [g for g in glyphs if g.horizontal and not g.text.isspace() |
| 298 | and rule.x0 <= g.x <= rule.x1 |
| 299 | and low <= (rule.y - g.baseline) / g.size <= high] |
| 300 | if not hits: |
| 301 | continue |
| 302 | left, right = min(g.x0 for g in hits), max(g.x1 for g in hits) |
| 303 | size = median(g.size for g in hits) |
| 304 | if left - rule.x0 <= 0.8 * size and rule.x1 - right <= 0.8 * size: |
| 305 | yield (rule.x0, min(g.center for g in hits) - 0.1, rule.x1, |
| 306 | max(g.center for g in hits) + 0.1), tag |
| 307 | |
| 308 | |
| 309 | def script_text(operator, text): |
| 310 | return operator + (text if len(text) == 1 else f"({text})") |
| 311 | |
| 312 | |
| 313 | def latex_script(operator, text): |
| 314 | text = text.strip() |
| 315 | if re.fullmatch(r"[A-Za-z0-9]|\\[A-Za-z]+", text): |
| 316 | return operator + text |
| 317 | return f"{operator}{{{text}}}" |
| 318 | |
| 319 | |
| 320 | def latex_symbol(text): |
| 321 | if text in LATEX_SYMBOLS: |
| 322 | return LATEX_SYMBOLS[text] |
| 323 | if text in NAMED_OPERATORS: |
| 324 | return "\\" + text |
| 325 | if text.startswith("[U+"): |
| 326 | return rf"\text{{{text}}}" |
| 327 | return text |
| 328 | |
| 329 | |
| 330 | def normalize_unicode_scripts(text, latex=False): |
| 331 | attach = latex_script if latex else script_text |
| 332 | for operator, symbols in UNICODE_SCRIPTS: |
| 333 | pattern = f"[{''.join(symbols)}]+" |
| 334 | text = re.sub(pattern, lambda m: attach(operator, "".join(symbols[c] for c in m[0])), text) |
| 335 | return text |
| 336 | |
| 337 | |
| 338 | def math_text(glyphs, latex=False): |
| 339 | """Join glyphs into one expression. |
| 340 | |
| 341 | The spacing decisions always use the plain `text`, so both notations agree; |
| 342 | with latex=True the joined pieces are each glyph's LaTeX form instead. |
| 343 | """ |
| 344 | text = "" |
| 345 | out = "" |
| 346 | previous = None |
| 347 | prose_space = False |
| 348 | for glyph in sorted(glyphs, key=lambda g: g.x0): |
| 349 | part = glyph.text.replace("\u2212", "-") |
| 350 | if part.isspace(): |
| 351 | prose_space |= not glyph.math |
| 352 | continue |
| 353 | piece = glyph.tex if latex else part |
| 354 | if text and previous: |
| 355 | gap = glyph.x0 - previous.x1 |
| 356 | operator = re.match(r"(?:lim|log|ln|sin|cos|tan)(?:$|[_^])", previous.text) |
| 357 | spaced = (prose_space or part in MATH_OPERATORS or previous.text in MATH_OPERATORS |
| 358 | or part == ":" or previous.text in (",", ":") or previous.text[0] in "∫∑∏" |
| 359 | or (operator and (part != "(" or previous.text.startswith("lim"))) |
| 360 | or (glyph.math != previous.math and gap > glyph.size * 0.12) |
| 361 | or gap > glyph.size * 0.38) |
| 362 | unary_minus = previous.text == "-" and (text == "-" or text[:-1].rstrip()[-1:] in ("=", "(", "[", ",", "+", "-")) |
| 363 | if spaced and not unary_minus and part[0] not in ")]}," and text[-1] not in "([{": |
| 364 | text += " " |
| 365 | out += " " |
| 366 | elif re.search(r"\\[A-Za-z]+$", out) and piece[:1].isalpha(): |
| 367 | out += " " # "\pi x", not the undefined command "\pix" |
| 368 | text += part |
| 369 | out += piece |
| 370 | previous = glyph |
| 371 | prose_space = False |
| 372 | return normalize_unicode_scripts(out if latex else text, latex) |
| 373 | |
| 374 | |
| 375 | def finish_latex(tex): |
| 376 | """Final touches for a whole formula: wrap Korean text and let parentheses |
| 377 | around a fraction grow with it.""" |
| 378 | tex = CJK_TEXT.sub(lambda m: rf"\text{{{m[1]}{m[2]}}}", tex) |
| 379 | return auto_size_parentheses(tex) |
| 380 | |
| 381 | |
| 382 | def auto_size_parentheses(tex): |
| 383 | pairs = [] |
| 384 | groups = [[]] # open "(" positions per brace group; \left/\right cannot cross groups |
| 385 | i = 0 |
| 386 | while i < len(tex): |
| 387 | char = tex[i] |
| 388 | if char == "\\": |
| 389 | word = re.match(r"\\(?:[A-Za-z]+|.)", tex[i:])[0] |
| 390 | i += len(word) |
| 391 | if word in (r"\left", r"\right"): |
| 392 | i += 1 # its delimiter is already sized |
| 393 | continue |
| 394 | if char == "{": |
| 395 | groups.append([]) |
| 396 | elif char == "}" and len(groups) > 1: |
| 397 | groups.pop() |
| 398 | elif char == "(": |
| 399 | groups[-1].append(i) |
| 400 | elif char == ")" and groups[-1]: |
| 401 | start = groups[-1].pop() |
| 402 | if r"\frac" in tex[start:i]: |
| 403 | pairs.append((start, i)) |
| 404 | i += 1 |
| 405 | if not pairs: |
| 406 | return tex |
| 407 | replacements = {} |
| 408 | for start, end in pairs: |
| 409 | replacements[start] = r"\left(" |
| 410 | replacements[end] = r"\right)" |
| 411 | return "".join(replacements.get(i, c) for i, c in enumerate(tex)) |
| 412 | |
| 413 | |
| 414 | def combine(glyphs, text, latex, anchor, baseline=None, size=None): |
| 415 | return replace(anchor, text=text, latex=latex, math=True, |
| 416 | x0=min(g.x0 for g in glyphs), x1=max(g.x1 for g in glyphs), |
| 417 | baseline=anchor.baseline if baseline is None else baseline, |
| 418 | size=anchor.size if size is None else size, |
| 419 | tags=frozenset.intersection(*(g.tags for g in glyphs))) |
| 420 | |
| 421 | |
| 422 | def nearest_row(glyphs, target, tolerance): |
| 423 | if not glyphs: |
| 424 | return [] |
| 425 | anchor = min(glyphs, key=lambda g: abs(g.baseline - target)) |
| 426 | return [g for g in glyphs if abs(g.baseline - anchor.baseline) <= tolerance] |
| 427 | |
| 428 | |
| 429 | def replace_glyphs(glyphs, used, new): |
| 430 | consumed = {id(g) for g in used} |
| 431 | return [g for g in glyphs if id(g) not in consumed] + [new] |
| 432 | |
| 433 | |
| 434 | def join_operator_names(glyphs): |
| 435 | for i in range(len(glyphs) - 1): |
| 436 | for length in (3, 2): |
| 437 | run = glyphs[i:i + length] |
| 438 | name = "".join(g.text for g in run) |
| 439 | first = run[0] |
| 440 | if (len(run) == length and name in NAMED_OPERATORS |
| 441 | and first.scope is not None |
| 442 | and all(g.scope == first.scope and abs(g.baseline - first.baseline) <= first.size * 0.2 |
| 443 | for g in run) |
| 444 | and all(0 <= b.x0 - a.x0 <= first.size for a, b in zip(run, run[1:]))): |
| 445 | yield run, combine(run, name, "\\" + name, first) |
| 446 | |
| 447 | |
| 448 | def attach_limit_scripts(glyphs): |
| 449 | for base in [g for g in glyphs if g.text in LIMIT_OPERATORS and g.scope is not None]: |
| 450 | groups = {} |
| 451 | is_limit = base.text == "lim" |
| 452 | for sign, operator in ((1, "_"), (-1, "^")): |
| 453 | if is_limit: |
| 454 | offset, min_size, max_size = 0.72, 0.40, 0.83 |
| 455 | min_shift, max_shift = 0.46, 1.20 |
| 456 | x0, x1 = base.x0 - 0.5 * base.size, base.x1 + 0.48 * base.size |
| 457 | else: |
| 458 | offset, min_size, max_size = 0.52, 0.25, 0.52 |
| 459 | min_shift, max_shift = 0.24, 0.85 |
| 460 | if base.text == "∫": |
| 461 | x0, x1 = base.x1 - 0.17 * base.size, base.x1 + 0.35 * base.size |
| 462 | else: |
| 463 | x0, x1 = base.x0 - 0.23 * base.size, base.x1 + 0.23 * base.size |
| 464 | def fits(glyph): |
| 465 | # A fraction drawn as a separate text object can straddle the |
| 466 | # integral's original baseline even when it is a bound. |
| 467 | separate_bound = base.text == "∫" and glyph.math and ")/(" in glyph.text |
| 468 | return (glyph is not base and glyph.horizontal |
| 469 | and (glyph.scope == base.scope or separate_bound) |
| 470 | and glyph.text not in LIMIT_OPERATORS and glyph.text != HWP_BAR |
| 471 | and x0 <= glyph.x <= x1 and min_size <= glyph.size / base.size <= max_size |
| 472 | and (0.16 if separate_bound else min_shift) |
| 473 | <= sign * (glyph.baseline - base.baseline) / base.size <= max_shift) |
| 474 | |
| 475 | options = [g for g in glyphs if fits(g)] |
| 476 | if options: |
| 477 | groups[operator] = nearest_row(options, base.baseline + sign * base.size * offset, |
| 478 | base.size * 0.14) |
| 479 | if groups or not is_limit: |
| 480 | scripts = {op: math_text(group) for op, group in groups.items()} |
| 481 | latex_scripts = {op: math_text(group, latex=True) for op, group in groups.items()} |
| 482 | if is_limit and "_" in scripts: |
| 483 | # One-sided limits: "x → 0 -" reads "x → 0-", in LaTeX "x \to 0^-". |
| 484 | scripts["_"] = re.sub(r" ([+-])$", r"\1", scripts["_"]) |
| 485 | latex_scripts["_"] = re.sub(r" ?([+-])$", r"^\1", latex_scripts["_"]) |
| 486 | text = base.text + "".join(script_text(op, value) for op, value in scripts.items()) |
| 487 | latex = base.tex + "".join(latex_script(op, value) for op, value in latex_scripts.items()) |
| 488 | used = [base, *(g for group in groups.values() for g in group)] |
| 489 | baseline = base.baseline if is_limit else base.center + 0.17 * base.size |
| 490 | glyphs = replace_glyphs(glyphs, used, combine(used, text, latex, base, baseline, |
| 491 | size=base.size if is_limit else base.size * 0.56)) |
| 492 | return glyphs |
| 493 | |
| 494 | |
| 495 | def resize_delimiters(glyphs): |
| 496 | adjusted = [] |
| 497 | for glyph in glyphs: |
| 498 | if glyph.scope is not None and glyph.text in "()[]{}|" and glyph.size >= 8: |
| 499 | neighbors = [g for g in glyphs if g.scope == glyph.scope and g.text not in "()[]{}|" |
| 500 | and g.text != HWP_BAR and abs(g.x - glyph.x) <= glyph.size * 1.85 |
| 501 | and abs(g.center - glyph.center) <= glyph.size * 0.44 |
| 502 | and glyph.size * 0.40 <= g.size <= glyph.size * 1.05] |
| 503 | if neighbors: |
| 504 | size = max(g.size for g in neighbors) |
| 505 | if glyph.size >= 1.35 * size: |
| 506 | glyph = replace(glyph, size=size, baseline=glyph.center + 0.3 * size, |
| 507 | script_reach=glyph.size * 0.62) |
| 508 | adjusted.append(glyph) |
| 509 | return adjusted |
| 510 | |
| 511 | |
| 512 | def attach_scripts(glyphs, extra=()): |
| 513 | extras = {id(g) for g in extra} |
| 514 | available = [*glyphs, *extra] |
| 515 | for original in sorted(glyphs, key=lambda g: (g.size, g.x0)): |
| 516 | if (not original.horizontal or original.text[0] in "∫∑∏" |
| 517 | or original.text.startswith("lim_") |
| 518 | or not (original.math or re.fullmatch("[A-Za-z0-9]", original.text))): |
| 519 | continue |
| 520 | if not re.search(r"[\w)\]}|]$", original.text) or original.text.startswith("[U+"): |
| 521 | continue |
| 522 | base = next((g for g in available if g is original), None) |
| 523 | if base is None: |
| 524 | continue |
| 525 | if not base.math and any( |
| 526 | g is not base and not g.math and g.text.isalpha() |
| 527 | and 0 <= base.x0 - g.x0 <= base.size |
| 528 | and abs(g.baseline - base.baseline) < base.size * 0.15 |
| 529 | and abs(base.x0 - g.x1) < base.size * 0.14 for g in glyphs |
| 530 | ): |
| 531 | continue |
| 532 | used = [base] |
| 533 | suffix = "" |
| 534 | latex_suffix = "" |
| 535 | for sign, operator in ((1, "_"), (-1, "^")): |
| 536 | options = [g for g in available if g.horizontal and g not in used and not g.text.isspace() |
| 537 | and g.text != HWP_BAR and g.scope == base.scope |
| 538 | and (g.math or re.fullmatch(r"[A-Za-z0-9+()=-]", g.text)) |
| 539 | and 0.42 <= g.size / base.size <= 0.85 |
| 540 | and base.size * 0.19 <= sign * (g.baseline - base.baseline) |
| 541 | <= max(base.size * 0.94, base.script_reach) |
| 542 | and g.x0 >= base.x1 - base.size * 0.28] |
| 543 | run = [] |
| 544 | end = max(g.x1 for g in used) |
| 545 | for g in sorted(options, key=lambda g: g.x0): |
| 546 | if g.x0 - end > base.size * 0.32: |
| 547 | break |
| 548 | if run and abs(g.baseline - run[0].baseline) > base.size * 0.22: |
| 549 | continue |
| 550 | run.append(g) |
| 551 | end = max(end, g.x1) |
| 552 | if run: |
| 553 | used.extend(run) |
| 554 | suffix += script_text(operator, math_text(run)) |
| 555 | latex_suffix += latex_script(operator, math_text(run, latex=True)) |
| 556 | if suffix: |
| 557 | base_tex = base.tex |
| 558 | if base.latex is not None and re.search(r"[_^]", base_tex): |
| 559 | base_tex = f"{{{base_tex}}}" # avoid a "double superscript" error |
| 560 | available = replace_glyphs(available, used, combine( |
| 561 | used, base.text + suffix, base_tex + latex_suffix, base)) |
| 562 | if extra: |
| 563 | return ([g for g in available if id(g) not in extras], |
| 564 | [g for g in available if id(g) in extras]) |
| 565 | return available |
| 566 | |
| 567 | |
| 568 | |
| 569 | def math_scope(glyphs, rule): |
| 570 | if rule.glyph: |
| 571 | return rule.glyph.scope |
| 572 | nearby = [g.scope for g in glyphs if g.scope is not None and g.horizontal |
| 573 | and rule.x0 <= g.x <= rule.x1 and abs(g.baseline - rule.y) <= g.size * 1.1] |
| 574 | return Counter(nearby).most_common(1)[0][0] if nearby else None |
| 575 | |
| 576 | |
| 577 | def fraction_row(glyphs, y, sign, size): |
| 578 | candidates = [g for g in glyphs if size * 0.16 <= sign * (g.baseline - y) <= size * 1.55] |
| 579 | if not candidates: |
| 580 | return [] |
| 581 | largest = max(g.size for g in candidates) |
| 582 | bases = [g for g in candidates if g.size >= min(largest * 0.80, size * 0.77)] |
| 583 | anchor = min(bases, key=lambda g: abs(g.baseline - y - sign * size * 0.68)) |
| 584 | return [g for g in candidates if abs(g.baseline - anchor.baseline) <= size * 0.23] |
| 585 | |
| 586 | |
| 587 | def rebuild_bars(glyphs, rules): |
| 588 | bars = [Rule(g.x0, g.x1, g.baseline - 0.31 * g.size, g) |
| 589 | for g in glyphs if g.scope is not None and g.text == HWP_BAR] |
| 590 | fraction_rules = set() |
| 591 | for rule in sorted([*bars, *rules], key=lambda r: r.x1 - r.x0): |
| 592 | bar = rule.glyph |
| 593 | scope = math_scope(glyphs, rule) |
| 594 | x0, x1, y = rule.x0, rule.x1, rule.y |
| 595 | nearby = [g for g in glyphs if g.horizontal and g.scope == scope |
| 596 | and g.text not in (HWP_BAR, "√") and not g.text.isspace() |
| 597 | and x0 - 0.75 <= g.x <= x1 + 0.75 |
| 598 | and abs(g.baseline - y) <= max(g.size * 2.05, bar.size * 1.65 if bar else 0) |
| 599 | and (scope is not None or g.math or re.fullmatch(r"[A-Za-z0-9()+.,=/−-]", g.text))] |
| 600 | if not nearby: |
| 601 | continue |
| 602 | size = bar.size if bar else median(g.size for g in nearby) |
| 603 | roots = [g for g in glyphs if bar and g.scope == scope and g.text == "√" |
| 604 | and abs(g.x1 - x0) <= size * 0.27 |
| 605 | and abs(g.baseline - y - size * 0.6) <= size * 0.85] |
| 606 | if roots: |
| 607 | root = min(roots, key=lambda g: abs(g.x1 - x0)) |
| 608 | body = [g for g in nearby if y + size * 0.05 < g.baseline <= y + size * 1.65] |
| 609 | index = [g for g in glyphs if g.scope == scope and g.x0 >= root.x0 - size * 0.2 |
| 610 | and g.x1 <= x0 + size * 0.15 and g.text != HWP_BAR |
| 611 | and 0.35 <= g.size / root.size <= 0.64 |
| 612 | and root.baseline - g.baseline >= size * 0.18] |
| 613 | if body: |
| 614 | rebuilt = attach_scripts(resize_delimiters(body)) |
| 615 | radicand = math_text(rebuilt) |
| 616 | latex_radicand = math_text(rebuilt, latex=True) |
| 617 | if index: |
| 618 | text = f"root({math_text(index)}, {radicand})" |
| 619 | latex = rf"\sqrt[{math_text(index, latex=True)}]{{{latex_radicand}}}" |
| 620 | else: |
| 621 | text = f"sqrt({radicand})" |
| 622 | latex = rf"\sqrt{{{latex_radicand}}}" |
| 623 | used = [bar, root, *body, *index] |
| 624 | glyphs = replace_glyphs(glyphs, used, combine(used, text, latex, root)) |
| 625 | continue |
| 626 | |
| 627 | numerator = fraction_row(nearby, y, -1, size) |
| 628 | denominator = fraction_row(nearby, y, 1, size) |
| 629 | arrow = next((g for g in nearby if bar and g.text == "→" |
| 630 | and abs(g.baseline - bar.baseline) < size * 0.12 |
| 631 | and abs(g.x0 - x1) < size * 0.36), None) |
| 632 | if arrow or not numerator or not denominator: |
| 633 | if bar and denominator: |
| 634 | group = denominator |
| 635 | if max(g.x1 for g in group) - min(g.x0 for g in group) >= (x1 - x0) * 0.45: |
| 636 | command = "vec" if arrow else "overline" |
| 637 | text = f"{command}({math_text(group)})" |
| 638 | latex_command = r"\overrightarrow" if arrow else r"\overline" |
| 639 | latex = f"{latex_command}{{{math_text(group, latex=True)}}}" |
| 640 | markers = [bar, arrow] if arrow else [bar] |
| 641 | glyphs = replace_glyphs(glyphs, [*markers, *group], |
| 642 | combine(group, text, latex, group[0])) |
| 643 | continue |
| 644 | |
| 645 | if not bar: |
| 646 | width = max(max(g.x1 for g in row) - min(g.x0 for g in row) |
| 647 | for row in (numerator, denominator)) |
| 648 | if x1 - x0 > width + size * 1.55: |
| 649 | continue |
| 650 | if any(abs(median(g.x for g in row) - (x1 + x0) / 2) > (x1 - x0) * 0.28 |
| 651 | for row in (numerator, denominator)): |
| 652 | continue |
| 653 | if min(g.baseline - y for g in denominator) < size * 0.40: |
| 654 | continue |
| 655 | |
| 656 | upper_y = median(g.baseline for g in numerator) |
| 657 | lower_y = median(g.baseline for g in denominator) |
| 658 | extra = [g for g in nearby if g not in numerator and g not in denominator] |
| 659 | rows = [] |
| 660 | latex_rows = [] |
| 661 | remaining = [] |
| 662 | for group, row_y, other_y in ((numerator, upper_y, lower_y), (denominator, lower_y, upper_y)): |
| 663 | scripts = [g for g in extra if abs(g.baseline - row_y) <= abs(g.baseline - other_y)] |
| 664 | group = resize_delimiters(group) |
| 665 | rebuilt, leftover = attach_scripts(group, scripts) if scripts else (attach_scripts(group), []) |
| 666 | rows.append(math_text(rebuilt)) |
| 667 | latex_rows.append(math_text(rebuilt, latex=True)) |
| 668 | remaining.extend(leftover) |
| 669 | if not all(rows): |
| 670 | continue |
| 671 | |
| 672 | baseline = (upper_y + lower_y) / 2 |
| 673 | used = [g for g in nearby if g not in remaining] |
| 674 | compound = combine(used, f"({rows[0]})/({rows[1]})", |
| 675 | rf"\frac{{{latex_rows[0]}}}{{{latex_rows[1]}}}", |
| 676 | bar or used[0], baseline, size) |
| 677 | compound = replace(compound, x0=x0, x1=x1, center=baseline - size * 0.3) |
| 678 | if bar: |
| 679 | used.append(bar) |
| 680 | else: |
| 681 | fraction_rules.add(rule) |
| 682 | glyphs = replace_glyphs(glyphs, used, compound) |
| 683 | return glyphs, fraction_rules |
| 684 | |
| 685 | |
| 686 | def reconstruct_math(glyphs, rules): |
| 687 | for run, name in list(join_operator_names(glyphs)): |
| 688 | glyphs = replace_glyphs(glyphs, run, name) |
| 689 | glyphs, fraction_rules = rebuild_bars(glyphs, rules) |
| 690 | glyphs = attach_limit_scripts(glyphs) |
| 691 | glyphs = attach_scripts(resize_delimiters(glyphs)) |
| 692 | glyphs = [replace(g, text="-") if g.text == HWP_BAR else g for g in glyphs] |
| 693 | return join_prime_marks(glyphs), fraction_rules |
| 694 | |
| 695 | |
| 696 | def join_prime_marks(glyphs): |
| 697 | for mark in [g for g in glyphs if g.text in ("′", "″", "‴") and not g.math]: |
| 698 | if any(g.math and -0.15 * mark.size <= mark.x0 - g.x1 <= 0.35 * mark.size |
| 699 | and abs(g.baseline - mark.baseline) <= mark.size * 0.24 for g in glyphs): |
| 700 | glyphs = replace_glyphs(glyphs, [mark], replace(mark, math=True)) |
| 701 | return glyphs |
| 702 | |
| 703 | |
| 704 | def reading_regions(page, glyphs, verticals, rules): |
| 705 | middle = (page.bbox[0] + page.bbox[2]) / 2 |
| 706 | dividers = [v for v in verticals if abs((v[0] + v[2]) / 2 - middle) < page.width * 0.12 |
| 707 | and v[3] - v[1] > page.height * 0.42] |
| 708 | if dividers: |
| 709 | x0, top, x1, bottom = max(dividers, key=lambda v: v[3] - v[1]) |
| 710 | split = (x0 + x1) / 2 |
| 711 | # A full-width heading can be painted over the top of the divider. |
| 712 | header_rules = [r.y for r in rules if top <= r.y <= top + page.height * 0.07 |
| 713 | and r.x0 <= split - page.width * 0.3 |
| 714 | and r.x1 >= split + page.width * 0.3] |
| 715 | top = max(header_rules, default=top) |
| 716 | body = [g for g in glyphs if top <= g.center <= bottom] |
| 717 | left = [g for g in body if g.x < split] |
| 718 | right = [g for g in body if g.x >= split] |
| 719 | if len(left) >= 10 and len(right) >= 10: |
| 720 | return ([g for g in glyphs if g.center < top], left, right, |
| 721 | [g for g in glyphs if g.center > bottom]) |
| 722 | return (glyphs,) |
| 723 | |
| 724 | |
| 725 | def text_lines(glyphs): |
| 726 | lines = [] |
| 727 | for glyph in sorted(glyphs, key=lambda g: (g.baseline, g.x0)): |
| 728 | if lines: |
| 729 | anchor = lines[-1][0] |
| 730 | if abs(glyph.baseline - anchor.baseline) <= max(2.2, min(glyph.size, anchor.size) * 0.34): |
| 731 | lines[-1].append(glyph) |
| 732 | continue |
| 733 | lines.append([glyph]) |
| 734 | return [sorted(line, key=lambda g: g.x0) for line in lines] |
| 735 | |
| 736 | |
| 737 | def reconstruct_cases(glyphs): |
| 738 | # A tall brace is drawn as a middle piece plus separate top and bottom pieces. |
| 739 | for brace in [g for g in glyphs if g.text == HWP_BRACE_MIDDLE]: |
| 740 | pieces = [g for g in glyphs if g.scope == brace.scope and g.text in HWP_BRACE |
| 741 | and abs(g.x0 - brace.x0) < 1.0] |
| 742 | if (not any(g.text == HWP_BRACE_TOP for g in pieces) |
| 743 | or not any(g.text == HWP_BRACE_BOTTOM for g in pieces)): |
| 744 | continue |
| 745 | top, bottom = min(g.baseline for g in pieces), max(g.baseline for g in pieces) |
| 746 | values = [g for g in glyphs if g.scope == brace.scope and g not in pieces |
| 747 | and brace.x1 <= g.x0 < brace.x1 + brace.size * 2 and top <= g.baseline <= bottom] |
| 748 | rows = [] |
| 749 | latex_rows = [] |
| 750 | used = list(pieces) |
| 751 | for value in sorted(values, key=lambda g: g.baseline): |
| 752 | row = [g for g in glyphs if g not in used and g.x0 >= value.x0 - 0.2 |
| 753 | and abs(g.baseline - value.baseline) <= brace.size * 0.24] |
| 754 | if not row: |
| 755 | continue |
| 756 | row.sort(key=lambda g: g.x0) |
| 757 | # Leave a neighboring table cell or separate column outside the expression. |
| 758 | stop = next((i for i in range(1, len(row)) |
| 759 | if row[i].x0 - row[i - 1].x1 > brace.size * 2.3), len(row)) |
| 760 | row = row[:stop] |
| 761 | rows.append(math_text(row)) |
| 762 | # The widest gap separates a value from its condition: "1 & x > 0". |
| 763 | size = median(g.size for g in row) |
| 764 | gaps = [(row[i].x0 - row[i - 1].x1, i) for i in range(1, len(row))] |
| 765 | gap, split = max(gaps, default=(0, 0)) |
| 766 | if gap > size * 0.9: |
| 767 | latex_rows.append(f"{math_text(row[:split], latex=True)} & " |
| 768 | f"{math_text(row[split:], latex=True)}") |
| 769 | else: |
| 770 | latex_rows.append(math_text(row, latex=True)) |
| 771 | used.extend(row) |
| 772 | if len(rows) >= 2: |
| 773 | latex = r"\begin{cases} " + r" \\ ".join(latex_rows) + r" \end{cases}" |
| 774 | new = combine(used, "cases(" + ", ".join(rows) + ")", latex, brace) |
| 775 | glyphs = replace_glyphs(glyphs, used, new) |
| 776 | return [replace(g, text=HWP_BRACE[g.text]) if g.text in HWP_BRACE else g for g in glyphs] |
| 777 | |
| 778 | |
| 779 | def markdown_text(text): |
| 780 | return MARKDOWN_SPECIAL.sub(r"\\\1", html.escape(text, quote=False)) |
| 781 | |
| 782 | |
| 783 | def join_tagged(chunks): |
| 784 | """Join (text, tags) chunks, keeping a tag open across neighbouring chunks |
| 785 | that share it instead of emitting <mark>a</mark> <mark>b</mark>.""" |
| 786 | out, opened, pending_space = [], [], False |
| 787 | for text, tags in chunks: |
| 788 | if text == " ": |
| 789 | pending_space = bool(out) |
| 790 | continue |
| 791 | wanted = [tag for tag in TAG_ORDER if tag in tags] |
| 792 | keep = 0 |
| 793 | while keep < min(len(opened), len(wanted)) and opened[keep] == wanted[keep]: |
| 794 | keep += 1 |
| 795 | out.extend(f"</{tag}>" for tag in reversed(opened[keep:])) |
| 796 | if pending_space: |
| 797 | out.append(" ") |
| 798 | pending_space = False |
| 799 | out.extend(f"<{tag}>" for tag in wanted[keep:]) |
| 800 | opened = wanted |
| 801 | out.append(text) |
| 802 | out.extend(f"</{tag}>" for tag in reversed(opened)) |
| 803 | return "".join(out) |
| 804 | |
| 805 | |
| 806 | def is_closing_punctuation(text): |
| 807 | return len(text) == 1 and text in ".,?!:;)]}" |
| 808 | |
| 809 | |
| 810 | def render_line(glyphs): |
| 811 | chunks = [] |
| 812 | i = 0 |
| 813 | previous = None |
| 814 | while i < len(glyphs): |
| 815 | glyph = glyphs[i] |
| 816 | if glyph.text.isspace(): |
| 817 | if chunks and chunks[-1][0] != " ": |
| 818 | chunks.append((" ", frozenset(), False)) |
| 819 | i += 1 |
| 820 | continue |
| 821 | if previous and chunks and chunks[-1][0] != " ": |
| 822 | gap = glyph.x0 - previous.x1 |
| 823 | if gap > min(glyph.size, previous.size) * 0.19 and not is_closing_punctuation(glyph.text): |
| 824 | chunks.append((" ", frozenset(), False)) |
| 825 | end = i + 1 |
| 826 | while end < len(glyphs): |
| 827 | candidate = glyphs[end] |
| 828 | prior = glyphs[end - 1] |
| 829 | if candidate.math != glyph.math or candidate.tags != glyph.tags: |
| 830 | break |
| 831 | if candidate.text.isspace() and ( |
| 832 | end + 1 == len(glyphs) or glyphs[end + 1].tags != glyph.tags |
| 833 | or glyphs[end + 1].math != glyph.math |
| 834 | ): |
| 835 | break |
| 836 | if glyph.math and candidate.x0 - prior.x1 > min(prior.size, candidate.size) * 0.8: |
| 837 | break |
| 838 | end += 1 |
| 839 | run = glyphs[i:end] |
| 840 | if glyph.math: |
| 841 | tex = finish_latex(math_text(run, latex=True)).strip() |
| 842 | chunks.append((tex, glyph.tags, True)) |
| 843 | previous = run[-1] |
| 844 | i = end |
| 845 | continue |
| 846 | else: |
| 847 | parts = [] |
| 848 | prior = run[0] |
| 849 | for part in run: |
| 850 | if (parts and part.x0 - prior.x1 > min(prior.size, part.size) * 0.19 |
| 851 | and not is_closing_punctuation(part.text)): |
| 852 | parts.append(" ") |
| 853 | parts.append(part.text) |
| 854 | prior = part |
| 855 | value = markdown_text(re.sub(r"\s+", " ", "".join(parts))) |
| 856 | chunks.append((value, glyph.tags, False)) |
| 857 | previous = run[-1] |
| 858 | i = end |
| 859 | |
| 860 | words = [chunk for chunk in chunks if chunk[0] != " "] |
| 861 | if not words: |
| 862 | return "" |
| 863 | # A line drawn wholly inside a box becomes a blockquote. Wrapping it in |
| 864 | # <mark> would stop many Markdown viewers from rendering the math inside. |
| 865 | quote = all("mark" in tags for _, tags, _ in words) |
| 866 | if quote: |
| 867 | chunks = [(value, tags - {"mark"}, is_math) for value, tags, is_math in chunks] |
| 868 | if len(words) == 1 and words[0][2] and not quote and not (words[0][1] - {"mark"}): |
| 869 | # A formula on a line of its own becomes a display block. |
| 870 | return f"\n$${words[0][0]}$$\n" |
| 871 | # Never put math inside HTML tags; carry its formatting in LaTeX instead. |
| 872 | chunks = [(f"${latex_decorations(value, tags)}$", frozenset()) if is_math else (value, tags) |
| 873 | for value, tags, is_math in chunks] |
| 874 | line = escape_line_start(join_tagged(chunks).strip()) |
| 875 | return f"> {line}" if quote else line |
| 876 | |
| 877 | |
| 878 | def latex_decorations(tex, tags): |
| 879 | for tag, command in (("b", r"\boldsymbol"), ("del", r"\cancel"), ("u", r"\underline")): |
| 880 | if tag in tags: |
| 881 | tex = f"{command}{{{tex}}}" |
| 882 | return tex |
| 883 | |
| 884 | |
| 885 | def escape_line_start(line): |
| 886 | # A problem number such as "2." should stay verbatim in the rendered Markdown. |
| 887 | line = re.sub(r"^(\d+)([.)])(?= |$)", r"\1\\\2", line) |
| 888 | # Keep a leading "-"/"+" from becoming a list item, and a line of "-" or "=" |
| 889 | # from turning the previous line into a setext heading. |
| 890 | if re.fullmatch(r"[-=]+ *", line): |
| 891 | return "\\" + line |
| 892 | return re.sub(r"^([-+])(?= |$)", r"\\\1", line) |
| 893 | |
| 894 | |
| 895 | def convert_page(page, unknown): |
| 896 | glyphs = list(page_glyphs(page, unknown)) |
| 897 | if not glyphs: |
| 898 | return "" |
| 899 | rules, verticals, boxes = drawing_regions(page) |
| 900 | regions = [(b, "mark") for b in boxes] |
| 901 | regions.extend(annotation_regions(page)) |
| 902 | glyphs = apply_regions(glyphs, regions) |
| 903 | expressions, fraction_rules = reconstruct_math(glyphs, rules) |
| 904 | decor = list(line_decorations(expressions, [r for r in rules if r not in fraction_rules])) |
| 905 | expressions = apply_regions(expressions, decor) |
| 906 | blocks = [] |
| 907 | for region in reading_regions(page, expressions, verticals, rules): |
| 908 | lines = [line for row in text_lines(reconstruct_cases(region)) if (line := render_line(row))] |
| 909 | out = [] |
| 910 | for line in lines: |
| 911 | quoted = line.startswith("> ") |
| 912 | if out and out[-1].startswith("> ") != quoted: |
| 913 | # Separate a blockquote from plain lines, or the next plain line |
| 914 | # would be pulled into the quote as a lazy continuation. |
| 915 | out.append("") |
| 916 | elif out and out[-1] not in ("", ">") and BLOCK_START.match(line.removeprefix("> ")): |
| 917 | # A new problem, choice row, 보기 item or condition starts its own |
| 918 | # paragraph; lines wrapped mid-sentence keep flowing together. |
| 919 | out.append(">" if quoted else "") |
| 920 | out.append(line) |
| 921 | if out: |
| 922 | blocks.append("\n".join(out)) |
| 923 | # Display formulas bring their own blank lines; collapse any extras. |
| 924 | return re.sub(r"\n{3,}", "\n\n", "\n\n".join(blocks)).strip() |
| 925 | |
| 926 | |
| 927 | def fallback_page(page): |
| 928 | """Plain-text rendering used when the layout heuristics fail on a page.""" |
| 929 | text = (page.extract_text() or "").translate(HWP_SYMBOLS) |
| 930 | return "\n".join(escape_line_start(line) for raw in text.splitlines() |
| 931 | if (line := markdown_text(raw.strip()))) |
| 932 | |
| 933 | |
| 934 | def output_mode(destination): |
| 935 | # NamedTemporaryFile creates files with mode 0600; give the result the mode |
| 936 | # an ordinary new file would get (or keep the mode of the file we replace). |
| 937 | try: |
| 938 | return destination.stat().st_mode & 0o7777 |
| 939 | except FileNotFoundError: |
| 940 | umask = os.umask(0) |
| 941 | os.umask(umask) |
| 942 | return 0o666 & ~umask |
| 943 | |
| 944 | |
| 945 | def convert(source, destination): |
| 946 | import pdfplumber |
| 947 | |
| 948 | unknown = Counter() |
| 949 | empty_pages = [] |
| 950 | failed_pages = [] |
| 951 | total = 0 |
| 952 | temporary = None |
| 953 | try: |
| 954 | with pdfplumber.open(source, strict_metadata=False) as pdf: |
| 955 | with NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", |
| 956 | dir=destination.parent, prefix=f".{destination.name}.", |
| 957 | suffix=".tmp", delete=False) as output: |
| 958 | temporary = Path(output.name) |
| 959 | for page in pdf.pages: |
| 960 | try: |
| 961 | content = convert_page(page, unknown) |
| 962 | except (KeyboardInterrupt, MemoryError): |
| 963 | raise |
| 964 | except Exception as error: |
| 965 | # One unusual page should not discard the whole document. |
| 966 | failed_pages.append(f"{page.page_number} ({type(error).__name__}: {error})") |
| 967 | content = fallback_page(page) |
| 968 | finally: |
| 969 | page.close() |
| 970 | if not content.strip(): |
| 971 | empty_pages.append(page.page_number) |
| 972 | continue |
| 973 | if total: |
| 974 | output.write("\n\n---\n\n") |
| 975 | output.write(content) |
| 976 | total += 1 |
| 977 | if not total: |
| 978 | raise ValueError("추출할 수 있는 텍스트가 없습니다. 이미지 PDF는 OCR이 필요합니다.") |
| 979 | output.write("\n") |
| 980 | os.chmod(temporary, output_mode(destination)) |
| 981 | os.replace(temporary, destination) |
| 982 | finally: |
| 983 | if temporary is not None: |
| 984 | temporary.unlink(missing_ok=True) |
| 985 | |
| 986 | if failed_pages: |
| 987 | print("레이아웃 분석에 실패해 일반 텍스트로 변환한 페이지: " + ", ".join(failed_pages), |
| 988 | file=sys.stderr) |
| 989 | if empty_pages: |
| 990 | print("텍스트가 없는 페이지: " + ", ".join(map(str, empty_pages)), file=sys.stderr) |
| 991 | if unknown: |
| 992 | codes = ", ".join(f"U+{code:04X} ({count}개)" for code, count in sorted(unknown.items())) |
| 993 | print(f"확인할 수 없는 문자: {codes}", file=sys.stderr) |
| 994 | |
| 995 | |
| 996 | def main(): |
| 997 | parser = argparse.ArgumentParser(description="텍스트가 포함된 PDF를 Markdown으로 변환합니다.") |
| 998 | parser.add_argument("--file", required=True, type=Path, help="원본 PDF 경로") |
| 999 | parser.add_argument("--output", type=Path, |
| 1000 | help="출력 Markdown 경로 (생략하면 원본 PDF 옆에 .md로 저장)") |
| 1001 | args = parser.parse_args() |
| 1002 | source = args.file.expanduser() |
| 1003 | destination = (args.output or source.with_suffix(".md")).expanduser() |
| 1004 | if not source.is_file(): |
| 1005 | parser.error(f"PDF 파일을 찾을 수 없습니다. {source}") |
| 1006 | if destination.is_dir(): |
| 1007 | parser.error(f"출력 경로가 디렉터리입니다. 파일 경로를 지정하세요. {destination}") |
| 1008 | if source.resolve() == destination.resolve() or (destination.exists() and source.samefile(destination)): |
| 1009 | parser.error("원본 PDF와 출력 파일의 경로를 다르게 지정하세요.") |
| 1010 | if not destination.parent.is_dir(): |
| 1011 | parser.error(f"출력 디렉터리가 없습니다. {destination.parent}") |
| 1012 | |
| 1013 | try: |
| 1014 | from pdfminer.pdfdocument import PDFPasswordIncorrect, PDFTextExtractionNotAllowed |
| 1015 | from pdfminer.pdfparser import PDFSyntaxError |
| 1016 | from pdfplumber.utils.exceptions import MalformedPDFException, PdfminerException |
| 1017 | except ImportError: |
| 1018 | parser.exit(1, 'pdfplumber가 필요합니다. python3 -m pip install "pdfplumber>=0.11.9,<1"\n') |
| 1019 | |
| 1020 | try: |
| 1021 | convert(source, destination) |
| 1022 | except (OSError, ValueError, PDFSyntaxError, PDFPasswordIncorrect, |
| 1023 | PDFTextExtractionNotAllowed, PdfminerException, MalformedPDFException) as error: |
| 1024 | message = str(error) or type(error).__name__ |
| 1025 | parser.exit(1, f"변환 실패. {message}\n") |
| 1026 | return 0 |
| 1027 | |
| 1028 | |
| 1029 | if __name__ == "__main__": |
| 1030 | raise SystemExit(main()) |