line-markdown-parser 0.1.2__py3-none-any.whl

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.
@@ -0,0 +1,260 @@
1
+ """Public conversion API and size-aware splitting.
2
+
3
+ All results are fresh JSON-compatible dictionaries. No input is logged, cached
4
+ across calls, sent over the network, or written to disk.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from collections.abc import Callable
12
+ from typing import Any
13
+
14
+ from ._renderer import _iter_links
15
+ from ._renderer import build_flex_contents as _render_contents
16
+
17
+ DEFAULT_MAX_FLEX_PAYLOAD_BYTES = 28_000
18
+ _MAX_BUBBLE_BYTES = 30_000
19
+ _MAX_ALT_TEXT_UNITS = 1_500
20
+ _MAX_INPUT_BYTES = 200_000
21
+ # Keep fence recognition aligned with the renderer's supported Markdown subset.
22
+ _CODE_FENCE_RE = re.compile(r"(```[\s\S]*?```)")
23
+
24
+
25
+ def _require_text(text: str) -> str:
26
+ if not isinstance(text, str):
27
+ raise TypeError("text must be a string")
28
+ if any(0xD800 <= ord(char) <= 0xDFFF for char in text):
29
+ raise ValueError("text must contain valid Unicode scalar values")
30
+ if len(text.encode("utf-8")) > _MAX_INPUT_BYTES:
31
+ raise ValueError("text exceeds the 200,000-byte UTF-8 input limit")
32
+ return text
33
+
34
+
35
+ def build_flex_contents(text: str) -> list[dict[str, Any]]:
36
+ """Build body components without a bubble, footer, or delivery metadata.
37
+
38
+ This low-level function does not split or enforce the bubble byte limit.
39
+ """
40
+ _require_text(text)
41
+ if not text.strip():
42
+ return []
43
+ contents = _render_contents(text)
44
+ # Separators alone can be removed by the renderer. A bubble cannot be empty.
45
+ return contents or [{"type": "text", "text": text.strip(), "wrap": True}]
46
+
47
+
48
+ def _bubble(text: str) -> dict[str, Any]:
49
+ return {
50
+ "type": "bubble",
51
+ "size": "giga",
52
+ "body": {
53
+ "type": "box",
54
+ "layout": "vertical",
55
+ "contents": build_flex_contents(text),
56
+ "paddingAll": "16px",
57
+ "backgroundColor": "#FFFFFF",
58
+ },
59
+ }
60
+
61
+
62
+ def _json_size(value: dict[str, Any]) -> int:
63
+ return len(
64
+ json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
65
+ )
66
+
67
+
68
+ def estimate_flex_payload_size(text: str) -> int:
69
+ """Return compact UTF-8 JSON bytes of the bubble (not the HTTP envelope).
70
+
71
+ Use the same JSON serialization for delivery. The default split budget
72
+ reserves 2,000 bytes below LINE's 30 KB bubble limit.
73
+ """
74
+ return _json_size(_bubble(_require_text(text)))
75
+
76
+
77
+ def _alt_text(text: str) -> str:
78
+ text = _require_text(text).strip()
79
+ if not text:
80
+ raise ValueError("alt_text must not be empty")
81
+ units = 0
82
+ end = 0
83
+ for end, char in enumerate(text, start=1):
84
+ units += 2 if ord(char) > 0xFFFF else 1
85
+ if units > _MAX_ALT_TEXT_UNITS:
86
+ # The truncation marker itself consumes one UTF-16 code unit.
87
+ prefix = text[: end - 1]
88
+ while len(prefix.encode("utf-16-le")) // 2 >= _MAX_ALT_TEXT_UNITS:
89
+ prefix = prefix[:-1]
90
+ return prefix + "…"
91
+ return text
92
+
93
+
94
+ def build_flex_message(text: str, *, alt_text: str | None = None) -> dict[str, Any]:
95
+ """Build one standalone Flex message; raise ValueError if it exceeds 30 KB.
96
+
97
+ Use convert_markdown_to_line_messages for automatic splitting. alt_text
98
+ defaults to the source text and is bounded to 1,500 UTF-16 code units.
99
+ """
100
+ _require_text(text)
101
+ if not text.strip():
102
+ raise ValueError("text must not be empty")
103
+ bubble = _bubble(text)
104
+ if _json_size(bubble) > _MAX_BUBBLE_BYTES:
105
+ raise ValueError(
106
+ "bubble exceeds 30,000 bytes; use convert_markdown_to_line_messages"
107
+ )
108
+ return {
109
+ "type": "flex",
110
+ "altText": _alt_text(text if alt_text is None else alt_text),
111
+ "contents": bubble,
112
+ }
113
+
114
+
115
+ def _validate_limits(max_length: int, max_payload_bytes: int) -> None:
116
+ if (
117
+ isinstance(max_length, bool)
118
+ or not isinstance(max_length, int)
119
+ or max_length < 1
120
+ ):
121
+ raise ValueError("max_length must be a positive integer")
122
+ if (
123
+ isinstance(max_payload_bytes, bool)
124
+ or not isinstance(max_payload_bytes, int)
125
+ or not 1 <= max_payload_bytes <= _MAX_BUBBLE_BYTES
126
+ ):
127
+ raise ValueError("max_payload_bytes must be an integer between 1 and 30,000")
128
+
129
+
130
+ def split_long_text(
131
+ text: str,
132
+ max_length: int = 1600,
133
+ max_payload_bytes: int = DEFAULT_MAX_FLEX_PAYLOAD_BYTES,
134
+ ) -> list[str]:
135
+ """Split Markdown into pieces that fit both source length and rendered bytes.
136
+
137
+ Prefer paragraph/line/word boundaries. Closed triple-backtick code fences
138
+ are repeated around each code fragment, including a single oversized line.
139
+ Other inline syntax may become plain text when split. Impossible budgets
140
+ raise ValueError; no over-budget fragment is returned.
141
+ """
142
+ _require_text(text)
143
+ _validate_limits(max_length, max_payload_bytes)
144
+ if not text.strip():
145
+ return []
146
+
147
+ def fits(candidate: str) -> bool:
148
+ return (
149
+ len(candidate) <= max_length
150
+ and estimate_flex_payload_size(candidate) <= max_payload_bytes
151
+ )
152
+
153
+ def split_unit(
154
+ body: str, wrap: Callable[[str], str], *, preserve_links: bool = False
155
+ ) -> list[str]:
156
+ if fits(wrap(body)):
157
+ return [wrap(body)]
158
+ pieces: list[str] = []
159
+ start = 0
160
+ overhead = len(wrap(""))
161
+ link_ranges = (
162
+ [(link.start, link.end) for link in _iter_links(body)]
163
+ if preserve_links
164
+ else []
165
+ )
166
+
167
+ def safe_boundary(end: int) -> int:
168
+ for link_start, link_end in link_ranges:
169
+ if link_start < end < link_end:
170
+ return link_start
171
+ return end
172
+
173
+ while start < len(body):
174
+ end = safe_boundary(min(len(body), start + max_length - overhead))
175
+ while end > start and not fits(wrap(body[start:end])):
176
+ end = safe_boundary(start + (end - start) * 3 // 4)
177
+ if end <= start:
178
+ # Shrinking is conservative, and can jump past a whole link.
179
+ # Try that atomic token before declaring the budget impossible.
180
+ for link_start, link_end in link_ranges:
181
+ if link_start == start and fits(wrap(body[start:link_end])):
182
+ end = link_end
183
+ break
184
+ if end <= start:
185
+ raise ValueError(
186
+ "limits are too small for a rendered fragment or intact link"
187
+ )
188
+ if end < len(body):
189
+ # Keep at least half the fitting candidate to avoid tiny chunks.
190
+ for separator in ("\n\n", "\n", " "):
191
+ boundary = body.rfind(separator, start + (end - start) // 2, end)
192
+ if boundary >= 0:
193
+ preferred_end = safe_boundary(boundary + len(separator))
194
+ if preferred_end > start and fits(
195
+ wrap(body[start:preferred_end])
196
+ ):
197
+ end = preferred_end
198
+ break
199
+ pieces.append(wrap(body[start:end]))
200
+ start = end
201
+ if not pieces:
202
+ raise ValueError("limits are too small for an empty fenced block")
203
+ return pieces
204
+
205
+ if fits(text):
206
+ return [text]
207
+
208
+ chunks: list[str] = []
209
+ for segment in _CODE_FENCE_RE.split(text):
210
+ if not segment:
211
+ continue
212
+ if _CODE_FENCE_RE.fullmatch(segment) and "\n" in segment:
213
+ header, body = segment[:-3].split("\n", 1)
214
+ if body.endswith("\n"):
215
+ body = body[:-1]
216
+
217
+ def wrap_code(piece: str, opening: str = header) -> str:
218
+ return opening + "\n" + piece + "\n```"
219
+
220
+ chunks.extend(split_unit(body, wrap_code))
221
+ else:
222
+ chunks.extend(split_unit(segment, lambda piece: piece, preserve_links=True))
223
+
224
+ parts: list[str] = []
225
+ current = ""
226
+ for chunk in chunks:
227
+ candidate = current + chunk
228
+ if not current or fits(candidate):
229
+ current = candidate
230
+ else:
231
+ if current.strip():
232
+ parts.append(current)
233
+ current = chunk
234
+ if current.strip():
235
+ parts.append(current)
236
+ # Validate rendered output after every boundary decision; Markdown size is
237
+ # not monotonic with source length (a closing delimiter can change layout).
238
+ if any(not fits(part) for part in parts):
239
+ raise ValueError("unable to split text within the requested limits")
240
+ return parts
241
+
242
+
243
+ def convert_markdown_to_line_messages(
244
+ text: str,
245
+ *,
246
+ alt_text: str | None = None,
247
+ max_length: int = 1600,
248
+ max_payload_bytes: int = DEFAULT_MAX_FLEX_PAYLOAD_BYTES,
249
+ ) -> list[dict[str, Any]]:
250
+ """Convert Markdown to ordered standalone Flex messages, without sending.
251
+
252
+ Empty input returns []. The caller manages LINE's five-message request
253
+ limit and delivery. This function never truncates the message list.
254
+ """
255
+ if alt_text is not None:
256
+ _alt_text(alt_text)
257
+ return [
258
+ build_flex_message(part, alt_text=alt_text)
259
+ for part in split_long_text(text, max_length, max_payload_bytes)
260
+ ]
File without changes
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: line-markdown-parser
3
+ Version: 0.1.2
4
+ Summary: Convert LLM Markdown into readable LINE Flex Messages without runtime dependencies.
5
+ Author: line-markdown-parser contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/darkgaldragon/line-markdown-parser
8
+ Project-URL: Source, https://github.com/darkgaldragon/line-markdown-parser
9
+ Project-URL: Issues, https://github.com/darkgaldragon/line-markdown-parser/issues
10
+ Keywords: line,markdown,flex-message,llm,chatbot
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=8; extra == "dev"
25
+ Requires-Dist: ruff>=0.11; extra == "dev"
26
+ Requires-Dist: build>=1.2; extra == "dev"
27
+ Requires-Dist: twine>=6; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # line-markdown-parser
31
+
32
+ Convert LLM Markdown into readable LINE Flex Message dictionaries with no runtime dependencies.
33
+
34
+ [日本語](README-ja.md)
35
+
36
+ Headings, paragraphs, lists, quotes, code, and links receive a chat-friendly layout. Long output is split into separate messages. Sending remains the responsibility of your application.
37
+
38
+ ## Installation
39
+
40
+ Requires Python 3.10 or later.
41
+
42
+ ```bash
43
+ python -m pip install line-markdown-parser
44
+ ```
45
+
46
+ ## Quick start
47
+
48
+ ```python
49
+ import json
50
+
51
+ from line_markdown_parser import convert_markdown_to_line_messages
52
+
53
+ markdown = """# Project update
54
+
55
+ The **first draft** is ready.
56
+
57
+ - Review the examples
58
+ - Read the [guide](https://example.com/guide)
59
+ """
60
+
61
+ messages = convert_markdown_to_line_messages(markdown)
62
+ print(json.dumps(messages, ensure_ascii=False, indent=2))
63
+ ```
64
+
65
+ Each item has `type: "flex"`, `altText`, and one `bubble` in `contents`. Pass these dictionaries to your LINE API integration. The library makes no network requests and does not require the LINE SDK.
66
+
67
+ The converter returns all generated messages. LINE accepts up to five message objects per [reply](https://developers.line.biz/en/reference/messaging-api/#send-reply-message) or [push](https://developers.line.biz/en/reference/messaging-api/#send-push-message) request, so your application must handle longer results and reply-token restrictions.
68
+
69
+ ## API
70
+
71
+ All functions are exported from `line_markdown_parser`.
72
+
73
+ | Function | Purpose |
74
+ | --- | --- |
75
+ | `convert_markdown_to_line_messages` | Split Markdown and return a `list[dict]` of Flex Messages. |
76
+ | `build_flex_message` | Build one message without splitting; reject oversized input. |
77
+ | `build_flex_contents` | Build body components for a custom bubble, without a bubble size check. |
78
+ | `split_long_text` | Return Markdown chunks as a `list[str]`. |
79
+ | `estimate_flex_payload_size` | Measure the rendered bubble's compact UTF-8 JSON size. |
80
+
81
+ The converter defaults to 1,600 source characters and 28,000 rendered bytes per chunk. See the [API specification](docs/spec.md) for signatures, limits, alternative text, and error behavior.
82
+
83
+ ## Limitations
84
+
85
+ - Markdown tables use code-style text boxes; column alignment varies by client font.
86
+ - Images appear as labels and links, without fetching or embedding images.
87
+ - Only `http` and `https` links receive URI actions; destinations are not verified.
88
+ - Full CommonMark support, arbitrary nesting, and every code-fence style are outside the scope.
89
+ - This is an alpha release with automated tests. Live LINE delivery and client appearance have not been verified. Check integration with the [Flex Message Simulator](https://developers.line.biz/flex-simulator/) and your target LINE clients.
90
+
91
+ ## Contributing
92
+
93
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for setup and checks, [SECURITY.md](SECURITY.md) for vulnerability reporting, and [CHANGELOG.md](CHANGELOG.md) for release history.
94
+
95
+ ## License
96
+
97
+ [MIT](LICENSE). This independent project is not an official LINE product.
@@ -0,0 +1,9 @@
1
+ line_markdown_parser/__init__.py,sha256=JVWtYjb8ESOB3MpiR8YXmA0W7uI_LrDM0Sl-NdFMQYQ,506
2
+ line_markdown_parser/_renderer.py,sha256=JluqobiP9iBtXhUYAr9bwrY9uDo4zYxh2cKtOToSm28,58959
3
+ line_markdown_parser/converter.py,sha256=lH-k66ckNNNG8X6CZdPAI2b_Cy0EDAtGHWiQai8Gezk,9199
4
+ line_markdown_parser/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ line_markdown_parser-0.1.2.dist-info/licenses/LICENSE,sha256=u5FUkJhpVNaUIe78mhEt0qPwcjgkSIMlhIwaA8xQaLY,1090
6
+ line_markdown_parser-0.1.2.dist-info/METADATA,sha256=1tHxGGIDHRAecD7RODV9vFm7owVQXH2K2EQ4n5hZX0k,4224
7
+ line_markdown_parser-0.1.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
8
+ line_markdown_parser-0.1.2.dist-info/top_level.txt,sha256=TdLst9mUdFc2XS5t3t-Gg-xIJh3BLmzaHigypJ2qqZ8,21
9
+ line_markdown_parser-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 line-markdown-parser contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ line_markdown_parser