chatgpt-md-converter 0.3.7__tar.gz → 0.3.9__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {chatgpt_md_converter-0.3.7 → chatgpt_md_converter-0.3.9}/PKG-INFO +19 -1
- chatgpt_md_converter-0.3.9/README.md +165 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/__init__.py +5 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/html_markdown/escaping.py +68 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/html_markdown/handlers.py +155 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/html_markdown/renderer.py +16 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/html_markdown/state.py +16 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/html_markdown/tree.py +65 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/html_splitter.py +239 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/html_to_markdown.py +5 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/telegram_formatter.py +3 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/telegram_markdown/__init__.py +5 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/telegram_markdown/code_blocks.py +95 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/telegram_markdown/inline.py +73 -0
- chatgpt_md_converter-0.3.7/chatgpt_md_converter/helpers.py → chatgpt_md_converter-0.3.9/chatgpt_md_converter/telegram_markdown/postprocess.py +5 -11
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/telegram_markdown/preprocess.py +39 -0
- chatgpt_md_converter-0.3.9/chatgpt_md_converter/telegram_markdown/renderer.py +55 -0
- {chatgpt_md_converter-0.3.7 → chatgpt_md_converter-0.3.9}/chatgpt_md_converter.egg-info/PKG-INFO +19 -1
- chatgpt_md_converter-0.3.9/chatgpt_md_converter.egg-info/SOURCES.txt +25 -0
- {chatgpt_md_converter-0.3.7 → chatgpt_md_converter-0.3.9}/setup.py +2 -2
- {chatgpt_md_converter-0.3.7 → chatgpt_md_converter-0.3.9}/tests/test_parser.py +31 -3
- chatgpt_md_converter-0.3.9/tests/test_roundtrip_markdown.py +32 -0
- chatgpt_md_converter-0.3.9/tests/test_splitter.py +103 -0
- chatgpt_md_converter-0.3.7/chatgpt_md_converter/__init__.py +0 -3
- chatgpt_md_converter-0.3.7/chatgpt_md_converter/converters.py +0 -27
- chatgpt_md_converter-0.3.7/chatgpt_md_converter/extractors.py +0 -94
- chatgpt_md_converter-0.3.7/chatgpt_md_converter/formatters.py +0 -68
- chatgpt_md_converter-0.3.7/chatgpt_md_converter/html_splitter.py +0 -114
- chatgpt_md_converter-0.3.7/chatgpt_md_converter/telegram_formatter.py +0 -99
- chatgpt_md_converter-0.3.7/chatgpt_md_converter.egg-info/SOURCES.txt +0 -15
- chatgpt_md_converter-0.3.7/tests/test_splitter.py +0 -436
- {chatgpt_md_converter-0.3.7 → chatgpt_md_converter-0.3.9}/LICENSE +0 -0
- {chatgpt_md_converter-0.3.7 → chatgpt_md_converter-0.3.9}/chatgpt_md_converter.egg-info/dependency_links.txt +0 -0
- {chatgpt_md_converter-0.3.7 → chatgpt_md_converter-0.3.9}/chatgpt_md_converter.egg-info/top_level.txt +0 -0
- {chatgpt_md_converter-0.3.7 → chatgpt_md_converter-0.3.9}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: chatgpt_md_converter
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.9
|
|
4
4
|
Summary: A package for converting markdown to HTML for chat Telegram bots
|
|
5
5
|
Home-page: https://github.com/botfather-dev/formatter-chatgpt-telegram
|
|
6
6
|
Author: Kostiantyn Kriuchkov
|
|
@@ -114,6 +114,24 @@ Hidden by default
|
|
|
114
114
|
Multiple lines</blockquote>
|
|
115
115
|
```
|
|
116
116
|
|
|
117
|
+
|
|
118
|
+
## Performance
|
|
119
|
+
|
|
120
|
+
Benchmarks were recorded on Linux 6.16.6 (Python 3.11.10) using 1,000 iterations per sample.
|
|
121
|
+
|
|
122
|
+
| Sample | Direction | Avg ms/call | Ops/sec |
|
|
123
|
+
|--------------|---------------|-------------|---------|
|
|
124
|
+
| short_inline | Markdown→HTML | 0.043 | 23,476 |
|
|
125
|
+
| short_inline | HTML→Markdown | 0.078 | 12,824 |
|
|
126
|
+
| medium_block | Markdown→HTML | 0.108 | 9,270 |
|
|
127
|
+
| medium_block | HTML→Markdown | 0.155 | 6,437 |
|
|
128
|
+
| long_mixed | Markdown→HTML | 0.446 | 2,242 |
|
|
129
|
+
| long_mixed | HTML→Markdown | 0.730 | 1,370 |
|
|
130
|
+
|
|
131
|
+
These numbers provide a baseline; real-world throughput depends on text length and interpreter speed.
|
|
132
|
+
|
|
133
|
+
Reproduce the measurements with `python scripts/benchmark.py --iterations 1000 --json benchmarks.json --summary BENCHMARKS.md`.
|
|
134
|
+
|
|
117
135
|
## Requirements
|
|
118
136
|
|
|
119
137
|
- Python 3.x
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# ChatGPT Markdown to Telegram HTML Parser
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
This project provides a solution for converting Telegram-style Markdown formatted text into HTML markup supported by the Telegram Bot API, specifically tailored for use in ChatGPT bots developed with the OpenAI API. It includes features for handling various Markdown elements and ensures proper tag closure, making it suitable for streaming mode applications.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Converts Telegram-style Markdown syntax to Telegram-compatible HTML
|
|
10
|
+
- Supports text styling:
|
|
11
|
+
- Bold: `**text**` → `<b>text</b>`
|
|
12
|
+
- Italic: `*text*` or `_text_` → `<i>text</i>`
|
|
13
|
+
- Underline: `__text__` → `<u>text</u>`
|
|
14
|
+
- Strikethrough: `~~text~~` → `<s>text</s>`
|
|
15
|
+
- Spoiler: `||text||` → `<span class="tg-spoiler">text</span>`
|
|
16
|
+
- Inline code: `` `code` `` → `<code>code</code>`
|
|
17
|
+
- Handles nested text styling
|
|
18
|
+
- Converts links: `[text](URL)` → `<a href="URL">text</a>`
|
|
19
|
+
- Processes code blocks with language specification
|
|
20
|
+
- Supports blockquotes:
|
|
21
|
+
- Regular blockquotes: `> text` → `<blockquote>text</blockquote>`
|
|
22
|
+
- Expandable blockquotes: `**> text` → `<blockquote expandable>text</blockquote>`
|
|
23
|
+
- Automatically appends missing closing delimiters for code blocks
|
|
24
|
+
- Escapes HTML special characters to prevent unwanted HTML rendering
|
|
25
|
+
|
|
26
|
+
## Usage
|
|
27
|
+
|
|
28
|
+
To use the Markdown to Telegram HTML Parser in your ChatGPT bot, integrate the provided Python functions into your bot's processing pipeline. Here is a brief overview of how to incorporate the parser:
|
|
29
|
+
|
|
30
|
+
1. **Ensure Closing Delimiters**: Automatically appends missing closing delimiters for backticks to ensure proper parsing.
|
|
31
|
+
|
|
32
|
+
2. **Extract and Convert Code Blocks**: Extracts Markdown code blocks, converts them to HTML `<pre><code>` format, and replaces them with placeholders to prevent formatting within code blocks.
|
|
33
|
+
|
|
34
|
+
3. **Markdown to HTML Conversion**: Applies various regex substitutions and custom logic to convert supported Markdown formatting to Telegram-compatible HTML tags.
|
|
35
|
+
|
|
36
|
+
4. **Reinsert Code Blocks**: Reinserts the previously extracted and converted code blocks back into the main text, replacing placeholders with the appropriate HTML content.
|
|
37
|
+
|
|
38
|
+
Simply call the `telegram_format(text: str) -> str` function with your Markdown-formatted text as input to receive the converted HTML output ready for use with the Telegram Bot API.
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
pip install chatgpt-md-converter
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Example
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from chatgpt_md_converter import telegram_format
|
|
50
|
+
|
|
51
|
+
# Basic formatting example
|
|
52
|
+
text = """
|
|
53
|
+
Here is some **bold**, __underline__, and `inline code`.
|
|
54
|
+
This is a ||spoiler text|| and *italic*.
|
|
55
|
+
|
|
56
|
+
Code example:
|
|
57
|
+
print('Hello, world!')
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
# Blockquotes example
|
|
61
|
+
blockquote_text = """
|
|
62
|
+
> Regular blockquote
|
|
63
|
+
> Multiple lines
|
|
64
|
+
|
|
65
|
+
**> Expandable blockquote
|
|
66
|
+
> Hidden by default
|
|
67
|
+
> Multiple lines
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
formatted_text = telegram_format(text)
|
|
71
|
+
formatted_blockquote = telegram_format(blockquote_text)
|
|
72
|
+
|
|
73
|
+
print(formatted_text)
|
|
74
|
+
print(formatted_blockquote)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Output:
|
|
78
|
+
|
|
79
|
+
```
|
|
80
|
+
Here is some <b>bold</b>, <u>underline</u>, and <code>inline code</code>.
|
|
81
|
+
This is a <span class="tg-spoiler">spoiler text</span> and <i>italic</i>.
|
|
82
|
+
|
|
83
|
+
Code example:
|
|
84
|
+
print('Hello, world!')
|
|
85
|
+
|
|
86
|
+
<blockquote>Regular blockquote
|
|
87
|
+
Multiple lines</blockquote>
|
|
88
|
+
|
|
89
|
+
<blockquote expandable>Expandable blockquote
|
|
90
|
+
Hidden by default
|
|
91
|
+
Multiple lines</blockquote>
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
## Performance
|
|
96
|
+
|
|
97
|
+
Benchmarks were recorded on Linux 6.16.6 (Python 3.11.10) using 1,000 iterations per sample.
|
|
98
|
+
|
|
99
|
+
| Sample | Direction | Avg ms/call | Ops/sec |
|
|
100
|
+
|--------------|---------------|-------------|---------|
|
|
101
|
+
| short_inline | Markdown→HTML | 0.043 | 23,476 |
|
|
102
|
+
| short_inline | HTML→Markdown | 0.078 | 12,824 |
|
|
103
|
+
| medium_block | Markdown→HTML | 0.108 | 9,270 |
|
|
104
|
+
| medium_block | HTML→Markdown | 0.155 | 6,437 |
|
|
105
|
+
| long_mixed | Markdown→HTML | 0.446 | 2,242 |
|
|
106
|
+
| long_mixed | HTML→Markdown | 0.730 | 1,370 |
|
|
107
|
+
|
|
108
|
+
These numbers provide a baseline; real-world throughput depends on text length and interpreter speed.
|
|
109
|
+
|
|
110
|
+
Reproduce the measurements with `python scripts/benchmark.py --iterations 1000 --json benchmarks.json --summary BENCHMARKS.md`.
|
|
111
|
+
|
|
112
|
+
## Requirements
|
|
113
|
+
|
|
114
|
+
- Python 3.x
|
|
115
|
+
- No external libraries required (uses built-in `re` module for regex operations)
|
|
116
|
+
|
|
117
|
+
## Contribution
|
|
118
|
+
|
|
119
|
+
Feel free to contribute to this project by submitting pull requests or opening issues for bugs, feature requests, or improvements.
|
|
120
|
+
|
|
121
|
+
## Prompting LLMs for Telegram-Specific Formatting
|
|
122
|
+
|
|
123
|
+
> **Note**:
|
|
124
|
+
> Since standard Markdown doesn't include Telegram-specific features like spoilers (`||text||`) and expandable blockquotes (`**> text`), you'll need to explicitly instruct LLMs to use these formats. Here's a suggested prompt addition to include in your system message or initial instructions:
|
|
125
|
+
|
|
126
|
+
````
|
|
127
|
+
When formatting your responses for Telegram, please use these special formatting conventions:
|
|
128
|
+
|
|
129
|
+
1. For content that should be hidden as a spoiler (revealed only when users click):
|
|
130
|
+
Use: ||spoiler content here||
|
|
131
|
+
Example: This is visible, but ||this is hidden until clicked||.
|
|
132
|
+
|
|
133
|
+
2. For lengthy explanations or optional content that should be collapsed:
|
|
134
|
+
Use: **> Expandable section title
|
|
135
|
+
|
|
136
|
+
> Content line 1
|
|
137
|
+
> Content line 2
|
|
138
|
+
> (Each line of the expandable blockquote should start with ">")
|
|
139
|
+
|
|
140
|
+
3. Continue using standard markdown for other formatting:
|
|
141
|
+
- **bold text**
|
|
142
|
+
- *italic text*
|
|
143
|
+
- __underlined text__
|
|
144
|
+
- ~~strikethrough~~
|
|
145
|
+
- `inline code`
|
|
146
|
+
- ```code blocks```
|
|
147
|
+
- [link text](URL)
|
|
148
|
+
|
|
149
|
+
Apply spoilers for:
|
|
150
|
+
|
|
151
|
+
- Solution reveals
|
|
152
|
+
- Potential plot spoilers
|
|
153
|
+
- Sensitive information
|
|
154
|
+
- Surprising facts
|
|
155
|
+
|
|
156
|
+
Use expandable blockquotes for:
|
|
157
|
+
|
|
158
|
+
- Detailed explanations
|
|
159
|
+
- Long examples
|
|
160
|
+
- Optional reading
|
|
161
|
+
- Technical details
|
|
162
|
+
- Additional context not needed by all users
|
|
163
|
+
````
|
|
164
|
+
|
|
165
|
+
You can add this prompt to your system message when initializing your ChatGPT interactions to ensure the model properly formats content for optimal display in Telegram.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Shared escaping utilities for Telegram Markdown conversion."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from .tree import Node
|
|
9
|
+
|
|
10
|
+
_SIMPLE_STAR_ITALIC = re.compile(
|
|
11
|
+
r"(?<!\\)(?<!\*)\*(?=[^\s])([^\*\n]+?)(?<!\s)\*(?![A-Za-z0-9\*])",
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _canonicalize_star_italics(text: str) -> str:
|
|
16
|
+
def _replace(match: re.Match[str]) -> str:
|
|
17
|
+
inner = match.group(1)
|
|
18
|
+
if "*" in inner or "_" in inner or "`" in inner:
|
|
19
|
+
return match.group(0)
|
|
20
|
+
return f"_{inner}_"
|
|
21
|
+
|
|
22
|
+
return _SIMPLE_STAR_ITALIC.sub(_replace, text)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def normalise_text(text: str) -> str:
|
|
26
|
+
if not text:
|
|
27
|
+
return ""
|
|
28
|
+
unescaped = html.unescape(text)
|
|
29
|
+
return unescaped.replace("\u00a0", " ")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def collect_text(node: Node) -> str:
|
|
33
|
+
if node.kind == "text":
|
|
34
|
+
return html.unescape(node.text)
|
|
35
|
+
parts: list[str] = []
|
|
36
|
+
for child in node.children:
|
|
37
|
+
if child.kind == "text":
|
|
38
|
+
parts.append(html.unescape(child.text))
|
|
39
|
+
elif child.kind == "element":
|
|
40
|
+
if child.tag.lower() == "br":
|
|
41
|
+
parts.append("\n")
|
|
42
|
+
else:
|
|
43
|
+
parts.append(collect_text(child))
|
|
44
|
+
return "".join(parts)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def escape_inline_code(text: str) -> str:
|
|
48
|
+
return text.replace("`", "\\`")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def escape_link_label(label: str) -> str:
|
|
52
|
+
escaped = label
|
|
53
|
+
for ch in "[]()":
|
|
54
|
+
escaped = escaped.replace(ch, f"\\{ch}")
|
|
55
|
+
return escaped
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def escape_link_url(url: str) -> str:
|
|
59
|
+
return url.replace("\\", "\\\\").replace(")", "\\)")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def post_process(markdown: str) -> str:
|
|
63
|
+
text = re.sub(r"(^|\n)•\s", r"\1- ", markdown)
|
|
64
|
+
text = re.sub(r"\n{3,}", "\n\n", text)
|
|
65
|
+
text = text.replace("\r", "")
|
|
66
|
+
text = "\n".join(line.rstrip() for line in text.split("\n"))
|
|
67
|
+
text = _canonicalize_star_italics(text)
|
|
68
|
+
return text.strip()
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Tag-specific renderers for Telegram Markdown."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Callable, Dict
|
|
6
|
+
|
|
7
|
+
from .escaping import (collect_text, escape_inline_code, escape_link_label,
|
|
8
|
+
escape_link_url, normalise_text)
|
|
9
|
+
from .state import RenderState
|
|
10
|
+
from .tree import Node
|
|
11
|
+
|
|
12
|
+
InlineHandler = Callable[[Node, RenderState], str]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_INLINE_MARKERS: Dict[str, tuple[str, str]] = {
|
|
16
|
+
"u": ("__", "__"),
|
|
17
|
+
"ins": ("__", "__"),
|
|
18
|
+
"s": ("~~", "~~"),
|
|
19
|
+
"strike": ("~~", "~~"),
|
|
20
|
+
"del": ("~~", "~~"),
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def render_nodes(nodes: list[Node], state: RenderState) -> str:
|
|
25
|
+
return "".join(render_node(node, state) for node in nodes)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def render_node(node: Node, state: RenderState) -> str:
|
|
29
|
+
if node.kind == "text":
|
|
30
|
+
return normalise_text(node.text)
|
|
31
|
+
|
|
32
|
+
handler = TAG_DISPATCH.get(node.tag.lower())
|
|
33
|
+
if handler:
|
|
34
|
+
return handler(node, state)
|
|
35
|
+
return render_nodes(node.children, state)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _handle_bold(node: Node, state: RenderState) -> str:
|
|
39
|
+
inner_state = state.child(bold_depth=state.bold_depth + 1)
|
|
40
|
+
inner = render_nodes(node.children, inner_state)
|
|
41
|
+
return f"**{inner}**"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _handle_italic(node: Node, state: RenderState) -> str:
|
|
45
|
+
depth = state.italic_depth
|
|
46
|
+
in_bold = state.bold_depth > 0 and depth == 0
|
|
47
|
+
marker = "_" if in_bold else ("*" if depth % 2 == 0 else "_")
|
|
48
|
+
inner_state = state.child(italic_depth=depth + 1)
|
|
49
|
+
inner = render_nodes(node.children, inner_state)
|
|
50
|
+
return f"{marker}{inner}{marker}"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _handle_inline_marker(node: Node, state: RenderState) -> str:
|
|
54
|
+
marker_open, marker_close = _INLINE_MARKERS[node.tag.lower()]
|
|
55
|
+
inner = render_nodes(node.children, state)
|
|
56
|
+
return f"{marker_open}{inner}{marker_close}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _handle_spoiler(node: Node, state: RenderState) -> str:
|
|
60
|
+
inner = render_nodes(node.children, state)
|
|
61
|
+
return f"||{inner}||"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _handle_code(node: Node, state: RenderState) -> str:
|
|
65
|
+
inner = collect_text(node)
|
|
66
|
+
return f"`{escape_inline_code(inner)}`"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _handle_pre(node: Node, state: RenderState) -> str:
|
|
70
|
+
children = node.children
|
|
71
|
+
language: str | None = None
|
|
72
|
+
content_node: Node
|
|
73
|
+
|
|
74
|
+
if len(children) == 1 and children[0].kind == "element" and children[0].tag.lower() == "code":
|
|
75
|
+
content_node = children[0]
|
|
76
|
+
class_attr = content_node.attrs.get("class") or ""
|
|
77
|
+
for part in class_attr.split():
|
|
78
|
+
if part.startswith("language-"):
|
|
79
|
+
language = part.split("-", 1)[1]
|
|
80
|
+
break
|
|
81
|
+
else:
|
|
82
|
+
content_node = Node(kind="element", tag="__virtual__", children=children)
|
|
83
|
+
|
|
84
|
+
inner_text = collect_text(content_node)
|
|
85
|
+
fence = f"```{language}" if language else "```"
|
|
86
|
+
if language or "\n" in inner_text:
|
|
87
|
+
return f"{fence}\n{inner_text}```"
|
|
88
|
+
return f"{fence}{inner_text}```"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _handle_link(node: Node, state: RenderState) -> str:
|
|
92
|
+
href = node.attrs.get("href", "") or ""
|
|
93
|
+
label = render_nodes(node.children, state)
|
|
94
|
+
if not label:
|
|
95
|
+
label = href
|
|
96
|
+
|
|
97
|
+
escaped_label = escape_link_label(label)
|
|
98
|
+
escaped_url = escape_link_url(href)
|
|
99
|
+
|
|
100
|
+
if href.startswith("tg://emoji?"):
|
|
101
|
+
return f""
|
|
102
|
+
return f"[{escaped_label}]({escaped_url})"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _handle_blockquote(node: Node, state: RenderState) -> str:
|
|
106
|
+
inner = render_nodes(node.children, state)
|
|
107
|
+
lines = inner.split("\n")
|
|
108
|
+
expandable = "expandable" in node.attrs
|
|
109
|
+
rendered: list[str] = []
|
|
110
|
+
for index, line in enumerate(lines):
|
|
111
|
+
prefix = "**>" if expandable and index == 0 else ">"
|
|
112
|
+
stripped = line.rstrip("\r")
|
|
113
|
+
if expandable:
|
|
114
|
+
rendered.append(prefix + stripped)
|
|
115
|
+
else:
|
|
116
|
+
rendered.append(f"{prefix} {stripped}" if stripped else prefix)
|
|
117
|
+
return "\n".join(rendered)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _handle_tg_emoji(node: Node, state: RenderState) -> str:
|
|
121
|
+
emoji_id = node.attrs.get("emoji-id")
|
|
122
|
+
label = render_nodes(node.children, state)
|
|
123
|
+
if emoji_id:
|
|
124
|
+
href = f"tg://emoji?id={emoji_id}"
|
|
125
|
+
return f""
|
|
126
|
+
return label
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _handle_span(node: Node, state: RenderState) -> str:
|
|
130
|
+
classes = (node.attrs.get("class") or "").split()
|
|
131
|
+
if any(cls == "tg-spoiler" for cls in classes):
|
|
132
|
+
return _handle_spoiler(node, state)
|
|
133
|
+
if any(cls == "tg-emoji" for cls in classes):
|
|
134
|
+
return render_nodes(node.children, state)
|
|
135
|
+
return render_nodes(node.children, state)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
TAG_DISPATCH: Dict[str, Callable[[Node, RenderState], str]] = {
|
|
139
|
+
"b": _handle_bold,
|
|
140
|
+
"strong": _handle_bold,
|
|
141
|
+
"i": _handle_italic,
|
|
142
|
+
"em": _handle_italic,
|
|
143
|
+
"u": _handle_inline_marker,
|
|
144
|
+
"ins": _handle_inline_marker,
|
|
145
|
+
"s": _handle_inline_marker,
|
|
146
|
+
"strike": _handle_inline_marker,
|
|
147
|
+
"del": _handle_inline_marker,
|
|
148
|
+
"span": _handle_span,
|
|
149
|
+
"tg-spoiler": _handle_spoiler,
|
|
150
|
+
"code": _handle_code,
|
|
151
|
+
"pre": _handle_pre,
|
|
152
|
+
"a": _handle_link,
|
|
153
|
+
"blockquote": _handle_blockquote,
|
|
154
|
+
"tg-emoji": _handle_tg_emoji,
|
|
155
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""High-level HTML → Telegram Markdown renderer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import List
|
|
6
|
+
|
|
7
|
+
from .escaping import post_process
|
|
8
|
+
from .handlers import render_nodes
|
|
9
|
+
from .state import RenderState
|
|
10
|
+
from .tree import Node, build_tree
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def html_to_telegram_markdown(html_text: str) -> str:
|
|
14
|
+
nodes: List[Node] = build_tree(html_text)
|
|
15
|
+
markdown = render_nodes(nodes, RenderState())
|
|
16
|
+
return post_process(markdown)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Rendering state for HTML → Telegram Markdown conversion."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class RenderState:
|
|
10
|
+
bold_depth: int = 0
|
|
11
|
+
italic_depth: int = 0
|
|
12
|
+
|
|
13
|
+
def child(self, **updates: int) -> "RenderState":
|
|
14
|
+
data = {"bold_depth": self.bold_depth, "italic_depth": self.italic_depth}
|
|
15
|
+
data.update(updates)
|
|
16
|
+
return RenderState(**data)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""DOM-like tree construction for Telegram HTML fragments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from html.parser import HTMLParser
|
|
7
|
+
from typing import Dict, List, Optional
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class Node:
|
|
12
|
+
kind: str # "text" or "element"
|
|
13
|
+
text: str = ""
|
|
14
|
+
tag: str = ""
|
|
15
|
+
attrs: Dict[str, Optional[str]] = field(default_factory=dict)
|
|
16
|
+
children: List["Node"] = field(default_factory=list)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _HTMLTreeBuilder(HTMLParser):
|
|
20
|
+
SELF_CLOSING_TAGS = {"br"}
|
|
21
|
+
|
|
22
|
+
def __init__(self) -> None:
|
|
23
|
+
super().__init__(convert_charrefs=False)
|
|
24
|
+
self.root = Node(kind="element", tag="__root__")
|
|
25
|
+
self._stack: List[Node] = [self.root]
|
|
26
|
+
|
|
27
|
+
def handle_starttag(self, tag: str, attrs: List[tuple[str, Optional[str]]]) -> None:
|
|
28
|
+
if tag in self.SELF_CLOSING_TAGS:
|
|
29
|
+
if tag == "br":
|
|
30
|
+
self._stack[-1].children.append(Node(kind="text", text="\n"))
|
|
31
|
+
return
|
|
32
|
+
node = Node(kind="element", tag=tag, attrs=dict(attrs))
|
|
33
|
+
self._stack[-1].children.append(node)
|
|
34
|
+
self._stack.append(node)
|
|
35
|
+
|
|
36
|
+
def handle_endtag(self, tag: str) -> None:
|
|
37
|
+
for index in range(len(self._stack) - 1, 0, -1):
|
|
38
|
+
if self._stack[index].tag == tag:
|
|
39
|
+
del self._stack[index:]
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
def handle_startendtag(self, tag: str, attrs: List[tuple[str, Optional[str]]]) -> None:
|
|
43
|
+
if tag in self.SELF_CLOSING_TAGS:
|
|
44
|
+
self.handle_starttag(tag, attrs)
|
|
45
|
+
return
|
|
46
|
+
node = Node(kind="element", tag=tag, attrs=dict(attrs))
|
|
47
|
+
self._stack[-1].children.append(node)
|
|
48
|
+
|
|
49
|
+
def handle_data(self, data: str) -> None:
|
|
50
|
+
if data:
|
|
51
|
+
self._stack[-1].children.append(Node(kind="text", text=data))
|
|
52
|
+
|
|
53
|
+
def handle_entityref(self, name: str) -> None:
|
|
54
|
+
self.handle_data(f"&{name};")
|
|
55
|
+
|
|
56
|
+
def handle_charref(self, name: str) -> None:
|
|
57
|
+
self.handle_data(f"&#{name};")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def build_tree(html_text: str) -> List[Node]:
|
|
61
|
+
"""Parse HTML and return the list of top-level nodes."""
|
|
62
|
+
builder = _HTMLTreeBuilder()
|
|
63
|
+
builder.feed(html_text)
|
|
64
|
+
builder.close()
|
|
65
|
+
return builder.root.children
|