mathfence 0.1.3__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,289 @@
1
+ Metadata-Version: 2.5
2
+ Name: mathfence
3
+ Version: 0.1.3
4
+ Summary: Normalize LLM math delimiters and escape currency dollar signs before Markdown rendering, without touching code or URLs.
5
+ Project-URL: Homepage, https://github.com/LeeGyeongPil/mathfence
6
+ Project-URL: Issues, https://github.com/LeeGyeongPil/mathfence/issues
7
+ Project-URL: Changelog, https://github.com/LeeGyeongPil/mathfence/blob/main/CHANGELOG.md
8
+ Author: LeeGyeongPil
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: gradio,jupyter,katex,latex,llm,markdown,math,streaming,streamlit
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+
25
+ # mathfence
26
+
27
+ **English** | [한국어](https://github.com/LeeGyeongPil/mathfence/blob/v0.1.3/README.ko.md)
28
+
29
+ Normalize LLM Markdown before it reaches a `$`-math renderer. One call, `mathfence.normalize(text)`, rewrites `\( \)` and `\[ \]` to `$ $` and `$$ $$`, escapes price dollars (`$5`) as `\$`, and leaves code, URLs and HTML untouched. A streaming helper keeps half-finished answers from flashing fake formulas. Pure Python standard library, zero runtime dependencies, plus a CLI that explains every decision.
30
+
31
+ ![Same answer through the same renderer, without and with mathfence](https://raw.githubusercontent.com/LeeGyeongPil/mathfence/main/docs/images/before-after.png)
32
+
33
+ *Left: prices such as `$5 ... $1,200` are paired into fake formulas (highlighted boxes) and `\(n\)` stays literal. Right: after `mathfence.normalize`, prices stay text, formulas render, `echo $HOME` is untouched. Rendered by markdown-it-py + dollarmath, see `examples/render_compare.py`.*
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ uv add mathfence # or: pip install mathfence
39
+ ```
40
+
41
+ Not on PyPI yet when you read this? Install from GitHub:
42
+
43
+ ```bash
44
+ uv add git+https://github.com/LeeGyeongPil/mathfence
45
+ ```
46
+
47
+ Python 3.10 or newer, no runtime dependencies. If you do not have uv: `curl -LsSf https://astral.sh/uv/install.sh | sh` ([uv docs](https://docs.astral.sh/uv/)).
48
+
49
+ ## Quick start
50
+
51
+ ```python
52
+ import mathfence
53
+
54
+ print(mathfence.normalize("It costs $5 and $10, area $x^2$."))
55
+ ```
56
+
57
+ ```text
58
+ It costs \$5 and \$10, area $x^2$.
59
+ ```
60
+
61
+ The two prices are escaped (they would otherwise pair up as the formula `5 and `). The real formula `$x^2$` stays.
62
+
63
+ Try the command line on the bundled sample answer:
64
+
65
+ ```bash
66
+ uv run mathfence examples/answer.md
67
+ ```
68
+
69
+ The sample input first (`cat examples/answer.md`):
70
+
71
+ ![Raw model answer with prices, bracket math and code](https://raw.githubusercontent.com/LeeGyeongPil/mathfence/main/docs/images/01-raw-answer.png)
72
+
73
+ *A typical raw answer: prices, `\( \)` and `\[ \]` math, an inline code span, a URL and a code block.*
74
+
75
+ Then the result (the text that goes to your renderer):
76
+
77
+ ![Normalized output](https://raw.githubusercontent.com/LeeGyeongPil/mathfence/main/docs/images/02-normalized.png)
78
+
79
+ *Prices escaped, brackets converted to dollars, display math kept as a block, list and quote prefixes kept, `echo $HOME`, the URL and the fenced block untouched.*
80
+
81
+ ## Core concepts
82
+
83
+ A single regex cannot do this safely, so mathfence works in three steps.
84
+
85
+ ```mermaid
86
+ flowchart LR
87
+ A[LLM text] --> B[1 Find protected regions]
88
+ B --> C[2 Convert brackets]
89
+ C --> D[3 Decide each dollar]
90
+ D --> E[Renderer]
91
+ ```
92
+
93
+ 1. **Protected regions** (fenced and indented code, code spans, HTML, autolinks, bare URLs) are found first and copied unchanged.
94
+ 2. **Brackets** `\( \)` and `\[ \]` outside those regions are replaced in place, so list indentation and `> ` quote prefixes survive.
95
+ 3. **Dollars** left over are paired inside the same paragraph. If the text between a pair looks like a formula it stays math, otherwise the `$` is escaped as `\$`. When in doubt it escapes, because a visible `$` is a smaller mistake than a broken sentence.
96
+
97
+ **Streaming.** While tokens arrive, a final `$` may be the start of a formula or the end of a price. `StreamNormalizer` holds a trailing `$` until the next character arrives, so the screen never shows math the finished answer does not contain. It also settles finished paragraphs so they are not processed again.
98
+
99
+ Every decision has a rule id (for example `body-edge-space`, `bracket-inline`), which is what `--explain` prints.
100
+
101
+ ## API
102
+
103
+ | Name | What it does | Main arguments | Returns |
104
+ |---|---|---|---|
105
+ | `normalize(text, *, profile="remark")` | Rewrites delimiters and escapes currency dollars | `text: str`; `profile`: `"remark"` or `"streamlit"` | `str` |
106
+ | `analyze(text, *, profile="remark")` | Same as `normalize`, plus every decision | same | `Result(text, decisions, changed)` |
107
+ | `Decision` | One decision: `offset`, `line`, `column`, `source`, `action` (`keep_math`, `convert`, `escape`, `protect`), `kind`, `rule` | | frozen dataclass |
108
+ | `StreamNormalizer(*, profile="remark")` | Normalizes a growing answer | | object |
109
+ | `StreamNormalizer.feed(chunk)` | Adds a chunk; returns the text to show now | `chunk: str` | `str` |
110
+ | `StreamNormalizer.finish()` | Final text, equal to `normalize(all text)`; no `feed()` after it | | `str` |
111
+ | `StreamNormalizer.stats` | `reprocessed_chars`, `committed_chars` | | `StreamStats` |
112
+ | `PROFILES` | Allowed profile names | | `("remark", "streamlit")` |
113
+
114
+ Errors: a non-`str` input raises `TypeError`, an unknown profile raises `ValueError` that lists the allowed names, `feed()` after `finish()` raises `RuntimeError`.
115
+
116
+ Profiles: `remark` (default) works for any renderer that reads `$` and `$$`; `streamlit` also puts every `$$` block on its own lines (list and quote prefixes kept).
117
+
118
+ ```python
119
+ import mathfence
120
+
121
+ r = mathfence.analyze(r"Cost $5, area \(x^2\).")
122
+ print(r.text)
123
+ print(r.changed)
124
+ for d in r.decisions:
125
+ print(d.line, d.column, d.action, d.rule)
126
+ print(mathfence.normalize(r"\[a\]", profile="streamlit"))
127
+ try:
128
+ mathfence.normalize("x", profile="nope")
129
+ except ValueError as e:
130
+ print(e)
131
+ try:
132
+ mathfence.normalize(b"x")
133
+ except TypeError as e:
134
+ print(e)
135
+ ```
136
+
137
+ ```text
138
+ Cost \$5, area $x^2$.
139
+ True
140
+ 1 6 escape body-edge-space
141
+ 1 15 convert bracket-inline
142
+ $$
143
+ a
144
+ $$
145
+ unknown profile 'nope'; choose one of: remark, streamlit
146
+ text must be str, got bytes (decode bytes with .decode('utf-8') first)
147
+ ```
148
+
149
+ ## Usage
150
+
151
+ ### 1. Streaming answers (`examples/stream_demo.py`)
152
+
153
+ ```python
154
+ from mathfence import StreamNormalizer
155
+
156
+ stream = StreamNormalizer()
157
+ for chunk in ["The fee is $", "5 and the tax is $", "10, area $x", "^2$."]:
158
+ print(repr(stream.feed(chunk)))
159
+ print("final:", repr(stream.finish()))
160
+ ```
161
+
162
+ ```text
163
+ 'The fee is \\$'
164
+ 'The fee is \\$5 and the tax is \\$'
165
+ 'The fee is \\$5 and the tax is \\$10, area \\$x'
166
+ 'The fee is \\$5 and the tax is \\$10, area $x^2$.'
167
+ final: 'The fee is \\$5 and the tax is \\$10, area $x^2$.'
168
+ ```
169
+
170
+ (`repr` doubles the backslash; the text itself contains `\$`.) The unfinished `$x` is shown as text until `^2$` arrives, then it becomes math. Pass `feed()`'s return value to your renderer on every chunk, instead of the raw text.
171
+
172
+ ![Stream output, chunk by chunk](https://raw.githubusercontent.com/LeeGyeongPil/mathfence/main/docs/images/04-stream.png)
173
+
174
+ *Each line is what the screen would show after one more chunk.*
175
+
176
+ The same chunks through the renderer, raw text on the left column and `StreamNormalizer` on the right:
177
+
178
+ ![Rendered streaming frames: raw text shows a fake formula after chunk 2, the stream does not](https://raw.githubusercontent.com/LeeGyeongPil/mathfence/main/docs/images/streaming.png)
179
+
180
+ *After chunk 2 the raw text already shows a highlighted fake formula (`5 and the tax is `); the normalized stream still shows the prices as text. Generated by `examples/render_compare.py`.*
181
+
182
+ ### 2. See why a dollar was kept or escaped
183
+
184
+ ```bash
185
+ uv run mathfence --lang en --explain examples/answer.md
186
+ ```
187
+
188
+ ![The explain table, one row per decision with its rule id](https://raw.githubusercontent.com/LeeGyeongPil/mathfence/main/docs/images/03-explain.png)
189
+
190
+ *Line and column, action, rule id, the original fragment and a plain-language reason for every decision. `protect` rows are code and URLs that were left alone.*
191
+
192
+ `--explain --format json` prints a JSON report with a `decisions` array (`line`, `column`, `action`, `rule`, `reason`, ...), handy for tools.
193
+
194
+ ### 3. Check files in CI
195
+
196
+ ```bash
197
+ uv run mathfence --lang en --check examples/answer.md
198
+ ```
199
+
200
+ ```text
201
+ examples/answer.md: would change
202
+ ```
203
+
204
+ `--check` prints the files that would change and exits with 1 (0 when nothing would change, 2 for an unreadable file or bad option).
205
+
206
+ ### 4. Streamlit
207
+
208
+ `examples/streamlit_chat.py` replays recorded answers token by token with and without mathfence. It is not a live model call. Run it with `uv run --with streamlit streamlit run examples/streamlit_chat.py` (open with `?lang=ko` for the Korean screen). It was exercised with Streamlit's `AppTest` only, not captured in a browser, so there is no screenshot of that app. The static before/after pages above come from `uv run python examples/render_compare.py` (writes `docs/demo/*.html`).
209
+
210
+ ## Settings
211
+
212
+ | Option / variable | Meaning |
213
+ |---|---|
214
+ | `--profile NAME` | `remark` (default) or `streamlit` |
215
+ | `--explain`, `--format text\|json` | Print decisions instead of the text; one input only |
216
+ | `--check` | Print files that would change, exit 1 if any |
217
+ | `--lang en\|ko`, `MATHFENCE_LANG` | Message language. Priority: `--lang` > `MATHFENCE_LANG` > `LC_ALL` > `LC_MESSAGES` > `LANG`; anything not Korean falls back to English |
218
+ | FILE or `-` | Input files; no file or `-` reads standard input |
219
+
220
+ ```bash
221
+ printf 'Pay $5 or $6\n' | uv run mathfence --lang en
222
+ ```
223
+
224
+ ```text
225
+ Pay \$5 or \$6
226
+ ```
227
+
228
+ ## Does it do better than the usual shortcuts?
229
+
230
+ `bench/compare.py` scores four approaches on the same 94-case corpus with one lenient judge (markdown-it-py with its dollarmath plugin):
231
+
232
+ ```bash
233
+ uv run python bench/compare.py
234
+ ```
235
+
236
+ ![Comparison table: no processing, escape every dollar, a regex recipe, mathfence](https://raw.githubusercontent.com/LeeGyeongPil/mathfence/main/docs/images/05-bench.png)
237
+
238
+ *`broken` counts code or URL text that was damaged. `flicker` counts character-by-character screens that showed a formula the final answer does not contain.*
239
+
240
+ ```text
241
+ approach pass score broken flicker
242
+ no processing 40/94 0.43 0 3
243
+ escape every $ 33/94 0.35 13 0
244
+ regex recipe 68/94 0.72 15 2
245
+ mathfence 94/94 1.00 0 0
246
+ ```
247
+
248
+ Read this with care: the corpus was written by the author of the rules, so the score is optimistic. `regex recipe` is a composite of common snippets, not a copy of any project.
249
+
250
+ ## When to use it
251
+
252
+ - Good fit: a Python app (Streamlit, Gradio, Jupyter, a bot server) sends LLM answers to a front end that reads `$` and `$$`, and prices or `\( \)` math show up wrongly.
253
+ - JavaScript or TypeScript front end: look at [remark-math](https://github.com/remarkjs/remark-math) and the markdown preprocessing options of your chat UI library instead.
254
+ - Server-side HTML rendering in Python: [mdit-py-plugins](https://github.com/executablebooks/mdit-py-plugins) (`dollarmath`) parses math itself.
255
+
256
+ ## Known limits
257
+
258
+ - It is a heuristic. An ambiguous sentence such as `$5 on the x$` is escaped (shown as text) rather than rendered as math.
259
+ - A blank line inside `$$ ... $$` or `\[ ... \]` ends the paragraph, so that pair is not matched.
260
+ - `StreamNormalizer` settles text at blank lines outside code, HTML and lists, and at top-level list item boundaries when the settled part has no `$` or backslash; other long runs without paragraph breaks are reprocessed on every `feed()`.
261
+ - Link destinations in `[text](https://github.com/LeeGyeongPil/mathfence/blob/v0.1.3/url)` and HTML blocks nested in lists or quotes are not protected regions.
262
+ - Tested on Python 3.11, 3.13 and 3.15 locally; CI covers 3.10 to 3.13. The Gradio profile and a Node cross-check are planned for 0.2.
263
+
264
+ ## Troubleshooting
265
+
266
+ | Symptom | Cause | Fix |
267
+ |---|---|---|
268
+ | A price still renders as math | The text was not passed through `normalize` before the renderer, or it is inside a code span or code block (protected on purpose) | Normalize the whole answer string right before rendering |
269
+ | `TypeError: text must be str` | Bytes were passed | `data.decode("utf-8")` first |
270
+ | `ValueError: unknown profile` | Misspelled profile | Use `remark` or `streamlit` |
271
+ | `RuntimeError: feed() called after finish()` | Reused a finished stream | Create a new `StreamNormalizer` per answer |
272
+ | `mathfence: error: file not found` (exit 2) | Wrong path | Check the path, or pass `-` to read standard input |
273
+ | A real formula was escaped | Spaces just inside the dollars, or two plain words in a row | Write `$x^2$` without edge spaces, or use `\( \)` / `$$` |
274
+
275
+ ## Versions
276
+
277
+ Semantic Versioning. While the major version is 0, a minor release may change the API; changes are listed in [CHANGELOG.md](https://github.com/LeeGyeongPil/mathfence/blob/v0.1.3/CHANGELOG.md).
278
+
279
+ ## Development
280
+
281
+ ```bash
282
+ uv sync
283
+ uv run pytest -q
284
+ uv run python bench/compare.py
285
+ ```
286
+
287
+ ## License
288
+
289
+ MIT.
@@ -0,0 +1,15 @@
1
+ mathfence/__init__.py,sha256=lKF1I_UC9oTJVUUBprvvp_b_LR5qT1eB-iqlQW_QC80,486
2
+ mathfence/cli.py,sha256=Q6NtK0kxgDwwLpT-nbQTSx8RCrDh_x0rzOnB97u7Qsc,7698
3
+ mathfence/core.py,sha256=1Y_krU-vSLWbmjAiEIA3cbqv9WKhiIiPPTWySfoww5Q,5095
4
+ mathfence/delimiters.py,sha256=bRSCEgmuacgJ-ZrAifDRiRLecod_b_fb4b9fo6prYdk,5767
5
+ mathfence/dollars.py,sha256=STcmUG9K4yXBE16vstdsALGOAJQDXNVDGC-Mc_bAW_I,9132
6
+ mathfence/i18n.py,sha256=U7KfdzrU7ek8yLaranjYiS8mPNhbBx55ZtMqSCobf0I,13154
7
+ mathfence/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ mathfence/regions.py,sha256=PJOnSdg1xBI82WHnmmlKEs-PNI6jFBfWq6UuXJ2mSXI,10146
9
+ mathfence/rules.py,sha256=CUYa3rx5CbAkFHLaLEWEUsJxcvmefY8LgMORCzORkjk,3578
10
+ mathfence/stream.py,sha256=_b54L4zu4IMJXBWS7V4RTthf1Nll66apI61d0-KkQvc,2833
11
+ mathfence-0.1.3.dist-info/METADATA,sha256=tDZyAY7BC49bi7QJcO5Q17u_8MJ2uMvRj8E5VH7nDBQ,13387
12
+ mathfence-0.1.3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ mathfence-0.1.3.dist-info/entry_points.txt,sha256=cVKMGm9g_cKpXTELmzKAWtchcrLPEzxyiFakCtoYwTE,49
14
+ mathfence-0.1.3.dist-info/licenses/LICENSE,sha256=RRsvuvgBgx_uEpuct2Q4NeA9z27j12FFqpzQt1KVHL0,1069
15
+ mathfence-0.1.3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mathfence = mathfence.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LeeGyeongPil
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.