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.
mathfence/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """mathfence: make LLM Markdown safe for ``$``-math renderers.
2
+
3
+ >>> import mathfence
4
+ >>> mathfence.normalize("It costs $5 and $10, area $x^2$.")
5
+ 'It costs \\\\$5 and \\\\$10, area $x^2$.'
6
+ """
7
+
8
+ from .core import PROFILES, Decision, Result, analyze, normalize
9
+ from .stream import StreamNormalizer, StreamStats
10
+
11
+ __version__ = "0.1.3"
12
+
13
+ __all__ = [
14
+ "PROFILES",
15
+ "Decision",
16
+ "Result",
17
+ "StreamNormalizer",
18
+ "StreamStats",
19
+ "__version__",
20
+ "analyze",
21
+ "normalize",
22
+ ]
mathfence/cli.py ADDED
@@ -0,0 +1,217 @@
1
+ """``mathfence`` command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import re
9
+ import sys
10
+ import unicodedata
11
+ from collections.abc import Sequence
12
+ from dataclasses import asdict
13
+ from typing import NoReturn
14
+
15
+ from . import __version__
16
+ from .core import PROFILES, Result, analyze
17
+ from .i18n import LANGS, message, resolve_lang
18
+
19
+ _FORMATS = ("text", "json")
20
+
21
+
22
+ class _UsageError(Exception):
23
+ """A command-line mistake; ``key``/``params`` pick the localized message."""
24
+
25
+ def __init__(self, key: str, **params: str) -> None:
26
+ super().__init__(key)
27
+ self.key = key
28
+ self.params = params
29
+
30
+
31
+ class _Parser(argparse.ArgumentParser):
32
+ def error(self, message: str) -> NoReturn: # noqa: A002 - argparse API
33
+ # Map argparse's English sentences to message keys so both languages work.
34
+ unknown = re.match(r"unrecognized arguments: (.*)$", message)
35
+ missing = re.match(r"argument (\S+): expected \S+ argument", message)
36
+ if unknown:
37
+ raise _UsageError("error.unknown_option", option=unknown.group(1))
38
+ if missing:
39
+ raise _UsageError("error.missing_value", option=missing.group(1))
40
+ raise _UsageError("error.usage_generic")
41
+
42
+
43
+ def _build_parser() -> argparse.ArgumentParser:
44
+ p = _Parser(prog="mathfence", add_help=False, allow_abbrev=False)
45
+ p.add_argument("files", nargs="*")
46
+ p.add_argument("--profile", default="remark")
47
+ p.add_argument("--explain", action="store_true")
48
+ p.add_argument("--format", dest="fmt", default="text")
49
+ p.add_argument("--check", action="store_true")
50
+ p.add_argument("--lang", default=None)
51
+ p.add_argument("--version", action="store_true")
52
+ p.add_argument("-h", "--help", action="store_true")
53
+ return p
54
+
55
+
56
+ def _prescan_lang(argv: Sequence[str]) -> str | None:
57
+ """Find ``--lang`` before full parsing so even usage errors use it."""
58
+ for i, arg in enumerate(argv):
59
+ if arg == "--lang" and i + 1 < len(argv):
60
+ return argv[i + 1]
61
+ if arg.startswith("--lang="):
62
+ return arg.split("=", 1)[1]
63
+ return None
64
+
65
+
66
+ def _read(path: str, lang: str) -> str:
67
+ try:
68
+ if path == "-":
69
+ return sys.stdin.buffer.read().decode("utf-8")
70
+ with open(path, "rb") as fh:
71
+ return fh.read().decode("utf-8")
72
+ except FileNotFoundError:
73
+ raise _Fail(message(lang, "error.file_not_found", path=path)) from None
74
+ except (IsADirectoryError, PermissionError, OSError):
75
+ raise _Fail(message(lang, "error.not_a_file", path=path)) from None
76
+ except UnicodeDecodeError:
77
+ raise _Fail(message(lang, "error.not_utf8", path=path)) from None
78
+
79
+
80
+ class _Fail(Exception):
81
+ """A user-facing error: the text is printed and the exit status is 2."""
82
+
83
+
84
+ def _short(source: str, limit: int = 32) -> str:
85
+ flat = source.replace("\n", "\\n")
86
+ return flat if len(flat) <= limit else flat[: limit - 1] + "…"
87
+
88
+
89
+ def _width(text: str) -> int:
90
+ """Display width: East Asian wide characters take two columns."""
91
+ return sum(2 if unicodedata.east_asian_width(c) in "WF" else 1 for c in text)
92
+
93
+
94
+ def _pad(text: str, width: int) -> str:
95
+ return text + " " * (width - _width(text))
96
+
97
+
98
+ def _explain_table(result: Result, path: str, lang: str) -> str:
99
+ if not result.decisions:
100
+ return message(lang, "explain.none") + "\n"
101
+ header = (
102
+ message(lang, "explain.col.position"),
103
+ message(lang, "explain.col.action"),
104
+ message(lang, "explain.col.rule"),
105
+ message(lang, "explain.col.source"),
106
+ message(lang, "explain.col.reason"),
107
+ )
108
+ rows = [
109
+ (
110
+ f"{d.line}:{d.column}",
111
+ d.action,
112
+ d.rule,
113
+ _short(d.source),
114
+ message(lang, "reason." + d.rule),
115
+ )
116
+ for d in result.decisions
117
+ ]
118
+ widths = [max(_width(header[c]), *(_width(r[c]) for r in rows)) for c in range(4)]
119
+ lines = []
120
+ for row in (header, *rows):
121
+ cells = [_pad(row[c], widths[c]) for c in range(4)] + [row[4]]
122
+ lines.append(" ".join(cells).rstrip())
123
+ lines.append("")
124
+ lines.append(message(lang, "explain.summary", total=len(result.decisions), path=path))
125
+ return "\n".join(lines) + "\n"
126
+
127
+
128
+ def _json_report(result: Result, path: str, profile: str, lang: str) -> str:
129
+ decisions = []
130
+ for d in result.decisions:
131
+ item = asdict(d)
132
+ item["reason"] = message(lang, "reason." + d.rule)
133
+ decisions.append(item)
134
+ report = {
135
+ "file": path,
136
+ "profile": profile,
137
+ "changed": result.changed,
138
+ "text": result.text,
139
+ "decisions": decisions,
140
+ }
141
+ return json.dumps(report, ensure_ascii=False, indent=2) + "\n"
142
+
143
+
144
+ def _write(stream: object, text: str) -> None:
145
+ write = getattr(stream, "write")
146
+ write(text)
147
+
148
+
149
+ def main(argv: Sequence[str] | None = None) -> int:
150
+ """Entry point; returns the exit status (0, 1 or 2)."""
151
+ args_in = list(sys.argv[1:] if argv is None else argv)
152
+ lang = resolve_lang(_prescan_lang(args_in), os.environ)
153
+ for stream in (sys.stdout, sys.stderr):
154
+ try:
155
+ stream.reconfigure(encoding="utf-8") # type: ignore[union-attr]
156
+ except (AttributeError, ValueError):
157
+ pass
158
+ try:
159
+ args = _build_parser().parse_intermixed_args(args_in)
160
+ if args.lang is not None:
161
+ if args.lang not in LANGS:
162
+ raise _Fail(message(lang, "error.lang", value=args.lang))
163
+ if args.help:
164
+ _write(sys.stdout, message(lang, "help.text"))
165
+ return 0
166
+ if args.version:
167
+ _write(sys.stdout, f"mathfence {__version__}\n")
168
+ return 0
169
+ if args.profile not in PROFILES:
170
+ raise _Fail(message(lang, "error.profile", value=args.profile, choices=", ".join(PROFILES)))
171
+ if args.fmt not in _FORMATS:
172
+ raise _Fail(message(lang, "error.format", value=args.fmt))
173
+ paths = args.files or ["-"]
174
+ if (args.explain or args.fmt == "json") and not args.check and len(paths) > 1:
175
+ option = "--explain" if args.explain else "--format json"
176
+ raise _Fail(message(lang, "error.single_input", option=option))
177
+ return _run(args, paths, lang)
178
+ except _UsageError as exc:
179
+ _write(sys.stderr, message(lang, exc.key, **exc.params) + "\n")
180
+ return 2
181
+ except _Fail as exc:
182
+ _write(sys.stderr, str(exc) + "\n")
183
+ return 2
184
+
185
+
186
+ def _run(args: argparse.Namespace, paths: list[str], lang: str) -> int:
187
+ if args.check:
188
+ changed = 0
189
+ for path in paths:
190
+ if analyze(_read(path, lang), profile=args.profile).changed:
191
+ changed += 1
192
+ _write(sys.stdout, message(lang, "check.would_change", path=_name(path, lang)) + "\n")
193
+ if not changed:
194
+ _write(sys.stdout, message(lang, "check.clean", count=len(paths)) + "\n")
195
+ return 1 if changed else 0
196
+ outputs = []
197
+ for path in paths:
198
+ result = analyze(_read(path, lang), profile=args.profile)
199
+ name = _name(path, lang)
200
+ if args.fmt == "json":
201
+ outputs.append(_json_report(result, name, args.profile, lang))
202
+ elif args.explain:
203
+ outputs.append(_explain_table(result, name, lang))
204
+ elif len(paths) > 1:
205
+ outputs.append(f"==> {name} <==\n{result.text}" + ("" if result.text.endswith("\n") else "\n"))
206
+ else:
207
+ outputs.append(result.text)
208
+ _write(sys.stdout, "".join(outputs))
209
+ return 0
210
+
211
+
212
+ def _name(path: str, lang: str) -> str:
213
+ return message(lang, "stdin.name") if path == "-" else path
214
+
215
+
216
+ if __name__ == "__main__": # pragma: no cover
217
+ raise SystemExit(main())
mathfence/core.py ADDED
@@ -0,0 +1,150 @@
1
+ """Public entry points: :func:`normalize` and :func:`analyze`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from bisect import bisect_right
6
+ from dataclasses import dataclass, field
7
+ from typing import Literal
8
+
9
+ from . import delimiters, dollars, regions
10
+ from . import rules
11
+ from .rules import Raw
12
+
13
+ PROFILES: tuple[str, ...] = ("remark", "streamlit")
14
+
15
+ Action = Literal["keep_math", "convert", "escape", "protect"]
16
+ Kind = Literal["inline", "display", "currency", "stray", "code", "url", "html"]
17
+
18
+ _SOURCE_LIMIT = 120
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Decision:
23
+ """One thing mathfence decided, with the rule that decided it.
24
+
25
+ ``offset``, ``line`` (1-based) and ``column`` (1-based, in characters) point
26
+ into the *input* text. ``source`` is the original fragment, clipped to
27
+ 120 characters.
28
+ """
29
+
30
+ offset: int
31
+ line: int
32
+ column: int
33
+ source: str
34
+ action: Action
35
+ kind: Kind
36
+ rule: str
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Result:
41
+ """What :func:`analyze` returns."""
42
+
43
+ text: str
44
+ decisions: list[Decision] = field(default_factory=list)
45
+ changed: bool = False
46
+
47
+
48
+ def check_input(text: object, profile: str) -> None:
49
+ """Raise ``TypeError`` / ``ValueError`` for bad arguments."""
50
+ if not isinstance(text, str):
51
+ hint = " (decode bytes with .decode('utf-8') first)" if isinstance(text, (bytes, bytearray)) else ""
52
+ raise TypeError(f"text must be str, got {type(text).__name__}{hint}")
53
+ if profile not in PROFILES:
54
+ raise ValueError(f"unknown profile {profile!r}; choose one of: {', '.join(PROFILES)}")
55
+
56
+
57
+ def _clip(s: str) -> str:
58
+ return s if len(s) <= _SOURCE_LIMIT else s[: _SOURCE_LIMIT - 1] + "…"
59
+
60
+
61
+ def run(text: str, profile: str, streaming: bool = False) -> Result:
62
+ """Normalize ``text`` (arguments already validated).
63
+
64
+ Decisions describe the first pass. A second pass runs over a changed text
65
+ until it stops changing (at most three more), which makes the result
66
+ idempotent even when a rewrite exposes new structure to the scanner.
67
+ """
68
+ first = _single_pass(text, profile, streaming)
69
+ if streaming or not first.changed:
70
+ return first
71
+ out = first.text
72
+ for _ in range(3):
73
+ again = _single_pass(out, profile, False).text
74
+ if again == out:
75
+ break
76
+ out = again
77
+ return Result(out, first.decisions, out != text)
78
+
79
+
80
+ def _single_pass(text: str, profile: str, streaming: bool) -> Result:
81
+ if "$" not in text and "\\(" not in text and "\\[" not in text:
82
+ return Result(text, [], False)
83
+ first = regions.scan(text, streaming=streaming)
84
+ conv = delimiters.convert(text, first.regions, streaming=streaming)
85
+ if conv.edits:
86
+ mid = conv.text
87
+ second = regions.scan(mid, streaming=streaming)
88
+ else:
89
+ mid, second = text, first
90
+ out, dollar_raws = dollars.process(
91
+ mid, second.regions, profile=profile, streaming=streaming, display_hints=conv.display_starts
92
+ )
93
+
94
+ raws: list[Raw] = []
95
+ for r in first.regions:
96
+ if r.rule == rules.STREAM_PENDING:
97
+ continue # reported by the dollar pass
98
+ piece = text[r.start : r.end]
99
+ if "$" in piece or "\\(" in piece or "\\[" in piece:
100
+ raws.append(Raw(r.start, piece, "protect", r.kind, r.rule))
101
+ raws.extend(conv.raws)
102
+ for r in dollar_raws:
103
+ if r.action == "keep_math" and delimiters.inside_edit(conv.edits, r.offset):
104
+ continue # already reported as a "convert" decision
105
+ raws.append(r._replace(offset=delimiters.to_original(conv.edits, r.offset)))
106
+ raws.sort(key=lambda r: r.offset)
107
+
108
+ newlines = [i for i, c in enumerate(text) if c == "\n"]
109
+ decisions: list[Decision] = []
110
+ for r in raws:
111
+ k = bisect_right(newlines, r.offset - 1)
112
+ line_start = newlines[k - 1] + 1 if k else 0
113
+ decisions.append(
114
+ Decision(
115
+ offset=r.offset,
116
+ line=k + 1,
117
+ column=r.offset - line_start + 1,
118
+ source=_clip(r.source),
119
+ action=r.action, # type: ignore[arg-type]
120
+ kind=r.kind, # type: ignore[arg-type]
121
+ rule=r.rule,
122
+ )
123
+ )
124
+ return Result(out, decisions, out != text)
125
+
126
+
127
+ def analyze(text: str, *, profile: str = "remark") -> Result:
128
+ """Normalize ``text`` and report every decision.
129
+
130
+ Args:
131
+ text: Markdown as produced by an LLM.
132
+ profile: ``"remark"`` (default; any renderer reading ``$``/``$$``) or
133
+ ``"streamlit"`` (block math on its own lines).
134
+
135
+ Raises:
136
+ TypeError: ``text`` is not a ``str``.
137
+ ValueError: ``profile`` is not one of :data:`PROFILES`.
138
+ """
139
+ check_input(text, profile)
140
+ return run(text, profile)
141
+
142
+
143
+ def normalize(text: str, *, profile: str = "remark") -> str:
144
+ """Return ``text`` ready for a Markdown renderer that reads ``$`` math.
145
+
146
+ Code, URLs and HTML are copied unchanged; ``\\( \\)`` and ``\\[ \\]`` become
147
+ ``$ $`` and ``$$ $$``; every ``$`` that is not math becomes ``\\$``.
148
+ """
149
+ check_input(text, profile)
150
+ return run(text, profile).text
@@ -0,0 +1,168 @@
1
+ """Rewrite ``\\( … \\)`` and ``\\[ … \\]`` into ``$ … $`` and ``$$ … $$``.
2
+
3
+ Only text outside protected regions is touched. The delimiters are replaced
4
+ in place, so list indentation and ``>`` quote prefixes on continuation lines
5
+ survive untouched. Brackets that cannot be converted safely are left as is.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import NamedTuple
12
+
13
+ from . import rules
14
+ from .regions import PARA, Region
15
+ from .rules import Raw
16
+
17
+ _OPEN = re.compile(r"\\[(\[]")
18
+
19
+
20
+ class Edit(NamedTuple):
21
+ """One replacement: ``text[orig_start:orig_end]`` became ``mid[mid_start:mid_end]``."""
22
+
23
+ orig_start: int
24
+ orig_end: int
25
+ mid_start: int
26
+ mid_end: int
27
+
28
+
29
+ class Converted(NamedTuple):
30
+ text: str
31
+ edits: list[Edit]
32
+ raws: list[Raw] # offsets are in the *original* text
33
+ display_starts: set[int] # mid offsets of converted ``$$`` pairs
34
+
35
+
36
+ def _odd_backslashes_before(text: str, idx: int) -> bool:
37
+ n = 0
38
+ k = idx - 1
39
+ while k >= 0 and text[k] == "\\":
40
+ n += 1
41
+ k -= 1
42
+ return n % 2 == 1
43
+
44
+
45
+ def _find_closer(text: str, start: int, limit: int, char: str) -> int:
46
+ pat = "\\" + char
47
+ k = start
48
+ while True:
49
+ k = text.find(pat, k, limit)
50
+ if k == -1:
51
+ return -1
52
+ if not _odd_backslashes_before(text, k):
53
+ return k
54
+ k += 1
55
+
56
+
57
+ def _segments(text: str, regions: tuple[Region, ...]) -> list[tuple[int, int]]:
58
+ segs: list[tuple[int, int]] = []
59
+ cursor = 0
60
+ for r in regions:
61
+ if cursor < r.start:
62
+ segs.append((cursor, r.start))
63
+ cursor = max(cursor, r.end)
64
+ if cursor < len(text):
65
+ segs.append((cursor, len(text)))
66
+ return segs
67
+
68
+
69
+ def convert(text: str, regions: tuple[Region, ...], *, streaming: bool = False) -> Converted:
70
+ """Convert bracket delimiters outside ``regions``.
71
+
72
+ With ``streaming=True`` a closing bracket that touches the end of the text
73
+ is not converted yet: the next character may change how it must be written.
74
+ """
75
+ out: list[str] = []
76
+ edits: list[Edit] = []
77
+ raws: list[Raw] = []
78
+ display_starts: set[int] = set()
79
+ last = 0
80
+ mid_len = 0
81
+ for seg_start, seg_end in _segments(text, regions):
82
+ pos = seg_start
83
+ while True:
84
+ m = _OPEN.search(text, pos, seg_end)
85
+ if not m:
86
+ break
87
+ if _odd_backslashes_before(text, m.start()):
88
+ pos = m.start() + 1
89
+ continue
90
+ display = text[m.start() + 1] == "["
91
+ para = PARA.search(text, m.end(), seg_end)
92
+ limit = para.start() if para else seg_end
93
+ k = _find_closer(text, m.end(), limit, "]" if display else ")")
94
+ if k == -1 or (streaming and k + 2 == len(text)):
95
+ pos = m.end()
96
+ continue
97
+ end = k + 2
98
+ raw_body = text[m.end() : k]
99
+ source = text[m.start() : end]
100
+ after = text[end] if end < len(text) else ""
101
+ replacement, kind, rule = _rewrite(raw_body, after, display)
102
+ pos = end
103
+ if replacement is None:
104
+ if raw_body.strip():
105
+ raws.append(Raw(m.start(), source, "protect", "stray", rules.BRACKET_AMBIGUOUS))
106
+ continue
107
+ out.append(text[last : m.start()])
108
+ mid_len += m.start() - last
109
+ if display:
110
+ display_starts.add(mid_len)
111
+ out.append(replacement)
112
+ edits.append(Edit(m.start(), end, mid_len, mid_len + len(replacement)))
113
+ mid_len += len(replacement)
114
+ last = end
115
+ raws.append(Raw(m.start(), source, "convert", kind, rule))
116
+ out.append(text[last:])
117
+ return Converted("".join(out), edits, raws, display_starts)
118
+
119
+
120
+ def _rewrite(raw_body: str, after: str, display: bool) -> tuple[str | None, str, str]:
121
+ """Return ``(replacement, kind, rule)``; ``replacement`` is ``None`` to leave the brackets."""
122
+ body = raw_body.strip()
123
+ if not body:
124
+ return None, "stray", rules.BRACKET_AMBIGUOUS
125
+ if display:
126
+ if "$$" in body or rules.judge_double(body) is not None:
127
+ return None, "display", rules.BRACKET_AMBIGUOUS
128
+ inner = raw_body if "\n" in raw_body else body
129
+ return "$$" + inner + "$$", "display", rules.BRACKET_DISPLAY
130
+ double_ok = "$$" not in body and rules.judge_double(body) is None
131
+ if "$" in body:
132
+ if double_ok:
133
+ return "$$" + body + "$$", "inline", rules.BRACKET_HAS_DOLLAR
134
+ return None, "inline", rules.BRACKET_AMBIGUOUS
135
+ if rules.judge_single(body, after) is None:
136
+ return "$" + body + "$", "inline", rules.BRACKET_INLINE
137
+ if double_ok:
138
+ return "$$" + body + "$$", "inline", rules.BRACKET_INLINE_DOUBLE
139
+ return None, "inline", rules.BRACKET_AMBIGUOUS
140
+
141
+
142
+ def _last_edit_index(edits: list[Edit], mid_offset: int) -> int:
143
+ """Number of edits starting at or before ``mid_offset`` (binary search)."""
144
+ lo, hi = 0, len(edits)
145
+ while lo < hi:
146
+ half = (lo + hi) // 2
147
+ if edits[half].mid_start <= mid_offset:
148
+ lo = half + 1
149
+ else:
150
+ hi = half
151
+ return lo
152
+
153
+
154
+ def inside_edit(edits: list[Edit], mid_offset: int) -> bool:
155
+ """True if ``mid_offset`` falls inside a converted piece."""
156
+ lo = _last_edit_index(edits, mid_offset)
157
+ return lo > 0 and mid_offset < edits[lo - 1].mid_end
158
+
159
+
160
+ def to_original(edits: list[Edit], mid_offset: int) -> int:
161
+ """Map an offset in the converted text back to the original text."""
162
+ lo = _last_edit_index(edits, mid_offset)
163
+ if lo == 0:
164
+ return mid_offset
165
+ e = edits[lo - 1]
166
+ if mid_offset >= e.mid_end:
167
+ return e.orig_end + (mid_offset - e.mid_end)
168
+ return e.orig_start