Skillfarm / skills · skillfarm.ai / converted / docx / scripts / office / validate.py
| 1 | """ |
| 2 | Command line tool to validate Office document XML files against XSD schemas and tracked changes. |
| 3 | |
| 4 | Usage: |
| 5 | python validate.py <path> [--original <original_file>] [--auto-repair] [--author NAME] |
| 6 | |
| 7 | The first argument can be either: |
| 8 | - An unpacked directory containing the Office document XML files |
| 9 | - A packed Office file (.docx/.pptx/.xlsx or .dotx/.potx/.xltx template) which will be unpacked to a temp directory |
| 10 | |
| 11 | Auto-repair fixes: |
| 12 | - paraId/durableId values that exceed OOXML limits |
| 13 | - Missing xml:space="preserve" on w:t elements with whitespace |
| 14 | """ |
| 15 | |
| 16 | import argparse |
| 17 | import shlex |
| 18 | import sys |
| 19 | import tempfile |
| 20 | import zipfile |
| 21 | from pathlib import Path |
| 22 | |
| 23 | import defusedxml.ElementTree as ET |
| 24 | from defusedxml.common import DefusedXmlException |
| 25 | |
| 26 | from helpers import OOXML_FAMILY, folder_entries, rezip, safe_extract |
| 27 | from validators import DOCXSchemaValidator, PPTXSchemaValidator, RedliningValidator |
| 28 | |
| 29 | WORD_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" |
| 30 | |
| 31 | |
| 32 | def _as_argument(path: Path) -> str: |
| 33 | name = str(path) |
| 34 | return shlex.quote("./" + name if name.startswith("-") else name) |
| 35 | |
| 36 | |
| 37 | def _count(folders: list[str]) -> str: |
| 38 | return "1 folder entry" if len(folders) == 1 else f"{len(folders)} folder entries" |
| 39 | |
| 40 | |
| 41 | def _fail(message: str): |
| 42 | print(f"Error: {message}", file=sys.stderr) |
| 43 | sys.exit(2) |
| 44 | |
| 45 | |
| 46 | def _unpack(package: Path, dest: Path): |
| 47 | try: |
| 48 | with zipfile.ZipFile(package, "r") as zf: |
| 49 | safe_extract(zf, dest) |
| 50 | except Exception as e: |
| 51 | _fail(f"cannot unpack {package}: {e}") |
| 52 | |
| 53 | |
| 54 | def _has_tracked_changes(unpacked_dir: Path) -> bool: |
| 55 | document = unpacked_dir / "word" / "document.xml" |
| 56 | if not document.is_file(): |
| 57 | return False |
| 58 | try: |
| 59 | root = ET.parse(document).getroot() |
| 60 | except (ET.ParseError, DefusedXmlException): |
| 61 | return False |
| 62 | tracked = {f"{{{WORD_NS}}}ins", f"{{{WORD_NS}}}del"} |
| 63 | return any(elem.tag in tracked for elem in root.iter()) |
| 64 | |
| 65 | |
| 66 | def main(): |
| 67 | parser = argparse.ArgumentParser(description="Validate Office document XML files") |
| 68 | parser.add_argument( |
| 69 | "path", |
| 70 | help="Path to unpacked directory or packed Office file (.docx/.pptx/.xlsx or .dotx/.potx/.xltx)", |
| 71 | ) |
| 72 | parser.add_argument( |
| 73 | "--original", |
| 74 | required=False, |
| 75 | default=None, |
| 76 | help="Path to original file (.docx/.pptx/.xlsx or .dotx/.potx/.xltx). If omitted, all XSD errors are reported and redlining validation is skipped.", |
| 77 | ) |
| 78 | parser.add_argument( |
| 79 | "-v", |
| 80 | "--verbose", |
| 81 | action="store_true", |
| 82 | help="Enable verbose output", |
| 83 | ) |
| 84 | parser.add_argument( |
| 85 | "--auto-repair", |
| 86 | action="store_true", |
| 87 | help="Automatically repair common issues (hex IDs, whitespace preservation). " |
| 88 | "Modifies the input in place: repairs to a packed file are written back to it.", |
| 89 | ) |
| 90 | parser.add_argument( |
| 91 | "--author", |
| 92 | default=None, |
| 93 | help="The name you are redlining under. Passing it turns on the " |
| 94 | "tracked-change check: any text differing from --original without a " |
| 95 | "<w:ins>/<w:del> recording it is reported. Untracked edits carry no " |
| 96 | "author, so the check covers them whoever made them — the name marks " |
| 97 | "the run as redlining work and is not used to filter. Requires " |
| 98 | "--original; docx only.", |
| 99 | ) |
| 100 | args = parser.parse_args() |
| 101 | |
| 102 | if args.author is not None and not args.original: |
| 103 | _fail("--author requires --original") |
| 104 | |
| 105 | path = Path(args.path) |
| 106 | if not path.exists(): |
| 107 | _fail(f"{path} does not exist") |
| 108 | |
| 109 | original_file = None |
| 110 | if args.original: |
| 111 | original_file = Path(args.original) |
| 112 | if not original_file.is_file(): |
| 113 | _fail(f"{original_file} is not a file") |
| 114 | if original_file.suffix.lower() not in OOXML_FAMILY: |
| 115 | _fail(f"{original_file} must be one of: {', '.join(sorted(OOXML_FAMILY))}") |
| 116 | with tempfile.TemporaryDirectory() as scratch: |
| 117 | _unpack(original_file, Path(scratch)) |
| 118 | |
| 119 | family = OOXML_FAMILY.get((original_file or path).suffix.lower()) |
| 120 | if family is None: |
| 121 | _fail( |
| 122 | f"Cannot determine file type from {path}. Use --original or provide one of: {', '.join(sorted(OOXML_FAMILY))}." |
| 123 | ) |
| 124 | |
| 125 | if args.author is not None and family != "docx": |
| 126 | _fail(f"--author only applies to docx files, not {family}") |
| 127 | |
| 128 | packed_file = None |
| 129 | temp_dir_ctx = None |
| 130 | if path.is_file() and path.suffix.lower() in OOXML_FAMILY: |
| 131 | packed_file = path |
| 132 | temp_dir_ctx = tempfile.TemporaryDirectory() |
| 133 | unpacked_dir = Path(temp_dir_ctx.name) |
| 134 | _unpack(path, unpacked_dir) |
| 135 | else: |
| 136 | if not path.is_dir(): |
| 137 | _fail(f"{path} is not a directory or Office file") |
| 138 | unpacked_dir = path |
| 139 | |
| 140 | match family: |
| 141 | case "docx": |
| 142 | validators = [ |
| 143 | DOCXSchemaValidator(unpacked_dir, original_file, verbose=args.verbose), |
| 144 | ] |
| 145 | if args.author is not None: |
| 146 | validators.append( |
| 147 | RedliningValidator(unpacked_dir, original_file, verbose=args.verbose) |
| 148 | ) |
| 149 | elif original_file and _has_tracked_changes(unpacked_dir): |
| 150 | print( |
| 151 | "Note: this document has tracked changes; they were not " |
| 152 | "checked against the original (pass --author to check)." |
| 153 | ) |
| 154 | case "pptx": |
| 155 | validators = [ |
| 156 | PPTXSchemaValidator(unpacked_dir, original_file, verbose=args.verbose), |
| 157 | ] |
| 158 | case "xlsx": |
| 159 | exts = ", ".join(k for k, v in sorted(OOXML_FAMILY.items()) if v == "xlsx") |
| 160 | print( |
| 161 | f"No XSD schema validation is performed for xlsx-family files ({exts}). " |
| 162 | "For formula-error checking, use scripts/recalc.py instead." |
| 163 | ) |
| 164 | sys.exit(0) |
| 165 | case _: |
| 166 | print(f"Error: Validation not supported for file type {family}") |
| 167 | sys.exit(1) |
| 168 | |
| 169 | folders = folder_entries(packed_file) if packed_file is not None else [] |
| 170 | |
| 171 | unsaved_repairs = 0 |
| 172 | if args.auto_repair: |
| 173 | total_repairs = sum(v.repair() for v in validators) |
| 174 | if total_repairs: |
| 175 | print(f"Auto-repaired {total_repairs} issue(s)") |
| 176 | if packed_file is not None and (total_repairs or folders): |
| 177 | try: |
| 178 | rezip(unpacked_dir, packed_file) |
| 179 | except OSError as e: |
| 180 | unsaved_repairs = total_repairs |
| 181 | left = [] |
| 182 | if total_repairs: |
| 183 | left.append(f"{total_repairs} repair(s) not saved") |
| 184 | if folders: |
| 185 | left.append(f"{_count(folders)} in its ZIP") |
| 186 | print(f"Could not write {packed_file} ({e.strerror or e}): it is as it was, " |
| 187 | f"with {' and '.join(left)}. Run --auto-repair on a copy in a folder " |
| 188 | "you can write to.") |
| 189 | else: |
| 190 | if folders: |
| 191 | print(f"Removed {_count(folders)} from the ZIP") |
| 192 | print(f"Wrote repaired file to {packed_file}") |
| 193 | elif folders: |
| 194 | print( |
| 195 | f"Note: {_count(folders)} in the ZIP. Such files have failed to open or co-edit " |
| 196 | f"through a cloud service. Remove them: zip -dq {_as_argument(packed_file)} '*/'" |
| 197 | ) |
| 198 | |
| 199 | success = all([v.validate() for v in validators]) |
| 200 | |
| 201 | if unsaved_repairs: |
| 202 | print(f"FAILED - {packed_file} was not rewritten and still has the {unsaved_repairs} " |
| 203 | "issue(s) repaired above; the checks ran on a repaired copy") |
| 204 | success = False |
| 205 | |
| 206 | if temp_dir_ctx is not None: |
| 207 | temp_dir_ctx.cleanup() |
| 208 | |
| 209 | if success: |
| 210 | print("All validations PASSED!") |
| 211 | |
| 212 | sys.exit(0 if success else 1) |
| 213 | |
| 214 | |
| 215 | if __name__ == "__main__": |
| 216 | main() |