Skillfarm / skills · skillfarm.ai / converted / docx / scripts / office / helpers / pptx_chart.py
| 1 | """Find chart XML that PowerPoint refuses or repairs. |
| 2 | |
| 3 | Detection only: more than one repair is usually valid, and only the author knows |
| 4 | which was meant. |
| 5 | """ |
| 6 | |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import html |
| 11 | import re |
| 12 | from collections import Counter |
| 13 | from typing import Mapping |
| 14 | |
| 15 | from defusedxml import ElementTree |
| 16 | from defusedxml.common import DefusedXmlException |
| 17 | |
| 18 | from . import part_text |
| 19 | |
| 20 | |
| 21 | _CHART_PART_RE = re.compile(r"ppt/charts/chart\d+\.xml") |
| 22 | |
| 23 | _GROUPING_RE = re.compile(r"""<c:grouping\b[^>]*?\bval=["'](\w+)["']""") |
| 24 | _DLBL_POS_RE = re.compile(r"""<c:dLblPos\b[^>]*?\bval=["'](\w+)["']""") |
| 25 | |
| 26 | def _strip_ext_lst(text: str) -> str: |
| 27 | return _strip_outermost(text, "c:extLst") |
| 28 | |
| 29 | |
| 30 | def _strip_outermost(text: str, name: str) -> str: |
| 31 | out, cursor = [], 0 |
| 32 | for lo, hi in _outermost_spans(text, name): |
| 33 | out.append(text[cursor:lo]) |
| 34 | cursor = hi |
| 35 | out.append(text[cursor:]) |
| 36 | return "".join(out) |
| 37 | |
| 38 | _BAR_GROUP_RE = re.compile(r"<c:(bar3DChart|barChart)\b[^>]*(?<!/)>.*?</c:\1\s*>", re.DOTALL) |
| 39 | |
| 40 | STACKED_GROUPINGS = frozenset({"stacked", "percentStacked"}) |
| 41 | ILLEGAL_ON_STACKED = frozenset({"outEnd"}) |
| 42 | LEGAL_ON_STACKED = ("ctr", "inEnd", "inBase") |
| 43 | |
| 44 | |
| 45 | def _check_stacked_label_positions(part: str, xml: str) -> list[str]: |
| 46 | problems: list[str] = [] |
| 47 | for match in _BAR_GROUP_RE.finditer(xml): |
| 48 | block = _strip_ext_lst(match.group(0)) |
| 49 | group = match.group(1) |
| 50 | |
| 51 | grouping = _GROUPING_RE.search(block) |
| 52 | if grouping is None or grouping.group(1) not in STACKED_GROUPINGS: |
| 53 | continue |
| 54 | |
| 55 | bad = [p for p in _DLBL_POS_RE.findall(block) if p in ILLEGAL_ON_STACKED] |
| 56 | for pos in sorted(set(bad)): |
| 57 | problems.append( |
| 58 | f'{part}: {bad.count(pos)} data label(s) use dLblPos="{pos}" on a ' |
| 59 | f"{grouping.group(1)} {group}; PowerPoint allows only " |
| 60 | f"{', '.join(LEGAL_ON_STACKED)} there" |
| 61 | ) |
| 62 | return problems |
| 63 | |
| 64 | |
| 65 | |
| 66 | _ANY_CHART_GROUP_RE = re.compile(r"<c:(\w+Chart)\b[^>]*(?<!/)>.*?</c:\1\s*>", re.DOTALL) |
| 67 | |
| 68 | _AXID_RE = re.compile( |
| 69 | r"""\s*<c:axId\b[^>]*?\bval=["'](-?\d+)["']\s*(?:/>|>\s*</c:axId\s*>)""" |
| 70 | ) |
| 71 | |
| 72 | _AXIS_DECL_RE = re.compile( |
| 73 | r"""<c:(catAx|valAx|serAx|dateAx)\b[^>]*(?<!/)>\s*<c:axId\b[^>]*?\bval=["'](-?\d+)["']""" |
| 74 | ) |
| 75 | |
| 76 | AXID_LIMIT = { |
| 77 | "barChart": 2, "lineChart": 2, "areaChart": 2, "scatterChart": 2, |
| 78 | "bubbleChart": 2, "radarChart": 2, "stockChart": 2, |
| 79 | "bar3DChart": 3, "line3DChart": 3, "area3DChart": 3, |
| 80 | "surfaceChart": 3, "surface3DChart": 3, |
| 81 | } |
| 82 | |
| 83 | AXID_MINIMUM = { |
| 84 | "barChart": 2, "lineChart": 2, "areaChart": 2, "scatterChart": 2, |
| 85 | "bubbleChart": 2, "radarChart": 2, "stockChart": 2, |
| 86 | "bar3DChart": 2, "area3DChart": 2, "surfaceChart": 2, |
| 87 | "line3DChart": 3, "surface3DChart": 3, |
| 88 | } |
| 89 | |
| 90 | |
| 91 | def _declared_axes(xml: str) -> dict[str, list[str]]: |
| 92 | axes: dict[str, list[str]] = {} |
| 93 | for kind, axid in _AXIS_DECL_RE.findall(xml): |
| 94 | axes.setdefault(kind, []).append(axid) |
| 95 | return axes |
| 96 | |
| 97 | |
| 98 | def _canonical_ids(axes: dict[str, list[str]], limit: int) -> list[str] | None: |
| 99 | category = axes.get("catAx", []) + axes.get("dateAx", []) |
| 100 | value = axes.get("valAx", []) |
| 101 | series = axes.get("serAx", []) |
| 102 | if len(category) != 1 or len(value) != 1 or len(series) > 1: |
| 103 | return None |
| 104 | ids = [category[0], value[0]] |
| 105 | if limit >= 3 and series: |
| 106 | ids.append(series[0]) |
| 107 | return ids |
| 108 | |
| 109 | |
| 110 | def _undeclared_axes(kind: str, block: str, axes: dict[str, list[str]]) -> list[str] | None: |
| 111 | if kind not in AXID_LIMIT: |
| 112 | return None |
| 113 | ids = _AXID_RE.findall(block) |
| 114 | declared = {i for group in axes.values() for i in group} |
| 115 | if len([i for i in ids if i in declared]) >= 2: |
| 116 | return None |
| 117 | return ids |
| 118 | |
| 119 | |
| 120 | def _check_chart_axis_references(part: str, xml: str) -> list[str]: |
| 121 | axes = _declared_axes(xml) |
| 122 | problems: list[str] = [] |
| 123 | declared = {i for group in axes.values() for i in group} |
| 124 | for match in _ANY_CHART_GROUP_RE.finditer(xml): |
| 125 | kind, block = match.group(1), match.group(0) |
| 126 | ids = _undeclared_axes(kind, block, axes) |
| 127 | if ids is None: |
| 128 | continue |
| 129 | if not ids: |
| 130 | problems.append( |
| 131 | f"{part}: <c:{kind}> declares no <c:axId> this part can resolve; a chart " |
| 132 | f"group needs {AXID_MINIMUM[kind]}, and PowerPoint discards one with fewer" |
| 133 | ) |
| 134 | continue |
| 135 | dead = [i for i in ids if i not in declared] |
| 136 | canonical = _canonical_ids(axes, AXID_LIMIT[kind]) |
| 137 | if canonical is not None and len(canonical) >= AXID_MINIMUM[kind]: |
| 138 | hint = f"Fix: point them at the axes this part declares ({', '.join(canonical)})" |
| 139 | else: |
| 140 | hint = ("Fix: the part declares several axes of a kind -- declare the " |
| 141 | "secondary axes the series expects, or drop them") |
| 142 | detail = (f"of which {', '.join(dead)} name no declared axis" |
| 143 | if dead else f"only {len(ids)} of which this part declares") |
| 144 | problems.append( |
| 145 | f"{part}: <c:{kind}> references axId {', '.join(ids)}, {detail}, " |
| 146 | f"leaving fewer than two live axes; PowerPoint discards the chart. {hint}" |
| 147 | ) |
| 148 | return problems |
| 149 | |
| 150 | |
| 151 | def _shown(value: str) -> str: |
| 152 | return '"' + repr(value[:20])[1:-1] + '"' |
| 153 | |
| 154 | |
| 155 | DECIMAL_SETTINGS = ( |
| 156 | "crossesAt", "max", "min", "majorUnit", "minorUnit", "logBase", |
| 157 | "forward", "backward", "intercept", "x", "y", "w", "h", |
| 158 | "splitPos", "custUnit", "pictureStackUnit", |
| 159 | ) |
| 160 | _DECIMAL_SETTING_RE = re.compile( |
| 161 | rf"""<c:({"|".join(DECIMAL_SETTINGS)})\b[^<>]*?\bval=["']([^"'<>]*)["']""" |
| 162 | ) |
| 163 | _DECIMAL_RE = re.compile( |
| 164 | r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?" |
| 165 | r"|[+-]?(inf|infinity|nan(\(\w*\))?|\u221e|1\.#(inf|qnan|snan|ind)\d*)", |
| 166 | re.IGNORECASE, |
| 167 | ) |
| 168 | |
| 169 | |
| 170 | def _check_decimal_settings(part: str, xml: str) -> list[str]: |
| 171 | problems = [] |
| 172 | for name, raw in sorted(set(_DECIMAL_SETTING_RE.findall(_strip_ext_lst(xml)))): |
| 173 | value = html.unescape(raw) |
| 174 | if _DECIMAL_RE.fullmatch(value.strip()): |
| 175 | continue |
| 176 | fix = "Fix: write a plain number, or remove the element" |
| 177 | if name == "crossesAt" and value.strip() == "autoZero": |
| 178 | fix = ("Fix: leave valAxisCrossesAt: 0 out of the pptxgenjs options, the axis " |
| 179 | "crosses at zero anyway. In the XML, write " |
| 180 | '<c:crosses val="autoZero"/> or a number') |
| 181 | problems.append( |
| 182 | f"{part}: <c:{name} val={_shown(value)}> is not a number, and PowerPoint " |
| 183 | f"will offer to repair the deck. {fix}" |
| 184 | ) |
| 185 | return problems |
| 186 | |
| 187 | |
| 188 | def _local(tag: str) -> str: |
| 189 | return tag.rsplit("}", 1)[-1] |
| 190 | |
| 191 | |
| 192 | def _drawn_series(root) -> list: |
| 193 | found, to_visit = [], [root] |
| 194 | while to_visit: |
| 195 | for child in to_visit.pop(): |
| 196 | name = _local(child.tag) |
| 197 | if name == "ser": |
| 198 | found.append(child) |
| 199 | elif name == "AlternateContent": |
| 200 | to_visit.extend(child[:1]) |
| 201 | elif name != "extLst": |
| 202 | to_visit.append(child) |
| 203 | return found |
| 204 | |
| 205 | |
| 206 | def _check_series_order(part: str, xml: str) -> list[str]: |
| 207 | try: |
| 208 | root = ElementTree.fromstring(xml.encode("utf-8", "surrogateescape")) |
| 209 | except (ElementTree.ParseError, DefusedXmlException, LookupError, ValueError): |
| 210 | return [] |
| 211 | orders = Counter() |
| 212 | for series in _drawn_series(root): |
| 213 | own = [c.get("val", "") for c in series if _local(c.tag) == "order"] |
| 214 | if own and own[0].isascii() and own[0].isdigit(): |
| 215 | orders[own[0]] += 1 |
| 216 | repeated = sorted((o for o, n in orders.items() if n > 1), key=lambda o: (len(o), o)) |
| 217 | if not repeated: |
| 218 | return [] |
| 219 | return [ |
| 220 | f"{part}: two or more series share the <c:order> value {', '.join(o[:12] for o in repeated)}, " |
| 221 | f"and PowerPoint will offer to repair the deck. Fix: number <c:order> " |
| 222 | f"(and <c:idx>) 0, 1, 2... across every series in the chart, a combo " |
| 223 | f"chart's line series carrying on from its bars" |
| 224 | ] |
| 225 | |
| 226 | |
| 227 | PRESET_DASHES = frozenset({ |
| 228 | "solid", "dot", "dash", "lgDash", "dashDot", "lgDashDot", "lgDashDotDot", |
| 229 | "sysDash", "sysDot", "sysDashDot", "sysDashDotDot", |
| 230 | }) |
| 231 | _PRESET_DASH_RE = re.compile(r"""<a:prstDash\b[^<>]*?\bval=["']([^"'<>]*)["']""") |
| 232 | |
| 233 | |
| 234 | def _check_preset_dashes(part: str, xml: str) -> list[str]: |
| 235 | values = {html.unescape(v) for v in _PRESET_DASH_RE.findall(_strip_ext_lst(xml))} |
| 236 | return [ |
| 237 | f"{part}: <a:prstDash val={_shown(value)}> is not a dash style, and PowerPoint " |
| 238 | f"will offer to repair the deck. Use one of {', '.join(sorted(PRESET_DASHES))}. " |
| 239 | f"In pptxgenjs, lineDash takes one such word for the whole chart, not an array" |
| 240 | for value in sorted(values) |
| 241 | if value.strip() not in PRESET_DASHES |
| 242 | ] |
| 243 | |
| 244 | |
| 245 | def _outermost_spans(text: str, name: str) -> list[tuple[int, int]]: |
| 246 | spans: list[tuple[int, int]] = [] |
| 247 | depth = 0 |
| 248 | start = 0 |
| 249 | for match in re.finditer(rf"<(/?){name}\b[^<>]*?(/?)>", text): |
| 250 | closing, self_closing = match.group(1), match.group(2) |
| 251 | if self_closing: |
| 252 | continue |
| 253 | if closing: |
| 254 | if depth: |
| 255 | depth -= 1 |
| 256 | if depth == 0: |
| 257 | spans.append((start, match.end())) |
| 258 | else: |
| 259 | if depth == 0: |
| 260 | start = match.start() |
| 261 | depth += 1 |
| 262 | return spans |
| 263 | |
| 264 | |
| 265 | CHART_CHECKS = ( |
| 266 | _check_stacked_label_positions, |
| 267 | _check_chart_axis_references, |
| 268 | _check_decimal_settings, |
| 269 | _check_series_order, |
| 270 | _check_preset_dashes, |
| 271 | ) |
| 272 | |
| 273 | |
| 274 | _COMMENT_OR_PI_RE = re.compile(r"<!--.*?(?:-->|\Z)|<\?(?!xml\s).*?(?:\?>|\Z)", re.DOTALL) |
| 275 | |
| 276 | |
| 277 | def find_chart_problems(files: Mapping[str, bytes]) -> list[str]: |
| 278 | problems: list[str] = [] |
| 279 | for part in sorted(n for n in files if _CHART_PART_RE.fullmatch(n)): |
| 280 | xml = _strip_outermost(_COMMENT_OR_PI_RE.sub("", part_text(files[part])), "mc:Fallback") |
| 281 | for check in CHART_CHECKS: |
| 282 | problems.extend(check(part, xml)) |
| 283 | return problems |