Repository navigation
fix: preserve native VLM inline math through exports #4908
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
PierreMesure
wants to merge
4
commits into
docling-project:main
Choose a base branch
from
PierreMesure:fix/vlm-inline-math
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+334
−88
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b059336
fix: preserve native VLM inline math through exports
PierreMesure 78bf8c3
fix: keep GFM syntax out of native inline math blocks
PierreMesure 6992439
fix: preserve currency ranges in shared VLM math parsing
PierreMesure e219b3a
fix: cache VLM math parsers safely and share literal math rules
PierreMesure File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| # SPDX-FileCopyrightText: The Docling Contributors | ||
| # SPDX-License-Identifier: MIT | ||
|
|
||
| """Math-aware Markdown rendering for native VLM response adapters.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import html | ||
| import re | ||
| from threading import local | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| if TYPE_CHECKING: | ||
| import marko | ||
|
|
||
| _MATH = re.compile( | ||
| r"(?<!\\)(?:\$\$([\s\S]*?)(?<!\\)\$\$" | ||
| # A dollar before a digit starts an amount, not a closing math delimiter. | ||
| r"|(?<!\$)\$(?![\s$])([^\n$]*?)(?<![\\\s])\$(?![\d$])" | ||
| r"|\\\(([\s\S]*?)\\\)|\\\[([\s\S]*?)\\\])" | ||
| ) | ||
|
|
||
|
|
||
| class _MarkdownParsers(local): | ||
| def __init__(self) -> None: | ||
| self.by_mode: dict[bool, marko.Markdown] = {} | ||
|
|
||
|
|
||
| _parsers = _MarkdownParsers() | ||
|
|
||
|
|
||
| def create_markdown_parser(*, inline_only: bool = False) -> marko.Markdown: | ||
| """Render LaTeX as literal math nodes and keep code and currency literal. | ||
|
|
||
| ``inline_only`` leaves the enclosing native block type in control instead | ||
| of interpreting its text as new Markdown lists, headings, or tables. | ||
|
|
||
| Reuse one parser per mode and thread: Marko instances are not thread-safe. | ||
| """ | ||
| # Markdown is an optional dependency for slim installations. | ||
| try: | ||
| import marko | ||
| except ImportError as exc: | ||
| raise ImportError( | ||
| "Markdown parsing requires `pip install 'docling-slim[format-markdown]'`." | ||
| ) from exc | ||
| from marko.helpers import MarkoExtension | ||
|
|
||
| if inline_only in _parsers.by_mode: | ||
| return _parsers.by_mode[inline_only] | ||
|
|
||
| class Math(marko.inline.InlineElement): | ||
| children: str | ||
| pattern = _MATH | ||
| priority = 8 | ||
| parse_group = 0 | ||
|
|
||
| class CodeSpan(marko.inline.CodeSpan): | ||
| override = True | ||
| priority = 9 | ||
|
|
||
| class LiteralCode(marko.inline.InlineElement): | ||
| children: str | ||
| pattern = re.compile(r"<code\b[^>]*>[\s\S]*?</code>", re.IGNORECASE) | ||
| priority = 10 | ||
| parse_group = 0 | ||
|
|
||
| class MathRenderer: | ||
| def render_math(self, element: Math) -> str: | ||
| match = _MATH.fullmatch(element.children) | ||
| if match is None: | ||
| return html.escape(element.children) | ||
| latex = next(group for group in match.groups() if group is not None) | ||
| display = match.group(1) is not None or match.group(4) is not None | ||
| attrs = ' display="block"' if display else "" | ||
| return f"<math{attrs}>{html.escape(latex.strip())}</math>" | ||
|
|
||
| def render_literal_code(self, element: LiteralCode) -> str: | ||
| return element.children | ||
|
|
||
| class Paragraph(marko.block.Paragraph): | ||
| override = True | ||
|
|
||
| @classmethod | ||
| def break_paragraph( | ||
| cls, source: marko.source.Source, lazy: bool = False | ||
| ) -> bool: | ||
| return False | ||
|
|
||
| @staticmethod | ||
| def is_setext_heading(line: str) -> bool: | ||
| return False | ||
|
|
||
| class InlineParser(marko.Parser): | ||
| def __init__(self) -> None: | ||
| super().__init__() | ||
| self.block_elements = { | ||
| name: element | ||
| for name, element in self.block_elements.items() | ||
| if name in {"Document", "Paragraph", "BlankLine"} | ||
| } | ||
|
|
||
| markdown = marko.Markdown( | ||
| parser=InlineParser if inline_only else marko.Parser, | ||
| extensions=[ | ||
| # GFM adds block elements after InlineParser filters them, and its | ||
| # strikethrough and autolinks change literal native block content. | ||
| *([] if inline_only else ["gfm"]), | ||
| MarkoExtension( | ||
| elements=[ | ||
| Math, | ||
| CodeSpan, | ||
| LiteralCode, | ||
| *([Paragraph] if inline_only else []), | ||
| ], | ||
| renderer_mixins=[MathRenderer], | ||
| ), | ||
| ], | ||
| ) | ||
| _parsers.by_mode[inline_only] = markdown | ||
| return markdown |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.