Branchwell

Skillfarm / skills · skillfarm.ai / converted / docx / scripts / office / validators / docx.py

1"""
2Validator for Word document XML files against XSD schemas.
3"""
4
5import random
6import re
7import tempfile
8import zipfile
9from collections import Counter
10from pathlib import Path
11
12import defusedxml.minidom
13import lxml.etree
14
15from helpers import one_line, safe_extract
16
17from .base import BaseSchemaValidator
18
19
20class DOCXSchemaValidator(BaseSchemaValidator):
21
22 WORD_2006_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
23 W14_NAMESPACE = "http://schemas.microsoft.com/office/word/2010/wordml"
24 W16CID_NAMESPACE = "http://schemas.microsoft.com/office/word/2016/wordml/cid"
25
26 ELEMENT_RELATIONSHIP_TYPES = {}
27
28 def validate(self):
29 if not self.validate_xml():
30 return False
31
32 all_valid = True
33 if not self.validate_namespaces():
34 all_valid = False
35
36 if not self.validate_unique_ids():
37 all_valid = False
38
39 if not self.validate_file_references():
40 all_valid = False
41
42 if not self.validate_content_types():
43 all_valid = False
44
45 if not self.validate_against_xsd():
46 all_valid = False
47
48 if not self.validate_whitespace_preservation():
49 all_valid = False
50
51 if not self.validate_deletions():
52 all_valid = False
53
54 if not self.validate_insertions():
55 all_valid = False
56
57 if not self.validate_all_relationship_ids():
58 all_valid = False
59
60 if not self.validate_id_constraints():
61 all_valid = False
62
63 if not self.validate_comment_markers():
64 all_valid = False
65
66 if not self.validate_style_ids():
67 all_valid = False
68
69 self.compare_paragraph_counts()
70
71 return all_valid
72
73 def validate_whitespace_preservation(self):
74 errors = []
75
76 for xml_file in self.xml_files:
77 if xml_file.name != "document.xml":
78 continue
79
80 try:
81 root = lxml.etree.parse(str(xml_file)).getroot()
82
83 for elem in root.iter(f"{{{self.WORD_2006_NAMESPACE}}}t"):
84 if elem.text:
85 text = elem.text
86 if re.search(r"^[ \t\n\r]", text) or re.search(
87 r"[ \t\n\r]$", text
88 ):
89 xml_space_attr = f"{{{self.XML_NAMESPACE}}}space"
90 if (
91 xml_space_attr not in elem.attrib
92 or elem.attrib[xml_space_attr] != "preserve"
93 ):
94 text_preview = (
95 repr(text)[:50] + "..."
96 if len(repr(text)) > 50
97 else repr(text)
98 )
99 errors.append(
100 f" {xml_file.relative_to(self.unpacked_dir)}: "
101 f"Line {elem.sourceline}: w:t element with whitespace missing xml:space='preserve': {text_preview}"
102 )
103
104 except (lxml.etree.XMLSyntaxError, Exception) as e:
105 errors.append(
106 f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}"
107 )
108
109 if errors:
110 print(f"FAILED - Found {len(errors)} whitespace preservation violations:")
111 for error in errors:
112 print(error)
113 return False
114 else:
115 if self.verbose:
116 print("PASSED - All whitespace is properly preserved")
117 return True
118
119 def validate_deletions(self):
120 errors = []
121
122 for xml_file in self.xml_files:
123 if xml_file.name != "document.xml":
124 continue
125
126 try:
127 root = lxml.etree.parse(str(xml_file)).getroot()
128 namespaces = {"w": self.WORD_2006_NAMESPACE}
129
130 for t_elem in root.xpath(".//w:del//w:t", namespaces=namespaces):
131 if t_elem.text:
132 text_preview = (
133 repr(t_elem.text)[:50] + "..."
134 if len(repr(t_elem.text)) > 50
135 else repr(t_elem.text)
136 )
137 errors.append(
138 f" {xml_file.relative_to(self.unpacked_dir)}: "
139 f"Line {t_elem.sourceline}: <w:t> found within <w:del>: {text_preview}"
140 )
141
142 for instr_elem in root.xpath(
143 ".//w:del//w:instrText", namespaces=namespaces
144 ):
145 text_preview = (
146 repr(instr_elem.text or "")[:50] + "..."
147 if len(repr(instr_elem.text or "")) > 50
148 else repr(instr_elem.text or "")
149 )
150 errors.append(
151 f" {xml_file.relative_to(self.unpacked_dir)}: "
152 f"Line {instr_elem.sourceline}: <w:instrText> found within <w:del> (use <w:delInstrText>): {text_preview}"
153 )
154
155 except (lxml.etree.XMLSyntaxError, Exception) as e:
156 errors.append(
157 f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}"
158 )
159
160 if errors:
161 print(f"FAILED - Found {len(errors)} deletion validation violations:")
162 for error in errors:
163 print(error)
164 return False
165 else:
166 if self.verbose:
167 print("PASSED - No w:t elements found within w:del elements")
168 return True
169
170 def count_paragraphs_in_unpacked(self):
171 count = 0
172
173 for xml_file in self.xml_files:
174 if xml_file.name != "document.xml":
175 continue
176
177 try:
178 root = lxml.etree.parse(str(xml_file)).getroot()
179 paragraphs = root.findall(f".//{{{self.WORD_2006_NAMESPACE}}}p")
180 count = len(paragraphs)
181 except Exception as e:
182 print(f"Error counting paragraphs in unpacked document: {e}")
183
184 return count
185
186 def count_paragraphs_in_original(self):
187 original = self.original_file
188 if original is None:
189 return 0
190
191 count = 0
192
193 try:
194 with tempfile.TemporaryDirectory() as temp_dir:
195 with zipfile.ZipFile(original, "r") as zip_ref:
196 safe_extract(zip_ref, Path(temp_dir))
197
198 doc_xml_path = temp_dir + "/word/document.xml"
199 root = lxml.etree.parse(doc_xml_path).getroot()
200
201 paragraphs = root.findall(f".//{{{self.WORD_2006_NAMESPACE}}}p")
202 count = len(paragraphs)
203
204 except Exception as e:
205 print(f"Error counting paragraphs in original document: {e}")
206
207 return count
208
209 def validate_insertions(self):
210 errors = []
211
212 for xml_file in self.xml_files:
213 if xml_file.name != "document.xml":
214 continue
215
216 try:
217 root = lxml.etree.parse(str(xml_file)).getroot()
218 namespaces = {"w": self.WORD_2006_NAMESPACE}
219
220 invalid_elements = root.xpath(
221 ".//w:ins//w:delText[not(ancestor::w:del)]", namespaces=namespaces
222 )
223
224 for elem in invalid_elements:
225 text_preview = (
226 repr(elem.text or "")[:50] + "..."
227 if len(repr(elem.text or "")) > 50
228 else repr(elem.text or "")
229 )
230 errors.append(
231 f" {xml_file.relative_to(self.unpacked_dir)}: "
232 f"Line {elem.sourceline}: <w:delText> within <w:ins>: {text_preview}"
233 )
234
235 except (lxml.etree.XMLSyntaxError, Exception) as e:
236 errors.append(
237 f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}"
238 )
239
240 if errors:
241 print(f"FAILED - Found {len(errors)} insertion validation violations:")
242 for error in errors:
243 print(error)
244 return False
245 else:
246 if self.verbose:
247 print("PASSED - No w:delText elements within w:ins elements")
248 return True
249
250 def compare_paragraph_counts(self):
251 new_count = self.count_paragraphs_in_unpacked()
252 if self.original_file is None:
253 print(f"\nParagraphs: {new_count}")
254 return
255
256 original_count = self.count_paragraphs_in_original()
257 diff = new_count - original_count
258 diff_str = f"+{diff}" if diff > 0 else str(diff)
259 print(f"\nParagraphs: {original_count} → {new_count} ({diff_str})")
260
261 def _parse_id_value(self, val: str, base: int = 16) -> int:
262 return int(val, base)
263
264 def validate_id_constraints(self):
265 errors = []
266 para_id_attr = f"{{{self.W14_NAMESPACE}}}paraId"
267 durable_id_attr = f"{{{self.W16CID_NAMESPACE}}}durableId"
268
269 for xml_file in self.xml_files:
270 try:
271 tree = lxml.etree.parse(str(xml_file))
272 is_numbering = lxml.etree.QName(tree.getroot()).localname == "numbering"
273 for elem in tree.iter():
274 if val := elem.get(para_id_attr):
275 try:
276 if self._parse_id_value(val, base=16) >= 0x80000000:
277 errors.append(
278 f" {xml_file.name}:{elem.sourceline}: paraId={val} >= 0x80000000"
279 )
280 except ValueError:
281 errors.append(
282 f" {xml_file.name}:{elem.sourceline}: "
283 f"paraId={val} is not valid hex"
284 )
285
286 if val := elem.get(durable_id_attr):
287 if is_numbering:
288 try:
289 if self._parse_id_value(val, base=10) >= 0x7FFFFFFF:
290 errors.append(
291 f" {xml_file.name}:{elem.sourceline}: "
292 f"durableId={val} >= 0x7FFFFFFF"
293 )
294 except ValueError:
295 errors.append(
296 f" {xml_file.name}:{elem.sourceline}: "
297 f"durableId={val} must be decimal in a numbering part"
298 )
299 else:
300 try:
301 if self._parse_id_value(val, base=16) >= 0x7FFFFFFF:
302 errors.append(
303 f" {xml_file.name}:{elem.sourceline}: "
304 f"durableId={val} >= 0x7FFFFFFF"
305 )
306 except ValueError:
307 errors.append(
308 f" {xml_file.name}:{elem.sourceline}: "
309 f"durableId={val} is not valid hex"
310 )
311 except lxml.etree.XMLSyntaxError:
312 continue
313
314 if errors:
315 print(f"FAILED - {len(errors)} ID constraint violations:")
316 for e in errors:
317 print(one_line(e, 300))
318 elif self.verbose:
319 print("PASSED - All paraId/durableId values within constraints")
320 return not errors
321
322 def _repeated_style_ids(self, styles_root) -> set[str]:
323 attr = f"{{{self.WORD_2006_NAMESPACE}}}styleId"
324 ids = Counter(s.get(attr) for s in styles_root.iter(f"{{{self.WORD_2006_NAMESPACE}}}style"))
325 return {i for i, n in ids.items() if i is not None and n > 1}
326
327 def _original_part(self, xml_file) -> bytes | None:
328 if self.original_file is None:
329 return None
330 name = xml_file.relative_to(self.unpacked_dir).as_posix()
331 try:
332 with zipfile.ZipFile(self.original_file) as zf:
333 return zf.read(name)
334 except (KeyError, OSError, zipfile.BadZipFile):
335 return None
336
337 def validate_style_ids(self):
338 errors = []
339 styles_tag = f"{{{self.WORD_2006_NAMESPACE}}}styles"
340 if self.original_file is None:
341 return True
342
343 for xml_file in self.xml_files:
344 try:
345 root = lxml.etree.parse(str(xml_file)).getroot()
346 if root.tag != styles_tag:
347 continue
348 repeated = self._repeated_style_ids(root)
349 original = self._original_part(xml_file) if repeated else None
350 if original is not None:
351 repeated -= self._repeated_style_ids(lxml.etree.fromstring(original))
352 except lxml.etree.XMLSyntaxError:
353 continue
354 errors.extend(
355 f" {xml_file.relative_to(self.unpacked_dir)}: style id {style_id!r:.40} is now "
356 f"defined more than once, and Word uses only the last definition, without "
357 f"warning. Delete the earlier ones"
358 for style_id in sorted(repeated)
359 )
360
361 if errors:
362 print(f"FAILED - Found {len(errors)} style id(s) defined more than once:")
363 for error in errors:
364 print(one_line(error, 300))
365 elif self.verbose:
366 print("PASSED - The edit defined no style id a second time")
367 return not errors
368
369 def validate_comment_markers(self):
370 errors = []
371
372 document_xml = None
373 comments_xml = None
374 for xml_file in self.xml_files:
375 if xml_file.name == "document.xml" and "word" in str(xml_file):
376 document_xml = xml_file
377 elif xml_file.name == "comments.xml":
378 comments_xml = xml_file
379
380 if not document_xml:
381 if self.verbose:
382 print("PASSED - No document.xml found (skipping comment validation)")
383 return True
384
385 try:
386 doc_root = lxml.etree.parse(str(document_xml)).getroot()
387 namespaces = {"w": self.WORD_2006_NAMESPACE}
388
389 range_starts = {
390 elem.get(f"{{{self.WORD_2006_NAMESPACE}}}id")
391 for elem in doc_root.xpath(
392 ".//w:commentRangeStart", namespaces=namespaces
393 )
394 }
395 range_ends = {
396 elem.get(f"{{{self.WORD_2006_NAMESPACE}}}id")
397 for elem in doc_root.xpath(
398 ".//w:commentRangeEnd", namespaces=namespaces
399 )
400 }
401 references = {
402 elem.get(f"{{{self.WORD_2006_NAMESPACE}}}id")
403 for elem in doc_root.xpath(
404 ".//w:commentReference", namespaces=namespaces
405 )
406 }
407
408 orphaned_ends = range_ends - range_starts
409 for comment_id in sorted(
410 orphaned_ends, key=lambda x: int(x) if x and x.isdigit() else 0
411 ):
412 errors.append(
413 f' document.xml: commentRangeEnd id="{comment_id}" has no matching commentRangeStart'
414 )
415
416 orphaned_starts = range_starts - range_ends
417 for comment_id in sorted(
418 orphaned_starts, key=lambda x: int(x) if x and x.isdigit() else 0
419 ):
420 errors.append(
421 f' document.xml: commentRangeStart id="{comment_id}" has no matching commentRangeEnd'
422 )
423
424 comment_ids = set()
425 if comments_xml and comments_xml.exists():
426 comments_root = lxml.etree.parse(str(comments_xml)).getroot()
427 comment_ids = {
428 elem.get(f"{{{self.WORD_2006_NAMESPACE}}}id")
429 for elem in comments_root.xpath(
430 ".//w:comment", namespaces=namespaces
431 )
432 }
433
434 marker_ids = range_starts | range_ends | references
435 invalid_refs = marker_ids - comment_ids
436 for comment_id in sorted(
437 invalid_refs, key=lambda x: int(x) if x and x.isdigit() else 0
438 ):
439 if comment_id:
440 errors.append(
441 f' document.xml: marker id="{comment_id}" references non-existent comment'
442 )
443
444 except (lxml.etree.XMLSyntaxError, Exception) as e:
445 errors.append(f" Error parsing XML: {e}")
446
447 if errors:
448 print(f"FAILED - {len(errors)} comment marker violations:")
449 for error in errors:
450 print(error)
451 return False
452 else:
453 if self.verbose:
454 print("PASSED - All comment markers properly paired")
455 return True
456
457 def repair(self) -> int:
458 repairs = super().repair()
459 repairs += self.repair_durableId()
460 return repairs
461
462 def repair_durableId(self) -> int:
463 DURABLE_ID_ATTRS = ("w16cid:durableId", "w16cex:durableId")
464 repairs = 0
465 renames: dict = {}
466
467 for xml_file in self.xml_files:
468 try:
469 content = xml_file.read_text(encoding="utf-8")
470 dom = defusedxml.minidom.parseString(content)
471 is_numbering = dom.documentElement.localName == "numbering"
472 base = 10 if is_numbering else 16
473 pending = []
474 seen_in_file = set()
475 modified = False
476
477 for elem in dom.getElementsByTagName("*"):
478 for attr_name in DURABLE_ID_ATTRS:
479 if not elem.hasAttribute(attr_name):
480 continue
481
482 durable_id = elem.getAttribute(attr_name)
483 try:
484 key = self._parse_id_value(durable_id, base=base)
485 needs_repair = key >= 0x7FFFFFFF
486 except ValueError:
487 key = durable_id
488 needs_repair = True
489
490 if needs_repair:
491 if key in seen_in_file:
492 value = random.randint(1, 0x7FFFFFFE)
493 else:
494 seen_in_file.add(key)
495 if key not in renames:
496 renames[key] = random.randint(1, 0x7FFFFFFE)
497 value = renames[key]
498 new_id = str(value) if is_numbering else f"{value:08X}"
499
500 elem.setAttribute(attr_name, new_id)
501 pending.append(
502 f" Repaired: {xml_file.name}: durableId {durable_id} → {new_id}"
503 )
504 modified = True
505
506 if modified:
507 xml_file.write_bytes(dom.toxml(encoding="UTF-8"))
508 for message in pending:
509 print(message)
510 repairs += len(pending)
511
512 except Exception:
513 pass
514
515 return repairs
516
517
518if __name__ == "__main__":
519 raise RuntimeError("This module should not be run directly.")