| | @@ -9,6 +9,7 @@ import html |
| 9 | 9 | import os |
| 10 | 10 | import re |
| 11 | 11 | import sys |
| 12 | +추가: import unicodedata |
| 12 | 13 | from collections import Counter |
| 13 | 14 | from dataclasses import dataclass, replace |
| 14 | 15 | from functools import lru_cache |
| | @@ -27,7 +28,18 @@ HWP_SYMBOLS = { |
| 27 | 28 | 0xE09D: "\u03b1", 0xE0AC: "\u03c0", 0xE0AE: "\u03c3", 0xE101: "|", |
| 28 | 29 | } |
| 29 | 30 | HWP_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. |
| 33 | +추가: MATH_FONT = re.compile(r"math|stix|xits|(?:^|\+)(?:cm(?:mi|sy|ex|r|bx|ti)\d+|msam|msbm|eufm|rsfs)", |
| 34 | +추가: re.I) |
| 30 | 35 | HWP_BRACE_TOP, HWP_BRACE_MIDDLE, HWP_BRACE_BOTTOM = "\ue078", "\ue079", "\ue07a" |
| 36 | +추가: TABLE = "" # text of a stand-in glyph whose `latex` holds a Markdown table |
| 37 | +추가: CHARACTER_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 | +추가: } |
| 31 | 43 | HWP_BRACE = {HWP_BRACE_TOP: "{", HWP_BRACE_MIDDLE: "{", HWP_BRACE_BOTTOM: "{", "\ue07b": "|"} |
| 32 | 44 | MATH_OPERATORS = frozenset("=+-\u00d7\u00f7\u2260<>\u2264\u2265\u00b1\u2192") |
| 33 | 45 | LIMIT_OPERATORS = frozenset(("lim", "\u2211", "\u222b", "\u220f")) |
| | @@ -60,7 +72,8 @@ CJK_TEXT = re.compile(r"( ?)([ᄀ-ᇿ-㈀-㋿一-鿿가-힣]" |
| 60 | 72 | r"(?:[ ᄀ-ᇿ-㈀-㋿一-鿿가-힣]*" |
| 61 | 73 | r"[ᄀ-ᇿ-㈀-㋿一-鿿가-힣])?)") |
| 62 | 74 | # Line openings that begin a new paragraph: "<b>12.</b>", "3\.", "①", "ㄱ.", "(가)", "\* ". |
| 63 | | -삭제: BLOCK_START = re.compile(r"(?:<b>)?\d{1,2}\\?[.)]|[①-⑳]|[ㄱ-ㅎ]\.|\([가-힣]\)|\\\* ") |
| 75 | +추가: BLOCK_START = re.compile(r"(?:<b>)?\d{1,2}\\?[.)]|[①-⑳❶-➓]|[ㄱ-ㅎ]\.|" |
| 76 | +추가: r"\([가-힣]\)|\\\* ") |
| 64 | 77 | UNICODE_SCRIPTS = ( |
| 65 | 78 | ("^", dict(zip("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207a\u207b\u207c\u207d\u207e\u207f", "0123456789+-=()n"))), |
| 66 | 79 | ("_", dict(zip("\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208a\u208b\u208c\u208d\u208e", "0123456789+-=()"))), |
| | @@ -180,20 +193,30 @@ def page_glyphs(page, unknown): |
| 180 | 193 | horizontal = abs(b) <= abs(a) * 0.08 |
| 181 | 194 | if horizontal and d and 0.08 < abs(c / d) < 0.7: |
| 182 | 195 | tags.add("em") |
| 183 | | -삭제: is_math = "hyhwpeq" in font.lower() |
| 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) |
| 184 | 200 | if is_math: |
| 185 | 201 | # Math letters are often slanted on purpose; that is notation, not |
| 186 | | -삭제: # emphasis, and an <em> tag would split the inline code span. |
| 202 | +추가: # emphasis, and an <em> tag would split the formula. |
| 187 | 203 | tags.discard("em") |
| 188 | 204 | if is_math and not was_math: |
| 189 | 205 | scope += 1 |
| 190 | | -삭제: was_math = is_math |
| 191 | | -삭제: if is_math and len(text) == 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: |
| 192 | 211 | text = HWP_SYMBOLS.get(ord(text), text) |
| 212 | +추가: text = normalize_character(text) |
| 193 | 213 | if (len(text) == 1 and "\ue000" <= text <= "\uf8ff" |
| 194 | 214 | and text != HWP_BAR and text not in HWP_BRACE): |
| 195 | 215 | unknown[ord(text)] += 1 |
| 196 | 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" |
| 197 | 220 | if text.startswith("(cid:") or "\ufffd" in text: |
| 198 | 221 | unknown[0xFFFD] += 1 |
| 199 | 222 | center = (char["top"] + char["bottom"]) / 2 |
| | @@ -202,6 +225,21 @@ def page_glyphs(page, unknown): |
| 202 | 225 | frozenset(tags), is_math, horizontal, scope if is_math else None) |
| 203 | 226 | |
| 204 | 227 | |
| 228 | +추가: def 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 | +추가: |
| 234 | +추가: def 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 | +추가: |
| 205 | 243 | def bounds(shape): |
| 206 | 244 | return shape["x0"], shape["top"], shape["x1"], shape["bottom"] |
| 207 | 245 | |
| | @@ -312,6 +350,8 @@ def script_text(operator, text): |
| 312 | 350 | |
| 313 | 351 | def latex_script(operator, text): |
| 314 | 352 | text = text.strip() |
| 353 | +추가: if operator == "^" and re.fullmatch(r"'+", text): |
| 354 | +추가: return text # a raised prime: f'(x), not f^{'}(x) |
| 315 | 355 | if re.fullmatch(r"[A-Za-z0-9]|\\[A-Za-z]+", text): |
| 316 | 356 | return operator + text |
| 317 | 357 | return f"{operator}{{{text}}}" |
| | @@ -353,13 +393,14 @@ def math_text(glyphs, latex=False): |
| 353 | 393 | piece = glyph.tex if latex else part |
| 354 | 394 | if text and previous: |
| 355 | 395 | 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"))) |
| 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"))) |
| 360 | 401 | or (glyph.math != previous.math and gap > glyph.size * 0.12) |
| 361 | 402 | or gap > glyph.size * 0.38) |
| 362 | | -삭제: unary_minus = previous.text == "-" and (text == "-" or text[:-1].rstrip()[-1:] in ("=", "(", "[", ",", "+", "-")) |
| 403 | +추가: unary_minus = before == "-" and (text == "-" or text[:-1].rstrip()[-1:] in ("=", "(", "[", ",", "+", "-")) |
| 363 | 404 | if spaced and not unary_minus and part[0] not in ")]}," and text[-1] not in "([{": |
| 364 | 405 | text += " " |
| 365 | 406 | out += " " |
| | @@ -443,6 +484,38 @@ def join_operator_names(glyphs): |
| 443 | 484 | for g in run) |
| 444 | 485 | and all(0 <= b.x0 - a.x0 <= first.size for a, b in zip(run, run[1:]))): |
| 445 | 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 | +추가: |
| 494 | +추가: def 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) |
| 446 | 519 | |
| 447 | 520 | |
| 448 | 521 | def attach_limit_scripts(glyphs): |
| | @@ -532,13 +605,16 @@ def attach_scripts(glyphs, extra=()): |
| 532 | 605 | used = [base] |
| 533 | 606 | suffix = "" |
| 534 | 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 |
| 535 | 611 | for sign, operator in ((1, "_"), (-1, "^")): |
| 536 | 612 | options = [g for g in available if g.horizontal and g not in used and not g.text.isspace() |
| 537 | 613 | and g.text != HWP_BAR and g.scope == base.scope |
| 538 | 614 | and (g.math or re.fullmatch(r"[A-Za-z0-9+()=-]", g.text)) |
| 539 | 615 | and 0.42 <= g.size / base.size <= 0.85 |
| 540 | 616 | and base.size * 0.19 <= sign * (g.baseline - base.baseline) |
| 541 | | -삭제: <= max(base.size * 0.94, base.script_reach) |
| 617 | +추가: <= reach |
| 542 | 618 | and g.x0 >= base.x1 - base.size * 0.28] |
| 543 | 619 | run = [] |
| 544 | 620 | end = max(g.x1 for g in used) |
| | @@ -566,6 +642,19 @@ def attach_scripts(glyphs, extra=()): |
| 566 | 642 | |
| 567 | 643 | |
| 568 | 644 | |
| 645 | +추가: def 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 | +추가: |
| 569 | 658 | def math_scope(glyphs, rule): |
| 570 | 659 | if rule.glyph: |
| 571 | 660 | return rule.glyph.scope |
| | @@ -590,8 +679,16 @@ def rebuild_bars(glyphs, rules): |
| 590 | 679 | fraction_rules = set() |
| 591 | 680 | for rule in sorted([*bars, *rules], key=lambda r: r.x1 - r.x0): |
| 592 | 681 | bar = rule.glyph |
| 593 | | -삭제: scope = math_scope(glyphs, rule) |
| 594 | 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) |
| 595 | 692 | nearby = [g for g in glyphs if g.horizontal and g.scope == scope |
| 596 | 693 | and g.text not in (HWP_BAR, "√") and not g.text.isspace() |
| 597 | 694 | and x0 - 0.75 <= g.x <= x1 + 0.75 |
| | @@ -600,9 +697,10 @@ def rebuild_bars(glyphs, rules): |
| 600 | 697 | if not nearby: |
| 601 | 698 | continue |
| 602 | 699 | 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] |
| 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] |
| 606 | 704 | if roots: |
| 607 | 705 | root = min(roots, key=lambda g: abs(g.x1 - x0)) |
| 608 | 706 | body = [g for g in nearby if y + size * 0.05 < g.baseline <= y + size * 1.65] |
| | @@ -610,6 +708,10 @@ def rebuild_bars(glyphs, rules): |
| 610 | 708 | and g.x1 <= x0 + size * 0.15 and g.text != HWP_BAR |
| 611 | 709 | and 0.35 <= g.size / root.size <= 0.64 |
| 612 | 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] |
| 613 | 715 | if body: |
| 614 | 716 | rebuilt = attach_scripts(resize_delimiters(body)) |
| 615 | 717 | radicand = math_text(rebuilt) |
| | @@ -620,8 +722,10 @@ def rebuild_bars(glyphs, rules): |
| 620 | 722 | else: |
| 621 | 723 | text = f"sqrt({radicand})" |
| 622 | 724 | latex = rf"\sqrt{{{latex_radicand}}}" |
| 623 | | -삭제: used = [bar, root, *body, *index] |
| 725 | +추가: used = [g for g in (bar, root, *body, *index) if g is not None] |
| 624 | 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 |
| 625 | 729 | continue |
| 626 | 730 | |
| 627 | 731 | numerator = fraction_row(nearby, y, -1, size) |
| | @@ -683,10 +787,40 @@ def rebuild_bars(glyphs, rules): |
| 683 | 787 | return glyphs, fraction_rules |
| 684 | 788 | |
| 685 | 789 | |
| 790 | +추가: def 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 | +추가: |
| 686 | 819 | def reconstruct_math(glyphs, rules): |
| 687 | 820 | for run, name in list(join_operator_names(glyphs)): |
| 688 | 821 | glyphs = replace_glyphs(glyphs, run, name) |
| 689 | 822 | glyphs, fraction_rules = rebuild_bars(glyphs, rules) |
| 823 | +추가: glyphs = rebuild_binomials(glyphs) |
| 690 | 824 | glyphs = attach_limit_scripts(glyphs) |
| 691 | 825 | glyphs = attach_scripts(resize_delimiters(glyphs)) |
| 692 | 826 | glyphs = [replace(g, text="-") if g.text == HWP_BAR else g for g in glyphs] |
| | @@ -719,7 +853,77 @@ def reading_regions(page, glyphs, verticals, rules): |
| 719 | 853 | if len(left) >= 10 and len(right) >= 10: |
| 720 | 854 | return ([g for g in glyphs if g.center < top], left, right, |
| 721 | 855 | [g for g in glyphs if g.center > bottom]) |
| 722 | | -삭제: return (glyphs,) |
| 856 | +추가: return gutter_regions(page, glyphs, rules) or (glyphs,) |
| 857 | +추가: |
| 858 | +추가: |
| 859 | +추가: def 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 |
| 723 | 927 | |
| 724 | 928 | |
| 725 | 929 | def text_lines(glyphs): |
| | @@ -737,18 +941,26 @@ def text_lines(glyphs): |
| 737 | 941 | def reconstruct_cases(glyphs): |
| 738 | 942 | # A tall brace is drawn as a middle piece plus separate top and bottom pieces. |
| 739 | 943 | 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] |
| 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 == "{")] |
| 742 | 947 | if (not any(g.text == HWP_BRACE_TOP for g in pieces) |
| 743 | 948 | or not any(g.text == HWP_BRACE_BOTTOM for g in pieces)): |
| 744 | 949 | continue |
| 745 | 950 | top, bottom = min(g.baseline for g in pieces), max(g.baseline for g in pieces) |
| 746 | 951 | 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] |
| 952 | +추가: and brace.x1 - 0.5 <= g.x0 < brace.x1 + brace.size * 2 # may touch the brace |
| 953 | +추가: and top <= g.baseline <= bottom] |
| 748 | 954 | rows = [] |
| 749 | 955 | latex_rows = [] |
| 750 | 956 | used = list(pieces) |
| 751 | 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) |
| 752 | 964 | row = [g for g in glyphs if g not in used and g.x0 >= value.x0 - 0.2 |
| 753 | 965 | and abs(g.baseline - value.baseline) <= brace.size * 0.24] |
| 754 | 966 | if not row: |
| | @@ -771,7 +983,12 @@ def reconstruct_cases(glyphs): |
| 771 | 983 | used.extend(row) |
| 772 | 984 | if len(rows) >= 2: |
| 773 | 985 | latex = r"\begin{cases} " + r" \\ ".join(latex_rows) + r" \end{cases}" |
| 774 | | -삭제: new = combine(used, "cases(" + ", ".join(rows) + ")", latex, brace) |
| 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) |
| 775 | 992 | glyphs = replace_glyphs(glyphs, used, new) |
| 776 | 993 | return [replace(g, text=HWP_BRACE[g.text]) if g.text in HWP_BRACE else g for g in glyphs] |
| 777 | 994 | |
| | @@ -807,7 +1024,41 @@ def is_closing_punctuation(text): |
| 807 | 1024 | return len(text) == 1 and text in ".,?!:;)]}" |
| 808 | 1025 | |
| 809 | 1026 | |
| 810 | | -삭제: def render_line(glyphs): |
| 1027 | +추가: def 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 | +추가: |
| 1053 | +추가: def 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) |
| 811 | 1062 | chunks = [] |
| 812 | 1063 | i = 0 |
| 813 | 1064 | previous = None |
| | @@ -857,9 +1108,26 @@ def render_line(glyphs): |
| 857 | 1108 | previous = run[-1] |
| 858 | 1109 | i = end |
| 859 | 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 | +추가: |
| 860 | 1121 | words = [chunk for chunk in chunks if chunk[0] != " "] |
| 861 | 1122 | if not words: |
| 862 | 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() |
| 863 | 1131 | # A line drawn wholly inside a box becomes a blockquote. Wrapping it in |
| 864 | 1132 | # <mark> would stop many Markdown viewers from rendering the math inside. |
| 865 | 1133 | quote = all("mark" in tags for _, tags, _ in words) |
| | @@ -892,6 +1160,102 @@ def escape_line_start(line): |
| 892 | 1160 | return re.sub(r"^([-+])(?= |$)", r"\\\1", line) |
| 893 | 1161 | |
| 894 | 1162 | |
| 1163 | +추가: def 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 | +추가: |
| 1178 | +추가: def 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 | +추가: |
| 1209 | +추가: def 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 | +추가: |
| 1224 | +추가: def 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 | +추가: |
| 1236 | +추가: def 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 | +추가: |
| 895 | 1259 | def convert_page(page, unknown): |
| 896 | 1260 | glyphs = list(page_glyphs(page, unknown)) |
| 897 | 1261 | if not glyphs: |
| | @@ -903,9 +1267,11 @@ def convert_page(page, unknown): |
| 903 | 1267 | expressions, fraction_rules = reconstruct_math(glyphs, rules) |
| 904 | 1268 | decor = list(line_decorations(expressions, [r for r in rules if r not in fraction_rules])) |
| 905 | 1269 | expressions = apply_regions(expressions, decor) |
| 1270 | +추가: expressions = ruled_tables(page, expressions) |
| 906 | 1271 | blocks = [] |
| 907 | 1272 | 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))] |
| 1273 | +추가: rows = aligned_tables(text_lines(reconstruct_cases(region))) |
| 1274 | +추가: lines = [line for row in rows if (line := render_line(row))] |
| 909 | 1275 | out = [] |
| 910 | 1276 | for line in lines: |
| 911 | 1277 | quoted = line.startswith("> ") |
| | @@ -913,9 +1279,12 @@ def convert_page(page, unknown): |
| 913 | 1279 | # Separate a blockquote from plain lines, or the next plain line |
| 914 | 1280 | # would be pulled into the quote as a lazy continuation. |
| 915 | 1281 | 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. |
| 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. |
| 919 | 1288 | out.append(">" if quoted else "") |
| 920 | 1289 | out.append(line) |
| 921 | 1290 | if out: |
| | @@ -924,9 +1293,14 @@ def convert_page(page, unknown): |
| 924 | 1293 | return re.sub(r"\n{3,}", "\n\n", "\n\n".join(blocks)).strip() |
| 925 | 1294 | |
| 926 | 1295 | |
| 1296 | +추가: def is_heading(line): |
| 1297 | +추가: return re.fullmatch(r"(?:> )?<b>(?:(?!</?b>).)+</b>", line) is not None |
| 1298 | +추가: |
| 1299 | +추가: |
| 927 | 1300 | def fallback_page(page): |
| 928 | 1301 | """Plain-text rendering used when the layout heuristics fail on a page.""" |
| 929 | 1302 | text = (page.extract_text() or "").translate(HWP_SYMBOLS) |
| 1303 | +추가: text = re.sub(r"[\x00-\x08\x0b-\x1f]+", "�", text) # raw glyph codes |
| 930 | 1304 | return "\n".join(escape_line_start(line) for raw in text.splitlines() |
| 931 | 1305 | if (line := markdown_text(raw.strip()))) |
| 932 | 1306 | |