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.
@@ -0,0 +1,181 @@
1
+ """Parse the supported TeX math dialect with source positions and bounded recursion."""
2
+ import re
3
+ from html.entities import name2codepoint
4
+
5
+ from .records import ACCENT_IDS, GLYPHS, GREEK_GLYPHS, STYLES, Expr, UnsupportedFormula, serialize
6
+
7
+ GREEK_NAMES = (
8
+ "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi pi rho "
9
+ "sigma tau upsilon phi chi psi omega Gamma Delta Theta Lambda Xi Pi Sigma Upsilon Phi Psi Omega"
10
+ ).split()
11
+ COMMAND_SYMBOL = {name: chr(name2codepoint[name]) for name in GREEK_NAMES}
12
+ COMMAND_SYMBOL.update({
13
+ "vartheta": "ϑ", "phi": "ϕ", "varphi": "φ", "varsigma": "ς", "varpi": "ϖ",
14
+ "pm": "±", "times": "×", "div": "÷", "le": "≤", "leq": "≤", "ge": "≥",
15
+ "geq": "≥", "ne": "≠", "neq": "≠", "approx": "≈", "in": "∈", "notin": "∉",
16
+ "partial": "∂", "nabla": "∇", "infty": "∞", "to": "→", "rightarrow": "→",
17
+ "leftarrow": "←", "leftrightarrow": "↔", "cup": "∪", "cap": "∩", "subset": "⊂",
18
+ "subseteq": "⊆", "cdot": "⋅", "parallel": "∥", "forall": "∀", "exists": "∃",
19
+ "{": "{", "}": "}", "|": "‖",
20
+ })
21
+ FUNCTIONS = frozenset("arg cos cot csc det dim exp gcd ln log max min mod sec sin tan".split())
22
+ SPACING = frozenset([",", ";", "!", " ", "enspace", "quad", "qquad"])
23
+ ACCENTS = set(ACCENT_IDS) | {"widehat", "overline", "overrightarrow", "vec"}
24
+ MATRIX_FENCES = {"matrix": ("", ""), "pmatrix": ("(", ")"), "bmatrix": ("[", "]"),
25
+ "cases": (r"\{", "."), "vmatrix": ("|", "|"), "Vmatrix": (r"\|", r"\|")}
26
+ DELIMITERS = {
27
+ "(": ("round", "("), ")": ("round", ")"), "[": ("square", "["), "]": ("square", "]"),
28
+ r"\{": ("brace", "{"), r"\}": ("brace", "}"), "|": ("absolute", "|"),
29
+ r"\|": ("norm", "‖"), r"\lVert": ("norm", "‖"), r"\rVert": ("norm", "‖"), ".": ("", "")
30
+ }
31
+ TERM_END = frozenset(r"+ - = < > , ; \le \leq \ge \geq \ne \neq \approx ≤ ≥ ≠ ≈".split())
32
+ LEXEME = re.compile(r"\\[A-Za-z]+|\\[^\n\r]|[^\s]")
33
+ MAX_TOKENS = 700
34
+
35
+
36
+ class _Reader:
37
+ def __init__(self, source):
38
+ if not isinstance(source, str) or len(source) > 16384:
39
+ raise UnsupportedFormula("Expected a formula of at most 16384 characters")
40
+ if any(ord(char) < 32 and char not in "\r\n\t" for char in source):
41
+ raise UnsupportedFormula("Control character in formula")
42
+ self.tokens = list(LEXEME.finditer(source))
43
+ if not 1 <= len(self.tokens) <= MAX_TOKENS:
44
+ raise UnsupportedFormula(f"Expected 1 to {MAX_TOKENS} tokens")
45
+ self.position = 0
46
+ self.end = len(source)
47
+
48
+ def error(self, message):
49
+ index = self.tokens[self.position].start() if self.position < len(self.tokens) else self.end
50
+ return UnsupportedFormula(f"{message} at character {index + 1}")
51
+
52
+ def look(self, offset=0):
53
+ index = self.position + offset
54
+ return self.tokens[index][0] if index < len(self.tokens) else None
55
+
56
+ def consume(self, expected=None):
57
+ actual = self.look()
58
+ if actual is None or (expected is not None and actual != expected):
59
+ raise self.error(f"Expected {expected or 'an operand'}, found {actual or 'end of input'}")
60
+ self.position += 1
61
+ return actual
62
+
63
+ def braced(self, depth):
64
+ self.consume("{")
65
+ item = self.sequence({"}"}, depth + 1)
66
+ self.consume("}")
67
+ return item
68
+
69
+ def indices(self, depth):
70
+ indices = {}
71
+ while self.look() in {"^", "_"}:
72
+ marker = self.consume()
73
+ if marker in indices:
74
+ raise self.error("Repeated script marker " + marker)
75
+ indices[marker] = self.atom(depth + 1)
76
+ return indices.get("_"), indices.get("^")
77
+
78
+ def sequence(self, stops, depth):
79
+ if depth > 64:
80
+ raise self.error("Formula nesting exceeds 64 levels")
81
+ items = []
82
+ while (token := self.look()) is not None and token not in stops:
83
+ if token in {r"\int", r"\sum", r"\prod"}:
84
+ name = self.consume()[1:]
85
+ lower, upper = self.indices(depth)
86
+ operand = self.sequence(stops | TERM_END, depth + 1)
87
+ if not operand.children:
88
+ raise self.error(f"Missing operand for {name}; brace signed operands")
89
+ item = Expr("operator", name, (lower, upper, operand))
90
+ elif token == r"\lim" or (token in {r"\min", r"\max"} and self.look(1) == "_"):
91
+ name = self.consume()[1:]
92
+ lower, upper = self.indices(depth)
93
+ if lower is None or upper is not None:
94
+ raise self.error(f"{name} requires one lower limit")
95
+ item = Expr("limit", name, (lower,))
96
+ else:
97
+ item = self.atom(depth)
98
+ lower, upper = self.indices(depth)
99
+ if lower is not None or upper is not None:
100
+ item = Expr("scripts", children=(item, lower, upper))
101
+ items.append(item)
102
+ return Expr("list", children=tuple(items))
103
+
104
+ def fence(self, left, inner, right):
105
+ if left not in DELIMITERS or right not in DELIMITERS:
106
+ raise self.error("Unsupported delimiter")
107
+ a, lchar = DELIMITERS[left]
108
+ b, rchar = DELIMITERS[right]
109
+ if (a and b and a != b) or not (a or b):
110
+ raise self.error("Unsupported delimiter pair")
111
+ return Expr("fence", a or b, (lchar, inner, rchar))
112
+
113
+ def environment_name(self):
114
+ self.consume("{")
115
+ name = []
116
+ while self.look() != "}":
117
+ name.append(self.consume())
118
+ self.consume("}")
119
+ return "".join(name)
120
+
121
+ def matrix(self, depth):
122
+ env = self.environment_name()
123
+ if env not in MATRIX_FENCES:
124
+ raise self.error(f"Unsupported environment {env}")
125
+ rows, row = [], []
126
+ while True:
127
+ row.append(self.sequence({"&", r"\\", r"\end"}, depth + 1))
128
+ if len(row) > 12 or len(rows) >= 12:
129
+ raise self.error("Matrix exceeds 12 by 12")
130
+ separator = self.consume()
131
+ if separator == "&":
132
+ continue
133
+ if rows and len(rows[0]) != len(row):
134
+ raise self.error("Unequal matrix row lengths")
135
+ rows.append(tuple(row))
136
+ row = []
137
+ if separator == r"\end":
138
+ break
139
+ if self.environment_name() != env:
140
+ raise self.error("Mismatched environment name")
141
+ table = Expr("matrix", env, tuple(rows))
142
+ left, right = MATRIX_FENCES[env]
143
+ return self.fence(left, table, right) if left else table
144
+
145
+ def atom(self, depth):
146
+ if self.look() == "{":
147
+ return self.braced(depth)
148
+ token = self.consume()
149
+ if not token.startswith("\\"):
150
+ if (token in GLYPHS or token in GREEK_GLYPHS or
151
+ token.isascii() and (token.isalnum() or token in "-()[]|.,:;/!")):
152
+ return Expr("letter", token)
153
+ raise self.error(f"Unexpected character {token!r}")
154
+ name = token[1:]
155
+ if name in COMMAND_SYMBOL:
156
+ return Expr("letter", COMMAND_SYMBOL[name])
157
+ if name in FUNCTIONS:
158
+ return Expr("function", name)
159
+ if name in SPACING:
160
+ return Expr("list")
161
+ if name in {"frac", "dfrac", "tfrac"}:
162
+ return Expr("fraction", children=(self.braced(depth), self.braced(depth)))
163
+ if name == "sqrt":
164
+ return Expr("sqrt", children=(self.braced(depth),))
165
+ if name in STYLES or name in ACCENTS:
166
+ return Expr("style" if name in STYLES else "accent", name, (self.braced(depth),))
167
+ if name == "left":
168
+ left = self.consume()
169
+ content = self.sequence({r"\right"}, depth + 1)
170
+ self.consume(r"\right")
171
+ return self.fence(left, content, self.consume())
172
+ if name == "begin":
173
+ return self.matrix(depth)
174
+ raise self.error(f"Unsupported command {token!r}")
175
+
176
+
177
+ def compile_latex(s):
178
+ """Return the MTEF object-list bytes for one supported LaTeX expression."""
179
+ reader = _Reader(s)
180
+ tree = reader.sequence(set(), 0)
181
+ return serialize(tree)
@@ -0,0 +1,236 @@
1
+ """Build and inspect an embedded Equation.DSMT4 object without a binary template."""
2
+
3
+ import struct
4
+ import sys
5
+ from uuid import UUID
6
+
7
+ from .compound import read_compound, write_compound
8
+ from .prefix import parse_prefix
9
+
10
+ CLSID = UUID("0002ce03-0000-0000-c000-000000000046")
11
+ NATIVE = "Equation Native"
12
+ HEADER = struct.Struct("<HIHI4I")
13
+ FULL_LINE = bytes((10, 1, 0))
14
+ DEFAULT_DEFINITIONS = bytes((18, 0, 0, 0, 0)) # EQN_PREFS, three default arrays
15
+ MAX_BODY = 1024 * 1024
16
+ MAX_DEPTH = 192
17
+
18
+
19
+ def _ansi(text):
20
+ data = text.encode("ascii") + b"\0"
21
+ return struct.pack("<I", len(data)) + data
22
+
23
+
24
+ def _template_slots(selector, variation):
25
+ # Child record kinds in the supported writer dialect. Size switches may
26
+ # appear between slots. A null LINE still occupies a slot.
27
+ if 1 <= selector <= 5 and 0 < variation <= 3:
28
+ return (1,) + (2,) * variation.bit_count()
29
+ slots = {10: (1, 1), 11: (1, 1), 13: (1,), 15: (1, 1, 1, 1),
30
+ 16: (1, 1, 1, 1), 17: (1, 1, 1, 1), 22: (1, 1, 1, 1),
31
+ 27: (1, 1), 28: (1, 1), 29: (1, 1, 1), 31: (1, 2), 33: (1, 2)}
32
+ if selector not in slots:
33
+ raise ValueError(f"Unsupported MTEF template selector {selector}")
34
+ return slots[selector]
35
+
36
+
37
+ def _inspect_records(data):
38
+ """Walk record boundaries in the writer's MTEF 5 dialect, consuming all data."""
39
+ pos = 0
40
+
41
+ def take(size):
42
+ nonlocal pos
43
+ if pos + size > len(data):
44
+ raise ValueError(f"Truncated MTEF record at byte {pos}")
45
+ start = pos
46
+ pos += size
47
+ return data[start:pos]
48
+
49
+ def objects(depth=0, parent="body", cells=None, slots=None):
50
+ nonlocal pos
51
+ if depth > MAX_DEPTH:
52
+ raise ValueError("MTEF nesting limit exceeded")
53
+ count = 0
54
+ slot_index = 0
55
+ while pos < len(data):
56
+ tag = take(1)[0]
57
+ if tag == 0:
58
+ if (depth == 0 or (cells is not None and cells != count) or
59
+ (slots is not None and len(slots) != slot_index)):
60
+ raise ValueError(f"Unexpected MTEF END or matrix cell count at {pos-1}")
61
+ return
62
+ if parent == "embellishment" and tag != 6:
63
+ raise ValueError("Expected MTEF embellishment")
64
+ if parent == "matrix" and tag != 1:
65
+ raise ValueError("Expected MTEF matrix cell")
66
+ if slots is not None and tag not in (10, 11, 12, 13, 14):
67
+ if slot_index >= len(slots) or tag != slots[slot_index]:
68
+ raise ValueError("Unexpected MTEF template subobject")
69
+ slot_index += 1
70
+ if parent in ("body", "line") and tag == 1:
71
+ raise ValueError("Unexpected nested MTEF LINE")
72
+ count += 1
73
+ if tag == 1:
74
+ options = take(1)[0]
75
+ if options == 0:
76
+ objects(depth + 1, "line")
77
+ elif options != 1:
78
+ raise ValueError("Unsupported MTEF LINE options")
79
+ elif tag == 2:
80
+ options, face = take(2)
81
+ if options & ~7 or face == 255:
82
+ raise ValueError("Unsupported MTEF CHAR options or typeface")
83
+ take(2 + int(bool(options & 4)))
84
+ if options & 1:
85
+ objects(depth + 1, "embellishment")
86
+ elif tag == 3:
87
+ options, selector, variation, template_options = take(4)
88
+ if options or selector > 37 or variation & 128 or template_options:
89
+ raise ValueError("Unsupported MTEF TMPL record")
90
+ objects(depth + 1, "template", slots=_template_slots(selector, variation))
91
+ elif tag == 5:
92
+ options, valign, halign, vjust, rows, cols = take(6)
93
+ if options or max(valign, vjust) > 4 or halign > 5 or not (rows and cols):
94
+ raise ValueError("Invalid MTEF MATRIX dimensions or flags")
95
+ take((rows + 4) // 4 + (cols + 4) // 4)
96
+ objects(depth + 1, "matrix", rows * cols)
97
+ elif tag == 6:
98
+ flags, embell = take(2)
99
+ if parent != "embellishment" or flags or not 2 <= embell <= 37:
100
+ raise ValueError("Invalid MTEF EMBELL record")
101
+ elif tag not in (10, 11, 12, 13, 14):
102
+ raise ValueError(f"Unsupported MTEF record {tag} at byte {pos - 1}")
103
+ if depth:
104
+ raise ValueError("Missing MTEF END")
105
+
106
+ objects()
107
+
108
+
109
+ def _header(inline):
110
+ # Version 5, Windows target dialect, MathType product family, version 4.0
111
+ # features. The independent writer has its own application key.
112
+ return bytes((5, 1, 0, 4, 0)) + b"AME1\0" + bytes((int(bool(inline)),))
113
+
114
+
115
+ def _clipboard_format():
116
+ if sys.platform == "win32":
117
+ import ctypes
118
+ # Register the name in the current Windows session; no clipboard
119
+ # contents are read or modified.
120
+ register = ctypes.WinDLL("user32", use_last_error=True).RegisterClipboardFormatW
121
+ register.argtypes = [ctypes.c_wchar_p]
122
+ register.restype = ctypes.c_uint
123
+ value = register("MathType EF")
124
+ if not value:
125
+ raise OSError(ctypes.get_last_error(), "Cannot register MathType EF clipboard format")
126
+ return value
127
+ # There is no Windows clipboard registry on the other target platforms.
128
+ return 0xC000
129
+
130
+
131
+ def pack_ole(body, *, inline=False):
132
+ """Package compiled expression records as native MTEF inside CFB/OLE."""
133
+ if not isinstance(body, bytes) or len(body) > MAX_BODY:
134
+ raise ValueError("Expected at most 1 MiB of compiled MTEF records")
135
+ _inspect_records(body)
136
+ mtef = _header(inline) + DEFAULT_DEFINITIONS + FULL_LINE + body + bytes(2)
137
+ header = HEADER.pack(HEADER.size, 0x00020000, _clipboard_format(), len(mtef), 0, 0, 0, 0)
138
+ streams = {
139
+ "\x01Ole": struct.pack("<5I", 0x02000001, 0, 0, 0, 0),
140
+ "\x01CompObj": bytes(28) + _ansi("MathType Equation") + _ansi("MathType EF"),
141
+ NATIVE: header + mtef,
142
+ }
143
+ return write_compound(streams, CLSID)
144
+
145
+
146
+ def read_streams(blob):
147
+ return read_compound(blob, CLSID)
148
+
149
+
150
+ def _check_compobj(data):
151
+ # MS-OLEDS 2.3.7 requires readers to ignore all 28 bytes of the header.
152
+ cursor = 28
153
+
154
+ def dword():
155
+ nonlocal cursor
156
+ if cursor + 4 > len(data):
157
+ raise ValueError("Truncated OLE CompObj field")
158
+ number, = struct.unpack_from("<I", data, cursor)
159
+ cursor += 4
160
+ return number
161
+
162
+ def string(size, wide=False):
163
+ nonlocal cursor
164
+ if size == 0:
165
+ return ""
166
+ if cursor + size > len(data) or (wide and size % 2):
167
+ raise ValueError("Invalid OLE CompObj string length")
168
+ raw = data[cursor:cursor + size]
169
+ cursor += size
170
+ text = raw.decode("utf-16le" if wide else "latin1")
171
+ if not text.endswith("\0") or "\0" in text[:-1]:
172
+ raise ValueError("Invalid OLE CompObj string terminator")
173
+ return text[:-1]
174
+
175
+ string(dword()) # AnsiUserType; descriptive only
176
+ clip_length = dword()
177
+ if clip_length > 400 or string(clip_length) != "MathType EF":
178
+ raise ValueError("Expected MathType EF registered clipboard format")
179
+
180
+ if cursor == len(data):
181
+ return
182
+ reserved = dword()
183
+ # MS-OLEDS 2.3.8 explicitly ignores the rest in these cases.
184
+ if not 1 <= reserved <= 40:
185
+ return
186
+ string(reserved)
187
+ if cursor == len(data) or dword() != 0x71B239F4:
188
+ return
189
+
190
+ string(dword(), wide=True) # UnicodeUserType length in bytes
191
+ clip_length = dword() # Unicode clipboard name length in characters
192
+ if clip_length:
193
+ if clip_length > 400 or string(2 * clip_length, wide=True) != "MathType EF":
194
+ raise ValueError("Unsupported OLE Unicode clipboard format")
195
+ string(dword(), wide=True) # Reserved2 length in bytes
196
+ if cursor != len(data):
197
+ raise ValueError("Unexpected data after OLE Unicode CompObj fields")
198
+
199
+
200
+ def _extract(blob):
201
+ streams = read_streams(blob)
202
+ ole = streams.get("\x01Ole", b"")
203
+ if len(ole) != 20:
204
+ raise ValueError("Expected an embedded OLE stream without a moniker")
205
+ version, flags, _, reserved, moniker = struct.unpack("<5I", ole)
206
+ # Bit 3 occurs in the controlled legacy Word sample. Do not follow links.
207
+ if version != 0x02000001 or flags not in (0, 8, 0x1000) or reserved or moniker:
208
+ raise ValueError("Unsupported OLE metadata or linked object")
209
+ _check_compobj(streams.get("\x01CompObj", b""))
210
+ native = streams.get(NATIVE, b"")
211
+ if len(native) < HEADER.size:
212
+ raise ValueError("Missing or truncated Equation Native stream")
213
+ size, version, clipboard_id, length, *_ = HEADER.unpack_from(native)
214
+ if (size, version, length) != (HEADER.size, 0x00020000, len(native) - size):
215
+ raise ValueError("Invalid Equation Native header or declared length")
216
+ if clipboard_id < 0xC000:
217
+ raise ValueError("Expected a registered clipboard ID in Equation Native")
218
+ mtef = native[size:]
219
+ pos = parse_prefix(mtef)
220
+ if mtef[pos:pos + 3] != FULL_LINE or not mtef.endswith(bytes(2)) or pos + 5 > len(mtef):
221
+ raise ValueError("Missing outer MTEF FULL/LINE or END records")
222
+ body = mtef[pos + 3:-2]
223
+ if len(body) > MAX_BODY:
224
+ raise ValueError("MTEF body exceeds 1 MiB")
225
+ _inspect_records(body)
226
+ return native, body
227
+
228
+
229
+ def read_equation(blob):
230
+ """Return the intact, validated Equation Native stream (including its header)."""
231
+ return _extract(blob)[0]
232
+
233
+
234
+ def read_body(blob):
235
+ """Return the inner expression record bytes for comparison with compile_latex."""
236
+ return _extract(blob)[1]
@@ -0,0 +1,205 @@
1
+ """Bounded, read-only inspection of transitional WordprocessingML equation parts."""
2
+
3
+ import os
4
+ import re
5
+ import struct
6
+ import time
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+ from zipfile import BadZipFile, ZIP_DEFLATED, ZIP_STORED, ZipFile
10
+
11
+ from lxml import etree as ET
12
+
13
+ W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
14
+ M = "http://schemas.openxmlformats.org/officeDocument/2006/math"
15
+ R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
16
+ V = "urn:schemas-microsoft-com:vml"
17
+ O = "urn:schemas-microsoft-com:office:office"
18
+ P = "http://schemas.openxmlformats.org/package/2006/relationships"
19
+ CT = "http://schemas.openxmlformats.org/package/2006/content-types"
20
+ OLE_TYPE = "application/vnd.openxmlformats-officedocument.oleObject"
21
+ DOCUMENT_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
22
+ PROG_ID = "Equation.DSMT4"
23
+
24
+ MAX_PACKAGE = 128 * 1024 * 1024
25
+ MAX_PART = 16 * 1024 * 1024
26
+ MAX_XML = 4 * 1024 * 1024
27
+ MAX_ENTRIES = 4096
28
+
29
+
30
+ def replace_file(source, destination):
31
+ """Atomically install a closed staging file, tolerating short Windows sharing conflicts."""
32
+ delays = (0.01, 0.02, 0.04, 0.08, 0.16, 0.25, 0.25, 0.25)
33
+ for delay in delays:
34
+ try:
35
+ os.replace(source, destination)
36
+ return
37
+ except OSError as exc:
38
+ # Win32 ACCESS_DENIED, SHARING_VIOLATION and LOCK_VIOLATION can
39
+ # occur while another process is finishing a rename or reading the file.
40
+ if getattr(exc, "winerror", None) not in (5, 32, 33):
41
+ raise
42
+ time.sleep(delay)
43
+ os.replace(source, destination)
44
+
45
+
46
+ def tag(namespace, name):
47
+ return f"{{{namespace}}}{name}"
48
+
49
+
50
+ def _part_name(name):
51
+ components = name.split("/")
52
+ if (not name or any(x in ("", ".", "..") for x in components)
53
+ or re.search(r"[\\:%?#\x00-\x1f]", name)):
54
+ raise ValueError(f"Invalid OPC part name: {name!r}")
55
+ return name
56
+
57
+
58
+ @contextmanager
59
+ def open_package(path):
60
+ """Limit the central directory before ZipFile allocates per-member metadata."""
61
+ with Path(path).open("rb") as file:
62
+ size = file.seek(0, 2)
63
+ if size > MAX_PACKAGE:
64
+ raise ValueError("DOCX exceeds the package size limit")
65
+ file.seek(max(size - 65557, 0))
66
+ tail = file.read()
67
+ marker = tail.rfind(b"PK\x05\x06")
68
+ if marker < 0 or len(tail) - marker < 22:
69
+ raise ValueError("Missing ZIP end-of-central-directory record")
70
+ disk, start_disk, on_disk, entries, directory_size, _, comment = struct.unpack_from(
71
+ "<4H2IH", tail, marker + 4
72
+ )
73
+ zip64 = marker >= 20 and tail[marker - 20:marker - 16] == b"PK\x06\x07"
74
+ if (zip64
75
+ or disk or start_disk or on_disk != entries or entries > MAX_ENTRIES
76
+ or directory_size > MAX_XML or len(tail) - marker != 22 + comment):
77
+ raise ValueError("Unsupported or oversized DOCX ZIP directory")
78
+ try:
79
+ with ZipFile(file) as archive:
80
+ items = archive.infolist()
81
+ if len(items) != entries:
82
+ raise ValueError("Inconsistent ZIP directory entry count")
83
+ names = set()
84
+ total = 0
85
+ for item in items:
86
+ name = _part_name(item.orig_filename.removesuffix("/")).casefold()
87
+ if name in names:
88
+ raise ValueError(f"Duplicate ZIP member: {item.filename!r}")
89
+ names.add(name)
90
+ if (item.flag_bits & 1 or item.compress_type not in (ZIP_STORED, ZIP_DEFLATED)
91
+ or item.file_size > MAX_PART):
92
+ raise ValueError(f"Unsupported or oversized ZIP member: {item.filename!r}")
93
+ total += item.file_size
94
+ if total > MAX_PACKAGE:
95
+ raise ValueError("Uncompressed DOCX exceeds the size limit")
96
+ yield archive
97
+ except BadZipFile as exc:
98
+ raise ValueError(f"Invalid DOCX archive: {exc}") from exc
99
+
100
+
101
+ def _read(archive, name, limit=MAX_PART):
102
+ try:
103
+ info = archive.getinfo(name)
104
+ except KeyError as exc:
105
+ raise ValueError(f"Missing package part: {name}") from exc
106
+ if info.file_size > limit:
107
+ raise ValueError(f"Oversized package part: {name}")
108
+ return archive.read(info)
109
+
110
+
111
+ def _xml(archive, name, root_tag):
112
+ parser = ET.XMLParser(resolve_entities=False, no_network=True, load_dtd=False, huge_tree=False)
113
+ try:
114
+ root = ET.fromstring(_read(archive, name, MAX_XML), parser=parser)
115
+ except ET.XMLSyntaxError as exc:
116
+ raise ValueError(f"Invalid XML in {name}: {exc}") from exc
117
+ if root.getroottree().docinfo.doctype or root.tag != root_tag:
118
+ raise ValueError(f"Unexpected XML root or DOCTYPE in {name}")
119
+ return root
120
+
121
+
122
+ def _relationships(archive, name):
123
+ root = _xml(archive, name, tag(P, "Relationships"))
124
+ result = {}
125
+ for item in root:
126
+ rid = item.get("Id")
127
+ if item.tag != tag(P, "Relationship") or not rid or rid in result:
128
+ raise ValueError(f"Invalid or duplicate relationship in {name}")
129
+ result[rid] = item
130
+ return result
131
+
132
+
133
+ def _target(relationship, base, kind):
134
+ if (relationship is None or relationship.get("Type") != f"{R}/{kind}"
135
+ or relationship.get("TargetMode", "Internal") != "Internal"):
136
+ raise ValueError(f"Expected an internal {kind} relationship")
137
+ target = relationship.get("Target", "")
138
+ if target.startswith("/"):
139
+ return _part_name(target[1:])
140
+ return _part_name(base + target)
141
+
142
+
143
+ def _content_types(archive):
144
+ defaults, overrides = {}, {}
145
+ for item in _xml(archive, "[Content_Types].xml", tag(CT, "Types")):
146
+ if item.tag == tag(CT, "Default"):
147
+ key, table = item.get("Extension", "").lower(), defaults
148
+ elif item.tag == tag(CT, "Override"):
149
+ key, table = item.get("PartName", ""), overrides
150
+ else:
151
+ raise ValueError("Unexpected OPC content-type declaration")
152
+ if not key or key in table or not item.get("ContentType"):
153
+ raise ValueError("Invalid or duplicate OPC content type")
154
+ table[key] = item.get("ContentType")
155
+
156
+ def resolve(name):
157
+ return overrides.get("/" + name, defaults.get(name.rsplit(".", 1)[-1].lower(), ""))
158
+ return resolve
159
+
160
+
161
+ def equation_parts(archive, expected):
162
+ """Yield the validated embedding and preview part names in document order."""
163
+ root_rels = _relationships(archive, "_rels/.rels")
164
+ offices = [r for r in root_rels.values() if r.get("Type") == f"{R}/officeDocument"]
165
+ if len(offices) != 1:
166
+ raise ValueError("Expected one main Word document relationship")
167
+ main = _target(offices[0], "", "officeDocument")
168
+ content_type = _content_types(archive)
169
+ if content_type(main) != DOCUMENT_TYPE:
170
+ raise ValueError("Expected a DOCX main document part")
171
+ root = _xml(archive, main, tag(W, "document"))
172
+ if next(root.iter(tag(M, "oMath"), tag(M, "oMathPara")), None) is not None:
173
+ raise ValueError("Unexpected native Word math in equation collection")
174
+ objects = list(root.iter(tag(O, "OLEObject")))
175
+ if len(objects) != expected:
176
+ raise ValueError(f"Expected {expected} embedded objects, found {len(objects)}")
177
+ base, _, filename = main.rpartition("/")
178
+ base = (base + "/") if base else ""
179
+ rels = _relationships(archive, base + "_rels/" + filename + ".rels")
180
+ object_ids, shape_ids, embeddings = set(), set(), set()
181
+ for obj in objects:
182
+ parent = obj.getparent()
183
+ if (obj.get("Type") != "Embed" or obj.get("ProgID") != PROG_ID
184
+ or parent is None or parent.tag != tag(W, "object")):
185
+ raise ValueError("Expected an embedded Equation.DSMT4 Word object")
186
+ shape_id, object_id = obj.get("ShapeID"), obj.get("ObjectID")
187
+ if (not object_id or not re.fullmatch(r"_[0-9]{1,10}", object_id)
188
+ or int(object_id[1:]) > 2147483647 or object_id in object_ids
189
+ or not shape_id or shape_id in shape_ids):
190
+ raise ValueError("Missing or duplicate OLE object/shape identifier")
191
+ object_ids.add(object_id)
192
+ shape_ids.add(shape_id)
193
+ shapes = [s for s in parent.findall(tag(V, "shape")) if s.get("id") == shape_id]
194
+ images = shapes[0].findall(tag(V, "imagedata")) if len(shapes) == 1 else []
195
+ if len(images) != 1:
196
+ raise ValueError(f"Missing or ambiguous VML preview for {shape_id}")
197
+ embedded = _target(rels.get(obj.get(tag(R, "id"))), base, "oleObject")
198
+ preview = _target(rels.get(images[0].get(tag(R, "id"))), base, "image")
199
+ if embedded in embeddings or content_type(embedded) != OLE_TYPE:
200
+ raise ValueError(f"Duplicate or incorrectly typed embedding: {embedded}")
201
+ embeddings.add(embedded)
202
+ media_type = content_type(preview)
203
+ if media_type != "image/png":
204
+ raise ValueError(f"Invalid preview content type: {preview}")
205
+ yield embedded, preview