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