leejunyoung5819pdf-to-md

공개

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

Write math as LaTeX instead of plain code-span notation

Formulas are now emitted as $...$ inline and $$...$$ when a line holds
only a formula, using \frac, \sqrt, \lim_{...}, \overrightarrow,
\begin{cases} and so on, with Korean text wrapped in \text{...}. The
layout heuristics still match on the plain notation; each reconstructed
glyph carries a parallel LaTeX form used only for output.

Math is never wrapped in HTML tags, since several Markdown viewers then
skip rendering it: lines drawn inside a box become blockquotes, and
underline/strike/bold on math become \underline/\cancel/\boldsymbol.
Problem numbers, choice rows, 보기 items and conditions now start new
paragraphs so the rendered output keeps its structure.

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

변경된 파일 1개

+206-34
수정pdf-to-md.py+206-34
@@ -1,5 +1,5 @@
11#!/usr/bin/env python3
2삭제: """Convert a text-based PDF to UTF-8 Markdown with editable math notation."""
2추가: """Convert a text-based PDF to UTF-8 Markdown with LaTeX math ($...$, $$...$$)."""
33
44from __future__ import annotations
55
@@ -33,7 +33,34 @@ MATH_OPERATORS = frozenset("=+-\u00d7\u00f7\u2260<>\u2264\u2265\u00b1\u2192")
3333LIMIT_OPERATORS = frozenset(("lim", "\u2211", "\u222b", "\u220f"))
3434NAMED_OPERATORS = frozenset(("lim", "log", "ln", "sin", "cos", "tan"))
3535TAG_ORDER = ("mark", "u", "del", "b", "em")
36삭제: MARKDOWN_SPECIAL = re.compile(r"([\\`*_\[\]~|#])")
36추가: MARKDOWN_SPECIAL = re.compile(r"([\\`*_\[\]~|#$])")
37추가: GREEK = dict(zip(
38추가: "αβγδεζηθικλμνξπρστυφχψωΓΔΘΛΞΠΣΥΦΨΩ",
39추가: ("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi pi rho sigma "
40추가: "tau upsilon phi chi psi omega Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega").split(),
41추가: ))
42추가: LATEX_SYMBOLS = {
43추가: **{c: "\\" + name for c, name in GREEK.items()},
44추가: "×": r"\times", "÷": r"\div", "≠": r"\neq", "≤": r"\le", "≥": r"\ge", "±": r"\pm",
45추가: "∓": r"\mp", "→": r"\to", "←": r"\leftarrow", "↔": r"\leftrightarrow",
46추가: "⇒": r"\Rightarrow", "⇔": r"\Leftrightarrow", "∞": r"\infty", "∫": r"\int",
47추가: "∑": r"\sum", "∏": r"\prod", "√": r"\surd", "⋅": r"\cdot", "·": r"\cdot", "∙": r"\cdot",
48추가: "⋯": r"\cdots", "…": r"\ldots", "⋮": r"\vdots", "′": "'", "″": "''", "‴": "'''",
49추가: "∪": r"\cup", "∩": r"\cap", "∈": r"\in", "∉": r"\notin", "∋": r"\ni", "⊂": r"\subset",
50추가: "⊃": r"\supset", "⊆": r"\subseteq", "⊇": r"\supseteq", "∅": r"\varnothing",
51추가: "∀": r"\forall", "∃": r"\exists", "≈": r"\approx", "≒": r"\fallingdotseq",
52추가: "≡": r"\equiv", "∼": r"\sim", "∝": r"\propto", "∠": r"\angle", "△": r"\triangle",
53추가: "⊥": r"\perp", "∥": r"\parallel", "°": r"^{\circ}", "∴": r"\therefore",
54추가: "∵": r"\because", "∘": r"\circ", "−": "-", "{": r"\{", "}": r"\}", "%": r"\%",
55추가: "#": r"\#", "&": r"\&", "$": r"\$", "_": r"\_", "\\": r"\backslash", "~": r"\sim",
56추가: "^": r"\wedge",
57추가: }
58추가: # Korean (and other CJK) text inside a formula must be wrapped in \text{...}.
59추가: CJK_TEXT = re.compile(r"( ?)([ᄀ-ᇿ㄰-㆏㈀-㋿一-鿿가-힣]"
60추가: r"(?:[ ᄀ-ᇿ㄰-㆏㈀-㋿一-鿿가-힣]*"
61추가: r"[ᄀ-ᇿ㄰-㆏㈀-㋿一-鿿가-힣])?)")
62추가: # Line openings that begin a new paragraph: "<b>12.</b>", "3\.", "①", "ㄱ.", "(가)", "\* ".
63추가: BLOCK_START = re.compile(r"(?:<b>)?\d{1,2}\\?[.)]|[①-⑳]|[ㄱ-ㅎ]\.|\([가-힣]\)|\\\* ")
3764UNICODE_SCRIPTS = (
3865 ("^", dict(zip("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207a\u207b\u207c\u207d\u207e\u207f", "0123456789+-=()n"))),
3966 ("_", dict(zip("\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208a\u208b\u208c\u208d\u208e", "0123456789+-=()"))),
@@ -53,11 +80,18 @@ class Glyph:
5380 horizontal: bool = True
5481 scope: int | None = None
5582 script_reach: float = 0.0
83추가: # `text` keeps a plain notation such as "(1)/(3)" that the layout
84추가: # heuristics match against; `latex` holds what is written to Markdown.
85추가: latex: str | None = None
5686
5787 @property
5888 def x(self):
5989 return (self.x0 + self.x1) / 2
6090
91추가: @property
92추가: def tex(self):
93추가: return self.latex if self.latex is not None else latex_symbol(self.text)
94추가:
6195
6296@dataclass(frozen=True)
6397class Rule:
@@ -276,15 +310,39 @@ def script_text(operator, text):
276310 return operator + (text if len(text) == 1 else f"({text})")
277311
278312
279삭제: def normalize_unicode_scripts(text):
313추가: def latex_script(operator, text):
314추가: text = text.strip()
315추가: if re.fullmatch(r"[A-Za-z0-9]|\\[A-Za-z]+", text):
316추가: return operator + text
317추가: return f"{operator}{{{text}}}"
318추가:
319추가:
320추가: def latex_symbol(text):
321추가: if text in LATEX_SYMBOLS:
322추가: return LATEX_SYMBOLS[text]
323추가: if text in NAMED_OPERATORS:
324추가: return "\\" + text
325추가: if text.startswith("[U+"):
326추가: return rf"\text{{{text}}}"
327추가: return text
328추가:
329추가:
330추가: def normalize_unicode_scripts(text, latex=False):
331추가: attach = latex_script if latex else script_text
280332 for operator, symbols in UNICODE_SCRIPTS:
281333 pattern = f"[{''.join(symbols)}]+"
282삭제: text = re.sub(pattern, lambda m: script_text(operator, "".join(symbols[c] for c in m[0])), text)
334추가: text = re.sub(pattern, lambda m: attach(operator, "".join(symbols[c] for c in m[0])), text)
283335 return text
284336
285337
286삭제: def math_text(glyphs):
338추가: def math_text(glyphs, latex=False):
339추가: """Join glyphs into one expression.
340추가:
341추가: The spacing decisions always use the plain `text`, so both notations agree;
342추가: with latex=True the joined pieces are each glyph's LaTeX form instead.
343추가: """
287344 text = ""
345추가: out = ""
288346 previous = None
289347 prose_space = False
290348 for glyph in sorted(glyphs, key=lambda g: g.x0):
@@ -292,6 +350,7 @@ def math_text(glyphs):
292350 if part.isspace():
293351 prose_space |= not glyph.math
294352 continue
353추가: piece = glyph.tex if latex else part
295354 if text and previous:
296355 gap = glyph.x0 - previous.x1
297356 operator = re.match(r"(?:lim|log|ln|sin|cos|tan)(?:$|[_^])", previous.text)
@@ -303,14 +362,57 @@ def math_text(glyphs):
303362 unary_minus = previous.text == "-" and (text == "-" or text[:-1].rstrip()[-1:] in ("=", "(", "[", ",", "+", "-"))
304363 if spaced and not unary_minus and part[0] not in ")]}," and text[-1] not in "([{":
305364 text += " "
365추가: out += " "
366추가: elif re.search(r"\\[A-Za-z]+$", out) and piece[:1].isalpha():
367추가: out += " " # "\pi x", not the undefined command "\pix"
306368 text += part
369추가: out += piece
307370 previous = glyph
308371 prose_space = False
309삭제: return normalize_unicode_scripts(text)
372추가: return normalize_unicode_scripts(out if latex else text, latex)
373추가:
310374
375추가: def finish_latex(tex):
376추가: """Final touches for a whole formula: wrap Korean text and let parentheses
377추가: around a fraction grow with it."""
378추가: tex = CJK_TEXT.sub(lambda m: rf"\text{{{m[1]}{m[2]}}}", tex)
379추가: return auto_size_parentheses(tex)
311380
312삭제: def combine(glyphs, text, anchor, baseline=None, size=None):
313삭제: return replace(anchor, text=text, math=True,
381추가:
382추가: def auto_size_parentheses(tex):
383추가: pairs = []
384추가: groups = [[]] # open "(" positions per brace group; \left/\right cannot cross groups
385추가: i = 0
386추가: while i < len(tex):
387추가: char = tex[i]
388추가: if char == "\\":
389추가: word = re.match(r"\\(?:[A-Za-z]+|.)", tex[i:])[0]
390추가: i += len(word)
391추가: if word in (r"\left", r"\right"):
392추가: i += 1 # its delimiter is already sized
393추가: continue
394추가: if char == "{":
395추가: groups.append([])
396추가: elif char == "}" and len(groups) > 1:
397추가: groups.pop()
398추가: elif char == "(":
399추가: groups[-1].append(i)
400추가: elif char == ")" and groups[-1]:
401추가: start = groups[-1].pop()
402추가: if r"\frac" in tex[start:i]:
403추가: pairs.append((start, i))
404추가: i += 1
405추가: if not pairs:
406추가: return tex
407추가: replacements = {}
408추가: for start, end in pairs:
409추가: replacements[start] = r"\left("
410추가: replacements[end] = r"\right)"
411추가: return "".join(replacements.get(i, c) for i, c in enumerate(tex))
412추가:
413추가:
414추가: def combine(glyphs, text, latex, anchor, baseline=None, size=None):
415추가: return replace(anchor, text=text, latex=latex, math=True,
314416 x0=min(g.x0 for g in glyphs), x1=max(g.x1 for g in glyphs),
315417 baseline=anchor.baseline if baseline is None else baseline,
316418 size=anchor.size if size is None else size,
@@ -340,7 +442,7 @@ def join_operator_names(glyphs):
340442 and all(g.scope == first.scope and abs(g.baseline - first.baseline) <= first.size * 0.2
341443 for g in run)
342444 and all(0 <= b.x0 - a.x0 <= first.size for a, b in zip(run, run[1:]))):
343삭제: yield run, combine(run, name, first)
445추가: yield run, combine(run, name, "\\" + name, first)
344446
345447
346448def attach_limit_scripts(glyphs):
@@ -376,13 +478,17 @@ def attach_limit_scripts(glyphs):
376478 base.size * 0.14)
377479 if groups or not is_limit:
378480 scripts = {op: math_text(group) for op, group in groups.items()}
481추가: latex_scripts = {op: math_text(group, latex=True) for op, group in groups.items()}
379482 if is_limit and "_" in scripts:
380삭제: # One-sided limits: "x → 0 -" should read "x → 0-".
483추가: # One-sided limits: "x → 0 -" reads "x → 0-", in LaTeX "x \to 0^-".
381484 scripts["_"] = re.sub(r" ([+-])$", r"\1", scripts["_"])
485추가: latex_scripts["_"] = re.sub(r" ?([+-])$", r"^\1", latex_scripts["_"])
382486 text = base.text + "".join(script_text(op, value) for op, value in scripts.items())
487추가: latex = base.tex + "".join(latex_script(op, value) for op, value in latex_scripts.items())
383488 used = [base, *(g for group in groups.values() for g in group)]
384489 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))
490추가: glyphs = replace_glyphs(glyphs, used, combine(used, text, latex, base, baseline,
491추가: size=base.size if is_limit else base.size * 0.56))
386492 return glyphs
387493
388494
@@ -425,6 +531,7 @@ def attach_scripts(glyphs, extra=()):
425531 continue
426532 used = [base]
427533 suffix = ""
534추가: latex_suffix = ""
428535 for sign, operator in ((1, "_"), (-1, "^")):
429536 options = [g for g in available if g.horizontal and g not in used and not g.text.isspace()
430537 and g.text != HWP_BAR and g.scope == base.scope
@@ -445,8 +552,13 @@ def attach_scripts(glyphs, extra=()):
445552 if run:
446553 used.extend(run)
447554 suffix += script_text(operator, math_text(run))
555추가: latex_suffix += latex_script(operator, math_text(run, latex=True))
448556 if suffix:
449삭제: available = replace_glyphs(available, used, combine(used, base.text + suffix, base))
557추가: base_tex = base.tex
558추가: if base.latex is not None and re.search(r"[_^]", base_tex):
559추가: base_tex = f"{{{base_tex}}}" # avoid a "double superscript" error
560추가: available = replace_glyphs(available, used, combine(
561추가: used, base.text + suffix, base_tex + latex_suffix, base))
450562 if extra:
451563 return ([g for g in available if id(g) not in extras],
452564 [g for g in available if id(g) in extras])
@@ -499,10 +611,17 @@ def rebuild_bars(glyphs, rules):
499611 and 0.35 <= g.size / root.size <= 0.64
500612 and root.baseline - g.baseline >= size * 0.18]
501613 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})"
614추가: rebuilt = attach_scripts(resize_delimiters(body))
615추가: radicand = math_text(rebuilt)
616추가: latex_radicand = math_text(rebuilt, latex=True)
617추가: if index:
618추가: text = f"root({math_text(index)}, {radicand})"
619추가: latex = rf"\sqrt[{math_text(index, latex=True)}]{{{latex_radicand}}}"
620추가: else:
621추가: text = f"sqrt({radicand})"
622추가: latex = rf"\sqrt{{{latex_radicand}}}"
504623 used = [bar, root, *body, *index]
505삭제: glyphs = replace_glyphs(glyphs, used, combine(used, text, root))
624추가: glyphs = replace_glyphs(glyphs, used, combine(used, text, latex, root))
506625 continue
507626
508627 numerator = fraction_row(nearby, y, -1, size)
@@ -516,8 +635,11 @@ def rebuild_bars(glyphs, rules):
516635 if max(g.x1 for g in group) - min(g.x0 for g in group) >= (x1 - x0) * 0.45:
517636 command = "vec" if arrow else "overline"
518637 text = f"{command}({math_text(group)})"
638추가: latex_command = r"\overrightarrow" if arrow else r"\overline"
639추가: latex = f"{latex_command}{{{math_text(group, latex=True)}}}"
519640 markers = [bar, arrow] if arrow else [bar]
520삭제: glyphs = replace_glyphs(glyphs, [*markers, *group], combine(group, text, group[0]))
641추가: glyphs = replace_glyphs(glyphs, [*markers, *group],
642추가: combine(group, text, latex, group[0]))
521643 continue
522644
523645 if not bar:
@@ -535,19 +657,23 @@ def rebuild_bars(glyphs, rules):
535657 lower_y = median(g.baseline for g in denominator)
536658 extra = [g for g in nearby if g not in numerator and g not in denominator]
537659 rows = []
660추가: latex_rows = []
538661 remaining = []
539662 for group, row_y, other_y in ((numerator, upper_y, lower_y), (denominator, lower_y, upper_y)):
540663 scripts = [g for g in extra if abs(g.baseline - row_y) <= abs(g.baseline - other_y)]
541664 group = resize_delimiters(group)
542665 rebuilt, leftover = attach_scripts(group, scripts) if scripts else (attach_scripts(group), [])
543666 rows.append(math_text(rebuilt))
667추가: latex_rows.append(math_text(rebuilt, latex=True))
544668 remaining.extend(leftover)
545669 if not all(rows):
546670 continue
547671
548672 baseline = (upper_y + lower_y) / 2
549673 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)
674추가: compound = combine(used, f"({rows[0]})/({rows[1]})",
675추가: rf"\frac{{{latex_rows[0]}}}{{{latex_rows[1]}}}",
676추가: bar or used[0], baseline, size)
551677 compound = replace(compound, x0=x0, x1=x1, center=baseline - size * 0.3)
552678 if bar:
553679 used.append(bar)
@@ -620,6 +746,7 @@ def reconstruct_cases(glyphs):
620746 values = [g for g in glyphs if g.scope == brace.scope and g not in pieces
621747 and brace.x1 <= g.x0 < brace.x1 + brace.size * 2 and top <= g.baseline <= bottom]
622748 rows = []
749추가: latex_rows = []
623750 used = list(pieces)
624751 for value in sorted(values, key=lambda g: g.baseline):
625752 row = [g for g in glyphs if g not in used and g.x0 >= value.x0 - 0.2
@@ -632,9 +759,19 @@ def reconstruct_cases(glyphs):
632759 if row[i].x0 - row[i - 1].x1 > brace.size * 2.3), len(row))
633760 row = row[:stop]
634761 rows.append(math_text(row))
762추가: # The widest gap separates a value from its condition: "1 & x > 0".
763추가: size = median(g.size for g in row)
764추가: gaps = [(row[i].x0 - row[i - 1].x1, i) for i in range(1, len(row))]
765추가: gap, split = max(gaps, default=(0, 0))
766추가: if gap > size * 0.9:
767추가: latex_rows.append(f"{math_text(row[:split], latex=True)} & "
768추가: f"{math_text(row[split:], latex=True)}")
769추가: else:
770추가: latex_rows.append(math_text(row, latex=True))
635771 used.extend(row)
636772 if len(rows) >= 2:
637삭제: new = combine(used, "cases(" + ", ".join(rows) + ")", brace)
773추가: latex = r"\begin{cases} " + r" \\ ".join(latex_rows) + r" \end{cases}"
774추가: new = combine(used, "cases(" + ", ".join(rows) + ")", latex, brace)
638775 glyphs = replace_glyphs(glyphs, used, new)
639776 return [replace(g, text=HWP_BRACE[g.text]) if g.text in HWP_BRACE else g for g in glyphs]
640777
@@ -643,13 +780,6 @@ def markdown_text(text):
643780 return MARKDOWN_SPECIAL.sub(r"\\\1", html.escape(text, quote=False))
644781
645782
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삭제:
653783def join_tagged(chunks):
654784 """Join (text, tags) chunks, keeping a tag open across neighbouring chunks
655785 that share it instead of emitting <mark>a</mark> <mark>b</mark>."""
@@ -685,13 +815,13 @@ def render_line(glyphs):
685815 glyph = glyphs[i]
686816 if glyph.text.isspace():
687817 if chunks and chunks[-1][0] != " ":
688삭제: chunks.append((" ", frozenset()))
818추가: chunks.append((" ", frozenset(), False))
689819 i += 1
690820 continue
691821 if previous and chunks and chunks[-1][0] != " ":
692822 gap = glyph.x0 - previous.x1
693823 if gap > min(glyph.size, previous.size) * 0.19 and not is_closing_punctuation(glyph.text):
694삭제: chunks.append((" ", frozenset()))
824추가: chunks.append((" ", frozenset(), False))
695825 end = i + 1
696826 while end < len(glyphs):
697827 candidate = glyphs[end]
@@ -708,7 +838,11 @@ def render_line(glyphs):
708838 end += 1
709839 run = glyphs[i:end]
710840 if glyph.math:
711삭제: value = code_span(math_text(run))
841추가: tex = finish_latex(math_text(run, latex=True)).strip()
842추가: chunks.append((tex, glyph.tags, True))
843추가: previous = run[-1]
844추가: i = end
845추가: continue
712846 else:
713847 parts = []
714848 prior = run[0]
@@ -719,10 +853,33 @@ def render_line(glyphs):
719853 parts.append(part.text)
720854 prior = part
721855 value = markdown_text(re.sub(r"\s+", " ", "".join(parts)))
722삭제: chunks.append((value, glyph.tags))
856추가: chunks.append((value, glyph.tags, False))
723857 previous = run[-1]
724858 i = end
725삭제: return escape_line_start(join_tagged(chunks).strip())
859추가:
860추가: words = [chunk for chunk in chunks if chunk[0] != " "]
861추가: if not words:
862추가: return ""
863추가: # A line drawn wholly inside a box becomes a blockquote. Wrapping it in
864추가: # <mark> would stop many Markdown viewers from rendering the math inside.
865추가: quote = all("mark" in tags for _, tags, _ in words)
866추가: if quote:
867추가: chunks = [(value, tags - {"mark"}, is_math) for value, tags, is_math in chunks]
868추가: if len(words) == 1 and words[0][2] and not quote and not (words[0][1] - {"mark"}):
869추가: # A formula on a line of its own becomes a display block.
870추가: return f"\n$${words[0][0]}$$\n"
871추가: # Never put math inside HTML tags; carry its formatting in LaTeX instead.
872추가: chunks = [(f"${latex_decorations(value, tags)}$", frozenset()) if is_math else (value, tags)
873추가: for value, tags, is_math in chunks]
874추가: line = escape_line_start(join_tagged(chunks).strip())
875추가: return f"> {line}" if quote else line
876추가:
877추가:
878추가: def latex_decorations(tex, tags):
879추가: for tag, command in (("b", r"\boldsymbol"), ("del", r"\cancel"), ("u", r"\underline")):
880추가: if tag in tags:
881추가: tex = f"{command}{{{tex}}}"
882추가: return tex
726883
727884
728885def escape_line_start(line):
@@ -746,10 +903,25 @@ def convert_page(page, unknown):
746903 expressions, fraction_rules = reconstruct_math(glyphs, rules)
747904 decor = list(line_decorations(expressions, [r for r in rules if r not in fraction_rules]))
748905 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삭제: )
906추가: blocks = []
907추가: for region in reading_regions(page, expressions, verticals, rules):
908추가: lines = [line for row in text_lines(reconstruct_cases(region)) if (line := render_line(row))]
909추가: out = []
910추가: for line in lines:
911추가: quoted = line.startswith("> ")
912추가: if out and out[-1].startswith("> ") != quoted:
913추가: # Separate a blockquote from plain lines, or the next plain line
914추가: # would be pulled into the quote as a lazy continuation.
915추가: out.append("")
916추가: elif out and out[-1] not in ("", ">") and BLOCK_START.match(line.removeprefix("> ")):
917추가: # A new problem, choice row, 보기 item or condition starts its own
918추가: # paragraph; lines wrapped mid-sentence keep flowing together.
919추가: out.append(">" if quoted else "")
920추가: out.append(line)
921추가: if out:
922추가: blocks.append("\n".join(out))
923추가: # Display formulas bring their own blank lines; collapse any extras.
924추가: return re.sub(r"\n{3,}", "\n\n", "\n\n".join(blocks)).strip()
753925
754926
755927def fallback_page(page):