mathfence 0.1.3__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 (57) hide show
  1. mathfence-0.1.3/.github/ISSUE_TEMPLATE/bug.yml +22 -0
  2. mathfence-0.1.3/.github/ISSUE_TEMPLATE/question.yml +11 -0
  3. mathfence-0.1.3/.github/workflows/ci.yml +107 -0
  4. mathfence-0.1.3/.gitignore +38 -0
  5. mathfence-0.1.3/CHANGELOG.md +37 -0
  6. mathfence-0.1.3/LICENSE +21 -0
  7. mathfence-0.1.3/PKG-INFO +289 -0
  8. mathfence-0.1.3/README.ko.md +265 -0
  9. mathfence-0.1.3/README.md +265 -0
  10. mathfence-0.1.3/SECURITY.md +7 -0
  11. mathfence-0.1.3/bench/baselines.py +26 -0
  12. mathfence-0.1.3/bench/compare.py +96 -0
  13. mathfence-0.1.3/docs/demo/before-after.en.html +22 -0
  14. mathfence-0.1.3/docs/demo/before-after.ko.html +22 -0
  15. mathfence-0.1.3/docs/demo/streaming.en.html +16 -0
  16. mathfence-0.1.3/docs/demo/streaming.ko.html +16 -0
  17. mathfence-0.1.3/docs/images/01-raw-answer.png +0 -0
  18. mathfence-0.1.3/docs/images/02-normalized.png +0 -0
  19. mathfence-0.1.3/docs/images/03-explain.ko.png +0 -0
  20. mathfence-0.1.3/docs/images/03-explain.png +0 -0
  21. mathfence-0.1.3/docs/images/04-stream.png +0 -0
  22. mathfence-0.1.3/docs/images/05-bench.png +0 -0
  23. mathfence-0.1.3/docs/images/before-after.ko.png +0 -0
  24. mathfence-0.1.3/docs/images/before-after.png +0 -0
  25. mathfence-0.1.3/docs/images/streaming.ko.png +0 -0
  26. mathfence-0.1.3/docs/images/streaming.png +0 -0
  27. mathfence-0.1.3/examples/answer.md +27 -0
  28. mathfence-0.1.3/examples/render_compare.py +149 -0
  29. mathfence-0.1.3/examples/stream_demo.py +8 -0
  30. mathfence-0.1.3/examples/streamlit_chat.py +122 -0
  31. mathfence-0.1.3/pyproject.toml +48 -0
  32. mathfence-0.1.3/src/mathfence/__init__.py +22 -0
  33. mathfence-0.1.3/src/mathfence/cli.py +217 -0
  34. mathfence-0.1.3/src/mathfence/core.py +150 -0
  35. mathfence-0.1.3/src/mathfence/delimiters.py +168 -0
  36. mathfence-0.1.3/src/mathfence/dollars.py +242 -0
  37. mathfence-0.1.3/src/mathfence/i18n.py +188 -0
  38. mathfence-0.1.3/src/mathfence/py.typed +0 -0
  39. mathfence-0.1.3/src/mathfence/regions.py +264 -0
  40. mathfence-0.1.3/src/mathfence/rules.py +123 -0
  41. mathfence-0.1.3/src/mathfence/stream.py +76 -0
  42. mathfence-0.1.3/tests/corpus/cases.json +707 -0
  43. mathfence-0.1.3/tests/corpus/streams.json +18 -0
  44. mathfence-0.1.3/tests/fuzzgen.py +21 -0
  45. mathfence-0.1.3/tests/judge.py +60 -0
  46. mathfence-0.1.3/tests/test_bench.py +32 -0
  47. mathfence-0.1.3/tests/test_cli.py +155 -0
  48. mathfence-0.1.3/tests/test_corpus.py +45 -0
  49. mathfence-0.1.3/tests/test_delimiters.py +66 -0
  50. mathfence-0.1.3/tests/test_dollars.py +84 -0
  51. mathfence-0.1.3/tests/test_i18n.py +140 -0
  52. mathfence-0.1.3/tests/test_invariants.py +60 -0
  53. mathfence-0.1.3/tests/test_package.py +46 -0
  54. mathfence-0.1.3/tests/test_profiles.py +60 -0
  55. mathfence-0.1.3/tests/test_regions.py +88 -0
  56. mathfence-0.1.3/tests/test_stream.py +162 -0
  57. mathfence-0.1.3/uv.lock +213 -0
@@ -0,0 +1,22 @@
1
+ name: 버그 / Bug
2
+ description: README대로 했는데 다르게 동작해요 / Something does not work as the README says
3
+ labels: [bug]
4
+ body:
5
+ - type: textarea
6
+ id: what
7
+ attributes:
8
+ label: 무엇이 일어났나요? / What happened?
9
+ description: 실행한 명령과 나온 메시지를 그대로 붙여 주세요. / Paste the command and the output.
10
+ validations:
11
+ required: true
12
+ - type: textarea
13
+ id: expected
14
+ attributes:
15
+ label: 기대한 결과 / Expected
16
+ - type: input
17
+ id: env
18
+ attributes:
19
+ label: 환경 / Environment
20
+ placeholder: "macOS 15 (M3) · Ubuntu 24.04 · Windows 11 / uv 0.x / mock or real mode"
21
+ validations:
22
+ required: true
@@ -0,0 +1,11 @@
1
+ name: 질문 / Question
2
+ description: 이해가 안 되는 부분이나 더 알고 싶은 점 / Something unclear or worth explaining
3
+ labels: [question]
4
+ body:
5
+ - type: textarea
6
+ id: question
7
+ attributes:
8
+ label: 질문 / Question
9
+ description: README의 어느 부분(절 제목)에 대한 질문인지 알려 주세요. / Which README section is this about?
10
+ validations:
11
+ required: true
@@ -0,0 +1,107 @@
1
+ # Pure string processing: no keys, no network after the dependencies are installed.
2
+ # Dependencies come from uv.lock, so a scheduled run would only repeat the same test.
3
+ # Every step also writes its output to $RUNNER_TEMP/ci-logs; the last step always runs
4
+ # and puts the step results and the tail of a failing step's output into the job summary.
5
+ name: ci
6
+ on:
7
+ push:
8
+ pull_request:
9
+ workflow_dispatch:
10
+ permissions:
11
+ contents: read
12
+ defaults:
13
+ run:
14
+ # An explicit "bash" makes the runner use "bash -eo pipefail", so "cmd | tee log"
15
+ # still fails the step when cmd fails.
16
+ shell: bash
17
+ jobs:
18
+ test:
19
+ runs-on: ubuntu-latest
20
+ timeout-minutes: 15
21
+ strategy:
22
+ fail-fast: false
23
+ matrix:
24
+ python: ["3.10", "3.11", "3.12", "3.13"]
25
+ env:
26
+ # Never let uv fetch another interpreter: the matrix Python must be the one tested.
27
+ UV_PYTHON_DOWNLOADS: never
28
+ steps:
29
+ - uses: actions/checkout@v5
30
+ - uses: actions/setup-python@v6
31
+ id: setup
32
+ with:
33
+ python-version: ${{ matrix.python }}
34
+ - name: Point uv at the matrix Python
35
+ run: echo "UV_PYTHON=${{ steps.setup.outputs.python-path }}" >> "$GITHUB_ENV"
36
+ - name: Install uv
37
+ id: install
38
+ run: |
39
+ mkdir -p "$RUNNER_TEMP/ci-logs"
40
+ python -m pip install "uv==0.13.9" 2>&1 | tee "$RUNNER_TEMP/ci-logs/install.log"
41
+ - name: Show versions and the checked-out files
42
+ id: versions
43
+ run: |
44
+ {
45
+ uname -sm
46
+ python -VV
47
+ uv --version
48
+ echo "UV_PYTHON=$UV_PYTHON"
49
+ echo "LANG=${LANG-unset} LC_ALL=${LC_ALL-unset}"
50
+ git log -1 --format='%H %s'
51
+ echo "tracked files: $(git ls-files | wc -l)"
52
+ } 2>&1 | tee "$RUNNER_TEMP/ci-logs/versions.log"
53
+ - name: uv sync --locked
54
+ id: sync
55
+ run: |
56
+ {
57
+ uv sync --locked
58
+ echo "project environment: $(.venv/bin/python -c 'import sys; print(sys.version.split()[0])')"
59
+ } 2>&1 | tee "$RUNNER_TEMP/ci-logs/sync.log"
60
+ - name: uv run pytest -q
61
+ id: test
62
+ run: uv run pytest -q 2>&1 | tee "$RUNNER_TEMP/ci-logs/test.log"
63
+ - name: uv run python bench/compare.py
64
+ id: bench
65
+ run: uv run python bench/compare.py 2>&1 | tee "$RUNNER_TEMP/ci-logs/bench.log"
66
+ - name: Job summary
67
+ if: always()
68
+ env:
69
+ PY: ${{ matrix.python }}
70
+ INSTALL: ${{ steps.install.outcome }}
71
+ VERSIONS: ${{ steps.versions.outcome }}
72
+ SYNC: ${{ steps.sync.outcome }}
73
+ TEST: ${{ steps.test.outcome }}
74
+ BENCH: ${{ steps.bench.outcome }}
75
+ run: |
76
+ logs="$RUNNER_TEMP/ci-logs"
77
+ {
78
+ echo "### Python $PY"
79
+ echo
80
+ echo "| step | outcome |"
81
+ echo "|---|---|"
82
+ echo "| install uv | ${INSTALL:-not run} |"
83
+ echo "| show versions | ${VERSIONS:-not run} |"
84
+ echo "| uv sync --locked | ${SYNC:-not run} |"
85
+ echo "| uv run pytest -q | ${TEST:-not run} |"
86
+ echo "| bench/compare.py | ${BENCH:-not run} |"
87
+ if [ -f "$logs/versions.log" ]; then
88
+ echo
89
+ echo '```'
90
+ cat "$logs/versions.log"
91
+ echo '```'
92
+ fi
93
+ for step in install versions sync test bench; do
94
+ var=$(echo "$step" | tr '[:lower:]' '[:upper:]')
95
+ if [ "${!var}" = "failure" ] && [ -f "$logs/$step.log" ]; then
96
+ echo
97
+ echo "#### $step failed (last 60 lines)"
98
+ echo '```'
99
+ tail -n 60 "$logs/$step.log"
100
+ echo '```'
101
+ fi
102
+ done
103
+ if [ "$INSTALL" != "success" ] && [ "$INSTALL" != "failure" ]; then
104
+ echo
105
+ echo "No command ran: checkout or setup-python failed first. Open that step's log."
106
+ fi
107
+ } >> "$GITHUB_STEP_SUMMARY"
@@ -0,0 +1,38 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ .venv/
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ .mypy_cache/
8
+ *.egg-info/
9
+
10
+ # Node
11
+ node_modules/
12
+ dist/
13
+ .next/
14
+
15
+ # 실행 산출물·모델·데이터 캐시
16
+ runs/
17
+ outputs/
18
+ .cache/
19
+ *.safetensors
20
+ *.gguf
21
+ *.bin
22
+
23
+ # 환경·비밀
24
+ .env
25
+ .env.*
26
+ !.env.example
27
+
28
+ # OS·에디터
29
+ .DS_Store
30
+ .vscode/
31
+ .idea/
32
+
33
+ # Flutter·Dart
34
+ .dart_tool/
35
+ build/
36
+ .flutter-plugins
37
+ .flutter-plugins-dependencies
38
+ coverage/
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
5
+
6
+ ## [0.1.3]
7
+
8
+ ### Changed
9
+ - CI: uv is pointed at the interpreter from setup-python (`UV_PYTHON`, no interpreter downloads), steps run with `bash -eo pipefail`, every step keeps its output, and a final step always writes the step results, the versions and the last 60 lines of a failing step to the job summary.
10
+
11
+ ## [0.1.2]
12
+
13
+ ### Changed
14
+ - CI: actions that run on Node 24 (`actions/checkout@v5`, `actions/setup-python@v6`), uv pinned to 0.13.9, read-only token, 15-minute job limit, a step that prints the Python and uv versions and the number of checked-out files, and no weekly schedule (dependencies are locked, so it only repeated the same run).
15
+ - `uv run pytest -q` now ends with the `N passed` summary line (the extra `-q` in the pytest settings was removed).
16
+
17
+ ## [0.1.1]
18
+
19
+ ### Fixed
20
+ - CI: install uv with pip after setup-python and sync with `uv sync --locked`.
21
+
22
+ ## [0.1.0]
23
+
24
+ ### Added
25
+ - `normalize()` and `analyze()`: rewrite `\( \)` and `\[ \]` to `$ $` and `$$ $$`, decide every other `$` by its pair, and escape currency and stray dollars as `\$`.
26
+ - Protected regions copied byte for byte: fenced code (also inside lists and quotes, also unclosed), indented code, code spans, HTML blocks and tags, autolinks, bare URLs.
27
+ - `StreamNormalizer` for token streams: holds a closing `$` at the end of the text until the next character arrives, leaves unclosed code spans alone and settles finished paragraphs and top-level list items whose settled part has no `$` or backslash so they are not processed again.
28
+ - Profiles `remark` (default) and `streamlit` (display math on its own lines, list and quote prefixes kept).
29
+ - `mathfence` command: `--explain` (table or JSON with a rule id per decision), `--check`, `--profile`, `--format`, `--lang en|ko`.
30
+ - English and Korean command line messages (`--lang`, `MATHFENCE_LANG`, `LC_ALL`, `LC_MESSAGES`, `LANG`).
31
+ - 94-case corpus, a lenient markdown-it-py judge and `bench/compare.py` comparing mathfence with no processing, escaping every `$` and a typical regex recipe.
32
+ - Streamlit replay example in `examples/streamlit_chat.py`.
33
+
34
+ [Unreleased]: https://github.com/LeeGyeongPil/mathfence/compare/v0.1.2...HEAD
35
+ [0.1.2]: https://github.com/LeeGyeongPil/mathfence/compare/v0.1.1...v0.1.2
36
+ [0.1.1]: https://github.com/LeeGyeongPil/mathfence/compare/v0.1.0...v0.1.1
37
+ [0.1.0]: https://github.com/LeeGyeongPil/mathfence/releases/tag/v0.1.0
@@ -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.
@@ -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.