|
| 1 | +"""Convert LLM-generated Markdown into Telegram-safe HTML. |
| 2 | +
|
| 3 | +The LLM providers (Anthropic, OpenAI, Ollama) return standard CommonMark: |
| 4 | +``**bold**``, ``# headings``, ``*italic*``, ``` ``` ``` fenced code blocks. Telegram's |
| 5 | +legacy Markdown parse mode does not understand double-asterisk bold or |
| 6 | +headings, so that output renders with literal ``*`` characters all over it |
| 7 | +(or fails to parse and gets stripped to plain text entirely). |
| 8 | +
|
| 9 | +Telegram's HTML parse mode is the most forgiving target for arbitrary model |
| 10 | +output: the text is HTML-escaped first and we only ever emit a small set of |
| 11 | +*balanced* tags (``<b>``, ``<i>``, ``<code>``, ``<pre>``, ``<a>``, ``<s>``), so an |
| 12 | +unmatched Markdown delimiter degrades to a harmless literal character instead |
| 13 | +of breaking the whole message. See the Telegram Bot API "HTML style" docs for |
| 14 | +the supported tag set. |
| 15 | +""" |
| 16 | + |
| 17 | +import html |
| 18 | +import re |
| 19 | + |
| 20 | +__all__ = ["markdown_to_telegram_html", "strip_html_tags"] |
| 21 | + |
| 22 | +# Fenced code blocks: ```lang\n ... ``` (contents preserved verbatim). |
| 23 | +_FENCE_RE = re.compile(r"```[^\n]*\n?(.*?)```", re.DOTALL) |
| 24 | +# Inline code: `code`. |
| 25 | +_INLINE_CODE_RE = re.compile(r"`([^`\n]+)`") |
| 26 | +# Markdown links: [text](url). |
| 27 | +_LINK_RE = re.compile(r"\[([^\]\n]+)\]\((https?://[^)\s]+)\)") |
| 28 | +# Headings: up to three leading spaces, 1-6 '#', text, optional trailing '#'. |
| 29 | +_HEADING_RE = re.compile(r"^[ \t]{0,3}#{1,6}[ \t]+(.+?)[ \t]*#*[ \t]*$", re.MULTILINE) |
| 30 | +# Bold: **text** / __text__ (no surrounding word char for underscores). |
| 31 | +_BOLD_STAR_RE = re.compile(r"\*\*(?=\S)(.+?)(?<=\S)\*\*") |
| 32 | +_BOLD_UNDER_RE = re.compile(r"(?<!\w)__(?=\S)(.+?)(?<=\S)__(?!\w)") |
| 33 | +# Italic: *text* / _text_ (single delimiter, no adjacent space, snake_case-safe). |
| 34 | +_ITALIC_STAR_RE = re.compile(r"(?<!\*)\*(?!\s)([^*\n]+?)(?<!\s)\*(?!\*)") |
| 35 | +_ITALIC_UNDER_RE = re.compile(r"(?<!\w)_(?=\S)([^_\n]+?)(?<=\S)_(?!\w)") |
| 36 | +# Strikethrough: ~~text~~. |
| 37 | +_STRIKE_RE = re.compile(r"~~(?=\S)(.+?)(?<=\S)~~") |
| 38 | +# List markers using '*' or '+' (a literal '*' bullet would otherwise show raw). |
| 39 | +_BULLET_RE = re.compile(r"^([ \t]*)[*+][ \t]+(?=\S)", re.MULTILINE) |
| 40 | +# Placeholder token used to protect code spans from further processing. |
| 41 | +_PLACEHOLDER_RE = re.compile(r"\x00(\d+)\x00") |
| 42 | +_TAG_RE = re.compile(r"<[^>]+>") |
| 43 | + |
| 44 | + |
| 45 | +def markdown_to_telegram_html(text: str) -> str: |
| 46 | + """Convert Markdown produced by an LLM into Telegram-safe HTML. |
| 47 | +
|
| 48 | + Args: |
| 49 | + text: Raw model output in CommonMark-ish Markdown. |
| 50 | +
|
| 51 | + Returns: |
| 52 | + HTML suitable for ``parse_mode="HTML"``. Returns an empty string for |
| 53 | + empty input. |
| 54 | + """ |
| 55 | + if not text: |
| 56 | + return "" |
| 57 | + |
| 58 | + protected: list[str] = [] |
| 59 | + |
| 60 | + def _stash(fragment: str) -> str: |
| 61 | + protected.append(fragment) |
| 62 | + return f"\x00{len(protected) - 1}\x00" |
| 63 | + |
| 64 | + # 1. Pull out code (fenced first, then inline) and escape its contents now, |
| 65 | + # so later Markdown/HTML passes never touch it. |
| 66 | + def _repl_fence(m: re.Match[str]) -> str: |
| 67 | + return _stash(f"<pre>{html.escape(m.group(1).rstrip(chr(10)), quote=False)}</pre>") |
| 68 | + |
| 69 | + def _repl_inline_code(m: re.Match[str]) -> str: |
| 70 | + return _stash(f"<code>{html.escape(m.group(1), quote=False)}</code>") |
| 71 | + |
| 72 | + text = _FENCE_RE.sub(_repl_fence, text) |
| 73 | + text = _INLINE_CODE_RE.sub(_repl_inline_code, text) |
| 74 | + |
| 75 | + # 2. Escape everything else. Telegram HTML only requires &, < and > to be |
| 76 | + # escaped in text; quotes are left intact so they read naturally. Markdown |
| 77 | + # delimiters (*, _, #, [, ]) survive escaping, so the regex passes below |
| 78 | + # still work; '\x00' placeholders are untouched. |
| 79 | + text = html.escape(text, quote=False) |
| 80 | + |
| 81 | + # 3. Links -> <a>. The captured url already had '&' escaped to '&'; also |
| 82 | + # make any quote attribute-safe inside the href. |
| 83 | + def _repl_link(m: re.Match[str]) -> str: |
| 84 | + label, url = m.group(1), m.group(2).replace('"', """) |
| 85 | + return _stash(f'<a href="{url}">{label}</a>') |
| 86 | + |
| 87 | + text = _LINK_RE.sub(_repl_link, text) |
| 88 | + |
| 89 | + # 4. Headings -> bold line. |
| 90 | + text = _HEADING_RE.sub(r"<b>\1</b>", text) |
| 91 | + |
| 92 | + # 5. Bold, then italic, then strikethrough. |
| 93 | + text = _BOLD_STAR_RE.sub(r"<b>\1</b>", text) |
| 94 | + text = _BOLD_UNDER_RE.sub(r"<b>\1</b>", text) |
| 95 | + text = _ITALIC_STAR_RE.sub(r"<i>\1</i>", text) |
| 96 | + text = _ITALIC_UNDER_RE.sub(r"<i>\1</i>", text) |
| 97 | + text = _STRIKE_RE.sub(r"<s>\1</s>", text) |
| 98 | + |
| 99 | + # 6. Normalise '*'/'+' bullets to a clean glyph ('-' bullets already read |
| 100 | + # fine and are left as-is). |
| 101 | + text = _BULLET_RE.sub(r"\1• ", text) |
| 102 | + |
| 103 | + # 7. Collapse the doubled tags a heading-with-bold produces (e.g. '## **x**'). |
| 104 | + text = text.replace("<b><b>", "<b>").replace("</b></b>", "</b>") |
| 105 | + |
| 106 | + # 8. Restore protected code/link fragments. |
| 107 | + text = _PLACEHOLDER_RE.sub(lambda m: protected[int(m.group(1))], text) |
| 108 | + return text |
| 109 | + |
| 110 | + |
| 111 | +def strip_html_tags(text: str) -> str: |
| 112 | + """Strip HTML tags and unescape entities for a plain-text fallback.""" |
| 113 | + return html.unescape(_TAG_RE.sub("", text)) |
0 commit comments