Update docx, pptx, xlsx, and pdf skills (#2217)

This commit is contained in:
Peter Lai
2026-11-14 07:16:42 -08:00
committed by GitHub
parent 2c5958ecac
commit 1780c5e5a5
36 changed files with 3274 additions and 623 deletions

View File

@@ -7,6 +7,7 @@ Does all of the package bookkeeping, so the deck stays valid:
- adds a slide relationship with a fresh rId to presentation.xml.rels
- inserts <p:sldId id="..." r:id="..."/> with a fresh id into
<p:sldIdLst> — at the end, or after --after SLIDE
- counts the new slide in docProps/app.xml
Works on an unpacked directory (during an editing session) or directly on a
.pptx/.potx file (extracted to a temp dir, then rezipped atomically; the
@@ -25,6 +26,7 @@ A duplicated slide still holds the source's content: edit ppt/slides/slideN.xml
"""
import argparse
import posixpath
import re
import shutil
import sys
@@ -32,8 +34,12 @@ from typing import NoReturn
import tempfile
import zipfile
from pathlib import Path
from xml.parsers.expat import ExpatError
from office.helpers import rezip, safe_extract
import defusedxml.minidom
from defusedxml.common import DefusedXmlException
from office.helpers import opc_target, rezip, safe_extract
MINIMAL_SLIDE_XML = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
@@ -62,6 +68,8 @@ MINIMAL_SLIDE_XML = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
SHARED_PART_TYPES = ("chart", "diagramData", "oleObject", "package")
NOTES_SLIDE_TYPE_RE = re.compile(r"""Type=["'][^"']*/relationships/notesSlide["']""")
TAGS_TYPE_RE = re.compile(r"""Type=["'][^"']*/relationships/tags["']""")
TAGS_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml"
RELATIONSHIP_RE = re.compile(r"<Relationship\b[^>]*?(?:/>|>.*?</Relationship\s*>)", re.DOTALL)
SLIDE_ID_MIN = 256
@@ -136,6 +144,11 @@ def duplicate_slide(unpacked_dir: Path, source: str, after: str | None = None) -
lambda m: "" if NOTES_SLIDE_TYPE_RE.search(m.group(0)) else m.group(0),
rels_content,
)
rels_content = RELATIONSHIP_RE.sub(
lambda m: _with_own_tags_part(unpacked_dir, m.group(0), f"ppt/slides/{dest}")
if TAGS_TYPE_RE.search(m.group(0)) else m.group(0),
rels_content,
)
dest_rels.write_text(rels_content, encoding="utf-8")
shared_parts = sorted({
t for t in re.findall(r'Type="[^"]*/relationships/(\w+)"', rels_content)
@@ -151,6 +164,32 @@ def duplicate_slide(unpacked_dir: Path, source: str, after: str | None = None) -
return dest
def _with_own_tags_part(unpacked_dir: Path, relationship: str, slide_part: str) -> str:
target = re.search(r"""Target=["']([^"']*)["']""", relationship)
try:
source = opc_target(target.group(1), slide_part) if target else None
except ValueError:
source = None
if source is None or not (unpacked_dir / source).is_file():
return relationship
tags_dir = (unpacked_dir / source).parent
content_types_path = unpacked_dir / "[Content_Types].xml"
content_types = content_types_path.read_text(encoding="utf-8")
names = [f.name for f in tags_dir.iterdir()] + re.findall(r"""PartName=["'][^"']*/([^/"']+)["']""", content_types)
taken = [int(m.group(1)) for name in names if (m := re.fullmatch(r"tag(\d{1,9})\.xml", name, re.I))]
copy = tags_dir / f"tag{max(taken, default=0) + 1}.xml"
shutil.copy2(unpacked_dir / source, copy)
part = copy.relative_to(unpacked_dir).as_posix()
override = f'<Override PartName="/{part}" ContentType="{TAGS_CONTENT_TYPE}"/>'
content_types_path.write_text(
content_types.replace("</Types>", f" {override}\n</Types>"), encoding="utf-8"
)
relative = posixpath.relpath(part, posixpath.dirname(slide_part))
return relationship.replace(target.group(0), f'Target="{relative}"')
def _precheck_registration(unpacked_dir: Path, after: str | None, dest: str) -> str | None:
pres_path = unpacked_dir / "ppt" / "presentation.xml"
if not pres_path.exists():
@@ -194,6 +233,8 @@ def _register_slide(unpacked_dir: Path, dest: str, source_desc: str, after_rid:
slide_id = _get_next_slide_id(unpacked_dir)
pos, total = _insert_into_sld_id_lst(unpacked_dir, slide_id, rid, after_rid)
_count_slide_in_app_properties(unpacked_dir, pos)
print(f"Created ppt/slides/{dest} from {source_desc}")
print(
f'Inserted <p:sldId id="{slide_id}" r:id="{rid}"/> into <p:sldIdLst> '
@@ -201,6 +242,61 @@ def _register_slide(unpacked_dir: Path, dest: str, source_desc: str, after_rid:
)
def _count_slide_in_app_properties(unpacked_dir: Path, position: int) -> None:
path = unpacked_dir / "docProps" / "app.xml"
if not path.is_file():
return
try:
dom = defusedxml.minidom.parse(str(path))
slides = _only_child(dom.documentElement, "Slides")
was = int(slides.firstChild.data)
if not _add_slide_title(dom, was, position):
return
except (AttributeError, LookupError, ValueError, TypeError, OSError, ExpatError, DefusedXmlException):
return
slides.firstChild.data = str(was + 1)
path.write_bytes(dom.toxml(encoding="UTF-8", standalone=dom.standalone))
def _add_slide_title(dom, was: int, position: int) -> bool:
heading_pairs = _only_child(dom.documentElement, "HeadingPairs")
titles_of_parts = _only_child(dom.documentElement, "TitlesOfParts")
if heading_pairs is None and titles_of_parts is None:
return True
headings, titles = _only_child(heading_pairs, "vector"), _only_child(titles_of_parts, "vector")
pairs = [v.getElementsByTagName("*")[0] for v in _elements(headings)]
names = [n.firstChild.data if n.firstChild else "" for n in pairs[0::2]]
counts = pairs[1::2]
sizes = [int(c.firstChild.data) for c in counts]
entries = _elements(titles)
consistent = (
int(headings.getAttribute("size")) == 2 * len(counts) == len(_elements(headings))
and int(titles.getAttribute("size")) == len(entries) == sum(sizes)
)
titled = [i for i, name in enumerate(names) if name == "Slide Titles"]
as_long = [i for i in titled or range(len(sizes)) if sizes[i] == was > 0]
if not consistent or len(as_long) != 1:
return False
(group,) = as_long
title = entries[0].cloneNode(False)
title.appendChild(dom.createTextNode(f"Slide {was + 1}"))
at = sum(sizes[:group]) + min(position - 1, was)
titles.insertBefore(title, entries[at] if at < len(entries) else None)
titles.setAttribute("size", str(len(entries) + 1))
counts[group].firstChild.data = str(was + 1)
return True
def _elements(node) -> list:
return [c for c in node.childNodes if c.nodeType == c.ELEMENT_NODE]
def _only_child(node, local_name: str):
found = [c for c in _elements(node) if c.localName == local_name] if node else []
return found[0] if len(found) == 1 else None
def _add_to_content_types(unpacked_dir: Path, dest: str) -> None:
content_types_path = unpacked_dir / "[Content_Types].xml"
content_types = content_types_path.read_text(encoding="utf-8")

View File

@@ -0,0 +1,107 @@
// Give a deck pptxgenjs wrote its own theme colors and theme name. pptxgenjs sets the theme's
// two fonts (pres.theme) but hard-codes Office's palette, so scheme colors resolve to Office
// blue and orange until the deck's colors are written into ppt/theme/theme1.xml.
//
// const { applyTheme } = require("<this skill's directory>/scripts/apply_theme.js");
// await pres.writeFile({ fileName: "deck.pptx" });
// await applyTheme("deck.pptx", {
// name: "Northwind",
// colors: { dk1, lt1, dk2, lt2, accent1, accent2, accent3, accent4, accent5, accent6, hlink, folHlink },
// }); // extra keys (headFontFace, ...) are ignored, and the twelve colors may sit beside name instead
//
// node scripts/apply_theme.js deck.pptx theme.json [out.pptx] # the same, from a shell
//
// Colors are six hex digits, no "#". The deck is rewritten in place unless a third argument
// names another file. It throws, changing nothing, if a color anywhere in the deck is not six
// hex digits, which is what a scheme color passed to a hex-only option turns into.
//
// As the step that rewrites the deck after pres.writeFile(), it also handles two faults pptxgenjs writes
// that make PowerPoint offer to repair the deck: it mends <c:crossesAt val="autoZero"/>, and it
// throws on a line dash that is not a dash style.
const fs = require("fs");
// jszip comes with pptxgenjs but is not always installed where a bare require("jszip") finds
// it, so it is loaded from beside pptxgenjs. Both are found the way any require() in this file
// would find them: from this file's directory upward, then NODE_PATH and Node's global folders.
// No search starts at the working directory or the calling script's directory.
function loadJSZip() {
try {
return require(require.resolve("jszip", { paths: [require.resolve("pptxgenjs")] }));
} catch {
throw new Error(`pptxgenjs and the jszip that comes with it cannot be found from ${__filename}. If pptxgenjs is installed beside your own script, run node with NODE_PATH set to that node_modules folder. Nothing was changed.`);
}
}
const SLOTS = ["dk1", "lt1", "dk2", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink"];
// A name or value from the deck, for an error a model reads: quoted, cut, and with nothing unprintable left raw.
const shown = (s) => JSON.stringify(String(s).slice(0, 80)).replace(/[\p{C}\u2028\u2029]/gu, (c) => "\\u{" + c.codePointAt(0).toString(16) + "}");
const DASHES = ["solid", "dot", "dash", "lgDash", "dashDot", "lgDashDot", "lgDashDotDot", "sysDash", "sysDot", "sysDashDot", "sysDashDotDot"];
function themeXml(xml, theme) {
if (!theme || !theme.name) throw new Error("theme.name is required. Nothing was changed.");
// The name goes into XML attributes: drop control characters, escape & < > and the double quote.
const name = String(theme.name).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const colors = theme.colors || theme; // { name, colors: {...} }, or flat { name, dk1, ... }
for (const k of SLOTS) {
if (!/^[0-9A-Fa-f]{6}$/.test(String(colors[k]))) throw new Error(`theme.colors.${k} is ${JSON.stringify(colors[k])}; it must be six hex digits with no "#" (slots: ${SLOTS.join(" ")}). Nothing was changed.`);
}
const scheme = `<a:clrScheme name="${name}">` + SLOTS.map((k) => `<a:${k}><a:srgbClr val="${String(colors[k]).toUpperCase()}"/></a:${k}>`).join("") + "</a:clrScheme>";
// Function replacements, so a "$" in the name is not read as a replacement pattern.
// The theme, its color scheme and its font scheme each carry a name; none should still say Office.
const out = xml
.replace(/<a:clrScheme\b[\s\S]*?<\/a:clrScheme>/, () => scheme)
.replace(/(<a:(?:theme|fontScheme)\b[^>]*?\bname=")[^"]*"/g, (_, head) => `${head}${name}"`);
if (!out.includes(scheme)) throw new Error("ppt/theme/theme1.xml has no <a:clrScheme> to replace; this script expects the theme part pptxgenjs writes. Nothing was changed.");
return out;
}
async function applyTheme(deckPath, theme, outPath = deckPath) {
const zip = await loadJSZip().loadAsync(fs.readFileSync(deckPath));
const part = "ppt/theme/theme1.xml"; // the one theme part pptxgenjs writes; the slide master and the notes master share it
if (!zip.file(part)) throw new Error(`${deckPath} has no ${part}; this script is for decks pptxgenjs wrote. Nothing was changed.`);
zip.file(part, themeXml(await zip.file(part).async("string"), theme));
// A scheme color given to a hex-only option is written as <a:srgbClr val="bg2"/>, which is
// not a color. pptxgenjs does not warn; stop here instead.
for (const name of Object.keys(zip.files)) {
if (!name.endsWith(".xml")) continue;
const xml = await zip.file(name).async("string");
const bad = xml.match(/<a:srgbClr val="((?![0-9A-Fa-f]{6}")[^"]*)"/);
if (bad) throw new Error(`${shown(name)} has an <a:srgbClr> whose val is ${shown(bad[1])}, not six hex digits. Usually a scheme color was given to an option that takes hex only (valGridLine.color, catGridLine.color, shadow.color, or chartColors / invertedColors on a one-series bar chart). Pass the six-digit hex from your theme object there and rebuild. Nothing was changed.`);
// pptxgenjs writes a dash option through unchecked, and an array as "solid,dash".
const dash = [...xml.matchAll(/<a:prstDash val="([^"]*)"/g)].find((m) => !DASHES.includes(m[1].trim()));
if (dash) throw new Error(`${shown(name)} has an <a:prstDash> whose val is ${shown(dash[1])}, which is not a dash style, and PowerPoint would offer to repair the deck. Give line.dashType, a chart's lineDash (one word for the whole chart, not an array), catAxisLineStyle or valAxisLineStyle one of: ${DASHES.join(" ")}. Then rebuild. Nothing was changed.`);
// pptxgenjs writes valAxisCrossesAt: 0 as <c:crossesAt val="autoZero"/>. <c:crossesAt> takes
// a number; the word belongs in <c:crosses>, where it means the same: cross at zero.
if (xml.includes('<c:crossesAt val="autoZero"/>')) zip.file(name, xml.replaceAll('<c:crossesAt val="autoZero"/>', '<c:crosses val="autoZero"/>'));
}
// A ZIP entry for a folder ("ppt/slides/") is not a part, and pptxgenjs writes one per folder.
// A cloud co-editing service reported issues editing decks that carry them. They are dropped
// here for that reason, not to save space. (zip.remove() would take the folder's files too.)
for (const name of Object.keys(zip.files)) if (zip.files[name].dir) delete zip.files[name];
fs.writeFileSync(outPath, await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" }));
}
module.exports = { applyTheme };
if (require.main === module) {
const [deck, themeFile, out] = process.argv.slice(2);
if (!deck || !themeFile) {
console.error("usage: node apply_theme.js deck.pptx theme.json [out.pptx]");
process.exit(2);
}
let theme;
try {
theme = JSON.parse(fs.readFileSync(themeFile, "utf8"));
} catch (e) {
console.error(`Error: cannot read ${themeFile} as JSON (${e.message}). Nothing was changed.`);
process.exit(1);
}
applyTheme(deck, theme, out || deck).then(
() => console.log(`Theme written to ${out || deck}`),
(e) => { console.error(`Error: ${e.message}`); process.exit(1); }
);
}

View File

@@ -5,7 +5,7 @@ import stat
import tempfile
import urllib.parse
import zipfile
from pathlib import Path
from pathlib import Path, PureWindowsPath
OOXML_FAMILY = {
".docx": "docx",
@@ -21,16 +21,24 @@ _SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*:")
SLIDE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"
def one_line(text: str, limit: int) -> str:
return "".join(c if c.isprintable() else c.encode("unicode_escape").decode() for c in text)[:limit]
def names_another_root(name: str) -> bool:
return bool(PureWindowsPath(name).anchor)
def opc_target(target: str, source_part: str, target_mode: str = "") -> str | None:
if not target:
return None
if target_mode.lower() == "external":
return None
target = urllib.parse.unquote(target)
if _SCHEME_RE.match(target):
return None
target = urllib.parse.unquote(target)
if "\\" in target:
raise ValueError(f"relationship target is not a POSIX part name: {target!r}")
@@ -52,12 +60,15 @@ def opc_target(target: str, source_part: str, target_mode: str = "") -> str | No
if not parts:
raise ValueError(f"relationship target resolves to nothing: {target!r}")
if names_another_root("/".join(parts)):
raise ValueError(f"relationship target is not a part name: {target!r}")
return "/".join(parts)
def rels_source_part(rels_file: Path, unpacked_dir: Path) -> str:
owner_dir = rels_file.parent.parent.relative_to(unpacked_dir)
return posixpath.join(owner_dir.as_posix(), rels_file.name[: -len(".rels")]).lstrip("./")
part = posixpath.join(owner_dir.as_posix(), rels_file.name[: -len(".rels")])
return part.removeprefix("./")
def part_text(data: bytes) -> str:
@@ -76,12 +87,19 @@ def safe_extract(zf: zipfile.ZipFile, dest: Path) -> None:
for m in zf.infolist():
if stat.S_ISLNK(m.external_attr >> 16):
raise ValueError(f"symlink archive entry not allowed: {m.filename!r}")
if names_another_root(m.filename):
raise ValueError(f"unsafe archive entry: {m.filename!r}")
target = (dest / m.filename).resolve()
if not target.is_relative_to(dest):
raise ValueError(f"unsafe archive entry: {m.filename!r}")
zf.extract(m, dest)
def folder_entries(package: Path) -> list[str]:
with zipfile.ZipFile(package) as zf:
return [info.filename for info in zf.infolist() if info.is_dir()]
def rezip(src_dir: Path, out_path: Path) -> None:
files = sorted(p for p in src_dir.rglob("*") if p.is_file())
ct = src_dir / "[Content_Types].xml"

View File

@@ -1,15 +1,20 @@
"""Find chart XML that PowerPoint refuses but the schema accepts.
"""Find chart XML that PowerPoint refuses or repairs.
Detection only: for either fault more than one repair is valid, and only the
author knows which was meant.
Detection only: more than one repair is usually valid, and only the author knows
which was meant.
"""
from __future__ import annotations
import html
import re
from collections import Counter
from typing import Mapping
from defusedxml import ElementTree
from defusedxml.common import DefusedXmlException
from . import part_text
@@ -19,8 +24,12 @@ _GROUPING_RE = re.compile(r"""<c:grouping\b[^>]*?\bval=["'](\w+)["']""")
_DLBL_POS_RE = re.compile(r"""<c:dLblPos\b[^>]*?\bval=["'](\w+)["']""")
def _strip_ext_lst(text: str) -> str:
return _strip_outermost(text, "c:extLst")
def _strip_outermost(text: str, name: str) -> str:
out, cursor = [], 0
for lo, hi in _ext_lst_spans(text):
for lo, hi in _outermost_spans(text, name):
out.append(text[cursor:lo])
cursor = hi
out.append(text[cursor:])
@@ -139,18 +148,113 @@ def _check_chart_axis_references(part: str, xml: str) -> list[str]:
return problems
def _ext_lst_spans(text: str) -> list[tuple[int, int]]:
def _shown(value: str) -> str:
return '"' + repr(value[:20])[1:-1] + '"'
DECIMAL_SETTINGS = (
"crossesAt", "max", "min", "majorUnit", "minorUnit", "logBase",
"forward", "backward", "intercept", "x", "y", "w", "h",
"splitPos", "custUnit", "pictureStackUnit",
)
_DECIMAL_SETTING_RE = re.compile(
rf"""<c:({"|".join(DECIMAL_SETTINGS)})\b[^<>]*?\bval=["']([^"'<>]*)["']"""
)
_DECIMAL_RE = re.compile(
r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?"
r"|[+-]?(inf|infinity|nan(\(\w*\))?|\u221e|1\.#(inf|qnan|snan|ind)\d*)",
re.IGNORECASE,
)
def _check_decimal_settings(part: str, xml: str) -> list[str]:
problems = []
for name, raw in sorted(set(_DECIMAL_SETTING_RE.findall(_strip_ext_lst(xml)))):
value = html.unescape(raw)
if _DECIMAL_RE.fullmatch(value.strip()):
continue
fix = "Fix: write a plain number, or remove the element"
if name == "crossesAt" and value.strip() == "autoZero":
fix = ("Fix: leave valAxisCrossesAt: 0 out of the pptxgenjs options, the axis "
"crosses at zero anyway. In the XML, write "
'<c:crosses val="autoZero"/> or a number')
problems.append(
f"{part}: <c:{name} val={_shown(value)}> is not a number, and PowerPoint "
f"will offer to repair the deck. {fix}"
)
return problems
def _local(tag: str) -> str:
return tag.rsplit("}", 1)[-1]
def _drawn_series(root) -> list:
found, to_visit = [], [root]
while to_visit:
for child in to_visit.pop():
name = _local(child.tag)
if name == "ser":
found.append(child)
elif name == "AlternateContent":
to_visit.extend(child[:1])
elif name != "extLst":
to_visit.append(child)
return found
def _check_series_order(part: str, xml: str) -> list[str]:
try:
root = ElementTree.fromstring(xml.encode("utf-8", "surrogateescape"))
except (ElementTree.ParseError, DefusedXmlException, LookupError, ValueError):
return []
orders = Counter()
for series in _drawn_series(root):
own = [c.get("val", "") for c in series if _local(c.tag) == "order"]
if own and own[0].isascii() and own[0].isdigit():
orders[own[0]] += 1
repeated = sorted((o for o, n in orders.items() if n > 1), key=lambda o: (len(o), o))
if not repeated:
return []
return [
f"{part}: two or more series share the <c:order> value {', '.join(o[:12] for o in repeated)}, "
f"and PowerPoint will offer to repair the deck. Fix: number <c:order> "
f"(and <c:idx>) 0, 1, 2... across every series in the chart, a combo "
f"chart's line series carrying on from its bars"
]
PRESET_DASHES = frozenset({
"solid", "dot", "dash", "lgDash", "dashDot", "lgDashDot", "lgDashDotDot",
"sysDash", "sysDot", "sysDashDot", "sysDashDotDot",
})
_PRESET_DASH_RE = re.compile(r"""<a:prstDash\b[^<>]*?\bval=["']([^"'<>]*)["']""")
def _check_preset_dashes(part: str, xml: str) -> list[str]:
values = {html.unescape(v) for v in _PRESET_DASH_RE.findall(_strip_ext_lst(xml))}
return [
f"{part}: <a:prstDash val={_shown(value)}> is not a dash style, and PowerPoint "
f"will offer to repair the deck. Use one of {', '.join(sorted(PRESET_DASHES))}. "
f"In pptxgenjs, lineDash takes one such word for the whole chart, not an array"
for value in sorted(values)
if value.strip() not in PRESET_DASHES
]
def _outermost_spans(text: str, name: str) -> list[tuple[int, int]]:
spans: list[tuple[int, int]] = []
depth = 0
start = 0
for match in re.finditer(r"<(/?)c:extLst\b[^>]*?(/?)>", text):
for match in re.finditer(rf"<(/?){name}\b[^<>]*?(/?)>", text):
closing, self_closing = match.group(1), match.group(2)
if self_closing:
continue
if closing:
depth -= 1
if depth == 0:
spans.append((start, match.end()))
if depth:
depth -= 1
if depth == 0:
spans.append((start, match.end()))
else:
if depth == 0:
start = match.start()
@@ -158,13 +262,22 @@ def _ext_lst_spans(text: str) -> list[tuple[int, int]]:
return spans
CHART_CHECKS = (_check_stacked_label_positions, _check_chart_axis_references)
CHART_CHECKS = (
_check_stacked_label_positions,
_check_chart_axis_references,
_check_decimal_settings,
_check_series_order,
_check_preset_dashes,
)
_COMMENT_OR_PI_RE = re.compile(r"<!--.*?(?:-->|\Z)|<\?(?!xml\s).*?(?:\?>|\Z)", re.DOTALL)
def find_chart_problems(files: Mapping[str, bytes]) -> list[str]:
problems: list[str] = []
for part in sorted(n for n in files if _CHART_PART_RE.fullmatch(n)):
xml = part_text(files[part])
xml = _strip_outermost(_COMMENT_OR_PI_RE.sub("", part_text(files[part])), "mc:Fallback")
for check in CHART_CHECKS:
problems.extend(check(part, xml))
return problems

View File

@@ -1,7 +1,8 @@
"""Pick the slide-XML schema errors PowerPoint refuses the file over.
"""Find the slide-XML defects known or predicted to make PowerPoint refuse or repair the file.
A denylist over lxml's messages, so an unrecognised error class is a miss rather
than a false alarm.
Schema errors are picked by a denylist over lxml's messages, so an unrecognised
error class is a miss rather than a false alarm. Animations that name a shape
the slide no longer has are found by reading the part.
"""
@@ -43,6 +44,14 @@ FATAL_SLIDE_ERRORS: tuple[tuple[re.Pattern[str], str], ...] = (
re.compile(r"\}nvGrpSpPr': Missing child element"),
"a <p:nvGrpSpPr> with no children",
),
(
re.compile(r"\}(?:off|ext|chOff|chExt)', attribute '\w+': '-?(?:Infinity|NaN)'"),
"a position or size that is not a number (check the x, y, w, h you worked out)",
),
(
re.compile(r"\}prstDash', attribute 'val'"),
"an unknown line dash style (for line.dashType try dash, sysDash or solid)",
),
)
@@ -50,6 +59,37 @@ def is_schema_verdict(error: str) -> bool:
return error.startswith("Element ")
_PML = "{http://schemas.openxmlformats.org/presentationml/2006/main}"
_MC = "{http://schemas.openxmlformats.org/markup-compatibility/2006}"
_NAMES_A_SHAPE = frozenset({f"{_PML}spTgt", f"{_PML}bldP", f"{_PML}bldGraphic"})
def _shape_id(value: str | None) -> int | str | None:
text = (value or "").strip()
if text.isascii() and text.isdigit() and len(text) <= 18:
return int(text)
return text or None
def stranded_animation_targets(root) -> list[str]:
timing = root.find(f"{_PML}timing")
if timing is None:
timing = root.find(f"{_MC}AlternateContent/{_MC}Choice/{_PML}timing")
if timing is None:
return []
on_slide = {_shape_id(e.get("id")) for e in root.iter("{*}cNvPr")}
named = {_shape_id(e.get("spid")) for e in timing.iter(*_NAMES_A_SHAPE)} - {None}
stranded = named - on_slide
return [
f"<p:timing> animates shape id {spid if isinstance(spid, int) else repr(spid[:16])}, which is gone, so PowerPoint will "
f"offer to repair the deck. Fix: delete the slide's whole <p:timing> element "
f"(the slide loses its animations), or put the shape back"
for spid in sorted(stranded, key=str)
]
def fatal_slide_errors(errors: set[str]) -> list[str]:
out = []
for error in sorted(errors):

View File

@@ -64,7 +64,7 @@ def _ensure_shim() -> Path:
return _SHIM_SO
src = Path(tempfile.gettempdir()) / "lo_socket_shim.c"
src.write_text(_SHIM_SOURCE)
src.write_text(_SHIM_SOURCE, encoding="utf-8")
subprocess.run(
["gcc", "-shared", "-fPIC", "-o", str(_SHIM_SO), str(src), "-ldl"],
check=True,

View File

@@ -14,6 +14,7 @@ Auto-repair fixes:
"""
import argparse
import shlex
import sys
import tempfile
import zipfile
@@ -22,12 +23,21 @@ from pathlib import Path
import defusedxml.ElementTree as ET
from defusedxml.common import DefusedXmlException
from helpers import OOXML_FAMILY, rezip, safe_extract
from helpers import OOXML_FAMILY, folder_entries, rezip, safe_extract
from validators import DOCXSchemaValidator, PPTXSchemaValidator, RedliningValidator
WORD_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
def _as_argument(path: Path) -> str:
name = str(path)
return shlex.quote("./" + name if name.startswith("-") else name)
def _count(folders: list[str]) -> str:
return "1 folder entry" if len(folders) == 1 else f"{len(folders)} folder entries"
def _fail(message: str):
print(f"Error: {message}", file=sys.stderr)
sys.exit(2)
@@ -150,16 +160,43 @@ def main():
print(f"Error: Validation not supported for file type {family}")
sys.exit(1)
folders = folder_entries(packed_file) if packed_file is not None else []
unsaved_repairs = 0
if args.auto_repair:
total_repairs = sum(v.repair() for v in validators)
if total_repairs:
print(f"Auto-repaired {total_repairs} issue(s)")
if packed_file is not None:
if packed_file is not None and (total_repairs or folders):
try:
rezip(unpacked_dir, packed_file)
except OSError as e:
unsaved_repairs = total_repairs
left = []
if total_repairs:
left.append(f"{total_repairs} repair(s) not saved")
if folders:
left.append(f"{_count(folders)} in its ZIP")
print(f"Could not write {packed_file} ({e.strerror or e}): it is as it was, "
f"with {' and '.join(left)}. Run --auto-repair on a copy in a folder "
"you can write to.")
else:
if folders:
print(f"Removed {_count(folders)} from the ZIP")
print(f"Wrote repaired file to {packed_file}")
elif folders:
print(
f"Note: {_count(folders)} in the ZIP. Such files have failed to open or co-edit "
f"through a cloud service. Remove them: zip -dq {_as_argument(packed_file)} '*/'"
)
success = all([v.validate() for v in validators])
if unsaved_repairs:
print(f"FAILED - {packed_file} was not rewritten and still has the {unsaved_repairs} "
"issue(s) repaired above; the checks ran on a repaired copy")
success = False
if temp_dir_ctx is not None:
temp_dir_ctx.cleanup()

View File

@@ -2,6 +2,7 @@
Base validator with common validation logic for document files.
"""
import os
import re
from pathlib import Path
@@ -10,7 +11,7 @@ from functools import lru_cache
import lxml.etree
from helpers import safe_extract
from helpers import names_another_root, safe_extract
@lru_cache(maxsize=None)
@@ -352,6 +353,9 @@ class BaseSchemaValidator:
if target and not target.startswith(
("http", "mailto:")
):
if names_another_root(target.lstrip("/")):
broken_refs.append((target, rel.sourceline))
continue
if target.startswith("/"):
target_path = self.unpacked_dir / target.lstrip("/")
elif rels_file.name == ".rels":
@@ -360,9 +364,18 @@ class BaseSchemaValidator:
base_dir = rels_dir.parent
target_path = base_dir / target
target_path = Path(os.path.normpath(target_path))
if not target_path.is_relative_to(self.unpacked_dir):
broken_refs.append((target, rel.sourceline))
continue
try:
target_path = target_path.resolve()
if target_path.exists() and target_path.is_file():
if (
target_path.is_relative_to(self.unpacked_dir)
and target_path.exists()
and target_path.is_file()
):
referenced_files.add(target_path)
all_referenced_files.add(target_path)
else:
@@ -783,8 +796,7 @@ class BaseSchemaValidator:
try:
schema = _load_schema(str(schema_path))
with open(xml_file, "r") as f:
xml_doc = lxml.etree.parse(f)
xml_doc = lxml.etree.parse(str(xml_file))
xml_doc, _ = self._remove_template_tags_from_text_nodes(xml_doc)
xml_doc = self._preprocess_for_mc_ignorable(xml_doc)

View File

@@ -6,12 +6,13 @@ import random
import re
import tempfile
import zipfile
from collections import Counter
from pathlib import Path
import defusedxml.minidom
import lxml.etree
from helpers import safe_extract
from helpers import one_line, safe_extract
from .base import BaseSchemaValidator
@@ -62,6 +63,9 @@ class DOCXSchemaValidator(BaseSchemaValidator):
if not self.validate_comment_markers():
all_valid = False
if not self.validate_style_ids():
all_valid = False
self.compare_paragraph_counts()
return all_valid
@@ -264,7 +268,9 @@ class DOCXSchemaValidator(BaseSchemaValidator):
for xml_file in self.xml_files:
try:
for elem in lxml.etree.parse(str(xml_file)).iter():
tree = lxml.etree.parse(str(xml_file))
is_numbering = lxml.etree.QName(tree.getroot()).localname == "numbering"
for elem in tree.iter():
if val := elem.get(para_id_attr):
try:
if self._parse_id_value(val, base=16) >= 0x80000000:
@@ -278,7 +284,7 @@ class DOCXSchemaValidator(BaseSchemaValidator):
)
if val := elem.get(durable_id_attr):
if xml_file.name == "numbering.xml":
if is_numbering:
try:
if self._parse_id_value(val, base=10) >= 0x7FFFFFFF:
errors.append(
@@ -288,7 +294,7 @@ class DOCXSchemaValidator(BaseSchemaValidator):
except ValueError:
errors.append(
f" {xml_file.name}:{elem.sourceline}: "
f"durableId={val} must be decimal in numbering.xml"
f"durableId={val} must be decimal in a numbering part"
)
else:
try:
@@ -308,11 +314,58 @@ class DOCXSchemaValidator(BaseSchemaValidator):
if errors:
print(f"FAILED - {len(errors)} ID constraint violations:")
for e in errors:
print(e)
print(one_line(e, 300))
elif self.verbose:
print("PASSED - All paraId/durableId values within constraints")
return not errors
def _repeated_style_ids(self, styles_root) -> set[str]:
attr = f"{{{self.WORD_2006_NAMESPACE}}}styleId"
ids = Counter(s.get(attr) for s in styles_root.iter(f"{{{self.WORD_2006_NAMESPACE}}}style"))
return {i for i, n in ids.items() if i is not None and n > 1}
def _original_part(self, xml_file) -> bytes | None:
if self.original_file is None:
return None
name = xml_file.relative_to(self.unpacked_dir).as_posix()
try:
with zipfile.ZipFile(self.original_file) as zf:
return zf.read(name)
except (KeyError, OSError, zipfile.BadZipFile):
return None
def validate_style_ids(self):
errors = []
styles_tag = f"{{{self.WORD_2006_NAMESPACE}}}styles"
if self.original_file is None:
return True
for xml_file in self.xml_files:
try:
root = lxml.etree.parse(str(xml_file)).getroot()
if root.tag != styles_tag:
continue
repeated = self._repeated_style_ids(root)
original = self._original_part(xml_file) if repeated else None
if original is not None:
repeated -= self._repeated_style_ids(lxml.etree.fromstring(original))
except lxml.etree.XMLSyntaxError:
continue
errors.extend(
f" {xml_file.relative_to(self.unpacked_dir)}: style id {style_id!r:.40} is now "
f"defined more than once, and Word uses only the last definition, without "
f"warning. Delete the earlier ones"
for style_id in sorted(repeated)
)
if errors:
print(f"FAILED - Found {len(errors)} style id(s) defined more than once:")
for error in errors:
print(one_line(error, 300))
elif self.verbose:
print("PASSED - The edit defined no style id a second time")
return not errors
def validate_comment_markers(self):
errors = []
@@ -415,7 +468,7 @@ class DOCXSchemaValidator(BaseSchemaValidator):
try:
content = xml_file.read_text(encoding="utf-8")
dom = defusedxml.minidom.parseString(content)
is_numbering = xml_file.name == "numbering.xml"
is_numbering = dom.documentElement.localName == "numbering"
base = 10 if is_numbering else 16
pending = []
seen_in_file = set()

View File

@@ -63,6 +63,9 @@ class PPTXSchemaValidator(BaseSchemaValidator):
if not self.validate_master_theme_uniqueness():
all_valid = False
if not self.validate_tags():
all_valid = False
if not self.validate_charts():
all_valid = False
@@ -87,6 +90,30 @@ class PPTXSchemaValidator(BaseSchemaValidator):
if p.is_file()
}
@staticmethod
def _print_line(text: str, limit: int) -> None:
from helpers import one_line
print(one_line(text, limit))
def _listed_slides(self) -> set[str] | None:
import lxml.etree
from helpers import SLIDE_REL_TYPE
r_id = f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id"
try:
pres = lxml.etree.parse(str(self.unpacked_dir / "ppt" / "presentation.xml"))
rels = lxml.etree.parse(str(self.unpacked_dir / "ppt" / "_rels" / "presentation.xml.rels"))
listed = {e.get(r_id) for e in pres.iter(f"{{{self.PRESENTATIONML_NAMESPACE}}}sldId")}
return {
opc_target(rel.get("Target", ""), "ppt/presentation.xml", rel.get("TargetMode", ""))
for rel in rels.getroot()
if rel.get("Id") in listed and rel.get("Type") == SLIDE_REL_TYPE
}
except (OSError, ValueError, lxml.etree.XMLSyntaxError):
return None
def validate_master_theme_uniqueness(self):
from helpers.pptx_theme import _NOTES_MASTERS, live_shared_master_themes
@@ -94,7 +121,7 @@ class PPTXSchemaValidator(BaseSchemaValidator):
if shared:
print(f"FAILED - Found {len(shared)} master(s) sharing a theme part:")
for message in shared:
print(f" {message}")
self._print_line(f" {message}", 300)
if any(m.startswith(_NOTES_MASTERS) for m in shared):
print(" Fix: in ppt/presentation.xml, move <p:notesMasterIdLst> back to "
"directly after <p:sldIdLst>. PowerPoint reads that happily.")
@@ -106,6 +133,64 @@ class PPTXSchemaValidator(BaseSchemaValidator):
print("PASSED - No master shares a theme part in a way PowerPoint refuses")
return True
def validate_tags(self):
from collections import Counter
import lxml.etree
ns = {"p": self.PRESENTATIONML_NAMESPACE, "mc": self.MC_NAMESPACE}
r_id = f"{{{self.OFFICE_RELATIONSHIPS_NAMESPACE}}}id"
errors = []
owners: dict[str, list[str]] = {}
listed = self._listed_slides()
for slide in sorted(self.unpacked_dir.glob("ppt/slides/*.xml")):
relative = slide.relative_to(self.unpacked_dir).as_posix()
if listed is not None and relative not in listed:
continue
try:
root = lxml.etree.parse(str(slide)).getroot()
named = [t.get(r_id) for t in root.xpath(
".//p:tags[not(ancestor::mc:Fallback) and not(ancestor::mc:Choice[preceding-sibling::mc:Choice])]",
namespaces=ns)]
rels_file = slide.parent / "_rels" / f"{slide.name}.rels"
targets = {
rel.get("Id"): opc_target(rel.get("Target", ""), relative, rel.get("TargetMode", ""))
for rel in lxml.etree.parse(str(rels_file)).getroot()
if rel.get("Type", "").endswith("/relationships/tags")
} if rels_file.is_file() else {}
except (lxml.etree.XMLSyntaxError, ValueError):
continue
for rid, count in sorted(Counter(r for r in named if r).items()):
if count > 1:
errors.append(
f" {relative[:80]}: {count} <p:tags> elements name the tags relationship "
f"{rid!r:.20}. Fix: a copied shape kept its <p:custDataLst>; delete that "
f"from the copy, or give it a tags part and relationship of its own"
)
if targets.get(rid):
owners.setdefault(targets[rid], []).append(relative)
for part, slides in sorted(owners.items()):
if len(slides) > 1:
named_from = sorted(set(slides))
more = f" and {len(named_from) - 3} more" if len(named_from) > 3 else ""
errors.append(
f" {part[:80]}: {len(slides)} tags relationships name it, from "
f"{', '.join(s[:60] for s in named_from[:3])}{more}. Fix: copy the part under a new name, add "
f"its Override to [Content_Types].xml and point every relationship but one at a copy of its own "
f"(add_slide.py does this when it duplicates a slide)"
)
if errors:
print(f"FAILED - Found {len(errors)} tags part(s) with more than one owner; PowerPoint offers to repair the deck:")
for error in errors:
self._print_line(error, 700)
return False
if self.verbose:
print("PASSED - Every tags part has one owner")
return True
def validate_charts(self):
from helpers.pptx_chart import find_chart_problems
@@ -113,7 +198,7 @@ class PPTXSchemaValidator(BaseSchemaValidator):
if problems:
print(f"FAILED - Found {len(problems)} chart problem(s) PowerPoint rejects:")
for message in problems:
print(f" {message}")
self._print_line(f" {message}", 600)
return False
if self.verbose:
@@ -151,14 +236,18 @@ class PPTXSchemaValidator(BaseSchemaValidator):
return found
def validate_slides(self):
import lxml.etree
from helpers.pptx_slide import (
SLIDE_PART_RE,
fatal_slide_errors,
is_schema_verdict,
stranded_animation_targets,
)
schema = self.schemas_dir / self.SCHEMA_MAPPINGS["ppt"]
inherited = self._original_slide_defects(schema)
listed = self._listed_slides()
problems: list[str] = []
broken: list[str] = []
@@ -166,6 +255,14 @@ class PPTXSchemaValidator(BaseSchemaValidator):
relative = xml_file.relative_to(self.unpacked_dir).as_posix()
if not SLIDE_PART_RE.fullmatch(relative):
continue
unlisted = relative.startswith("ppt/slides/") and listed is not None and relative not in listed
try:
root = lxml.etree.parse(str(xml_file)).getroot()
stranded = [] if unlisted else stranded_animation_targets(root)
except lxml.etree.XMLSyntaxError:
stranded = []
problems.extend(f"{relative}: {m}" for m in stranded)
ok, errors = self._validate_single_file_xsd(
xml_file.resolve(), self.unpacked_dir.resolve(), schema_path=schema
)
@@ -187,12 +284,12 @@ class PPTXSchemaValidator(BaseSchemaValidator):
if broken:
print(f"FAILED - Could not check {len(broken)} slide part(s):")
for message in sorted(broken):
print(f" {message[:240]}")
self._print_line(f" {message}", 240)
if problems:
print(f"FAILED - Found {len(problems)} slide problem(s) PowerPoint rejects:")
for message in sorted(problems):
print(f" {message[:240]}")
self._print_line(f" {message}", 240)
if broken or problems:
return False
@@ -204,6 +301,17 @@ class PPTXSchemaValidator(BaseSchemaValidator):
def _get_schema_path(self, xml_file):
if xml_file.parent.name == "charts" and xml_file.name.startswith("chart"):
return None
if xml_file.parent.name == "ppt" and xml_file.suffix == ".xml":
import lxml.etree
try:
root = lxml.etree.parse(str(xml_file)).getroot()
except (lxml.etree.XMLSyntaxError, OSError):
root = None
if root is not None and (lxml.etree.QName(root).namespace or "").startswith(
"http://schemas.microsoft.com/office/"
):
return None
return super()._get_schema_path(xml_file)
def _preprocess_for_schema(self, xml_doc, relative_path):
@@ -256,7 +364,7 @@ class PPTXSchemaValidator(BaseSchemaValidator):
if errors:
print(f"FAILED - Found {len(errors)} UUID ID validation errors:")
for error in errors:
print(error)
self._print_line(error, 300)
return False
else:
if self.verbose:
@@ -325,7 +433,7 @@ class PPTXSchemaValidator(BaseSchemaValidator):
if errors:
print(f"FAILED - Found {len(errors)} slide layout ID validation errors:")
for error in errors:
print(error)
self._print_line(error, 300)
print(
"Remove invalid references or add missing slide layouts to the relationships file."
)
@@ -366,7 +474,7 @@ class PPTXSchemaValidator(BaseSchemaValidator):
if errors:
print("FAILED - Found slides with duplicate slideLayout references:")
for error in errors:
print(error)
self._print_line(error, 300)
return False
else:
if self.verbose:
@@ -428,7 +536,7 @@ class PPTXSchemaValidator(BaseSchemaValidator):
f"FAILED - Found {len([e for e in errors if not e.startswith(' ')])} notes slide reference validation errors:"
)
for error in errors:
print(error)
self._print_line(error, 300)
print("Each slide may optionally have its own slide file.")
return False
else:

View File

@@ -1,19 +1,24 @@
"""
Validator for tracked changes in Word documents.
Detects untracked edits in word/document.xml: text that differs from the
Detects untracked edits in a Word document: text that differs from the
original without a <w:ins>/<w:del> wrapper recording it. The tracked changes
that are new relative to the original are undone, and the result is compared
against the original; whatever text still differs was edited without being
tracked.
Only the document body is compared. Headers, footers, footnotes and endnotes
are separate parts and are not checked.
The body (word/document.xml) is compared, and so is each header, footer,
footnotes and endnotes part, against the original's part of the same name.
Other parts, comments among them, are not checked. A page-number field
whose cached result is a plain number counts as its name in braces
("{PAGE}"), not as that number, which any application that repaginates the
document rewrites.
"""
import subprocess
import re
import tempfile
import zipfile
from difflib import SequenceMatcher
from pathlib import Path
import defusedxml.ElementTree as ET
@@ -22,12 +27,35 @@ from defusedxml.common import DefusedXmlException
from helpers import rendered_text, safe_extract
XML_ERRORS = (ET.ParseError, DefusedXmlException, LookupError, ValueError)
class _WorkSpent(Exception):
pass
class _Matcher(SequenceMatcher):
def __init__(self, a, b, allowance):
self.allowance = allowance
super().__init__(None, a, b, autojunk=False)
def find_longest_match(self, alo=0, ahi=None, blo=0, bhi=None):
items = self.a[alo:ahi]
self.allowance[0] -= len(items) + sum(len(self.b2j.get(x, ())) for x in items)
if self.allowance[0] < 0:
raise _WorkSpent
return super().find_longest_match(alo, ahi, blo, bhi)
class RedliningValidator:
def __init__(self, unpacked_dir, original_docx, verbose=False):
self.unpacked_dir = Path(unpacked_dir)
self.original_docx = Path(original_docx)
self.verbose = verbose
self._work_left = [self.WORK_ALLOWED]
self.namespaces = {
"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
}
@@ -58,39 +86,81 @@ class RedliningValidator:
)
return False
try:
modified_tree = ET.parse(modified_file)
modified_root = modified_tree.getroot()
original_tree = ET.parse(original_file)
original_root = original_tree.getroot()
except (ET.ParseError, DefusedXmlException) as e:
print(f"FAILED - Error parsing XML files: {e}")
return False
sides = (("original", temp_path), ("modified", self.unpacked_dir))
change_count, failures, differences = 0, [], []
for part in self._parts_to_compare(temp_path, self.unpacked_dir):
roots = []
for side, unpacked in sides:
try:
roots.append(self._parse_part(unpacked / part))
except XML_ERRORS as e:
failures.append(
f"FAILED - Error parsing {part} of the {side} document: {e}"
)
if len(roots) < len(sides):
continue
new_changes, original_text, modified_text = self._compare_part(*roots)
change_count += len(new_changes)
if modified_text != original_text:
differences.append((part, original_text, modified_text))
new_changes = self._new_tracked_changes(original_root, modified_root)
self._remove_tracked_changes(modified_root, new_changes)
modified_text = self._extract_text_content(modified_root)
original_text = self._extract_text_content(original_root)
if modified_text != original_text:
error_message = self._generate_detailed_diff(
original_text, modified_text
)
print(error_message)
if differences:
failures.append(self._generate_detailed_diff(differences))
if failures:
print("\n".join(failures))
return False
if self.verbose:
print(
f"PASSED - All {len(new_changes)} change(s) against the original "
f"PASSED - All {change_count} change(s) against the original "
"are properly tracked"
)
return True
OTHER_PARTS = (
"word/header*.xml",
"word/footer*.xml",
"word/footnotes.xml",
"word/endnotes.xml",
)
def _parts_to_compare(self, original_dir, modified_dir):
others = set()
for unpacked in (Path(original_dir), Path(modified_dir)):
for pattern in self.OTHER_PARTS:
others.update(
path.relative_to(unpacked).as_posix()
for path in unpacked.glob(pattern)
)
return ["word/document.xml", *sorted(others)]
def _compare_part(self, original_root, modified_root):
for root in (original_root, modified_root):
self._flatten_text_elements(root)
new_changes = self._new_tracked_changes(original_root, modified_root)
self._remove_tracked_changes(modified_root, new_changes)
return (
new_changes,
self._extract_text_content(original_root),
self._extract_text_content(modified_root),
)
def _parse_part(self, path):
if not path.is_file():
return ET.fromstring("<absent/>")
return ET.parse(path).getroot()
def _flatten_text_elements(self, root):
for elem in self._text_elements(root):
if len(elem):
elem.text = "".join(elem.itertext())
for child in list(elem):
elem.remove(child)
def _tracked_change_elements(self, root):
ins_tag = f"{{{self.namespaces['w']}}}ins"
del_tag = f"{{{self.namespaces['w']}}}del"
return [elem for elem in root.iter() if elem.tag in (ins_tag, del_tag)]
w = self.namespaces["w"]
tags = (f"{{{w}}}ins", f"{{{w}}}del", f"{{{w}}}moveFrom", f"{{{w}}}moveTo")
return [elem for elem in root.iter() if elem.tag in tags]
def _rendered_text(self, elem):
preserve = elem.get("{http://www.w3.org/XML/1998/namespace}space") == "preserve"
@@ -148,7 +218,8 @@ class RedliningValidator:
new.update(elems)
return new
def _generate_detailed_diff(self, original_text, modified_text):
def _generate_detailed_diff(self, differences):
self._work_left = [self.WORK_ALLOWED]
error_parts = [
"FAILED - Document text doesn't match after removing the tracked changes",
"",
@@ -170,130 +241,238 @@ class RedliningValidator:
"",
]
git_diff = self._get_git_word_diff(original_text, modified_text)
if git_diff:
error_parts.extend(["Differences:", "============", git_diff])
else:
error_parts.append("Unable to generate word diff (git not available)")
explain_page_fields = False
for part, original_text, modified_text in differences:
body = part == "word/document.xml"
heading = "Differences:" if body else f"Differences in {part}:"
if error_parts[-1]:
error_parts.append("")
word_diff = self._word_diff(original_text, modified_text)
error_parts.extend([heading, "=" * len(heading), word_diff])
if original_text.replace("\n", "") == modified_text.replace("\n", ""):
error_parts.append("Only paragraph breaks differ here.")
if re.search(r"\{(%s)\}" % "|".join(self.PAGE_FIELDS), word_diff):
explain_page_fields = True
if explain_page_fields:
error_parts.extend(["", self.PAGE_FIELD_NOTE])
if self._work_left[0] < 0:
error_parts.extend(["", self.WORK_SPENT_NOTE])
return "\n".join(error_parts)
def _get_git_word_diff(self, original_text, modified_text):
def _word_diff(self, original_text, modified_text):
out = []
steps = self._steps(original_text.split("\n"), modified_text.split("\n"))
for tag, was, now in steps:
if tag == "replace" and len(was) == len(now):
out.extend(self._mark_changes(x, y) for x, y in zip(was, now) if x != y)
elif tag != "equal":
out.append(self._mark_changes("\n".join(was), "\n".join(now)))
return "\n".join(out)
def _mark_changes(self, old, new, by_character=False, trim=True):
def mark(text, opening, closing):
marked = re.sub(r"[^\n]+", lambda m: opening + m[0] + closing, text)
return marked if marked.strip("\n") or opening == "{+" else ""
pattern = "(?s)." if by_character else r"\S+\s*|\s+"
out = []
steps = self._steps(re.findall(pattern, old), re.findall(pattern, new), trim)
for tag, was, now in steps:
lone_word = len(was) == len(now) == 1
was, now = "".join(was), "".join(now)
if tag == "equal":
out.append(now)
elif tag == "replace" and not by_character:
long_word = lone_word and min(len(was), len(now)) > self.LONG_WORD
marked = self._mark_changes(was, now, by_character=True, trim=long_word)
out.append(marked)
else:
out.append(mark(was, "[-", "-]") + mark(now, "{+", "+}"))
return "".join(out)
WORK_ALLOWED = 10_000_000
LONG_WORD = 200
def _steps(self, a, b, trim=True):
def shared_start(x, y):
return next(
(i for i, (p, q) in enumerate(zip(x, y)) if p != q), min(len(x), len(y))
)
head = shared_start(a, b) if trim else 0
tail = shared_start(a[head:][::-1], b[head:][::-1]) if trim else 0
a_mid, b_mid = a[head : len(a) - tail], b[head : len(b) - tail]
try:
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
original_file = temp_path / "original.txt"
modified_file = temp_path / "modified.txt"
original_file.write_text(original_text, encoding="utf-8")
modified_file.write_text(modified_text, encoding="utf-8")
result = subprocess.run(
[
"git",
"diff",
"--word-diff=plain",
"--word-diff-regex=.",
"-U0",
"--no-index",
str(original_file),
str(modified_file),
],
capture_output=True,
text=True,
)
if result.stdout.strip():
lines = result.stdout.split("\n")
content_lines = []
in_content = False
for line in lines:
if line.startswith("@@"):
in_content = True
continue
if in_content and line.strip():
content_lines.append(line)
if content_lines:
return "\n".join(content_lines)
result = subprocess.run(
[
"git",
"diff",
"--word-diff=plain",
"-U0",
"--no-index",
str(original_file),
str(modified_file),
],
capture_output=True,
text=True,
)
if result.stdout.strip():
lines = result.stdout.split("\n")
content_lines = []
in_content = False
for line in lines:
if line.startswith("@@"):
in_content = True
continue
if in_content and line.strip():
content_lines.append(line)
return "\n".join(content_lines)
except (subprocess.CalledProcessError, FileNotFoundError, Exception):
pass
return None
if self._work_left[0] < len(a_mid):
self._work_left[0] = -1
raise _WorkSpent
numbers = {}
numbered = [
[numbers.setdefault(x, len(numbers)) for x in s] for s in (a_mid, b_mid)
]
opcodes = _Matcher(*numbered, self._work_left).get_opcodes()
steps = [(tag, a_mid[i:j], b_mid[m:n]) for tag, i, j, m, n in opcodes]
except _WorkSpent:
steps = [("replace", a_mid, b_mid)]
return [
("equal", a[:head], b[:head]),
*steps,
("equal", a[len(a) - tail :], b[len(b) - tail :]),
]
def _remove_tracked_changes(self, root, targets):
ins_tag = f"{{{self.namespaces['w']}}}ins"
del_tag = f"{{{self.namespaces['w']}}}del"
w = self.namespaces["w"]
ins_tag = f"{{{w}}}ins"
del_tag = f"{{{w}}}del"
move_from_tag = f"{{{w}}}moveFrom"
move_to_tag = f"{{{w}}}moveTo"
self._merge_split_paragraphs(root, targets)
for parent in root.iter():
to_remove = []
for child in parent:
if child.tag == ins_tag and child in targets:
if child.tag in (ins_tag, move_to_tag) and child in targets:
to_remove.append(child)
for elem in to_remove:
parent.remove(elem)
deltext_tag = f"{{{self.namespaces['w']}}}delText"
t_tag = f"{{{self.namespaces['w']}}}t"
renamed = {
f"{{{w}}}delText": f"{{{w}}}t",
f"{{{w}}}delInstrText": f"{{{w}}}instrText",
}
for parent in root.iter():
to_process = []
for child in parent:
if child.tag == del_tag and child in targets:
if child.tag in (del_tag, move_from_tag) and child in targets:
to_process.append((child, list(parent).index(child)))
for del_elem, del_index in reversed(to_process):
for elem in del_elem.iter():
if elem.tag == deltext_tag:
elem.tag = t_tag
elem.tag = renamed.get(elem.tag, elem.tag)
for child in reversed(list(del_elem)):
parent.insert(del_index, child)
parent.remove(del_elem)
range_tags = (
f"{{{w}}}moveFromRangeStart",
f"{{{w}}}moveFromRangeEnd",
f"{{{w}}}moveToRangeStart",
f"{{{w}}}moveToRangeEnd",
)
for parent in root.iter():
to_remove = [
c
for c in parent
if c.tag in range_tags and len(c) == 0 and not (c.text or "").strip()
]
for elem in to_remove:
parent.remove(elem)
def _merge_split_paragraphs(self, root, targets):
w = self.namespaces["w"]
p_tag = f"{{{w}}}p"
ppr_tag = f"{{{w}}}pPr"
marker_path = f"{ppr_tag}/{{{w}}}rPr/{{{w}}}ins"
for parent in list(root.iter()):
for para in reversed([child for child in parent if child.tag == p_tag]):
if not any(m in targets for m in para.findall(marker_path)):
continue
siblings = list(parent)
index = siblings.index(para)
following = siblings[index + 1] if index + 1 < len(siblings) else None
if following is None or following.tag != p_tag:
continue
if any(self._text_elements(c) for c in para if c.tag == ppr_tag):
continue
insert_at = 1 if len(following) and following[0].tag == ppr_tag else 0
for child in reversed([c for c in para if c.tag != ppr_tag]):
following.insert(insert_at, child)
parent.remove(para)
def _extract_text_content(self, root):
p_tag = f"{{{self.namespaces['w']}}}p"
t_tag = f"{{{self.namespaces['w']}}}t"
paragraphs = []
for p_elem in root.findall(f".//{p_tag}"):
text_parts = []
for t_elem in p_elem.findall(f".//{t_tag}"):
text_parts.append(self._rendered_text(t_elem))
paragraph_text = "".join(text_parts)
paragraph_text = self._paragraph_text(p_elem)
if paragraph_text:
paragraphs.append(paragraph_text)
return "\n".join(paragraphs)
PAGE_FIELDS = {"PAGE", "NUMPAGES", "SECTIONPAGES"}
PAGE_NUMBER = re.compile(r"-? ?[0-9]{1,6} ?-?|[ivxlcdm]{1,8}|[a-z]{1,2}|", re.I)
PAGE_FIELD_NOTE = (
"Note: {PAGE}, {NUMPAGES} or {SECTIONPAGES} above stands for a page-number\n"
"field. Word recomputes the number it displays, so the number stored in\n"
"the file is not compared, but adding or removing the field still counts."
)
WORK_SPENT_NOTE = (
"Note: the texts were too long or repetitive to compare closely all the\n"
"way through, so a passage shown whole, as removed and then added, may\n"
"differ in only a few characters. Compare such a passage with the\n"
"original directly to find the edit."
)
def _paragraph_text(self, p_elem):
w = self.namespaces["w"]
t_tag, instr_tag = f"{{{w}}}t", f"{{{w}}}instrText"
fld_char, fld_simple = f"{{{w}}}fldChar", f"{{{w}}}fldSimple"
def page_field(instruction, field):
words = instruction.split()
locked = field.get(f"{{{w}}}fldLock") in ("1", "true", "on")
if words and words[0].upper() in self.PAGE_FIELDS and not locked:
return words[0].upper()
def shown(name, result):
return "{%s}" % name if self.PAGE_NUMBER.fullmatch(result) else result
parts, fields = [], []
skipped = set()
def sink():
for *_, result in reversed(fields):
if result is not None:
return result
return parts
for elem in p_elem.iter():
if elem.tag == fld_simple:
name = page_field(elem.get(f"{{{w}}}instr", ""), elem)
if name:
texts = [self._rendered_text(t) for t in elem.iter(t_tag)]
sink().append(shown(name, "".join(texts).strip()))
skipped.update(elem.iter(t_tag))
elif elem.tag == fld_char:
kind = elem.get(f"{{{w}}}fldCharType")
if kind == "begin":
fields.append([elem, "", False, None])
elif kind == "separate" and fields and not fields[-1][2]:
fields[-1][2] = True
if page_field(fields[-1][1], fields[-1][0]):
fields[-1][3] = []
elif kind == "end" and fields:
begin, instruction, _, result = fields.pop()
name = page_field(instruction, begin)
if name:
sink().append(shown(name, "".join(result or []).strip()))
elif elem.tag == instr_tag and fields and not fields[-1][2]:
fields[-1][1] += elem.text or ""
elif elem.tag == t_tag and elem not in skipped:
sink().append(self._rendered_text(elem))
for *_, result in fields:
parts.extend(result or [])
return "".join(parts)
if __name__ == "__main__":
raise RuntimeError("This module should not be run directly.")

132
skills/pptx/scripts/slide_text.py Executable file
View File

@@ -0,0 +1,132 @@
"""Print each slide of a .pptx, .pptm, .potx or .ppsx as markdown under `<!-- Slide number: N -->`.
Title, text, tables, chart data, picture alt text and speaker notes; shapes top to bottom.
Usage: python slide_text.py deck.pptx
"""
import os
import re
import sys
import zipfile
from pptx.package import Package
def _position(shape):
try:
return (shape.top or 0, shape.left or 0)
except Exception:
return (0, 0)
def _one_line(text) -> str:
return " ".join(str(text).split())
def _table(rows) -> list[str]:
lines = ["| " + " | ".join(_one_line(c).replace("|", "\\|") for c in r) + " |" for r in rows]
if lines:
lines.insert(1, "|" + " --- |" * len(rows[0]))
return lines
def _chart(chart) -> list[str]:
heading = "### Chart"
try:
if chart.has_title and chart.chart_title.has_text_frame:
heading += ": " + _one_line(chart.chart_title.text_frame.text)
categories = [c.label for c in chart.plots[0].categories]
series = [(s.name, list(s.values)) for s in chart.series]
except Exception as e:
return [
heading,
f"[chart data not readable ({type(e).__name__}): render the slide to see it]",
]
rows = [["Category", *(name for name, _ in series)]]
for i, category in enumerate(categories):
rows.append([category, *(v[i] if i < len(v) else "" for _, v in series)])
return [heading, "", *_table(rows)]
def _shape(shape) -> list[str]:
tag = shape._element.tag
if tag.endswith("}grpSp"):
return _shapes(shape.shapes)
if tag.endswith("}pic"):
alt = _one_line(shape._element._nvXxPr.cNvPr.get("descr", ""))
return [f"![{alt}]({shape.name})"]
if getattr(shape, "has_table", False):
return ["", *_table([[c.text for c in r.cells] for r in shape.table.rows]), ""]
if getattr(shape, "has_chart", False):
return ["", *_chart(shape.chart), ""]
if shape.has_text_frame and shape.text_frame.text.strip():
text = shape.text_frame.text.replace("\v", "\n")
is_title = shape.is_placeholder and shape.placeholder_format.idx == 0
return ["# " + text.lstrip() if is_title else text]
return []
def _members(shapes) -> list:
try:
return list(shapes)
except Exception:
pass
members = []
for i in range(len(shapes)):
try:
members.append(shapes[i])
except Exception as e:
members.append(e)
return members
def _shapes(shapes) -> list[str]:
lines = []
for shape in sorted(_members(shapes), key=_position):
try:
if isinstance(shape, Exception):
raise shape
lines += _shape(shape)
except Exception as e:
lines.append(f"[shape not readable ({type(e).__name__}): render the slide to see it]")
return lines
def slide_text(slide, number: int) -> str:
lines = [f"<!-- Slide number: {number} -->", *_shapes(slide.shapes)]
try:
notes = slide.notes_slide.notes_text_frame if slide.has_notes_slide else None
if notes is not None and notes.text.strip():
lines += ["", "### Notes:", notes.text.replace("\v", "\n")]
except Exception as e:
lines += ["", f"[notes not readable ({type(e).__name__})]"]
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines).strip())
def main() -> None:
if len(sys.argv) != 2:
sys.exit("Usage: python slide_text.py deck.pptx")
path = sys.argv[1]
if not os.path.isfile(path):
sys.exit(f"Error: {path} {'is not a file' if os.path.exists(path) else 'does not exist'}")
if not zipfile.is_zipfile(path):
sys.exit(
f"Error: {path} is corrupt, password-protected, or an old .ppt (not a zip archive)"
)
try:
deck = getattr(Package.open(path).main_document_part, "presentation", None)
except Exception as e:
sys.exit(f"Error: cannot read {path}: {e}")
if deck is None:
sys.exit(f"Error: {path} is not a .pptx, .pptm, .potx or .ppsx file")
sys.stdout.reconfigure(errors="replace")
try:
blocks = [slide_text(s, n) for n, s in enumerate(deck.slides, 1)]
print("\n\n".join(blocks) or "[no slides; layouts and masters are not printed]", flush=True)
except BrokenPipeError:
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
if __name__ == "__main__":
main()