telegramify-markdown 1.4.2__tar.gz → 1.4.4__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.
Files changed (39) hide show
  1. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/PKG-INFO +2 -1
  2. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/pyproject.toml +8 -1
  3. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/rich.py +21 -1
  4. telegramify_markdown-1.4.4/tests/test_fuzz.py +198 -0
  5. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/test_rich.py +36 -0
  6. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/LICENSE +0 -0
  7. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/README.md +0 -0
  8. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/__init__.py +0 -0
  9. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/code_file.py +0 -0
  10. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/config.py +0 -0
  11. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/content.py +0 -0
  12. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/converter.py +0 -0
  13. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/entity.py +0 -0
  14. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/latex_escape/__init__.py +0 -0
  15. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/latex_escape/const.py +0 -0
  16. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/latex_escape/helper.py +0 -0
  17. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/logger.py +0 -0
  18. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/mdv2.py +0 -0
  19. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/mermaid.py +0 -0
  20. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/pipeline.py +0 -0
  21. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/py.typed +0 -0
  22. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/stream/__init__.py +0 -0
  23. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/stream/core.py +0 -0
  24. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/stream/draft.py +0 -0
  25. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/stream/edit.py +0 -0
  26. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/type.py +0 -0
  27. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/src/telegramify_markdown/word_count.py +0 -0
  28. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/exp1.md +0 -0
  29. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/exp2.md +0 -0
  30. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/send_showcase.py +0 -0
  31. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/showcase_latex.py +0 -0
  32. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/test_converter.py +0 -0
  33. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/test_entity.py +0 -0
  34. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/test_mdv2.py +0 -0
  35. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/test_mermaid.py +0 -0
  36. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/test_performance.py +0 -0
  37. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/test_pipeline.py +0 -0
  38. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/test_server.py +0 -0
  39. {telegramify_markdown-1.4.2 → telegramify_markdown-1.4.4}/tests/test_stream.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: telegramify-markdown
3
- Version: 1.4.2
3
+ Version: 1.4.4
4
4
  Summary: Convert Markdown to Telegram plain text + MessageEntity pairs
5
5
  Author-Email: sudoskys <coldlando@hotmail.com>
6
6
  License: MIT
@@ -16,6 +16,7 @@ Requires-Dist: python-dotenv>=1.0.1; extra == "tests"
16
16
  Requires-Dist: PyYAML>=6.0.3; extra == "tests"
17
17
  Requires-Dist: pytest>=8.0; extra == "tests"
18
18
  Requires-Dist: pytest-asyncio>=0.23; extra == "tests"
19
+ Requires-Dist: hypothesis>=6.168.5; extra == "tests"
19
20
  Description-Content-Type: text/markdown
20
21
 
21
22
  # telegramify-markdown
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telegramify-markdown"
3
- version = "1.4.2"
3
+ version = "1.4.4"
4
4
  description = "Convert Markdown to Telegram plain text + MessageEntity pairs"
5
5
  authors = [
6
6
  { name = "sudoskys", email = "coldlando@hotmail.com" },
@@ -25,6 +25,7 @@ tests = [
25
25
  "PyYAML>=6.0.3",
26
26
  "pytest>=8.0",
27
27
  "pytest-asyncio>=0.23",
28
+ "hypothesis>=6.168.5",
28
29
  ]
29
30
 
30
31
  [project.urls]
@@ -56,5 +57,11 @@ cmd = "python -m unittest tests.test_server.TelegramStreamDraftLiveTest"
56
57
  [tool.pdm.scripts.test-live-stream.env]
57
58
  TELEGRAM_LIVE_REQUIRED = "1"
58
59
 
60
+ [tool.pdm.scripts.test-fuzz]
61
+ cmd = "python -m unittest tests.test_fuzz"
62
+
63
+ [tool.pdm.scripts.test-fuzz.env]
64
+ HYPOTHESIS_PROFILE = "thorough"
65
+
59
66
  [tool.pytest.ini_options]
60
67
  asyncio_mode = "auto"
@@ -291,6 +291,7 @@ class _RichHtmlWalker:
291
291
  self._leave_block()
292
292
  elif isinstance(tag, dict):
293
293
  if "Heading" in tag:
294
+ self._close_inlines()
294
295
  level = self._heading_level(tag["Heading"])
295
296
  self._emit(f"</h{level}>")
296
297
  self._leave_block()
@@ -444,6 +445,7 @@ class _RichHtmlWalker:
444
445
  self._table_rows = []
445
446
 
446
447
  def _on_end_table_cell(self) -> None:
448
+ self._close_inlines()
447
449
  content = "".join(self._cell_parts)
448
450
  self._current_row.append((content, self._in_table_head))
449
451
  self._cell_parts = []
@@ -503,6 +505,13 @@ class _RichHtmlWalker:
503
505
  if closer:
504
506
  self._write_inline(closer)
505
507
 
508
+ def _close_inlines(self) -> None:
509
+ # Inline tags never outlive their leaf block. Parser events stay
510
+ # balanced on their own, but a spoiler is raw inline HTML whose
511
+ # ``||`` pair may straddle two blocks.
512
+ while self._inline_closers:
513
+ self._close_inline()
514
+
506
515
  def _write_inline(self, value: str) -> None:
507
516
  self._open_paragraph_if_pending()
508
517
  self._emit(value)
@@ -520,6 +529,7 @@ class _RichHtmlWalker:
520
529
  self._pending_paragraph = False
521
530
 
522
531
  def _close_paragraph(self) -> None:
532
+ self._close_inlines()
523
533
  self._pending_paragraph = False
524
534
  if self._paragraph_open:
525
535
  self._parts.append("</p>")
@@ -961,6 +971,9 @@ def _split_oversized_block(
961
971
  if pre is not None:
962
972
  open_tag, content, close_tag = pre
963
973
  budget = byte_limit - len((open_tag + close_tag).encode("utf-8"))
974
+ if budget <= 0:
975
+ # A long info string can leave no room for code text.
976
+ return []
964
977
  return [
965
978
  _make_block(open_tag + _escape_text(part) + close_tag)
966
979
  for part in _split_text_by_escaped_utf8_bytes(
@@ -1113,8 +1126,15 @@ def _extract_wrapped_text(html_text: str, tag: str) -> str | None:
1113
1126
  return None
1114
1127
 
1115
1128
 
1129
+ # A code block with a language and one without are matched separately: a single
1130
+ # pattern with a greedy body and an alternated close tag settles on "</pre>" and
1131
+ # leaves "</code>" in the body, which then gets escaped into visible text.
1132
+ _PRE_CODE_RE = re.compile(r'(<pre><code class="[^"]+">)(.*)(</code></pre>)', re.DOTALL)
1133
+ _PRE_RE = re.compile(r"(<pre>)(.*)(</pre>)", re.DOTALL)
1134
+
1135
+
1116
1136
  def _extract_pre_text(html_text: str) -> tuple[str, str, str] | None:
1117
- match = re.fullmatch(r"(<pre(?:><code class=\"[^\"]+\">|>))(.*)(</code></pre>|</pre>)", html_text, re.DOTALL)
1137
+ match = _PRE_CODE_RE.fullmatch(html_text) or _PRE_RE.fullmatch(html_text)
1118
1138
  if not match:
1119
1139
  return None
1120
1140
  return match.group(1), match.group(2), match.group(3)
@@ -0,0 +1,198 @@
1
+ """Property-based fuzz tests for the converters and splitters.
2
+
3
+ Inputs mix Markdown syntax fragments with arbitrary Unicode so that Hypothesis
4
+ reaches nested and malformed structures. Set HYPOTHESIS_PROFILE=thorough (or run
5
+ ``pdm run test-fuzz``) for a longer search than the default CI budget.
6
+ """
7
+
8
+ import logging
9
+ import os
10
+ import re
11
+ import unittest
12
+ from html.parser import HTMLParser
13
+
14
+ from hypothesis import HealthCheck, given, settings
15
+ from hypothesis import strategies as st
16
+
17
+ from telegramify_markdown import convert, entities_to_markdownv2, richify, split_entities, split_rich
18
+ from telegramify_markdown.entity import utf16_len
19
+
20
+ settings.register_profile(
21
+ "ci", max_examples=150, deadline=None, suppress_health_check=[HealthCheck.too_slow]
22
+ )
23
+ settings.register_profile(
24
+ "thorough", max_examples=5000, deadline=None, suppress_health_check=[HealthCheck.too_slow]
25
+ )
26
+ settings.load_profile(os.environ.get("HYPOTHESIS_PROFILE", "ci"))
27
+
28
+ _FRAGMENTS = [
29
+ "\n", "\n\n", " ", " \n", "\t", " ",
30
+ "# ", "## ", "###### ", "> ", ">> ", "- ", "* ", "1. ", "10) ", "- [ ] ", "- [x] ",
31
+ "**", "*", "_", "__", "~~", "~", "`", "``", "```", "```python\n", "~~~js\n", "\n```\n",
32
+ "||", "$", "$$", "\\(", "\\)", "\\", "[", "](", ")", "![", "[^1]", "[^1]: ",
33
+ "| a | b |\n", "|---|:-:|\n", " | ", "---\n", "***\n",
34
+ "<", ">", "&", "&amp;", "&lt;", "&#x1F600;", '"', "'",
35
+ "<b>", "</b>", "<br>", "<details>", "<!-- -->",
36
+ "https://example.com/a_b?c=d&e", "<https://example.com>", "user@example.com",
37
+ "😀", "👨‍👩‍👧", "🇨🇳", "​", "‮", "中文", "é", "\U0001d400",
38
+ "\\frac{a}{b}", "\\alpha", "^2", "_{i}",
39
+ ]
40
+
41
+ markdown_text = st.lists(
42
+ st.one_of(st.sampled_from(_FRAGMENTS), st.text(max_size=12)),
43
+ max_size=60,
44
+ ).map("".join)
45
+
46
+
47
+ def _is_surrogate_boundary(text: str, utf16_offset: int) -> bool:
48
+ """Whether a UTF-16 offset falls on a code point boundary of text."""
49
+ position = 0
50
+ for char in text:
51
+ if position == utf16_offset:
52
+ return True
53
+ position += 2 if ord(char) > 0xFFFF else 1
54
+ if position > utf16_offset:
55
+ return False
56
+ return position == utf16_offset
57
+
58
+
59
+ class _TagBalance(HTMLParser):
60
+ """Collects tag nesting errors in an HTML fragment."""
61
+
62
+ VOID = {"br", "hr", "img", "input"}
63
+
64
+ def __init__(self):
65
+ super().__init__(convert_charrefs=True)
66
+ self.stack: list[str] = []
67
+ self.errors: list[str] = []
68
+
69
+ def handle_starttag(self, tag, attrs):
70
+ if tag not in self.VOID:
71
+ self.stack.append(tag)
72
+
73
+ def handle_startendtag(self, tag, attrs):
74
+ pass
75
+
76
+ def handle_endtag(self, tag):
77
+ if tag in self.VOID:
78
+ return
79
+ if not self.stack or self.stack[-1] != tag:
80
+ self.errors.append(f"unexpected </{tag}>, open: {self.stack}")
81
+ return
82
+ self.stack.pop()
83
+
84
+
85
+ def _tag_errors(html_text: str) -> list[str]:
86
+ parser = _TagBalance()
87
+ parser.feed(html_text)
88
+ parser.close()
89
+ return parser.errors + [f"unclosed <{tag}>" for tag in parser.stack]
90
+
91
+
92
+ def _visible_text(html_text: str) -> str:
93
+ """Rendered text without markup and without whitespace."""
94
+
95
+ class _Text(HTMLParser):
96
+ def __init__(self):
97
+ super().__init__(convert_charrefs=True)
98
+ self.parts: list[str] = []
99
+
100
+ def handle_data(self, data):
101
+ self.parts.append(data)
102
+
103
+ parser = _Text()
104
+ parser.feed(html_text)
105
+ parser.close()
106
+ return re.sub(r"\s+", "", "".join(parser.parts))
107
+
108
+
109
+ class EntityFuzzTest(unittest.TestCase):
110
+ """convert() and split_entities() keep entities inside their text."""
111
+
112
+ @given(markdown_text, st.booleans())
113
+ def test_convert_entities_stay_in_bounds(self, markdown, latex_escape):
114
+ text, entities = convert(markdown, latex_escape=latex_escape)
115
+ total = utf16_len(text)
116
+ for entity in entities:
117
+ self.assertGreater(entity.length, 0, entity)
118
+ self.assertGreaterEqual(entity.offset, 0, entity)
119
+ self.assertLessEqual(entity.offset + entity.length, total, entity)
120
+ self.assertTrue(_is_surrogate_boundary(text, entity.offset), entity)
121
+ self.assertTrue(_is_surrogate_boundary(text, entity.offset + entity.length), entity)
122
+ entities_to_markdownv2(text, entities)
123
+
124
+ @given(markdown_text, st.integers(min_value=2, max_value=200))
125
+ def test_split_entities_respects_limit(self, markdown, limit):
126
+ text, entities = convert(markdown)
127
+ chunks = split_entities(text, entities, limit)
128
+ for chunk_text, chunk_entities in chunks:
129
+ chunk_len = utf16_len(chunk_text)
130
+ self.assertLessEqual(chunk_len, limit)
131
+ self.assertTrue(chunk_text.strip())
132
+ for entity in chunk_entities:
133
+ self.assertGreater(entity.length, 0, entity)
134
+ self.assertGreaterEqual(entity.offset, 0, entity)
135
+ self.assertLessEqual(entity.offset + entity.length, chunk_len, entity)
136
+ self.assertEqual(
137
+ "".join("".join(chunk_text.split()) for chunk_text, _ in chunks),
138
+ "".join(text.split()),
139
+ )
140
+
141
+
142
+ class RichFuzzTest(unittest.TestCase):
143
+ """richify() and split_rich() produce well-formed chunks within budget."""
144
+
145
+ @given(markdown_text)
146
+ def test_richify_html_is_well_formed(self, markdown):
147
+ html_text = richify(markdown).html
148
+ self.assertEqual(_tag_errors(html_text), [], html_text)
149
+
150
+ @given(markdown_text, st.integers(min_value=64, max_value=2048))
151
+ def test_split_rich_chunks_are_well_formed_and_lossless(self, markdown, byte_limit):
152
+ rich = richify(markdown)
153
+ logger = logging.getLogger("telegramify_markdown")
154
+ records: list[logging.LogRecord] = []
155
+ handler = logging.Handler(logging.WARNING)
156
+ handler.emit = records.append
157
+ logger.addHandler(handler)
158
+ try:
159
+ chunks = split_rich(rich, byte_limit=byte_limit)
160
+ finally:
161
+ logger.removeHandler(handler)
162
+
163
+ for chunk in chunks:
164
+ self.assertEqual(_tag_errors(chunk.html), [], chunk.html)
165
+ if len(chunk.html.encode("utf-8")) > byte_limit:
166
+ # The PRD allows an unsplittable block to pass through, but
167
+ # never silently.
168
+ self.assertTrue(
169
+ records,
170
+ chunk.html,
171
+ )
172
+ self.assertEqual(
173
+ "".join(_visible_text(chunk.html) for chunk in chunks),
174
+ _visible_text(rich.html),
175
+ )
176
+
177
+ @given(
178
+ st.sampled_from(["", "python", "c++", "js"]),
179
+ st.text(alphabet=st.sampled_from("ab <&>\"'\n😀中"), min_size=1, max_size=3000),
180
+ st.integers(min_value=64, max_value=1024),
181
+ )
182
+ def test_oversized_code_block_splits_into_code_blocks(self, language, code, byte_limit):
183
+ rich = richify(f"```{language}\n{code}\n```")
184
+ chunks = split_rich(rich, byte_limit=byte_limit)
185
+ open_tag = f'<pre><code class="language-{language}">' if language else "<pre>"
186
+ close_tag = "</code></pre>" if language else "</pre>"
187
+ for chunk in chunks:
188
+ self.assertTrue(chunk.html.startswith(open_tag), chunk.html)
189
+ self.assertTrue(chunk.html.endswith(close_tag), chunk.html)
190
+ self.assertLessEqual(len(chunk.html.encode("utf-8")), byte_limit)
191
+ self.assertEqual(
192
+ "".join(_visible_text(chunk.html) for chunk in chunks),
193
+ _visible_text(rich.html),
194
+ )
195
+
196
+
197
+ if __name__ == "__main__":
198
+ unittest.main()
@@ -118,6 +118,18 @@ class RichifyHtmlTest(unittest.TestCase):
118
118
  '<p><tg-emoji emoji-id="5368324170671202286">👍</tg-emoji></p>',
119
119
  )
120
120
 
121
+ def test_spoiler_spanning_blocks_closes_inside_each_block(self):
122
+ """跨 block 的 ||spoiler|| 必须在所在 block 内闭合。"""
123
+ self.assertEqual(
124
+ richify("**a ||b**\n\nc||").html,
125
+ "<p><b>a <tg-spoiler>b</tg-spoiler></b></p><p>c</p>",
126
+ )
127
+ self.assertEqual(
128
+ richify("# a ||b\n\n| x |\n|---|\n| ||c |").html,
129
+ "<h1>a <tg-spoiler>b</tg-spoiler></h1>"
130
+ "<table><tr><th>x</th></tr><tr><td>c</td></tr></table>",
131
+ )
132
+
121
133
  def test_markdown_mode_passthrough(self):
122
134
  rich = richify("**x**", mode="markdown", skip_entity_detection=True)
123
135
  self.assertEqual(
@@ -312,6 +324,30 @@ class SplitRichTest(unittest.TestCase):
312
324
  self.assertTrue(html.endswith("</pre>"))
313
325
  self.assertLessEqual(len(html.encode("utf-8")), 32768)
314
326
 
327
+ def test_html_mode_splits_oversized_pre_block_with_language(self):
328
+ """带语言的超长 code block 每个 chunk 都以 </code></pre> 闭合,且不泄漏 </code> 文本。"""
329
+ code = "\n".join(f"x_{n} = {n}" for n in range(4000))
330
+ result = telegramify_rich(f"```python\n{code}\n```")
331
+
332
+ self.assertGreater(len(result), 1)
333
+ open_tag = '<pre><code class="language-python">'
334
+ recovered = []
335
+ for item in result:
336
+ html = item.to_dict()["html"]
337
+ self.assertTrue(html.startswith(open_tag))
338
+ self.assertTrue(html.endswith("</code></pre>"))
339
+ self.assertNotIn("&lt;/code&gt;", html)
340
+ self.assertLessEqual(len(html.encode("utf-8")), 32768)
341
+ recovered.append(unescape(html.removeprefix(open_tag).removesuffix("</code></pre>")))
342
+ self.assertEqual("".join(recovered), code)
343
+
344
+ def test_code_block_with_oversized_info_string_is_sent_with_warning(self):
345
+ """info string 超过字节预算时不抛异常,原样发出并警告。"""
346
+ with self.assertLogs("telegramify_markdown.rich", level="WARNING"):
347
+ result = telegramify_rich("```" + "x" * 40000 + "\ncode\n```")
348
+ self.assertEqual(len(result), 1)
349
+ self.assertTrue(result[0].to_dict()["html"].endswith("code</code></pre>"))
350
+
315
351
  def test_html_mode_splits_oversized_escaped_pre_block(self):
316
352
  """超长 code block 含 HTML 特殊字符时保持可见文本。"""
317
353
  visible = "<&>" * 12000