Branchwell

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

1"""
2Validator for PowerPoint presentation XML files against XSD schemas.
3"""
4
5import re
6from pathlib import Path
7
8from helpers import opc_target, rels_source_part, safe_extract
9
10from .base import BaseSchemaValidator
11
12
13class PPTXSchemaValidator(BaseSchemaValidator):
14
15 PRESENTATIONML_NAMESPACE = (
16 "http://schemas.openxmlformats.org/presentationml/2006/main"
17 )
18
19 ELEMENT_RELATIONSHIP_TYPES = {
20 "sldid": "slide",
21 "sldmasterid": "slidemaster",
22 "notesmasterid": "notesmaster",
23 "sldlayoutid": "slidelayout",
24 "themeid": "theme",
25 "tablestyleid": "tablestyles",
26 }
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_uuid_ids():
40 all_valid = False
41
42 if not self.validate_file_references():
43 all_valid = False
44
45 if not self.validate_slide_layout_ids():
46 all_valid = False
47
48 if not self.validate_content_types():
49 all_valid = False
50
51 if not self.validate_against_xsd():
52 all_valid = False
53
54 if not self.validate_notes_slide_references():
55 all_valid = False
56
57 if not self.validate_all_relationship_ids():
58 all_valid = False
59
60 if not self.validate_no_duplicate_slide_layouts():
61 all_valid = False
62
63 if not self.validate_master_theme_uniqueness():
64 all_valid = False
65
66 if not self.validate_tags():
67 all_valid = False
68
69 if not self.validate_charts():
70 all_valid = False
71
72 if not self.validate_slides():
73 all_valid = False
74
75 return all_valid
76
77 def _package_map(self) -> dict:
78 wanted = []
79 wanted += list(self.unpacked_dir.glob("[[]Content_Types[]].xml"))
80 wanted += list(self.unpacked_dir.glob("ppt/presentation.xml"))
81 wanted += list(self.unpacked_dir.glob("ppt/theme/*.xml"))
82 wanted += list(self.unpacked_dir.glob("ppt/theme/_rels/*.rels"))
83 wanted += list(self.unpacked_dir.glob("ppt/charts/chart*.xml"))
84 for group in ("slideMasters", "notesMasters", "handoutMasters"):
85 wanted += list(self.unpacked_dir.glob(f"ppt/{group}/*.xml"))
86 wanted += list(self.unpacked_dir.glob(f"ppt/{group}/_rels/*.rels"))
87 return {
88 p.relative_to(self.unpacked_dir).as_posix(): p.read_bytes()
89 for p in wanted
90 if p.is_file()
91 }
92
93 @staticmethod
94 def _print_line(text: str, limit: int) -> None:
95 from helpers import one_line
96
97 print(one_line(text, limit))
98
99 def _listed_slides(self) -> set[str] | None:
100 import lxml.etree
101
102 from helpers import SLIDE_REL_TYPE
103
104 r_id = f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id"
105 try:
106 pres = lxml.etree.parse(str(self.unpacked_dir / "ppt" / "presentation.xml"))
107 rels = lxml.etree.parse(str(self.unpacked_dir / "ppt" / "_rels" / "presentation.xml.rels"))
108 listed = {e.get(r_id) for e in pres.iter(f"{{{self.PRESENTATIONML_NAMESPACE}}}sldId")}
109 return {
110 opc_target(rel.get("Target", ""), "ppt/presentation.xml", rel.get("TargetMode", ""))
111 for rel in rels.getroot()
112 if rel.get("Id") in listed and rel.get("Type") == SLIDE_REL_TYPE
113 }
114 except (OSError, ValueError, lxml.etree.XMLSyntaxError):
115 return None
116
117 def validate_master_theme_uniqueness(self):
118 from helpers.pptx_theme import _NOTES_MASTERS, live_shared_master_themes
119
120 shared = live_shared_master_themes(self._package_map())
121 if shared:
122 print(f"FAILED - Found {len(shared)} master(s) sharing a theme part:")
123 for message in shared:
124 self._print_line(f" {message}", 300)
125 if any(m.startswith(_NOTES_MASTERS) for m in shared):
126 print(" Fix: in ppt/presentation.xml, move <p:notesMasterIdLst> back to "
127 "directly after <p:sldIdLst>. PowerPoint reads that happily.")
128 else:
129 print(" Fix: give each master its own theme part.")
130 return False
131
132 if self.verbose:
133 print("PASSED - No master shares a theme part in a way PowerPoint refuses")
134 return True
135
136 def validate_tags(self):
137 from collections import Counter
138
139 import lxml.etree
140
141 ns = {"p": self.PRESENTATIONML_NAMESPACE, "mc": self.MC_NAMESPACE}
142 r_id = f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id"
143 errors = []
144 owners: dict[str, list[str]] = {}
145 listed = self._listed_slides()
146
147 for slide in sorted(self.unpacked_dir.glob("ppt/slides/*.xml")):
148 relative = slide.relative_to(self.unpacked_dir).as_posix()
149 if listed is not None and relative not in listed:
150 continue
151 try:
152 root = lxml.etree.parse(str(slide)).getroot()
153 named = [t.get(r_id) for t in root.xpath(
154 ".//p:tags[not(ancestor::mc:Fallback) and not(ancestor::mc:Choice[preceding-sibling::mc:Choice])]",
155 namespaces=ns)]
156 rels_file = slide.parent / "_rels" / f"{slide.name}.rels"
157 targets = {
158 rel.get("Id"): opc_target(rel.get("Target", ""), relative, rel.get("TargetMode", ""))
159 for rel in lxml.etree.parse(str(rels_file)).getroot()
160 if rel.get("Type", "").endswith("/relationships/tags")
161 } if rels_file.is_file() else {}
162 except (lxml.etree.XMLSyntaxError, ValueError):
163 continue
164 for rid, count in sorted(Counter(r for r in named if r).items()):
165 if count > 1:
166 errors.append(
167 f" {relative[:80]}: {count} <p:tags> elements name the tags relationship "
168 f"{rid!r:.20}. Fix: a copied shape kept its <p:custDataLst>; delete that "
169 f"from the copy, or give it a tags part and relationship of its own"
170 )
171 if targets.get(rid):
172 owners.setdefault(targets[rid], []).append(relative)
173
174 for part, slides in sorted(owners.items()):
175 if len(slides) > 1:
176 named_from = sorted(set(slides))
177 more = f" and {len(named_from) - 3} more" if len(named_from) > 3 else ""
178 errors.append(
179 f" {part[:80]}: {len(slides)} tags relationships name it, from "
180 f"{', '.join(s[:60] for s in named_from[:3])}{more}. Fix: copy the part under a new name, add "
181 f"its Override to [Content_Types].xml and point every relationship but one at a copy of its own "
182 f"(add_slide.py does this when it duplicates a slide)"
183 )
184
185 if errors:
186 print(f"FAILED - Found {len(errors)} tags part(s) with more than one owner; PowerPoint offers to repair the deck:")
187 for error in errors:
188 self._print_line(error, 700)
189 return False
190 if self.verbose:
191 print("PASSED - Every tags part has one owner")
192 return True
193
194 def validate_charts(self):
195 from helpers.pptx_chart import find_chart_problems
196
197 problems = find_chart_problems(self._package_map())
198 if problems:
199 print(f"FAILED - Found {len(problems)} chart problem(s) PowerPoint rejects:")
200 for message in problems:
201 self._print_line(f" {message}", 600)
202 return False
203
204 if self.verbose:
205 print("PASSED - Charts satisfy the constraints PowerPoint enforces")
206 return True
207
208 def _original_slide_defects(self, schema) -> set[str]:
209 import tempfile
210 import zipfile
211
212 from helpers.pptx_slide import SLIDE_PART_RE, fatal_slide_errors
213
214 if self.original_file is None:
215 return set()
216
217 found: set[str] = set()
218 with tempfile.TemporaryDirectory() as temp_dir:
219 temp_path = Path(temp_dir)
220 try:
221 with zipfile.ZipFile(self.original_file, "r") as zf:
222 safe_extract(zf, temp_path)
223 except (zipfile.BadZipFile, ValueError, OSError):
224 return set()
225
226 for part in sorted(temp_path.rglob("*.xml")):
227 relative = part.relative_to(temp_path).as_posix()
228 if not SLIDE_PART_RE.fullmatch(relative):
229 continue
230 ok, errors = self._validate_single_file_xsd(
231 part.resolve(), temp_path.resolve(), schema_path=schema
232 )
233 if ok is None or ok or not errors:
234 continue
235 found |= set(fatal_slide_errors(set(errors)))
236 return found
237
238 def validate_slides(self):
239 import lxml.etree
240
241 from helpers.pptx_slide import (
242 SLIDE_PART_RE,
243 fatal_slide_errors,
244 is_schema_verdict,
245 stranded_animation_targets,
246 )
247
248 schema = self.schemas_dir / self.SCHEMA_MAPPINGS["ppt"]
249 inherited = self._original_slide_defects(schema)
250 listed = self._listed_slides()
251 problems: list[str] = []
252 broken: list[str] = []
253
254 for xml_file in self.xml_files:
255 relative = xml_file.relative_to(self.unpacked_dir).as_posix()
256 if not SLIDE_PART_RE.fullmatch(relative):
257 continue
258 unlisted = relative.startswith("ppt/slides/") and listed is not None and relative not in listed
259 try:
260 root = lxml.etree.parse(str(xml_file)).getroot()
261 stranded = [] if unlisted else stranded_animation_targets(root)
262 except lxml.etree.XMLSyntaxError:
263 stranded = []
264 problems.extend(f"{relative}: {m}" for m in stranded)
265
266 ok, errors = self._validate_single_file_xsd(
267 xml_file.resolve(), self.unpacked_dir.resolve(), schema_path=schema
268 )
269 if ok is None or not errors:
270 continue
271
272 unreadable = [f"{relative}: {e}" for e in errors if not is_schema_verdict(e)]
273 if unreadable:
274 broken.extend(unreadable)
275 continue
276 if ok:
277 continue
278
279 for message in fatal_slide_errors(set(errors)):
280 if message in inherited:
281 continue
282 problems.append(f"{relative}: {message}")
283
284 if broken:
285 print(f"FAILED - Could not check {len(broken)} slide part(s):")
286 for message in sorted(broken):
287 self._print_line(f" {message}", 240)
288
289 if problems:
290 print(f"FAILED - Found {len(problems)} slide problem(s) PowerPoint rejects:")
291 for message in sorted(problems):
292 self._print_line(f" {message}", 240)
293
294 if broken or problems:
295 return False
296
297 if self.verbose:
298 print("PASSED - Slide XML has none of the defects PowerPoint refuses")
299 return True
300
301 def _get_schema_path(self, xml_file):
302 if xml_file.parent.name == "charts" and xml_file.name.startswith("chart"):
303 return None
304 if xml_file.parent.name == "ppt" and xml_file.suffix == ".xml":
305 import lxml.etree
306
307 try:
308 root = lxml.etree.parse(str(xml_file)).getroot()
309 except (lxml.etree.XMLSyntaxError, OSError):
310 root = None
311 if root is not None and (lxml.etree.QName(root).namespace or "").startswith(
312 "http://schemas.microsoft.com/office/"
313 ):
314 return None
315 return super()._get_schema_path(xml_file)
316
317 def _preprocess_for_schema(self, xml_doc, relative_path):
318 if relative_path.as_posix() != "ppt/presentation.xml":
319 return xml_doc
320
321 root = xml_doc.getroot()
322 ns = f"{{{self.PRESENTATIONML_NAMESPACE}}}"
323 notes = root.find(f"{ns}notesMasterIdLst")
324 slides = root.find(f"{ns}sldIdLst")
325 if notes is None or slides is None:
326 return xml_doc
327
328 children = list(root)
329 if children.index(notes) < children.index(slides):
330 return xml_doc
331
332 root.remove(notes)
333 root.insert(list(root).index(slides), notes)
334 return xml_doc
335
336 def validate_uuid_ids(self):
337 import lxml.etree
338
339 errors = []
340 uuid_pattern = re.compile(
341 r"^[\{\(]?[0-9A-Fa-f]{8}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{12}[\}\)]?$"
342 )
343
344 for xml_file in self.xml_files:
345 try:
346 root = lxml.etree.parse(str(xml_file)).getroot()
347
348 for elem in root.iter():
349 for attr, value in elem.attrib.items():
350 attr_name = attr.split("}")[-1].lower()
351 if attr_name == "id" or attr_name.endswith("id"):
352 if self._looks_like_uuid(value):
353 if not uuid_pattern.match(value):
354 errors.append(
355 f" {xml_file.relative_to(self.unpacked_dir)}: "
356 f"Line {elem.sourceline}: ID '{value}' appears to be a UUID but contains invalid hex characters"
357 )
358
359 except (lxml.etree.XMLSyntaxError, Exception) as e:
360 errors.append(
361 f" {xml_file.relative_to(self.unpacked_dir)}: Error: {e}"
362 )
363
364 if errors:
365 print(f"FAILED - Found {len(errors)} UUID ID validation errors:")
366 for error in errors:
367 self._print_line(error, 300)
368 return False
369 else:
370 if self.verbose:
371 print("PASSED - All UUID-like IDs contain valid hex values")
372 return True
373
374 def _looks_like_uuid(self, value):
375 clean_value = value.strip("{}()").replace("-", "")
376 return len(clean_value) == 32 and all(c.isalnum() for c in clean_value)
377
378 def validate_slide_layout_ids(self):
379 import lxml.etree
380
381 errors = []
382
383 slide_masters = list(self.unpacked_dir.glob("ppt/slideMasters/*.xml"))
384
385 if not slide_masters:
386 if self.verbose:
387 print("PASSED - No slide masters found")
388 return True
389
390 for slide_master in slide_masters:
391 try:
392 root = lxml.etree.parse(str(slide_master)).getroot()
393
394 rels_file = slide_master.parent / "_rels" / f"{slide_master.name}.rels"
395
396 if not rels_file.exists():
397 errors.append(
398 f" {slide_master.relative_to(self.unpacked_dir)}: "
399 f"Missing relationships file: {rels_file.relative_to(self.unpacked_dir)}"
400 )
401 continue
402
403 rels_root = lxml.etree.parse(str(rels_file)).getroot()
404
405 valid_layout_rids = set()
406 for rel in rels_root.findall(
407 f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship"
408 ):
409 rel_type = rel.get("Type", "")
410 if "slideLayout" in rel_type:
411 valid_layout_rids.add(rel.get("Id"))
412
413 for sld_layout_id in root.findall(
414 f".//{{{self.PRESENTATIONML_NAMESPACE}}}sldLayoutId"
415 ):
416 r_id = sld_layout_id.get(
417 f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id"
418 )
419 layout_id = sld_layout_id.get("id")
420
421 if r_id and r_id not in valid_layout_rids:
422 errors.append(
423 f" {slide_master.relative_to(self.unpacked_dir)}: "
424 f"Line {sld_layout_id.sourceline}: sldLayoutId with id='{layout_id}' "
425 f"references r:id='{r_id}' which is not found in slide layout relationships"
426 )
427
428 except (lxml.etree.XMLSyntaxError, Exception) as e:
429 errors.append(
430 f" {slide_master.relative_to(self.unpacked_dir)}: Error: {e}"
431 )
432
433 if errors:
434 print(f"FAILED - Found {len(errors)} slide layout ID validation errors:")
435 for error in errors:
436 self._print_line(error, 300)
437 print(
438 "Remove invalid references or add missing slide layouts to the relationships file."
439 )
440 return False
441 else:
442 if self.verbose:
443 print("PASSED - All slide layout IDs reference valid slide layouts")
444 return True
445
446 def validate_no_duplicate_slide_layouts(self):
447 import lxml.etree
448
449 errors = []
450 slide_rels_files = list(self.unpacked_dir.glob("ppt/slides/_rels/*.xml.rels"))
451
452 for rels_file in slide_rels_files:
453 try:
454 root = lxml.etree.parse(str(rels_file)).getroot()
455
456 layout_rels = [
457 rel
458 for rel in root.findall(
459 f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship"
460 )
461 if "slideLayout" in rel.get("Type", "")
462 ]
463
464 if len(layout_rels) > 1:
465 errors.append(
466 f" {rels_file.relative_to(self.unpacked_dir)}: has {len(layout_rels)} slideLayout references"
467 )
468
469 except Exception as e:
470 errors.append(
471 f" {rels_file.relative_to(self.unpacked_dir)}: Error: {e}"
472 )
473
474 if errors:
475 print("FAILED - Found slides with duplicate slideLayout references:")
476 for error in errors:
477 self._print_line(error, 300)
478 return False
479 else:
480 if self.verbose:
481 print("PASSED - All slides have exactly one slideLayout reference")
482 return True
483
484 def validate_notes_slide_references(self):
485 import lxml.etree
486
487 errors = []
488 notes_slide_references = {}
489
490 slide_rels_files = list(self.unpacked_dir.glob("ppt/slides/_rels/*.xml.rels"))
491
492 if not slide_rels_files:
493 if self.verbose:
494 print("PASSED - No slide relationship files found")
495 return True
496
497 for rels_file in slide_rels_files:
498 try:
499 root = lxml.etree.parse(str(rels_file)).getroot()
500
501 for rel in root.findall(
502 f".//{{{self.PACKAGE_RELATIONSHIPS_NAMESPACE}}}Relationship"
503 ):
504 rel_type = rel.get("Type", "")
505 if "notesSlide" in rel_type:
506 part = opc_target(
507 rel.get("Target", ""),
508 rels_source_part(rels_file, self.unpacked_dir),
509 rel.get("TargetMode", ""),
510 )
511 if part:
512 slide_name = rels_file.stem.replace(
513 ".xml", ""
514 )
515
516 notes_slide_references.setdefault(part, []).append(
517 (slide_name, rels_file)
518 )
519
520 except (lxml.etree.XMLSyntaxError, Exception) as e:
521 errors.append(
522 f" {rels_file.relative_to(self.unpacked_dir)}: Error: {e}"
523 )
524
525 for target, references in notes_slide_references.items():
526 if len(references) > 1:
527 slide_names = [ref[0] for ref in references]
528 errors.append(
529 f" Notes slide '{target}' is referenced by multiple slides: {', '.join(slide_names)}"
530 )
531 for slide_name, rels_file in references:
532 errors.append(f" - {rels_file.relative_to(self.unpacked_dir)}")
533
534 if errors:
535 print(
536 f"FAILED - Found {len([e for e in errors if not e.startswith(' ')])} notes slide reference validation errors:"
537 )
538 for error in errors:
539 self._print_line(error, 300)
540 print("Each slide may optionally have its own slide file.")
541 return False
542 else:
543 if self.verbose:
544 print("PASSED - All notes slide references are unique")
545 return True
546
547
548if __name__ == "__main__":
549 raise RuntimeError("This module should not be run directly.")