Branchwell

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

1"""
2Validator for tracked changes in Word documents.
3
4Detects untracked edits in a Word document: text that differs from the
5original without a <w:ins>/<w:del> wrapper recording it. The tracked changes
6that are new relative to the original are undone, and the result is compared
7against the original; whatever text still differs was edited without being
8tracked.
9
10The body (word/document.xml) is compared, and so is each header, footer,
11footnotes and endnotes part, against the original's part of the same name.
12Other parts, comments among them, are not checked. A page-number field
13whose cached result is a plain number counts as its name in braces
14("{PAGE}"), not as that number, which any application that repaginates the
15document rewrites.
16"""
17
18import re
19import tempfile
20import zipfile
21from difflib import SequenceMatcher
22from pathlib import Path
23
24import defusedxml.ElementTree as ET
25from defusedxml.common import DefusedXmlException
26
27from helpers import rendered_text, safe_extract
28
29
30XML_ERRORS = (ET.ParseError, DefusedXmlException, LookupError, ValueError)
31
32
33class _WorkSpent(Exception):
34
35 pass
36
37
38class _Matcher(SequenceMatcher):
39
40 def __init__(self, a, b, allowance):
41 self.allowance = allowance
42 super().__init__(None, a, b, autojunk=False)
43
44 def find_longest_match(self, alo=0, ahi=None, blo=0, bhi=None):
45 items = self.a[alo:ahi]
46 self.allowance[0] -= len(items) + sum(len(self.b2j.get(x, ())) for x in items)
47 if self.allowance[0] < 0:
48 raise _WorkSpent
49 return super().find_longest_match(alo, ahi, blo, bhi)
50
51
52class RedliningValidator:
53
54 def __init__(self, unpacked_dir, original_docx, verbose=False):
55 self.unpacked_dir = Path(unpacked_dir)
56 self.original_docx = Path(original_docx)
57 self.verbose = verbose
58 self._work_left = [self.WORK_ALLOWED]
59 self.namespaces = {
60 "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
61 }
62
63 def repair(self) -> int:
64 return 0
65
66 def validate(self):
67 modified_file = self.unpacked_dir / "word" / "document.xml"
68 if not modified_file.exists():
69 print(f"FAILED - Modified document.xml not found at {modified_file}")
70 return False
71
72 with tempfile.TemporaryDirectory() as temp_dir:
73 temp_path = Path(temp_dir)
74
75 try:
76 with zipfile.ZipFile(self.original_docx, "r") as zip_ref:
77 safe_extract(zip_ref, temp_path)
78 except Exception as e:
79 print(f"FAILED - Error unpacking original docx: {e}")
80 return False
81
82 original_file = temp_path / "word" / "document.xml"
83 if not original_file.exists():
84 print(
85 f"FAILED - Original document.xml not found in {self.original_docx}"
86 )
87 return False
88
89 sides = (("original", temp_path), ("modified", self.unpacked_dir))
90 change_count, failures, differences = 0, [], []
91 for part in self._parts_to_compare(temp_path, self.unpacked_dir):
92 roots = []
93 for side, unpacked in sides:
94 try:
95 roots.append(self._parse_part(unpacked / part))
96 except XML_ERRORS as e:
97 failures.append(
98 f"FAILED - Error parsing {part} of the {side} document: {e}"
99 )
100 if len(roots) < len(sides):
101 continue
102 new_changes, original_text, modified_text = self._compare_part(*roots)
103 change_count += len(new_changes)
104 if modified_text != original_text:
105 differences.append((part, original_text, modified_text))
106
107 if differences:
108 failures.append(self._generate_detailed_diff(differences))
109 if failures:
110 print("\n".join(failures))
111 return False
112
113 if self.verbose:
114 print(
115 f"PASSED - All {change_count} change(s) against the original "
116 "are properly tracked"
117 )
118 return True
119
120 OTHER_PARTS = (
121 "word/header*.xml",
122 "word/footer*.xml",
123 "word/footnotes.xml",
124 "word/endnotes.xml",
125 )
126
127 def _parts_to_compare(self, original_dir, modified_dir):
128 others = set()
129 for unpacked in (Path(original_dir), Path(modified_dir)):
130 for pattern in self.OTHER_PARTS:
131 others.update(
132 path.relative_to(unpacked).as_posix()
133 for path in unpacked.glob(pattern)
134 )
135 return ["word/document.xml", *sorted(others)]
136
137 def _compare_part(self, original_root, modified_root):
138 for root in (original_root, modified_root):
139 self._flatten_text_elements(root)
140 new_changes = self._new_tracked_changes(original_root, modified_root)
141 self._remove_tracked_changes(modified_root, new_changes)
142 return (
143 new_changes,
144 self._extract_text_content(original_root),
145 self._extract_text_content(modified_root),
146 )
147
148 def _parse_part(self, path):
149 if not path.is_file():
150 return ET.fromstring("<absent/>")
151 return ET.parse(path).getroot()
152
153 def _flatten_text_elements(self, root):
154 for elem in self._text_elements(root):
155 if len(elem):
156 elem.text = "".join(elem.itertext())
157 for child in list(elem):
158 elem.remove(child)
159
160 def _tracked_change_elements(self, root):
161 w = self.namespaces["w"]
162 tags = (f"{{{w}}}ins", f"{{{w}}}del", f"{{{w}}}moveFrom", f"{{{w}}}moveTo")
163 return [elem for elem in root.iter() if elem.tag in tags]
164
165 def _rendered_text(self, elem):
166 preserve = elem.get("{http://www.w3.org/XML/1998/namespace}space") == "preserve"
167 return rendered_text(elem.text or "", preserve)
168
169 def _text_elements(self, elem):
170 w = self.namespaces["w"]
171 return [
172 node
173 for node in elem.iter()
174 if node.tag in (f"{{{w}}}t", f"{{{w}}}delText")
175 ]
176
177 def _tracked_change_key(self, elem):
178 w = self.namespaces["w"]
179 text = "".join(self._rendered_text(node) for node in self._text_elements(elem))
180 return (elem.tag, elem.get(f"{{{w}}}author"), elem.get(f"{{{w}}}date"), text)
181
182 def _new_tracked_changes(self, original_root, modified_root):
183 original = self._tracked_change_elements(original_root)
184 modified = self._tracked_change_elements(modified_root)
185
186 pool = {}
187 for elem in original:
188 pool.setdefault(self._tracked_change_key(elem), []).append(elem)
189
190 matched, leftover = set(), []
191 for elem in modified:
192 bucket = pool.get(self._tracked_change_key(elem))
193 if bucket:
194 matched.add(bucket.pop())
195 else:
196 leftover.append(elem)
197
198 def group(elem):
199 return self._tracked_change_key(elem)[:3]
200
201 def text_of(elems):
202 return "".join(self._tracked_change_key(e)[3] for e in elems)
203
204 unmatched_original = {}
205 for elem in original:
206 if elem not in matched:
207 unmatched_original.setdefault(group(elem), []).append(elem)
208
209 by_group = {}
210 for elem in leftover:
211 by_group.setdefault(group(elem), []).append(elem)
212
213 new = set()
214 for key, elems in by_group.items():
215 rebuilt = text_of(elems)
216 if rebuilt and rebuilt == text_of(unmatched_original.get(key, [])):
217 continue
218 new.update(elems)
219 return new
220
221 def _generate_detailed_diff(self, differences):
222 self._work_left = [self.WORK_ALLOWED]
223 error_parts = [
224 "FAILED - Document text doesn't match after removing the tracked changes",
225 "",
226 "Likely causes:",
227 " 1. Modified text inside another author's <w:ins> or <w:del> tags",
228 " 2. Made edits without proper tracked changes",
229 " 3. Didn't nest <w:del> inside <w:ins> when deleting another's insertion",
230 " 4. Rewrote another author's <w:ins>/<w:del> and changed its text on",
231 " the way. A tracked change from the original is recognised by its",
232 " author, date and text; anything that doesn't reproduce one exactly",
233 " reads as new, and the text it carried is reported missing.",
234 "",
235 "For pre-redlined documents, use correct patterns:",
236 " - To reject another's INSERTION: Nest <w:del> inside their <w:ins>",
237 " - To reject PART of one: nest <w:del> around only the runs you reject.",
238 " Their <w:ins> may be split around it, so long as the pieces keep",
239 " their author and date and still spell out the same text.",
240 " - To restore another's DELETION: Add new <w:ins> AFTER their <w:del>",
241 "",
242 ]
243
244 explain_page_fields = False
245 for part, original_text, modified_text in differences:
246 body = part == "word/document.xml"
247 heading = "Differences:" if body else f"Differences in {part}:"
248 if error_parts[-1]:
249 error_parts.append("")
250 word_diff = self._word_diff(original_text, modified_text)
251 error_parts.extend([heading, "=" * len(heading), word_diff])
252 if original_text.replace("\n", "") == modified_text.replace("\n", ""):
253 error_parts.append("Only paragraph breaks differ here.")
254 if re.search(r"\{(%s)\}" % "|".join(self.PAGE_FIELDS), word_diff):
255 explain_page_fields = True
256 if explain_page_fields:
257 error_parts.extend(["", self.PAGE_FIELD_NOTE])
258 if self._work_left[0] < 0:
259 error_parts.extend(["", self.WORK_SPENT_NOTE])
260
261 return "\n".join(error_parts)
262
263 def _word_diff(self, original_text, modified_text):
264 out = []
265 steps = self._steps(original_text.split("\n"), modified_text.split("\n"))
266 for tag, was, now in steps:
267 if tag == "replace" and len(was) == len(now):
268 out.extend(self._mark_changes(x, y) for x, y in zip(was, now) if x != y)
269 elif tag != "equal":
270 out.append(self._mark_changes("\n".join(was), "\n".join(now)))
271 return "\n".join(out)
272
273 def _mark_changes(self, old, new, by_character=False, trim=True):
274
275 def mark(text, opening, closing):
276 marked = re.sub(r"[^\n]+", lambda m: opening + m[0] + closing, text)
277 return marked if marked.strip("\n") or opening == "{+" else ""
278
279 pattern = "(?s)." if by_character else r"\S+\s*|\s+"
280 out = []
281 steps = self._steps(re.findall(pattern, old), re.findall(pattern, new), trim)
282 for tag, was, now in steps:
283 lone_word = len(was) == len(now) == 1
284 was, now = "".join(was), "".join(now)
285 if tag == "equal":
286 out.append(now)
287 elif tag == "replace" and not by_character:
288 long_word = lone_word and min(len(was), len(now)) > self.LONG_WORD
289 marked = self._mark_changes(was, now, by_character=True, trim=long_word)
290 out.append(marked)
291 else:
292 out.append(mark(was, "[-", "-]") + mark(now, "{+", "+}"))
293 return "".join(out)
294
295 WORK_ALLOWED = 10_000_000
296 LONG_WORD = 200
297
298 def _steps(self, a, b, trim=True):
299
300 def shared_start(x, y):
301 return next(
302 (i for i, (p, q) in enumerate(zip(x, y)) if p != q), min(len(x), len(y))
303 )
304
305 head = shared_start(a, b) if trim else 0
306 tail = shared_start(a[head:][::-1], b[head:][::-1]) if trim else 0
307 a_mid, b_mid = a[head : len(a) - tail], b[head : len(b) - tail]
308 try:
309 if self._work_left[0] < len(a_mid):
310 self._work_left[0] = -1
311 raise _WorkSpent
312 numbers = {}
313 numbered = [
314 [numbers.setdefault(x, len(numbers)) for x in s] for s in (a_mid, b_mid)
315 ]
316 opcodes = _Matcher(*numbered, self._work_left).get_opcodes()
317 steps = [(tag, a_mid[i:j], b_mid[m:n]) for tag, i, j, m, n in opcodes]
318 except _WorkSpent:
319 steps = [("replace", a_mid, b_mid)]
320 return [
321 ("equal", a[:head], b[:head]),
322 *steps,
323 ("equal", a[len(a) - tail :], b[len(b) - tail :]),
324 ]
325
326 def _remove_tracked_changes(self, root, targets):
327 w = self.namespaces["w"]
328 ins_tag = f"{{{w}}}ins"
329 del_tag = f"{{{w}}}del"
330 move_from_tag = f"{{{w}}}moveFrom"
331 move_to_tag = f"{{{w}}}moveTo"
332
333 self._merge_split_paragraphs(root, targets)
334
335 for parent in root.iter():
336 to_remove = []
337 for child in parent:
338 if child.tag in (ins_tag, move_to_tag) and child in targets:
339 to_remove.append(child)
340 for elem in to_remove:
341 parent.remove(elem)
342
343 renamed = {
344 f"{{{w}}}delText": f"{{{w}}}t",
345 f"{{{w}}}delInstrText": f"{{{w}}}instrText",
346 }
347
348 for parent in root.iter():
349 to_process = []
350 for child in parent:
351 if child.tag in (del_tag, move_from_tag) and child in targets:
352 to_process.append((child, list(parent).index(child)))
353
354 for del_elem, del_index in reversed(to_process):
355 for elem in del_elem.iter():
356 elem.tag = renamed.get(elem.tag, elem.tag)
357
358 for child in reversed(list(del_elem)):
359 parent.insert(del_index, child)
360 parent.remove(del_elem)
361
362 range_tags = (
363 f"{{{w}}}moveFromRangeStart",
364 f"{{{w}}}moveFromRangeEnd",
365 f"{{{w}}}moveToRangeStart",
366 f"{{{w}}}moveToRangeEnd",
367 )
368 for parent in root.iter():
369 to_remove = [
370 c
371 for c in parent
372 if c.tag in range_tags and len(c) == 0 and not (c.text or "").strip()
373 ]
374 for elem in to_remove:
375 parent.remove(elem)
376
377 def _merge_split_paragraphs(self, root, targets):
378 w = self.namespaces["w"]
379 p_tag = f"{{{w}}}p"
380 ppr_tag = f"{{{w}}}pPr"
381 marker_path = f"{ppr_tag}/{{{w}}}rPr/{{{w}}}ins"
382
383 for parent in list(root.iter()):
384 for para in reversed([child for child in parent if child.tag == p_tag]):
385 if not any(m in targets for m in para.findall(marker_path)):
386 continue
387 siblings = list(parent)
388 index = siblings.index(para)
389 following = siblings[index + 1] if index + 1 < len(siblings) else None
390 if following is None or following.tag != p_tag:
391 continue
392 if any(self._text_elements(c) for c in para if c.tag == ppr_tag):
393 continue
394 insert_at = 1 if len(following) and following[0].tag == ppr_tag else 0
395 for child in reversed([c for c in para if c.tag != ppr_tag]):
396 following.insert(insert_at, child)
397 parent.remove(para)
398
399 def _extract_text_content(self, root):
400 p_tag = f"{{{self.namespaces['w']}}}p"
401
402 paragraphs = []
403 for p_elem in root.findall(f".//{p_tag}"):
404 paragraph_text = self._paragraph_text(p_elem)
405 if paragraph_text:
406 paragraphs.append(paragraph_text)
407
408 return "\n".join(paragraphs)
409
410 PAGE_FIELDS = {"PAGE", "NUMPAGES", "SECTIONPAGES"}
411 PAGE_NUMBER = re.compile(r"-? ?[0-9]{1,6} ?-?|[ivxlcdm]{1,8}|[a-z]{1,2}|", re.I)
412 PAGE_FIELD_NOTE = (
413 "Note: {PAGE}, {NUMPAGES} or {SECTIONPAGES} above stands for a page-number\n"
414 "field. Word recomputes the number it displays, so the number stored in\n"
415 "the file is not compared, but adding or removing the field still counts."
416 )
417
418 WORK_SPENT_NOTE = (
419 "Note: the texts were too long or repetitive to compare closely all the\n"
420 "way through, so a passage shown whole, as removed and then added, may\n"
421 "differ in only a few characters. Compare such a passage with the\n"
422 "original directly to find the edit."
423 )
424
425 def _paragraph_text(self, p_elem):
426 w = self.namespaces["w"]
427 t_tag, instr_tag = f"{{{w}}}t", f"{{{w}}}instrText"
428 fld_char, fld_simple = f"{{{w}}}fldChar", f"{{{w}}}fldSimple"
429
430 def page_field(instruction, field):
431 words = instruction.split()
432 locked = field.get(f"{{{w}}}fldLock") in ("1", "true", "on")
433 if words and words[0].upper() in self.PAGE_FIELDS and not locked:
434 return words[0].upper()
435
436 def shown(name, result):
437 return "{%s}" % name if self.PAGE_NUMBER.fullmatch(result) else result
438
439 parts, fields = [], []
440 skipped = set()
441
442 def sink():
443 for *_, result in reversed(fields):
444 if result is not None:
445 return result
446 return parts
447
448 for elem in p_elem.iter():
449 if elem.tag == fld_simple:
450 name = page_field(elem.get(f"{{{w}}}instr", ""), elem)
451 if name:
452 texts = [self._rendered_text(t) for t in elem.iter(t_tag)]
453 sink().append(shown(name, "".join(texts).strip()))
454 skipped.update(elem.iter(t_tag))
455 elif elem.tag == fld_char:
456 kind = elem.get(f"{{{w}}}fldCharType")
457 if kind == "begin":
458 fields.append([elem, "", False, None])
459 elif kind == "separate" and fields and not fields[-1][2]:
460 fields[-1][2] = True
461 if page_field(fields[-1][1], fields[-1][0]):
462 fields[-1][3] = []
463 elif kind == "end" and fields:
464 begin, instruction, _, result = fields.pop()
465 name = page_field(instruction, begin)
466 if name:
467 sink().append(shown(name, "".join(result or []).strip()))
468 elif elem.tag == instr_tag and fields and not fields[-1][2]:
469 fields[-1][1] += elem.text or ""
470 elif elem.tag == t_tag and elem not in skipped:
471 sink().append(self._rendered_text(elem))
472 for *_, result in fields:
473 parts.extend(result or [])
474 return "".join(parts)
475
476
477if __name__ == "__main__":
478 raise RuntimeError("This module should not be run directly.")