academic-mathtype-engine 1.0.0__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.
- academic_mathtype/__init__.py +7 -0
- academic_mathtype/__main__.py +4 -0
- academic_mathtype/cli.py +80 -0
- academic_mathtype/compound.py +208 -0
- academic_mathtype/document.py +227 -0
- academic_mathtype/formula.py +181 -0
- academic_mathtype/native.py +236 -0
- academic_mathtype/opc.py +205 -0
- academic_mathtype/prefix.py +104 -0
- academic_mathtype/records.py +157 -0
- academic_mathtype_engine-1.0.0.dist-info/METADATA +86 -0
- academic_mathtype_engine-1.0.0.dist-info/RECORD +18 -0
- academic_mathtype_engine-1.0.0.dist-info/WHEEL +5 -0
- academic_mathtype_engine-1.0.0.dist-info/entry_points.txt +2 -0
- academic_mathtype_engine-1.0.0.dist-info/licenses/LICENSE +202 -0
- academic_mathtype_engine-1.0.0.dist-info/licenses/LICENSE_STATUS.md +5 -0
- academic_mathtype_engine-1.0.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +20 -0
- academic_mathtype_engine-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Generate and structurally validate native equation objects in Word documents."""
|
|
2
|
+
from .document import build_docx, validate_docx
|
|
3
|
+
from .formula import UnsupportedFormula, compile_latex
|
|
4
|
+
from .native import pack_ole
|
|
5
|
+
|
|
6
|
+
__version__ = "1.0.0"
|
|
7
|
+
__all__ = ["UnsupportedFormula", "build_docx", "compile_latex", "pack_ole", "validate_docx"]
|
academic_mathtype/cli.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Command-line interface for independent equation generation."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .document import build_docx, validate_docx
|
|
12
|
+
from .formula import compile_latex
|
|
13
|
+
from .native import pack_ole, read_body
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _commands():
|
|
17
|
+
parser = argparse.ArgumentParser(prog="academic-mathtype")
|
|
18
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
19
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
20
|
+
|
|
21
|
+
build = sub.add_parser("build", help="Generate an equation collection")
|
|
22
|
+
build.add_argument("input", type=Path)
|
|
23
|
+
build.add_argument("output", type=Path)
|
|
24
|
+
build.add_argument("--title", default="MathType equation collection")
|
|
25
|
+
build.add_argument("--per-page", type=int, default=5)
|
|
26
|
+
build.add_argument("--overwrite", action="store_true")
|
|
27
|
+
|
|
28
|
+
check = sub.add_parser("validate", help="Validate embedded equation objects and previews")
|
|
29
|
+
check.add_argument("document", type=Path)
|
|
30
|
+
check.add_argument("--expected", type=int, required=True)
|
|
31
|
+
|
|
32
|
+
sub.add_parser("doctor", help="Check native records and preview tools")
|
|
33
|
+
return parser
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _build(args):
|
|
37
|
+
if args.output.suffix.lower() != ".docx" or args.per_page < 1:
|
|
38
|
+
raise ValueError("Use a .docx output and a positive --per-page")
|
|
39
|
+
if not args.overwrite and args.output.exists():
|
|
40
|
+
raise FileExistsError(f"Output already exists: {args.output}")
|
|
41
|
+
with args.input.open("rb") as stream:
|
|
42
|
+
data = stream.read(2 * 1024 * 1024 + 1)
|
|
43
|
+
if len(data) > 2 * 1024 * 1024:
|
|
44
|
+
raise ValueError("Equation collection JSON exceeds 2 MiB")
|
|
45
|
+
cases = json.loads(data.decode("utf-8-sig"))
|
|
46
|
+
options = dict(title=args.title, per_page=args.per_page)
|
|
47
|
+
if args.overwrite:
|
|
48
|
+
build_docx(cases, args.output, **options)
|
|
49
|
+
else:
|
|
50
|
+
# Link a complete file into place. An intervening concurrent creator wins.
|
|
51
|
+
with tempfile.TemporaryDirectory(dir=args.output.resolve().parent) as directory:
|
|
52
|
+
staged = Path(directory) / "equations.docx"
|
|
53
|
+
build_docx(cases, staged, **options)
|
|
54
|
+
os.link(staged, args.output)
|
|
55
|
+
print(f"Built and structurally validated {len(cases)} objects: {args.output}")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def main(argv=None):
|
|
59
|
+
args = _commands().parse_args(argv)
|
|
60
|
+
try:
|
|
61
|
+
if args.command == "build":
|
|
62
|
+
_build(args)
|
|
63
|
+
elif args.command == "validate":
|
|
64
|
+
if args.expected < 1:
|
|
65
|
+
raise ValueError("--expected must be positive")
|
|
66
|
+
validate_docx(args.document, args.expected)
|
|
67
|
+
print(f"Structural validation passed: {args.document}")
|
|
68
|
+
elif args.command == "doctor":
|
|
69
|
+
body = compile_latex(r"\frac{x_i}{2}")
|
|
70
|
+
if read_body(pack_ole(body)) != body:
|
|
71
|
+
raise ValueError("Native equation self-test failed")
|
|
72
|
+
print(json.dumps({
|
|
73
|
+
"version": __version__, "backend": "independent",
|
|
74
|
+
"native_round_trip": "passed", "latex": shutil.which("latex"),
|
|
75
|
+
"dvipng": shutil.which("dvipng"),
|
|
76
|
+
}, ensure_ascii=False, indent=2))
|
|
77
|
+
return 0
|
|
78
|
+
except Exception as exc:
|
|
79
|
+
print(f"Error: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
80
|
+
return 1
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Flat, size-bounded MS-CFB version 3 storage for embedded equation streams."""
|
|
2
|
+
|
|
3
|
+
import struct
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
SECTOR = 512
|
|
7
|
+
MINI = 64
|
|
8
|
+
CUTOFF = 4096
|
|
9
|
+
MAX_FILE = 4 * 1024 * 1024
|
|
10
|
+
MAX_STREAMS = 32
|
|
11
|
+
FREE, END, FAT_SECTOR = 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD
|
|
12
|
+
SIGNATURE = bytes.fromhex("D0CF11E0A1B11AE1")
|
|
13
|
+
HEADER = struct.Struct("<8s16s5H6x9I")
|
|
14
|
+
ENTRY = struct.Struct("<64sHBBIII16sIQQIQ")
|
|
15
|
+
EMPTY = ENTRY.pack(b"", 0, 0, 0, FREE, FREE, FREE, bytes(16), 0, 0, 0, 0, 0)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def units(size, width):
|
|
19
|
+
return (size + width - 1) // width
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def words(values):
|
|
23
|
+
return struct.pack(f"<{len(values)}I", *values)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _table(data):
|
|
27
|
+
return struct.unpack(f"<{len(data) // 4}I", data)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _sort_key(name):
|
|
31
|
+
# This bounded profile accepts the ASCII stream identifiers used by OLE.
|
|
32
|
+
return len(name), name.upper()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _dir(name, kind, left, right, child, clsid, start, size, color=1):
|
|
36
|
+
label = (name + "\0").encode("utf-16le")
|
|
37
|
+
return ENTRY.pack(label, len(label), kind, color, left, right, child,
|
|
38
|
+
clsid, 0, 0, 0, start, size)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def write_compound(streams, clsid: UUID):
|
|
42
|
+
"""Create a v3 storage with mini and regular streams in one flat directory."""
|
|
43
|
+
if not 1 <= len(streams) <= MAX_STREAMS:
|
|
44
|
+
raise ValueError("CFB stream count outside supported range")
|
|
45
|
+
for name, value in streams.items():
|
|
46
|
+
if (not name.isascii() or not 1 <= len(name) <= 31 or
|
|
47
|
+
any(c in name for c in "\0:/!\\") or not isinstance(value, bytes)):
|
|
48
|
+
raise ValueError("Invalid CFB stream name or data")
|
|
49
|
+
names = sorted(streams, key=_sort_key)
|
|
50
|
+
if len({n.upper() for n in names}) != len(names):
|
|
51
|
+
raise ValueError("Duplicate CFB stream name")
|
|
52
|
+
if sum(map(len, streams.values())) > MAX_FILE:
|
|
53
|
+
raise ValueError("CFB streams exceed the 4 MiB object budget")
|
|
54
|
+
|
|
55
|
+
sectors, fat = [], []
|
|
56
|
+
mini, minifat = bytearray(), []
|
|
57
|
+
locations = {}
|
|
58
|
+
|
|
59
|
+
def allocate(data):
|
|
60
|
+
if not data:
|
|
61
|
+
return END
|
|
62
|
+
first = len(sectors)
|
|
63
|
+
for offset in range(0, len(data), SECTOR):
|
|
64
|
+
sectors.append(data[offset:offset + SECTOR].ljust(SECTOR, b"\0"))
|
|
65
|
+
fat.append(len(sectors))
|
|
66
|
+
fat[-1] = END
|
|
67
|
+
return first
|
|
68
|
+
|
|
69
|
+
for name in names:
|
|
70
|
+
data = streams[name]
|
|
71
|
+
if not data:
|
|
72
|
+
locations[name] = END
|
|
73
|
+
elif len(data) < CUTOFF:
|
|
74
|
+
start = len(minifat)
|
|
75
|
+
count = units(len(data), MINI)
|
|
76
|
+
locations[name] = start
|
|
77
|
+
mini.extend(data.ljust(count * MINI, b"\0"))
|
|
78
|
+
minifat.extend(range(start + 1, start + count + 1))
|
|
79
|
+
minifat[-1] = END
|
|
80
|
+
else:
|
|
81
|
+
locations[name] = allocate(data)
|
|
82
|
+
|
|
83
|
+
root_start = allocate(mini)
|
|
84
|
+
mf_size = units(len(minifat) * 4, SECTOR)
|
|
85
|
+
minifat.extend([FREE] * (mf_size * 128 - len(minifat)))
|
|
86
|
+
mf_start = allocate(words(minifat))
|
|
87
|
+
|
|
88
|
+
# The median tree has external leaves at two consecutive depths. Color
|
|
89
|
+
# the lowest internal level red to equalize root-to-leaf black heights.
|
|
90
|
+
entries = [None] * (len(names) + 1)
|
|
91
|
+
bottom = len(names).bit_length() - 1
|
|
92
|
+
|
|
93
|
+
def tree(lo, hi, depth):
|
|
94
|
+
if lo >= hi:
|
|
95
|
+
return FREE
|
|
96
|
+
mid = (lo + hi) // 2
|
|
97
|
+
name = names[mid]
|
|
98
|
+
entries[mid + 1] = _dir(name, 2, tree(lo, mid, depth + 1),
|
|
99
|
+
tree(mid + 1, hi, depth + 1), FREE, bytes(16),
|
|
100
|
+
locations[name], len(streams[name]),
|
|
101
|
+
int(depth == 0 or depth < bottom))
|
|
102
|
+
return mid + 1
|
|
103
|
+
|
|
104
|
+
child = tree(0, len(names), 0)
|
|
105
|
+
entries[0] = _dir("Root Entry", 5, FREE, FREE, child, clsid.bytes_le,
|
|
106
|
+
root_start, len(mini))
|
|
107
|
+
directory = allocate(b"".join(entries + [EMPTY] * (-len(entries) % 4)))
|
|
108
|
+
|
|
109
|
+
# FAT sectors also occupy FAT slots. The object budget keeps all FAT IDs
|
|
110
|
+
# in the header DIFAT (109 entries).
|
|
111
|
+
fat_count = units(len(sectors), 127)
|
|
112
|
+
fat_ids = list(range(len(sectors), len(sectors) + fat_count))
|
|
113
|
+
fat.extend([FAT_SECTOR] * fat_count)
|
|
114
|
+
if (len(fat) + 1) * SECTOR > MAX_FILE:
|
|
115
|
+
raise ValueError("CFB storage exceeds the 4 MiB object budget")
|
|
116
|
+
fat.extend([FREE] * (fat_count * 128 - len(fat)))
|
|
117
|
+
header = HEADER.pack(SIGNATURE, bytes(16), 0x3E, 3, 0xFFFE, 9, 6, 0,
|
|
118
|
+
fat_count, directory, 0, CUTOFF, mf_start, mf_size, END, 0)
|
|
119
|
+
difat = words(fat_ids + [FREE] * (109 - fat_count))
|
|
120
|
+
return header + difat + b"".join(sectors) + words(fat)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def read_compound(blob, clsid: UUID):
|
|
124
|
+
"""Read reachable flat streams. Bound traversal and reject aliased sectors."""
|
|
125
|
+
if not SECTOR * 2 <= len(blob) <= MAX_FILE or len(blob) % SECTOR:
|
|
126
|
+
raise ValueError("Invalid or oversized CFB file")
|
|
127
|
+
magic, _, _, version, order, shift, mini_shift, dirs, nf, directory, _, cutoff, mf, nm, df, nd = HEADER.unpack_from(blob)
|
|
128
|
+
if (magic, version, order, shift, mini_shift, dirs, cutoff, df, nd) != (
|
|
129
|
+
SIGNATURE, 3, 0xFFFE, 9, 6, 0, CUTOFF, END, 0):
|
|
130
|
+
raise ValueError("Unsupported CFB geometry or external DIFAT")
|
|
131
|
+
n = len(blob) // SECTOR - 1
|
|
132
|
+
difat = _table(blob[76:512])
|
|
133
|
+
ids = difat[:nf]
|
|
134
|
+
used = set(ids)
|
|
135
|
+
if (not 1 <= nf <= 109 or len(used) != nf or max(ids) >= n or
|
|
136
|
+
nf * 128 < n or any(v != FREE for v in difat[nf:])):
|
|
137
|
+
raise ValueError("Invalid CFB header DIFAT")
|
|
138
|
+
|
|
139
|
+
def sector(i):
|
|
140
|
+
return blob[(i + 1) * SECTOR:(i + 2) * SECTOR]
|
|
141
|
+
|
|
142
|
+
fat = _table(b"".join(sector(i) for i in ids))[:n]
|
|
143
|
+
if any(fat[i] != FAT_SECTOR for i in ids):
|
|
144
|
+
raise ValueError("Invalid FAT sector marker")
|
|
145
|
+
|
|
146
|
+
def chain(start, table, claimed, limit, expected=None):
|
|
147
|
+
result = []
|
|
148
|
+
while start != END:
|
|
149
|
+
if start >= len(table) or start in claimed or len(result) >= limit:
|
|
150
|
+
raise ValueError("Invalid, repeated or oversized CFB chain")
|
|
151
|
+
claimed.add(start)
|
|
152
|
+
result.append(start)
|
|
153
|
+
start = table[start]
|
|
154
|
+
if expected is not None and len(result) != expected:
|
|
155
|
+
raise ValueError("CFB chain length disagrees with stream size")
|
|
156
|
+
return result
|
|
157
|
+
|
|
158
|
+
def regular(start, count):
|
|
159
|
+
return b"".join(sector(i) for i in chain(start, fat, used, count, count))
|
|
160
|
+
|
|
161
|
+
directory_ids = chain(directory, fat, used, units(MAX_STREAMS + 1, 4))
|
|
162
|
+
records = list(ENTRY.iter_unpack(b"".join(sector(i) for i in directory_ids)))
|
|
163
|
+
if not records:
|
|
164
|
+
raise ValueError("Missing CFB directory")
|
|
165
|
+
|
|
166
|
+
def record(i):
|
|
167
|
+
label, length, kind, color, left, right, child, ident, _, _, _, start, size = records[i]
|
|
168
|
+
if not 2 <= length <= 64 or length % 2 or label[length-2:length] != b"\0\0":
|
|
169
|
+
raise ValueError("Malformed CFB directory name")
|
|
170
|
+
name = label[:length-2].decode("utf-16le")
|
|
171
|
+
if not name or not name.isascii() or "\0" in name or size > MAX_FILE:
|
|
172
|
+
raise ValueError("Unsupported CFB name or stream size")
|
|
173
|
+
return name, kind, color, left, right, child, ident, start, size
|
|
174
|
+
|
|
175
|
+
name, kind, _, lft, rgt, child, ident, start, size = record(0)
|
|
176
|
+
if (name, kind, lft, rgt, ident) != ("Root Entry", 5, FREE, FREE, clsid.bytes_le):
|
|
177
|
+
raise ValueError("Unexpected CFB root or equation CLSID")
|
|
178
|
+
if size % MINI:
|
|
179
|
+
raise ValueError("Unaligned root mini-stream")
|
|
180
|
+
mini = regular(start, units(size, SECTOR))[:size]
|
|
181
|
+
minifat = _table(regular(mf, nm))[:size // MINI]
|
|
182
|
+
mini_used, seen, result = set(), set(), {}
|
|
183
|
+
|
|
184
|
+
def visit(i, lower, upper):
|
|
185
|
+
if i == FREE:
|
|
186
|
+
return
|
|
187
|
+
if not 0 < i < len(records) or i in seen or len(seen) >= MAX_STREAMS:
|
|
188
|
+
raise ValueError("Cyclic or invalid CFB directory tree")
|
|
189
|
+
seen.add(i)
|
|
190
|
+
name, kind, color, left, right, child, _, start, size = record(i)
|
|
191
|
+
key = _sort_key(name)
|
|
192
|
+
if (kind != 2 or child != FREE or color not in (0, 1) or
|
|
193
|
+
(lower is not None and key <= lower) or (upper is not None and key >= upper)):
|
|
194
|
+
raise ValueError("Invalid flat CFB directory entry or ordering")
|
|
195
|
+
if size < CUTOFF:
|
|
196
|
+
count = units(size, MINI)
|
|
197
|
+
ids = chain(start, minifat, mini_used, count, count)
|
|
198
|
+
data = b"".join(mini[i * MINI:(i + 1) * MINI] for i in ids)
|
|
199
|
+
else:
|
|
200
|
+
data = regular(start, units(size, SECTOR))
|
|
201
|
+
result[name] = data[:size]
|
|
202
|
+
visit(left, lower, key)
|
|
203
|
+
visit(right, key, upper)
|
|
204
|
+
|
|
205
|
+
visit(child, None, None)
|
|
206
|
+
if len(seen) != sum(r[2] != 0 for r in records) - 1:
|
|
207
|
+
raise ValueError("Unreachable CFB directory entry")
|
|
208
|
+
return result
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Build native equation collections with OPC parts and independently drawn previews."""
|
|
2
|
+
|
|
3
|
+
from io import BytesIO
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import tempfile
|
|
9
|
+
from threading import RLock
|
|
10
|
+
|
|
11
|
+
from docx import Document
|
|
12
|
+
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
|
13
|
+
from docx.opc.constants import RELATIONSHIP_TYPE as RT
|
|
14
|
+
from docx.opc.packuri import PackURI
|
|
15
|
+
from docx.opc.part import Part
|
|
16
|
+
from docx.shared import Mm, Pt
|
|
17
|
+
from lxml import etree as ET
|
|
18
|
+
from PIL import Image, ImageChops
|
|
19
|
+
|
|
20
|
+
from .formula import COMMAND_SYMBOL, LEXEME, UnsupportedFormula, compile_latex
|
|
21
|
+
from .native import pack_ole, read_equation
|
|
22
|
+
from .opc import MAX_PACKAGE, O, OLE_TYPE, PROG_ID, R, V, W, equation_parts, open_package, replace_file, tag
|
|
23
|
+
|
|
24
|
+
_RENDER_LOCK = RLock()
|
|
25
|
+
_MAX_PIXELS = 16_000_000
|
|
26
|
+
_MAX_CASES = 1000
|
|
27
|
+
_GLYPH_TEX = {symbol: "\\" + command + " " for command, symbol in COMMAND_SYMBOL.items()
|
|
28
|
+
if not symbol.isascii() and command.isalpha()}
|
|
29
|
+
_GLYPH_TEX.update({"−": "-", "∑": r"\sum ", "∏": r"\prod ", "∫": r"\int ",
|
|
30
|
+
"ο": "o", "∥": r"\parallel ", "‖": r"\|", "·": r"\cdot "})
|
|
31
|
+
_GLYPH_TEX.update({a: r"\mathrm{" + b + "}" for a, b in zip("ΑΒΕΖΗΙΚΜΝΟΡΤΧ", "ABEZHIKMNOPTX")})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _render_source(source, *, mathtext=False):
|
|
35
|
+
# Re-emit only tokens consumed by the math grammar. Whitespace around TeX
|
|
36
|
+
# control words ends the word; literal input is never inserted into a TeX file.
|
|
37
|
+
pieces = []
|
|
38
|
+
for match in LEXEME.finditer(source):
|
|
39
|
+
token = match[0]
|
|
40
|
+
if token in {"∑", "∏", "∫"}:
|
|
41
|
+
# A literal Unicode operator is a CHAR in MTEF. Group the text-size
|
|
42
|
+
# glyph so TeX does not assign large-operator limits to its scripts.
|
|
43
|
+
pieces.append(token if mathtext else r"{\textstyle" + _GLYPH_TEX[token] + "}")
|
|
44
|
+
elif token in (r"\lVert", r"\rVert"):
|
|
45
|
+
pieces.append(r"\|")
|
|
46
|
+
elif mathtext and token in (r"\mod", r"\tfrac"):
|
|
47
|
+
pieces.append(r"\operatorname{mod}" if token == r"\mod" else r"\frac ")
|
|
48
|
+
elif token in _GLYPH_TEX:
|
|
49
|
+
pieces.append(_GLYPH_TEX[token])
|
|
50
|
+
elif token.startswith("\\") and token[1:].isalpha():
|
|
51
|
+
pieces.append(token + " ")
|
|
52
|
+
else:
|
|
53
|
+
pieces.append(token)
|
|
54
|
+
text = "".join(pieces)
|
|
55
|
+
if "^^" in text or any(c in text for c in "$%#~"):
|
|
56
|
+
raise UnsupportedFormula("Unsupported TeX special character in preview")
|
|
57
|
+
return text
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _check_pixels(image):
|
|
61
|
+
if image.width * image.height > _MAX_PIXELS:
|
|
62
|
+
raise ValueError("Preview exceeds the 16-megapixel limit")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _preview(source, inline):
|
|
66
|
+
use_tex = bool(shutil.which("latex") and shutil.which("dvipng"))
|
|
67
|
+
text = _render_source(source, mathtext=not use_tex)
|
|
68
|
+
if use_tex:
|
|
69
|
+
mode = r"\textstyle " if inline else r"\displaystyle "
|
|
70
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
71
|
+
directory = Path(tmp)
|
|
72
|
+
(directory / "preview.tex").write_text(
|
|
73
|
+
"\\documentclass[12pt]{article}\n\\usepackage{amsmath,amssymb}\n"
|
|
74
|
+
"\\pagestyle{empty}\n\\begin{document}\n\\noindent\\hbox{$" + mode + text
|
|
75
|
+
+ "$}\n\\end{document}\n", encoding="ascii",
|
|
76
|
+
)
|
|
77
|
+
commands = [
|
|
78
|
+
["latex", "-no-shell-escape", "-interaction=batchmode", "-halt-on-error", "preview.tex"],
|
|
79
|
+
["dvipng", "-D", "360", "-T", "tight", "-bg", "White", "-o", "preview.png", "preview.dvi"],
|
|
80
|
+
]
|
|
81
|
+
for command in commands:
|
|
82
|
+
result = subprocess.run(command, cwd=tmp, stdin=subprocess.DEVNULL,
|
|
83
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
84
|
+
timeout=20, env={**os.environ, "openin_any": "p", "openout_any": "p"})
|
|
85
|
+
if result.returncode:
|
|
86
|
+
raise UnsupportedFormula(f"{command[0]} failed to render preview (exit {result.returncode})")
|
|
87
|
+
with Image.open(directory / "preview.png") as rendered:
|
|
88
|
+
_check_pixels(rendered)
|
|
89
|
+
image = rendered.convert("RGB")
|
|
90
|
+
else:
|
|
91
|
+
from matplotlib.font_manager import FontProperties
|
|
92
|
+
from matplotlib.mathtext import math_to_image
|
|
93
|
+
import matplotlib
|
|
94
|
+
output = BytesIO()
|
|
95
|
+
try:
|
|
96
|
+
with _RENDER_LOCK, matplotlib.rc_context({"mathtext.fontset": "stix", "text.usetex": False}):
|
|
97
|
+
math_to_image(f"${text}$", output, prop=FontProperties(size=13),
|
|
98
|
+
dpi=360, format="png", color="black")
|
|
99
|
+
except (ValueError, RuntimeError) as exc:
|
|
100
|
+
raise UnsupportedFormula("Mathtext rejected the preview; install latex, amsmath, "
|
|
101
|
+
"amssymb and dvipng for the full preview dialect") from exc
|
|
102
|
+
output.seek(0)
|
|
103
|
+
with Image.open(output) as rendered:
|
|
104
|
+
_check_pixels(rendered)
|
|
105
|
+
rgba = rendered.convert("RGBA")
|
|
106
|
+
image = Image.new("RGB", rgba.size, "white")
|
|
107
|
+
image.paste(rgba, mask=rgba.getchannel("A"))
|
|
108
|
+
box = ImageChops.difference(image, Image.new("RGB", image.size, "white")).getbbox()
|
|
109
|
+
if box is None:
|
|
110
|
+
raise UnsupportedFormula("Formula produced a blank preview")
|
|
111
|
+
image = image.crop(box)
|
|
112
|
+
preview = Image.new("RGB", (image.width + 8, image.height + 8), "white")
|
|
113
|
+
preview.paste(image, (4, 4))
|
|
114
|
+
output = BytesIO()
|
|
115
|
+
preview.save(output, format="PNG")
|
|
116
|
+
return output.getvalue(), preview.size
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _append_equation(run, index, embedded, preview, size, inline):
|
|
120
|
+
# Each OLE part is separately editable even when two equations have the same source.
|
|
121
|
+
part = run.part
|
|
122
|
+
base = f"/word/embeddings/formula{index}.bin"
|
|
123
|
+
native_id = part.relate_to(Part(PackURI(base), OLE_TYPE, embedded, part.package), RT.OLE_OBJECT)
|
|
124
|
+
image_id = part.relate_to(
|
|
125
|
+
Part(PackURI(f"/word/media/formula{index}.png"), "image/png", preview, part.package), RT.IMAGE
|
|
126
|
+
)
|
|
127
|
+
# Rasterization at 360 dpi gives five pixels per typographic point.
|
|
128
|
+
width, height = (pixels / 5 for pixels in size)
|
|
129
|
+
scale = min(1, 440 / width, (17 if inline else 85) / height)
|
|
130
|
+
width, height = width * scale, height * scale
|
|
131
|
+
obj = ET.SubElement(run._r, tag(W, "object"), {
|
|
132
|
+
tag(W, "dxaOrig"): str(max(1, round(20 * width))),
|
|
133
|
+
tag(W, "dyaOrig"): str(max(1, round(20 * height))),
|
|
134
|
+
}, nsmap={"v": V, "o": O})
|
|
135
|
+
sid = f"_x0000_i{1024 + index}"
|
|
136
|
+
# A self-contained rectangular VML picture frame (VML imagedata, §14.1.2.11).
|
|
137
|
+
shape = ET.SubElement(obj, tag(V, "shape"), id=sid, coordsize="100,100",
|
|
138
|
+
path="m0,0 l100,0,100,100,0,100 x e", filled="f", stroked="f",
|
|
139
|
+
style=f"width:{width:.2f}pt;height:{height:.2f}pt")
|
|
140
|
+
shape.set(tag(O, "ole"), "")
|
|
141
|
+
ET.SubElement(shape, tag(V, "imagedata"), {tag(R, "id"): image_id, tag(O, "title"): ""})
|
|
142
|
+
ET.SubElement(obj, tag(O, "OLEObject"), {
|
|
143
|
+
"Type": "Embed", "ProgID": PROG_ID, "ShapeID": sid,
|
|
144
|
+
"ObjectID": f"_{index}", "DrawAspect": "Content", tag(R, "id"): native_id,
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def validate_docx(path, expected):
|
|
149
|
+
"""Verify the bounded ZIP/OPC graph, CFB native streams and decoded PNGs."""
|
|
150
|
+
if type(expected) is not int or not 1 <= expected <= _MAX_CASES:
|
|
151
|
+
raise ValueError(f"Expected count must be between 1 and {_MAX_CASES}")
|
|
152
|
+
with open_package(path) as archive:
|
|
153
|
+
bad_part = archive.testzip()
|
|
154
|
+
if bad_part is not None:
|
|
155
|
+
raise ValueError(f"DOCX CRC check failed for {bad_part}")
|
|
156
|
+
for embedded, preview in equation_parts(archive, expected):
|
|
157
|
+
try:
|
|
158
|
+
read_equation(archive.read(embedded))
|
|
159
|
+
png = archive.read(preview)
|
|
160
|
+
with Image.open(BytesIO(png), formats=["PNG"]) as image:
|
|
161
|
+
_check_pixels(image)
|
|
162
|
+
image.verify()
|
|
163
|
+
with Image.open(BytesIO(png), formats=["PNG"]) as image:
|
|
164
|
+
image.load()
|
|
165
|
+
except (OSError, ValueError, SyntaxError) as exc:
|
|
166
|
+
raise ValueError(f"Invalid equation parts {embedded}, {preview}: {exc}") from exc
|
|
167
|
+
return True
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def build_docx(cases, out, title="MathType equation collection", per_page=5):
|
|
171
|
+
"""Compile a collection atomically. Return its path after structural validation."""
|
|
172
|
+
if type(per_page) is not int or per_page <= 0:
|
|
173
|
+
raise ValueError("per_page must be a positive integer")
|
|
174
|
+
if not isinstance(cases, (list, tuple)) or not 1 <= len(cases) <= _MAX_CASES:
|
|
175
|
+
raise ValueError(f"Supply 1 to {_MAX_CASES} equation cases")
|
|
176
|
+
if not isinstance(title, str) or len(title) > 512:
|
|
177
|
+
raise ValueError("Title must be a string of at most 512 characters")
|
|
178
|
+
doc = Document()
|
|
179
|
+
section = doc.sections[0]
|
|
180
|
+
section.page_width, section.page_height = Mm(210), Mm(297)
|
|
181
|
+
section.left_margin = section.right_margin = Mm(22)
|
|
182
|
+
section.top_margin = section.bottom_margin = Mm(18)
|
|
183
|
+
seen = set()
|
|
184
|
+
size_total = 0
|
|
185
|
+
for index, case in enumerate(cases, 1):
|
|
186
|
+
if not isinstance(case, dict) or any(not isinstance(case.get(key), str)
|
|
187
|
+
or not case[key].strip() for key in ("id", "label", "latex")):
|
|
188
|
+
raise ValueError(f"Case {index} requires nonempty id, label, and latex strings")
|
|
189
|
+
case_id = case["id"]
|
|
190
|
+
if len(case_id) > 256 or len(case["label"]) > 2048:
|
|
191
|
+
raise ValueError(f"Case {index}: oversized id or label")
|
|
192
|
+
inline = case.get("inline", False)
|
|
193
|
+
if case_id in seen or not isinstance(inline, bool):
|
|
194
|
+
raise ValueError(f"Case {index}: duplicate id or invalid inline flag ({case_id})")
|
|
195
|
+
seen.add(case_id)
|
|
196
|
+
try:
|
|
197
|
+
body = compile_latex(case["latex"])
|
|
198
|
+
embedded = pack_ole(body, inline=inline)
|
|
199
|
+
preview, size = _preview(case["latex"], inline)
|
|
200
|
+
except (UnsupportedFormula, subprocess.TimeoutExpired) as exc:
|
|
201
|
+
raise UnsupportedFormula(f"Case {case_id}: {exc}") from exc
|
|
202
|
+
size_total += len(embedded) + len(preview)
|
|
203
|
+
if size_total > MAX_PACKAGE:
|
|
204
|
+
raise ValueError("Generated equation collection exceeds package size limit")
|
|
205
|
+
if (index - 1) % per_page == 0:
|
|
206
|
+
if index > 1:
|
|
207
|
+
doc.add_page_break()
|
|
208
|
+
doc.add_heading(title if index == 1 else f"{title} (continued)", level=1)
|
|
209
|
+
label = doc.add_paragraph()
|
|
210
|
+
label.paragraph_format.keep_with_next = True
|
|
211
|
+
label.add_run(f"{case_id} | {case['label']}").bold = True
|
|
212
|
+
paragraph = doc.add_paragraph()
|
|
213
|
+
paragraph.paragraph_format.space_after = Pt(8)
|
|
214
|
+
if inline:
|
|
215
|
+
paragraph.add_run("In-line equation: ")
|
|
216
|
+
else:
|
|
217
|
+
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
218
|
+
_append_equation(paragraph.add_run(), index, embedded, preview, size, inline)
|
|
219
|
+
if inline:
|
|
220
|
+
paragraph.add_run(" within normal body text.")
|
|
221
|
+
out = Path(out)
|
|
222
|
+
with tempfile.TemporaryDirectory(dir=out.parent) as tmp:
|
|
223
|
+
staged = Path(tmp) / "collection.docx"
|
|
224
|
+
doc.save(staged)
|
|
225
|
+
validate_docx(staged, len(cases))
|
|
226
|
+
replace_file(staged, out)
|
|
227
|
+
return out
|