| | @@ -1,5 +1,5 @@ |
| 1 | 1 | #!/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 ($...$, $$...$$).""" |
| 3 | 3 | |
| 4 | 4 | from __future__ import annotations |
| 5 | 5 | |
| | @@ -33,7 +33,34 @@ MATH_OPERATORS = frozenset("=+-\u00d7\u00f7\u2260<>\u2264\u2265\u00b1\u2192") |
| 33 | 33 | LIMIT_OPERATORS = frozenset(("lim", "\u2211", "\u222b", "\u220f")) |
| 34 | 34 | NAMED_OPERATORS = frozenset(("lim", "log", "ln", "sin", "cos", "tan")) |
| 35 | 35 | TAG_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}\\?[.)]|[①-⑳]|[ㄱ-ㅎ]\.|\([가-힣]\)|\\\* ") |
| 37 | 64 | UNICODE_SCRIPTS = ( |
| 38 | 65 | ("^", dict(zip("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079\u207a\u207b\u207c\u207d\u207e\u207f", "0123456789+-=()n"))), |
| 39 | 66 | ("_", dict(zip("\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208a\u208b\u208c\u208d\u208e", "0123456789+-=()"))), |
| | @@ -53,11 +80,18 @@ class Glyph: |
| 53 | 80 | horizontal: bool = True |
| 54 | 81 | scope: int | None = None |
| 55 | 82 | script_reach: float = 0.0 |
| 83 | +추가: # `text` keeps a plain notation such as "(1)/(3)" that the layout |
| 84 | +추가: # heuristics match against; `latex` holds what is written to Markdown. |
| 85 | +추가: latex: str | None = None |
| 56 | 86 | |
| 57 | 87 | @property |
| 58 | 88 | def x(self): |
| 59 | 89 | return (self.x0 + self.x1) / 2 |
| 60 | 90 | |
| 91 | +추가: @property |
| 92 | +추가: def tex(self): |
| 93 | +추가: return self.latex if self.latex is not None else latex_symbol(self.text) |
| 94 | +추가: |
| 61 | 95 | |
| 62 | 96 | @dataclass(frozen=True) |
| 63 | 97 | class Rule: |
| | @@ -276,15 +310,39 @@ def script_text(operator, text): |
| 276 | 310 | return operator + (text if len(text) == 1 else f"({text})") |
| 277 | 311 | |
| 278 | 312 | |
| 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 |
| 280 | 332 | for operator, symbols in UNICODE_SCRIPTS: |
| 281 | 333 | 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) |
| 283 | 335 | return text |
| 284 | 336 | |
| 285 | 337 | |
| 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 | +추가: """ |
| 287 | 344 | text = "" |
| 345 | +추가: out = "" |
| 288 | 346 | previous = None |
| 289 | 347 | prose_space = False |
| 290 | 348 | for glyph in sorted(glyphs, key=lambda g: g.x0): |
| | @@ -292,6 +350,7 @@ def math_text(glyphs): |
| 292 | 350 | if part.isspace(): |
| 293 | 351 | prose_space |= not glyph.math |
| 294 | 352 | continue |
| 353 | +추가: piece = glyph.tex if latex else part |
| 295 | 354 | if text and previous: |
| 296 | 355 | gap = glyph.x0 - previous.x1 |
| 297 | 356 | operator = re.match(r"(?:lim|log|ln|sin|cos|tan)(?:$|[_^])", previous.text) |
| | @@ -303,14 +362,57 @@ def math_text(glyphs): |
| 303 | 362 | unary_minus = previous.text == "-" and (text == "-" or text[:-1].rstrip()[-1:] in ("=", "(", "[", ",", "+", "-")) |
| 304 | 363 | if spaced and not unary_minus and part[0] not in ")]}," and text[-1] not in "([{": |
| 305 | 364 | text += " " |
| 365 | +추가: out += " " |
| 366 | +추가: elif re.search(r"\\[A-Za-z]+$", out) and piece[:1].isalpha(): |
| 367 | +추가: out += " " # "\pi x", not the undefined command "\pix" |
| 306 | 368 | text += part |
| 369 | +추가: out += piece |
| 307 | 370 | previous = glyph |
| 308 | 371 | prose_space = False |
| 309 | | -삭제: return normalize_unicode_scripts(text) |
| 372 | +추가: return normalize_unicode_scripts(out if latex else text, latex) |
| 373 | +추가: |
| 310 | 374 | |
| 375 | +추가: def finish_latex(tex): |
| 376 | +추가: """Final touches for a whole formula: wrap Korean text and let parentheses |
| 377 | +추가: around a fraction grow with it.""" |
| 378 | +추가: tex = CJK_TEXT.sub(lambda m: rf"\text{{{m[1]}{m[2]}}}", tex) |
| 379 | +추가: return auto_size_parentheses(tex) |
| 311 | 380 | |
| 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, |
| 314 | 416 | x0=min(g.x0 for g in glyphs), x1=max(g.x1 for g in glyphs), |
| 315 | 417 | baseline=anchor.baseline if baseline is None else baseline, |
| 316 | 418 | size=anchor.size if size is None else size, |
| | @@ -340,7 +442,7 @@ def join_operator_names(glyphs): |
| 340 | 442 | and all(g.scope == first.scope and abs(g.baseline - first.baseline) <= first.size * 0.2 |
| 341 | 443 | for g in run) |
| 342 | 444 | 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) |
| 344 | 446 | |
| 345 | 447 | |
| 346 | 448 | def attach_limit_scripts(glyphs): |
| | @@ -376,13 +478,17 @@ def attach_limit_scripts(glyphs): |
| 376 | 478 | base.size * 0.14) |
| 377 | 479 | if groups or not is_limit: |
| 378 | 480 | scripts = {op: math_text(group) for op, group in groups.items()} |
| 481 | +추가: latex_scripts = {op: math_text(group, latex=True) for op, group in groups.items()} |
| 379 | 482 | 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^-". |
| 381 | 484 | scripts["_"] = re.sub(r" ([+-])$", r"\1", scripts["_"]) |
| 485 | +추가: latex_scripts["_"] = re.sub(r" ?([+-])$", r"^\1", latex_scripts["_"]) |
| 382 | 486 | text = base.text + "".join(script_text(op, value) for op, value in scripts.items()) |
| 487 | +추가: latex = base.tex + "".join(latex_script(op, value) for op, value in latex_scripts.items()) |
| 383 | 488 | used = [base, *(g for group in groups.values() for g in group)] |
| 384 | 489 | 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)) |
| 386 | 492 | return glyphs |
| 387 | 493 | |
| 388 | 494 | |
| | @@ -425,6 +531,7 @@ def attach_scripts(glyphs, extra=()): |
| 425 | 531 | continue |
| 426 | 532 | used = [base] |
| 427 | 533 | suffix = "" |
| 534 | +추가: latex_suffix = "" |
| 428 | 535 | for sign, operator in ((1, "_"), (-1, "^")): |
| 429 | 536 | options = [g for g in available if g.horizontal and g not in used and not g.text.isspace() |
| 430 | 537 | and g.text != HWP_BAR and g.scope == base.scope |
| | @@ -445,8 +552,13 @@ def attach_scripts(glyphs, extra=()): |
| 445 | 552 | if run: |
| 446 | 553 | used.extend(run) |
| 447 | 554 | suffix += script_text(operator, math_text(run)) |
| 555 | +추가: latex_suffix += latex_script(operator, math_text(run, latex=True)) |
| 448 | 556 | 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)) |
| 450 | 562 | if extra: |
| 451 | 563 | return ([g for g in available if id(g) not in extras], |
| 452 | 564 | [g for g in available if id(g) in extras]) |
| | @@ -499,10 +611,17 @@ def rebuild_bars(glyphs, rules): |
| 499 | 611 | and 0.35 <= g.size / root.size <= 0.64 |
| 500 | 612 | and root.baseline - g.baseline >= size * 0.18] |
| 501 | 613 | 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}}}" |
| 504 | 623 | 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)) |
| 506 | 625 | continue |
| 507 | 626 | |
| 508 | 627 | numerator = fraction_row(nearby, y, -1, size) |
| | @@ -516,8 +635,11 @@ def rebuild_bars(glyphs, rules): |
| 516 | 635 | if max(g.x1 for g in group) - min(g.x0 for g in group) >= (x1 - x0) * 0.45: |
| 517 | 636 | command = "vec" if arrow else "overline" |
| 518 | 637 | text = f"{command}({math_text(group)})" |
| 638 | +추가: latex_command = r"\overrightarrow" if arrow else r"\overline" |
| 639 | +추가: latex = f"{latex_command}{{{math_text(group, latex=True)}}}" |
| 519 | 640 | 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])) |
| 521 | 643 | continue |
| 522 | 644 | |
| 523 | 645 | if not bar: |
| | @@ -535,19 +657,23 @@ def rebuild_bars(glyphs, rules): |
| 535 | 657 | lower_y = median(g.baseline for g in denominator) |
| 536 | 658 | extra = [g for g in nearby if g not in numerator and g not in denominator] |
| 537 | 659 | rows = [] |
| 660 | +추가: latex_rows = [] |
| 538 | 661 | remaining = [] |
| 539 | 662 | for group, row_y, other_y in ((numerator, upper_y, lower_y), (denominator, lower_y, upper_y)): |
| 540 | 663 | scripts = [g for g in extra if abs(g.baseline - row_y) <= abs(g.baseline - other_y)] |
| 541 | 664 | group = resize_delimiters(group) |
| 542 | 665 | rebuilt, leftover = attach_scripts(group, scripts) if scripts else (attach_scripts(group), []) |
| 543 | 666 | rows.append(math_text(rebuilt)) |
| 667 | +추가: latex_rows.append(math_text(rebuilt, latex=True)) |
| 544 | 668 | remaining.extend(leftover) |
| 545 | 669 | if not all(rows): |
| 546 | 670 | continue |
| 547 | 671 | |
| 548 | 672 | baseline = (upper_y + lower_y) / 2 |
| 549 | 673 | 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) |
| 551 | 677 | compound = replace(compound, x0=x0, x1=x1, center=baseline - size * 0.3) |
| 552 | 678 | if bar: |
| 553 | 679 | used.append(bar) |
| | @@ -620,6 +746,7 @@ def reconstruct_cases(glyphs): |
| 620 | 746 | values = [g for g in glyphs if g.scope == brace.scope and g not in pieces |
| 621 | 747 | and brace.x1 <= g.x0 < brace.x1 + brace.size * 2 and top <= g.baseline <= bottom] |
| 622 | 748 | rows = [] |
| 749 | +추가: latex_rows = [] |
| 623 | 750 | used = list(pieces) |
| 624 | 751 | for value in sorted(values, key=lambda g: g.baseline): |
| 625 | 752 | 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): |
| 632 | 759 | if row[i].x0 - row[i - 1].x1 > brace.size * 2.3), len(row)) |
| 633 | 760 | row = row[:stop] |
| 634 | 761 | rows.append(math_text(row)) |
| 762 | +추가: # The widest gap separates a value from its condition: "1 & x > 0". |
| 763 | +추가: size = median(g.size for g in row) |
| 764 | +추가: gaps = [(row[i].x0 - row[i - 1].x1, i) for i in range(1, len(row))] |
| 765 | +추가: gap, split = max(gaps, default=(0, 0)) |
| 766 | +추가: if gap > size * 0.9: |
| 767 | +추가: latex_rows.append(f"{math_text(row[:split], latex=True)} & " |
| 768 | +추가: f"{math_text(row[split:], latex=True)}") |
| 769 | +추가: else: |
| 770 | +추가: latex_rows.append(math_text(row, latex=True)) |
| 635 | 771 | used.extend(row) |
| 636 | 772 | 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) |
| 638 | 775 | glyphs = replace_glyphs(glyphs, used, new) |
| 639 | 776 | return [replace(g, text=HWP_BRACE[g.text]) if g.text in HWP_BRACE else g for g in glyphs] |
| 640 | 777 | |
| | @@ -643,13 +780,6 @@ def markdown_text(text): |
| 643 | 780 | return MARKDOWN_SPECIAL.sub(r"\\\1", html.escape(text, quote=False)) |
| 644 | 781 | |
| 645 | 782 | |
| 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 | 783 | def join_tagged(chunks): |
| 654 | 784 | """Join (text, tags) chunks, keeping a tag open across neighbouring chunks |
| 655 | 785 | that share it instead of emitting <mark>a</mark> <mark>b</mark>.""" |
| | @@ -685,13 +815,13 @@ def render_line(glyphs): |
| 685 | 815 | glyph = glyphs[i] |
| 686 | 816 | if glyph.text.isspace(): |
| 687 | 817 | if chunks and chunks[-1][0] != " ": |
| 688 | | -삭제: chunks.append((" ", frozenset())) |
| 818 | +추가: chunks.append((" ", frozenset(), False)) |
| 689 | 819 | i += 1 |
| 690 | 820 | continue |
| 691 | 821 | if previous and chunks and chunks[-1][0] != " ": |
| 692 | 822 | gap = glyph.x0 - previous.x1 |
| 693 | 823 | 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)) |
| 695 | 825 | end = i + 1 |
| 696 | 826 | while end < len(glyphs): |
| 697 | 827 | candidate = glyphs[end] |
| | @@ -708,7 +838,11 @@ def render_line(glyphs): |
| 708 | 838 | end += 1 |
| 709 | 839 | run = glyphs[i:end] |
| 710 | 840 | 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 |
| 712 | 846 | else: |
| 713 | 847 | parts = [] |
| 714 | 848 | prior = run[0] |
| | @@ -719,10 +853,33 @@ def render_line(glyphs): |
| 719 | 853 | parts.append(part.text) |
| 720 | 854 | prior = part |
| 721 | 855 | value = markdown_text(re.sub(r"\s+", " ", "".join(parts))) |
| 722 | | -삭제: chunks.append((value, glyph.tags)) |
| 856 | +추가: chunks.append((value, glyph.tags, False)) |
| 723 | 857 | previous = run[-1] |
| 724 | 858 | 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 |
| 726 | 883 | |
| 727 | 884 | |
| 728 | 885 | def escape_line_start(line): |
| | @@ -746,10 +903,25 @@ def convert_page(page, unknown): |
| 746 | 903 | expressions, fraction_rules = reconstruct_math(glyphs, rules) |
| 747 | 904 | decor = list(line_decorations(expressions, [r for r in rules if r not in fraction_rules])) |
| 748 | 905 | 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() |
| 753 | 925 | |
| 754 | 926 | |
| 755 | 927 | def fallback_page(page): |