leejunyoung5819pdf-to-md

공개

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

Support TeX-style math PDFs and convert tables to Markdown

TeX-style PDFs (LaTeX, MathJax, Word) were converted as plain text
because math was only recognized in the HWP equation font, so a
formula like the cube root of 32 times 4^(-1/3) fell apart.

Math recognition and structure:
- Treat math fonts (Math, STIX, Cambria Math, cm*) and Mathematical
  Alphanumeric letters as math; normalize 𝑥 to x and halfwidth jamo.
- Rebuild radicals drawn as a "√" glyph plus a separate vinculum line,
  including tall radicals and indices, and stop an index search from
  taking a "3" that belongs to another radical.
- Join operator names set in the text font (lim, log, sin, ...) into
  the formula, and keep text-font letters from splitting math scopes.
- Add \binom, TeX brace pieces for \begin{cases}, f' primes, superscripts
  after a parenthesis that encloses a fraction, and minus spacing.
- Move ASCII letters touching a formula into it ("$P(5,1)$"), and never
  emit "$a$$b$".

Layout:
- Split two-column pages that have no divider line, reading band by
  band between full-width lines, rules and panels.
- Recognize ➀-style choices; give wholly bold lines their own paragraph.

Tables:
- Ruled tables come from pdfplumber's line finder, filtered so page
  frames, layout cards and graph grids are rejected; tables without
  vertical lines come from three or more column-aligned lines. Cells
  render inline, with "|" in math written as \vert.

Fixes:
- Glyphs from fonts without a Unicode map produced raw control bytes
  (NUL included) in the Markdown; they are now U+FFFD and reported.
- Cases rows lost their first glyph when it touched the brace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
작성자
이준영
작성 시각
커밋
6b2c885d702993b3a4c2fac76ea8157998b14dd8
부모
9efdd62
이 시점의 파일 보기

변경된 파일 1개

+400-26
수정pdf-to-md.py+400-26
@@ -9,6 +9,7 @@ import html
99import os
1010import re
1111import sys
12추가: import unicodedata
1213from collections import Counter
1314from dataclasses import dataclass, replace
1415from functools import lru_cache
@@ -27,7 +28,18 @@ HWP_SYMBOLS = {
2728 0xE09D: "\u03b1", 0xE0AC: "\u03c0", 0xE0AE: "\u03c3", 0xE101: "|",
2829}
2930HWP_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)
3035HWP_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추가: }
3143HWP_BRACE = {HWP_BRACE_TOP: "{", HWP_BRACE_MIDDLE: "{", HWP_BRACE_BOTTOM: "{", "\ue07b": "|"}
3244MATH_OPERATORS = frozenset("=+-\u00d7\u00f7\u2260<>\u2264\u2265\u00b1\u2192")
3345LIMIT_OPERATORS = frozenset(("lim", "\u2211", "\u222b", "\u220f"))
@@ -60,7 +72,8 @@ CJK_TEXT = re.compile(r"( ?)([ᄀ-ᇿ㄰-㆏㈀-㋿一-鿿가-힣]"
6072 r"(?:[ ᄀ-ᇿ㄰-㆏㈀-㋿一-鿿가-힣]*"
6173 r"[ᄀ-ᇿ㄰-㆏㈀-㋿一-鿿가-힣])?)")
6274# 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"\([가-힣]\)|\\\* ")
6477UNICODE_SCRIPTS = (
6578 ("^", dict(zip("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207a\u207b\u207c\u207d\u207e\u207f", "0123456789+-=()n"))),
6679 ("_", 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):
180193 horizontal = abs(b) <= abs(a) * 0.08
181194 if horizontal and d and 0.08 < abs(c / d) < 0.7:
182195 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)
184200 if is_math:
185201 # 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.
187203 tags.discard("em")
188204 if is_math and not was_math:
189205 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:
192211 text = HWP_SYMBOLS.get(ord(text), text)
212추가: text = normalize_character(text)
193213 if (len(text) == 1 and "\ue000" <= text <= "\uf8ff"
194214 and text != HWP_BAR and text not in HWP_BRACE):
195215 unknown[ord(text)] += 1
196216 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"
197220 if text.startswith("(cid:") or "\ufffd" in text:
198221 unknown[0xFFFD] += 1
199222 center = (char["top"] + char["bottom"]) / 2
@@ -202,6 +225,21 @@ def page_glyphs(page, unknown):
202225 frozenset(tags), is_math, horizontal, scope if is_math else None)
203226
204227
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추가:
205243def bounds(shape):
206244 return shape["x0"], shape["top"], shape["x1"], shape["bottom"]
207245
@@ -312,6 +350,8 @@ def script_text(operator, text):
312350
313351def latex_script(operator, text):
314352 text = text.strip()
353추가: if operator == "^" and re.fullmatch(r"'+", text):
354추가: return text # a raised prime: f'(x), not f^{'}(x)
315355 if re.fullmatch(r"[A-Za-z0-9]|\\[A-Za-z]+", text):
316356 return operator + text
317357 return f"{operator}{{{text}}}"
@@ -353,13 +393,14 @@ def math_text(glyphs, latex=False):
353393 piece = glyph.tex if latex else part
354394 if text and previous:
355395 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")))
360401 or (glyph.math != previous.math and gap > glyph.size * 0.12)
361402 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 ("=", "(", "[", ",", "+", "-"))
363404 if spaced and not unary_minus and part[0] not in ")]}," and text[-1] not in "([{":
364405 text += " "
365406 out += " "
@@ -443,6 +484,38 @@ def join_operator_names(glyphs):
443484 for g in run)
444485 and all(0 <= b.x0 - a.x0 <= first.size for a, b in zip(run, run[1:]))):
445486 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)
446519
447520
448521def attach_limit_scripts(glyphs):
@@ -532,13 +605,16 @@ def attach_scripts(glyphs, extra=()):
532605 used = [base]
533606 suffix = ""
534607 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
535611 for sign, operator in ((1, "_"), (-1, "^")):
536612 options = [g for g in available if g.horizontal and g not in used and not g.text.isspace()
537613 and g.text != HWP_BAR and g.scope == base.scope
538614 and (g.math or re.fullmatch(r"[A-Za-z0-9+()=-]", g.text))
539615 and 0.42 <= g.size / base.size <= 0.85
540616 and base.size * 0.19 <= sign * (g.baseline - base.baseline)
541삭제: <= max(base.size * 0.94, base.script_reach)
617추가: <= reach
542618 and g.x0 >= base.x1 - base.size * 0.28]
543619 run = []
544620 end = max(g.x1 for g in used)
@@ -566,6 +642,19 @@ def attach_scripts(glyphs, extra=()):
566642
567643
568644
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추가:
569658def math_scope(glyphs, rule):
570659 if rule.glyph:
571660 return rule.glyph.scope
@@ -590,8 +679,16 @@ def rebuild_bars(glyphs, rules):
590679 fraction_rules = set()
591680 for rule in sorted([*bars, *rules], key=lambda r: r.x1 - r.x0):
592681 bar = rule.glyph
593삭제: scope = math_scope(glyphs, rule)
594682 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)
595692 nearby = [g for g in glyphs if g.horizontal and g.scope == scope
596693 and g.text not in (HWP_BAR, "√") and not g.text.isspace()
597694 and x0 - 0.75 <= g.x <= x1 + 0.75
@@ -600,9 +697,10 @@ def rebuild_bars(glyphs, rules):
600697 if not nearby:
601698 continue
602699 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]
606704 if roots:
607705 root = min(roots, key=lambda g: abs(g.x1 - x0))
608706 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):
610708 and g.x1 <= x0 + size * 0.15 and g.text != HWP_BAR
611709 and 0.35 <= g.size / root.size <= 0.64
612710 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]
613715 if body:
614716 rebuilt = attach_scripts(resize_delimiters(body))
615717 radicand = math_text(rebuilt)
@@ -620,8 +722,10 @@ def rebuild_bars(glyphs, rules):
620722 else:
621723 text = f"sqrt({radicand})"
622724 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]
624726 glyphs = replace_glyphs(glyphs, used, combine(used, text, latex, root))
727추가: if not bar:
728추가: fraction_rules.add(rule) # consumed; not an underline either
625729 continue
626730
627731 numerator = fraction_row(nearby, y, -1, size)
@@ -683,10 +787,40 @@ def rebuild_bars(glyphs, rules):
683787 return glyphs, fraction_rules
684788
685789
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추가:
686819def reconstruct_math(glyphs, rules):
687820 for run, name in list(join_operator_names(glyphs)):
688821 glyphs = replace_glyphs(glyphs, run, name)
689822 glyphs, fraction_rules = rebuild_bars(glyphs, rules)
823추가: glyphs = rebuild_binomials(glyphs)
690824 glyphs = attach_limit_scripts(glyphs)
691825 glyphs = attach_scripts(resize_delimiters(glyphs))
692826 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):
719853 if len(left) >= 10 and len(right) >= 10:
720854 return ([g for g in glyphs if g.center < top], left, right,
721855 [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
723927
724928
725929def text_lines(glyphs):
@@ -737,18 +941,26 @@ def text_lines(glyphs):
737941def reconstruct_cases(glyphs):
738942 # A tall brace is drawn as a middle piece plus separate top and bottom pieces.
739943 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 == "{")]
742947 if (not any(g.text == HWP_BRACE_TOP for g in pieces)
743948 or not any(g.text == HWP_BRACE_BOTTOM for g in pieces)):
744949 continue
745950 top, bottom = min(g.baseline for g in pieces), max(g.baseline for g in pieces)
746951 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]
748954 rows = []
749955 latex_rows = []
750956 used = list(pieces)
751957 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)
752964 row = [g for g in glyphs if g not in used and g.x0 >= value.x0 - 0.2
753965 and abs(g.baseline - value.baseline) <= brace.size * 0.24]
754966 if not row:
@@ -771,7 +983,12 @@ def reconstruct_cases(glyphs):
771983 used.extend(row)
772984 if len(rows) >= 2:
773985 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)
775992 glyphs = replace_glyphs(glyphs, used, new)
776993 return [replace(g, text=HWP_BRACE[g.text]) if g.text in HWP_BRACE else g for g in glyphs]
777994
@@ -807,7 +1024,41 @@ def is_closing_punctuation(text):
8071024 return len(text) == 1 and text in ".,?!:;)]}"
8081025
8091026
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)
8111062 chunks = []
8121063 i = 0
8131064 previous = None
@@ -857,9 +1108,26 @@ def render_line(glyphs):
8571108 previous = run[-1]
8581109 i = end
8591110
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추가:
8601121 words = [chunk for chunk in chunks if chunk[0] != " "]
8611122 if not words:
8621123 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()
8631131 # A line drawn wholly inside a box becomes a blockquote. Wrapping it in
8641132 # <mark> would stop many Markdown viewers from rendering the math inside.
8651133 quote = all("mark" in tags for _, tags, _ in words)
@@ -892,6 +1160,102 @@ def escape_line_start(line):
8921160 return re.sub(r"^([-+])(?= |$)", r"\\\1", line)
8931161
8941162
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추가:
8951259def convert_page(page, unknown):
8961260 glyphs = list(page_glyphs(page, unknown))
8971261 if not glyphs:
@@ -903,9 +1267,11 @@ def convert_page(page, unknown):
9031267 expressions, fraction_rules = reconstruct_math(glyphs, rules)
9041268 decor = list(line_decorations(expressions, [r for r in rules if r not in fraction_rules]))
9051269 expressions = apply_regions(expressions, decor)
1270추가: expressions = ruled_tables(page, expressions)
9061271 blocks = []
9071272 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))]
9091275 out = []
9101276 for line in lines:
9111277 quoted = line.startswith("> ")
@@ -913,9 +1279,12 @@ def convert_page(page, unknown):
9131279 # Separate a blockquote from plain lines, or the next plain line
9141280 # would be pulled into the quote as a lazy continuation.
9151281 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.
9191288 out.append(">" if quoted else "")
9201289 out.append(line)
9211290 if out:
@@ -924,9 +1293,14 @@ def convert_page(page, unknown):
9241293 return re.sub(r"\n{3,}", "\n\n", "\n\n".join(blocks)).strip()
9251294
9261295
1296추가: def is_heading(line):
1297추가: return re.fullmatch(r"(?:> )?<b>(?:(?!</?b>).)+</b>", line) is not None
1298추가:
1299추가:
9271300def fallback_page(page):
9281301 """Plain-text rendering used when the layout heuristics fail on a page."""
9291302 text = (page.extract_text() or "").translate(HWP_SYMBOLS)
1303추가: text = re.sub(r"[\x00-\x08\x0b-\x1f]+", "�", text) # raw glyph codes
9301304 return "\n".join(escape_line_start(line) for raw in text.splitlines()
9311305 if (line := markdown_text(raw.strip())))
9321306