Skillfarm / skills · skillfarm.ai / converted / xlsx / scripts / recalc.py
| 1 | """ |
| 2 | Excel Formula Recalculation Script |
| 3 | Recalculates all formulas in an Excel file using LibreOffice |
| 4 | |
| 5 | LibreOffice recalculates a copy of the workbook. Only the values it computed are then written |
| 6 | into the workbook itself, so nothing else in the file is rewritten. |
| 7 | """ |
| 8 | |
| 9 | import contextlib |
| 10 | import copy |
| 11 | import html |
| 12 | import io |
| 13 | import json |
| 14 | import math |
| 15 | import os |
| 16 | import platform |
| 17 | import posixpath |
| 18 | import re |
| 19 | import shutil |
| 20 | import signal |
| 21 | import subprocess |
| 22 | import sys |
| 23 | import tempfile |
| 24 | import time |
| 25 | import zipfile |
| 26 | from pathlib import Path |
| 27 | from xml.parsers import expat |
| 28 | |
| 29 | from office.soffice import get_soffice_env, run_soffice |
| 30 | |
| 31 | MACRO_FILENAME = "Module1.xba" |
| 32 | SOFFICE_MISSING = "soffice not found on PATH; LibreOffice is required to recalculate" |
| 33 | |
| 34 | MAX_LOCATIONS = 100 |
| 35 | |
| 36 | RECALCULATE_MACRO = """<?xml version="1.0" encoding="UTF-8"?> |
| 37 | <!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd"> |
| 38 | <script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic"> |
| 39 | Sub RecalculateAndSave() |
| 40 | ThisComponent.calculateAll() |
| 41 | ThisComponent.store() |
| 42 | ThisComponent.close(True) |
| 43 | End Sub |
| 44 | </script:module>""" |
| 45 | |
| 46 | |
| 47 | def has_gtimeout(): |
| 48 | try: |
| 49 | subprocess.run( |
| 50 | ["gtimeout", "--version"], capture_output=True, timeout=1, check=False |
| 51 | ) |
| 52 | return True |
| 53 | except (FileNotFoundError, subprocess.TimeoutExpired): |
| 54 | return False |
| 55 | |
| 56 | |
| 57 | def _stamp(path): |
| 58 | st = os.stat(path) |
| 59 | return st.st_mtime_ns, st.st_size |
| 60 | |
| 61 | |
| 62 | def setup_libreoffice_macro(profile_dir: Path, timeout=30): |
| 63 | url = profile_dir.as_uri() |
| 64 | try: |
| 65 | run_soffice( |
| 66 | ["--headless", "--terminate_after_init", f"-env:UserInstallation={url}"], |
| 67 | capture_output=True, |
| 68 | timeout=timeout, |
| 69 | ) |
| 70 | except FileNotFoundError: |
| 71 | return None, SOFFICE_MISSING |
| 72 | except subprocess.TimeoutExpired: |
| 73 | return None, "LibreOffice timed out creating its profile; formulas were NOT recalculated" |
| 74 | |
| 75 | macro_dir = profile_dir / "user" / "basic" / "Standard" |
| 76 | if not macro_dir.exists(): |
| 77 | return None, "LibreOffice did not create a usable profile; formulas were NOT recalculated" |
| 78 | |
| 79 | try: |
| 80 | (macro_dir / MACRO_FILENAME).write_text(RECALCULATE_MACRO) |
| 81 | except OSError as e: |
| 82 | return None, f"Could not install the recalculation macro: {e}" |
| 83 | |
| 84 | return url, None |
| 85 | |
| 86 | |
| 87 | def _existing_cells(ws): |
| 88 | if not hasattr(ws, "iter_rows"): |
| 89 | return [] |
| 90 | return [ws._cells[key] for key in sorted(ws._cells)] |
| 91 | |
| 92 | |
| 93 | def _is_workbook(path): |
| 94 | try: |
| 95 | with zipfile.ZipFile(path) as archive: |
| 96 | return _workbook_part(archive) is not None |
| 97 | except Exception: |
| 98 | return False |
| 99 | |
| 100 | |
| 101 | def _part_that_is_not_xml(path): |
| 102 | with zipfile.ZipFile(path) as archive: |
| 103 | for item in archive.infolist(): |
| 104 | if not item.filename.endswith((".xml", ".rels")) or item.file_size > 50_000_000: |
| 105 | continue |
| 106 | data = archive.read(item) |
| 107 | plain = data.replace(b"\x00", b"") if b"\x00" in data[:64] else data |
| 108 | if b"<!" in plain: |
| 109 | continue |
| 110 | try: |
| 111 | expat.ParserCreate().Parse(data, True) |
| 112 | except expat.ExpatError as e: |
| 113 | return f"{item.filename} is not well-formed XML: {e}" |
| 114 | return None |
| 115 | |
| 116 | |
| 117 | def _has_formulas(path): |
| 118 | try: |
| 119 | with zipfile.ZipFile(path) as archive: |
| 120 | for _, part_name in _worksheets(archive, any_namespace=True): |
| 121 | raw = archive.read(part_name) |
| 122 | plain = raw.replace(b"\x00", b"") if b"\x00" in raw[:64] else raw |
| 123 | if re.search(rb"<(?:\w+:)?f[\s/>]", plain): |
| 124 | return True |
| 125 | if b"<!" not in plain: |
| 126 | expat.ParserCreate().Parse(raw, True) |
| 127 | return False |
| 128 | except Exception: |
| 129 | return True |
| 130 | |
| 131 | |
| 132 | def recalc(filename, timeout=30, force=False): |
| 133 | if not Path(filename).exists(): |
| 134 | return {"error": f"File {filename} does not exist"} |
| 135 | |
| 136 | abs_path = os.path.realpath(filename) |
| 137 | |
| 138 | if not _is_workbook(abs_path): |
| 139 | return {"error": f"{filename} is not an .xlsx or .xlsm workbook; recalc.py cannot read it"} |
| 140 | |
| 141 | if not _has_formulas(abs_path): |
| 142 | report = _report(filename) |
| 143 | if "error" not in report: |
| 144 | return report |
| 145 | broken = _part_that_is_not_xml(abs_path) |
| 146 | if broken: |
| 147 | return {"error": f"{broken}; {filename} is unchanged"} |
| 148 | return {"status": "success", "total_errors": 0, "error_summary": {}, "total_formulas": 0} |
| 149 | |
| 150 | if not (os.access(abs_path, os.W_OK) and os.access(os.path.dirname(abs_path), os.W_OK)): |
| 151 | return { |
| 152 | "error": f"{filename} or its folder is not writable; recalc.py needs to write to both" |
| 153 | } |
| 154 | |
| 155 | try: |
| 156 | get_soffice_env() |
| 157 | except Exception as e: |
| 158 | return {"error": f"Could not prepare the LibreOffice environment: {e}"} |
| 159 | |
| 160 | with tempfile.TemporaryDirectory(prefix="recalc-lo-", ignore_cleanup_errors=True) as work: |
| 161 | copy = os.path.join(work, "copy", os.path.basename(abs_path)) |
| 162 | profile_dir = Path(work) / "profile" |
| 163 | try: |
| 164 | os.mkdir(os.path.dirname(copy)) |
| 165 | shutil.copyfile(abs_path, copy) |
| 166 | profile_dir.mkdir() |
| 167 | except OSError as e: |
| 168 | return {"error": f"Could not copy {filename} for LibreOffice to work on: {e}"} |
| 169 | return _recalc_with_profile(filename, abs_path, copy, timeout, profile_dir) |
| 170 | |
| 171 | |
| 172 | def _recalc_with_profile(filename, abs_path, copy, timeout, profile_dir: Path): |
| 173 | started = time.monotonic() |
| 174 | profile_url, err = setup_libreoffice_macro(profile_dir, timeout=timeout) |
| 175 | if err: |
| 176 | return {"error": err} |
| 177 | |
| 178 | timeout = max(5, int(timeout - (time.monotonic() - started))) |
| 179 | |
| 180 | before = _stamp(copy) |
| 181 | |
| 182 | cmd = [ |
| 183 | "soffice", |
| 184 | "--headless", |
| 185 | "--norestore", |
| 186 | f"-env:UserInstallation={profile_url}", |
| 187 | "vnd.sun.star.script:Standard.Module1.RecalculateAndSave?language=Basic&location=application", |
| 188 | copy, |
| 189 | ] |
| 190 | |
| 191 | if platform.system() == "Linux" and shutil.which("timeout"): |
| 192 | cmd = ["timeout", str(timeout)] + cmd |
| 193 | elif platform.system() == "Darwin" and has_gtimeout(): |
| 194 | cmd = ["gtimeout", str(timeout)] + cmd |
| 195 | |
| 196 | timed_out = f"LibreOffice timed out after {timeout}s; formulas were NOT recalculated. Re-run with a longer timeout." |
| 197 | |
| 198 | try: |
| 199 | result = subprocess.run( |
| 200 | cmd, capture_output=True, text=True, env=get_soffice_env(), timeout=timeout + 15 |
| 201 | ) |
| 202 | except subprocess.TimeoutExpired: |
| 203 | return {"error": timed_out} |
| 204 | except FileNotFoundError: |
| 205 | return {"error": SOFFICE_MISSING} |
| 206 | |
| 207 | if result.returncode == 124: |
| 208 | return {"error": timed_out} |
| 209 | |
| 210 | if result.returncode != 0: |
| 211 | detail = (result.stderr or "").strip() or f"soffice exited {result.returncode}" |
| 212 | return {"error": f"LibreOffice failed to recalculate: {detail}"} |
| 213 | |
| 214 | try: |
| 215 | rewritten = _stamp(copy) != before |
| 216 | except OSError: |
| 217 | rewritten = False |
| 218 | if not rewritten: |
| 219 | return { |
| 220 | "error": ( |
| 221 | "LibreOffice exited cleanly but never rewrote its copy of the file, so nothing was " |
| 222 | "recalculated. Run it again; if the same happens, LibreOffice is not running the " |
| 223 | "recalculation macro on this machine." |
| 224 | ) |
| 225 | } |
| 226 | |
| 227 | try: |
| 228 | found = _write_values(abs_path, copy) |
| 229 | except Exception as e: |
| 230 | why = f"which is unchanged: {str(e) or type(e).__name__}" |
| 231 | return {"error": f"Could not write the new values into {filename}, {why}"} |
| 232 | |
| 233 | return _report(filename, found) |
| 234 | |
| 235 | |
| 236 | EXCEL_ERRORS = ["#VALUE!", "#DIV/0!", "#REF!", "#NAME?", "#NULL!", "#NUM!", "#N/A"] |
| 237 | |
| 238 | _MAIN_NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}" |
| 239 | _REL_NS = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}" |
| 240 | _CELL_REF_RE = re.compile(r"([A-Z]{1,3})([0-9]+)") |
| 241 | MAX_MERGE_CHECKS = 1_000_000 |
| 242 | _MERGE_RE = re.compile(rb'<(?:\w+:)?mergeCell\b[^>]*\bref="([^"]*)"') |
| 243 | |
| 244 | |
| 245 | def _error_in(text): |
| 246 | if "#" in text: |
| 247 | for err in EXCEL_ERRORS: |
| 248 | if err in text: |
| 249 | return err |
| 250 | return None |
| 251 | |
| 252 | |
| 253 | def _rich_text(node): |
| 254 | runs = node.findall(f"{_MAIN_NS}t") + node.findall(f"{_MAIN_NS}r/{_MAIN_NS}t") |
| 255 | return "".join(t.text or "" for t in runs) |
| 256 | |
| 257 | |
| 258 | def _row_major(coordinate): |
| 259 | address = _CELL_REF_RE.fullmatch(coordinate) |
| 260 | if address is None: |
| 261 | raise ValueError(f"{coordinate[:20]!r} is not the address of a cell") |
| 262 | column, row = address.groups() |
| 263 | number = 0 |
| 264 | for letter in column: |
| 265 | number = number * 26 + ord(letter) - ord("A") + 1 |
| 266 | return int(row), number |
| 267 | |
| 268 | |
| 269 | def _merged_ranges(sheet_xml): |
| 270 | ranges = [] |
| 271 | for ref in _MERGE_RE.findall(sheet_xml): |
| 272 | first, _, last = ref.decode().partition(":") |
| 273 | ranges.append((*_row_major(first), *_row_major(last))) |
| 274 | return ranges |
| 275 | |
| 276 | |
| 277 | def _hidden_by_a_merge(merged, row, column): |
| 278 | return any( |
| 279 | top <= row <= bottom and left <= column <= right and (row, column) != (top, left) |
| 280 | for top, left, bottom, right in merged |
| 281 | ) |
| 282 | |
| 283 | |
| 284 | def _utf8_or_refuse(data, what): |
| 285 | declared = re.search(rb"""<\?xml[^>]*\sencoding\s*=\s*["']([^"']+)""", data[:200]) |
| 286 | utf8 = declared is None or declared[1].lower().replace(b"-", b"") == b"utf8" |
| 287 | if data[:2] in (b"\xff\xfe", b"\xfe\xff") or b"\x00" in data[:64] or not utf8: |
| 288 | raise ValueError(f"{what} is not in UTF-8, which is all this script can read") |
| 289 | |
| 290 | |
| 291 | def _xml(data, what="an XML part"): |
| 292 | try: |
| 293 | from defusedxml.ElementTree import fromstring |
| 294 | except ImportError: |
| 295 | _utf8_or_refuse(data, what) |
| 296 | if b"<!DOCTYPE" in data or b"<!ENTITY" in data: |
| 297 | raise ValueError("XML with a DTD, and defusedxml is not installed") from None |
| 298 | from xml.etree.ElementTree import fromstring |
| 299 | return fromstring(data) |
| 300 | |
| 301 | |
| 302 | def _workbook_part(archive): |
| 303 | if "_rels/.rels" not in archive.namelist(): |
| 304 | return None |
| 305 | for rel in _xml(archive.read("_rels/.rels"), "_rels/.rels"): |
| 306 | if rel.get("Type", "").endswith("/officeDocument"): |
| 307 | name = posixpath.normpath(rel.get("Target", "")).lstrip("/") |
| 308 | return name if name in archive.namelist() else None |
| 309 | return None |
| 310 | |
| 311 | |
| 312 | def _workbook_xml(archive): |
| 313 | name = _workbook_part(archive) |
| 314 | if name is None: |
| 315 | raise ValueError("the package names no workbook part") |
| 316 | if archive.getinfo(name).file_size > 50_000_000: |
| 317 | raise ValueError(f"{name} is too large to be a workbook's") |
| 318 | return _xml(archive.read(name), name) |
| 319 | |
| 320 | |
| 321 | def _worksheets(archive, any_namespace=False): |
| 322 | workbook = _workbook_xml(archive) |
| 323 | if not any_namespace and workbook.tag != f"{_MAIN_NS}workbook": |
| 324 | namespace = workbook.tag.partition("}")[0].lstrip("{") |
| 325 | if "/ooxml/" in namespace: |
| 326 | raise ValueError("it is in Strict Open XML format, which this script cannot edit") |
| 327 | raise ValueError(f"its XML is in a namespace this script does not read ({namespace})") |
| 328 | folder, file_name = posixpath.split(_workbook_part(archive)) |
| 329 | rels_name = posixpath.join(folder, "_rels", f"{file_name}.rels") |
| 330 | rels = {rel.get("Id"): rel for rel in _xml(archive.read(rels_name), rels_name)} |
| 331 | found = [] |
| 332 | for sheet in workbook.iter(): |
| 333 | if not sheet.tag.endswith("}sheet"): |
| 334 | continue |
| 335 | rel_id = next((value for key, value in sheet.attrib.items() if key.endswith("}id")), None) |
| 336 | rel = rels.get(rel_id) |
| 337 | if rel is None or not rel.get("Type", "").endswith("/worksheet"): |
| 338 | continue |
| 339 | target = rel.get("Target") |
| 340 | if target.startswith("/"): |
| 341 | part_name = target.lstrip("/") |
| 342 | else: |
| 343 | part_name = posixpath.normpath(posixpath.join(folder, target)) |
| 344 | found.append((sheet.get("name"), part_name)) |
| 345 | return found |
| 346 | |
| 347 | |
| 348 | def _sheet_names(archive): |
| 349 | return [s.get("name") for s in _workbook_xml(archive).iter() if s.tag.endswith("}sheet")] |
| 350 | |
| 351 | |
| 352 | def _scan_xml(filename): |
| 353 | from defusedxml.ElementTree import iterparse |
| 354 | |
| 355 | error_details = {err: [] for err in EXCEL_ERRORS} |
| 356 | formula_count = 0 |
| 357 | merge_checks = 0 |
| 358 | |
| 359 | with zipfile.ZipFile(filename) as archive: |
| 360 | shared_errors, shared_equals = {}, set() |
| 361 | if "xl/sharedStrings.xml" in archive.namelist(): |
| 362 | with archive.open("xl/sharedStrings.xml") as part: |
| 363 | index = 0 |
| 364 | for _, node in iterparse(part): |
| 365 | if node.tag != f"{_MAIN_NS}si": |
| 366 | continue |
| 367 | text = _rich_text(node).replace("x005F_", "") |
| 368 | err = _error_in(text) |
| 369 | if err: |
| 370 | shared_errors[index] = err |
| 371 | if text.startswith("="): |
| 372 | shared_equals.add(index) |
| 373 | index += 1 |
| 374 | node.clear() |
| 375 | |
| 376 | for sheet_name, part_name in _worksheets(archive): |
| 377 | found = [] |
| 378 | xml = archive.read(part_name) |
| 379 | merged = _merged_ranges(xml) |
| 380 | for _, node in iterparse(io.BytesIO(xml)): |
| 381 | if node.tag == f"{_MAIN_NS}row": |
| 382 | node.clear() |
| 383 | if node.tag != f"{_MAIN_NS}c": |
| 384 | continue |
| 385 | if node.get("r") is None: |
| 386 | raise ValueError("a cell without its address") |
| 387 | formula = node.find(f"{_MAIN_NS}f") |
| 388 | is_formula = formula is not None and formula.get("t") != "dataTable" |
| 389 | err = None |
| 390 | cell_type = node.get("t", "n") |
| 391 | if cell_type == "s": |
| 392 | index = int(node.findtext(f"{_MAIN_NS}v")) |
| 393 | err = shared_errors.get(index) |
| 394 | is_formula = is_formula or (formula is None and index in shared_equals) |
| 395 | elif cell_type not in ("n", "b", "d"): |
| 396 | inline = node.find(f"{_MAIN_NS}is") |
| 397 | text = node.findtext(f"{_MAIN_NS}v") if inline is None else _rich_text(inline) |
| 398 | err = _error_in(text or "") |
| 399 | is_formula = is_formula or (formula is None and (text or "").startswith("=")) |
| 400 | if not is_formula and not err: |
| 401 | continue |
| 402 | row, column = _row_major(node.get("r")) |
| 403 | merge_checks += len(merged) |
| 404 | if merge_checks > MAX_MERGE_CHECKS: |
| 405 | raise ValueError("too many merged ranges for this many cells") |
| 406 | if _hidden_by_a_merge(merged, row, column): |
| 407 | continue |
| 408 | formula_count += is_formula |
| 409 | if err: |
| 410 | found.append(((row, column), err, node.get("r"))) |
| 411 | for _, err, coordinate in sorted(found): |
| 412 | error_details[err].append(f"{sheet_name}!{coordinate}") |
| 413 | |
| 414 | return error_details, formula_count |
| 415 | |
| 416 | |
| 417 | def _scan_with_openpyxl(filename): |
| 418 | from openpyxl import load_workbook |
| 419 | from openpyxl.worksheet.formula import ArrayFormula |
| 420 | |
| 421 | error_details = {err: [] for err in EXCEL_ERRORS} |
| 422 | wb = load_workbook(filename, data_only=True) |
| 423 | for sheet_name in wb.sheetnames: |
| 424 | ws = wb[sheet_name] |
| 425 | for cell in _existing_cells(ws): |
| 426 | if isinstance(cell.value, str): |
| 427 | err = _error_in(cell.value) |
| 428 | if err: |
| 429 | error_details[err].append(f"{sheet_name}!{cell.coordinate}") |
| 430 | wb.close() |
| 431 | |
| 432 | wb_formulas = load_workbook(filename, data_only=False) |
| 433 | formula_count = 0 |
| 434 | for sheet_name in wb_formulas.sheetnames: |
| 435 | ws = wb_formulas[sheet_name] |
| 436 | for cell in _existing_cells(ws): |
| 437 | v = cell.value |
| 438 | if isinstance(v, ArrayFormula): |
| 439 | v = v.text |
| 440 | if isinstance(v, str) and v.startswith("="): |
| 441 | formula_count += 1 |
| 442 | wb_formulas.close() |
| 443 | |
| 444 | return error_details, formula_count |
| 445 | |
| 446 | |
| 447 | def _sheet_names_too_long(filename): |
| 448 | try: |
| 449 | with zipfile.ZipFile(filename) as archive: |
| 450 | return [name for name in _sheet_names(archive) if len(name or "") > 31] |
| 451 | except Exception: |
| 452 | return [] |
| 453 | |
| 454 | |
| 455 | def _report(filename, found=None): |
| 456 | try: |
| 457 | try: |
| 458 | error_details, formula_count = _scan_xml(filename) |
| 459 | except Exception: |
| 460 | error_details, formula_count = _scan_with_openpyxl(filename) |
| 461 | except Exception as e: |
| 462 | return {"error": str(e)} |
| 463 | |
| 464 | found = found or {} |
| 465 | kept = found.get("not_computed", []) |
| 466 | apart = set(kept) | set(found.get("#NAME?", ())) |
| 467 | in_file = [where for where in error_details["#NAME?"] if where not in apart] |
| 468 | error_details["#NAME?"] = in_file + found.get("#NAME?", []) |
| 469 | for error in EXCEL_ERRORS: |
| 470 | if error != "#NAME?": |
| 471 | error_details[error] += found.get(error, []) |
| 472 | error_details[UNBALANCED] = found.get(UNBALANCED, []) |
| 473 | error_details[TOO_LONG] = _sheet_names_too_long(filename) |
| 474 | |
| 475 | total_errors = sum(len(locations) for locations in error_details.values()) |
| 476 | result = { |
| 477 | "status": "success" if total_errors == 0 else "errors_found", |
| 478 | "total_errors": total_errors, |
| 479 | "error_summary": {}, |
| 480 | } |
| 481 | |
| 482 | for err_type, locations in error_details.items(): |
| 483 | if locations: |
| 484 | entry = {"count": len(locations), "locations": locations[:MAX_LOCATIONS]} |
| 485 | if len(locations) > MAX_LOCATIONS: |
| 486 | entry["locations_truncated"] = len(locations) - MAX_LOCATIONS |
| 487 | result["error_summary"][err_type] = entry |
| 488 | |
| 489 | result["total_formulas"] = formula_count |
| 490 | if kept: |
| 491 | result["not_computed"] = {"count": len(kept), "locations": kept[:MAX_LOCATIONS]} |
| 492 | if len(kept) > MAX_LOCATIONS: |
| 493 | result["not_computed"]["locations_truncated"] = len(kept) - MAX_LOCATIONS |
| 494 | return result |
| 495 | |
| 496 | |
| 497 | |
| 498 | MAX_ARRAY_CELLS = 1_000_000 |
| 499 | |
| 500 | _ATTRS = rb"""((?:[^>"']|"[^"]*"|'[^']*')*?)""" |
| 501 | _ROW_OR_CELL_RE = re.compile( |
| 502 | rb"<((?:\w+:)?)(?:row(?=[\s/>])" + _ATTRS + rb"/?>" |
| 503 | rb"|c(?=[\s/>])" + _ATTRS + rb"(?:/>|>(.*?)</\1c\s*>))", |
| 504 | re.S, |
| 505 | ) |
| 506 | _F_RE = re.compile(rb"<(?:\w+:)?f(?=[\s/>])" + _ATTRS + rb"(?:/>|>(.*?)</(?:\w+:)?f\s*>)", re.S) |
| 507 | _V_RE = re.compile(rb"<(?:\w+:)?v(?=[\s/>])[^>]*?(?:/>|>(.*?)</(?:\w+:)?v\s*>)", re.S) |
| 508 | _T_OR_VM_RE = re.compile(rb"""\s(?:t|vm)\s*=\s*(?:"[^"]*"|'[^']*')""") |
| 509 | _EXT_LST_RE = re.compile(rb"<(?:\w+:)?extLst\b.*</(?:\w+:)?extLst\s*>", re.S) |
| 510 | _NAME_ERROR = (b"e", b"#NAME?") |
| 511 | _STRING_RE = re.compile(r'"[^"]*"') |
| 512 | _QUOTED_RE = re.compile(r""""[^"]*"|'[^']*'|\[[^\[\]]*\]""") |
| 513 | _CALL_RE = re.compile(r"(?<![\w.])([A-Za-z_][\w.]*)\(") |
| 514 | _DELIMS = r"\s+\-*/^&=<>(),;:!%{}#@~|" |
| 515 | _WORD_RE = re.compile(rf"(?<![^{_DELIMS}])[^{_DELIMS}]+(?![^{_DELIMS}]|[(!])") |
| 516 | _EXTERNAL_REF_RE = re.compile(r"""(?<![\w"\[])'?\[[1-9]\d*\][^!"\[\]]*'?!""") |
| 517 | _PREFIX_RE = re.compile(r"^(?:_xlfn\.|_xlws\.)+", re.I) |
| 518 | UNBALANCED = "unbalanced brackets" |
| 519 | TOO_LONG = "sheet name over 31 characters" |
| 520 | _STORED_BARE = frozenset( |
| 521 | "CUBEVALUE CUBEMEMBER CUBESET CUBESETCOUNT CUBERANKEDMEMBER CUBEKPIMEMBER CUBEMEMBERPROPERTY " |
| 522 | "RTD CALL DBCS PHONETIC REGISTER.ID SQL.REQUEST USDOLLAR BAHTTEXT ECMA.CEILING".split() |
| 523 | ) |
| 524 | LIBREOFFICE_LACKS = _STORED_BARE | frozenset( |
| 525 | "XLOOKUP XMATCH SORT SORTBY FILTER UNIQUE SEQUENCE RANDARRAY LET LAMBDA MAP REDUCE SCAN " |
| 526 | "MAKEARRAY BYROW BYCOL ISOMITTED TEXTBEFORE TEXTAFTER TEXTSPLIT VSTACK HSTACK TOROW TOCOL " |
| 527 | "WRAPROWS WRAPCOLS TAKE DROP CHOOSEROWS CHOOSECOLS EXPAND VALUETOTEXT ARRAYTOTEXT REGEXTEST " |
| 528 | "REGEXEXTRACT REGEXREPLACE PERCENTOF GROUPBY PIVOTBY TRIMRANGE IMAGE STOCKHISTORY FIELDVALUE " |
| 529 | "PY COPILOT TRANSLATE DETECTLANGUAGE ANCHORARRAY SINGLE BINOM.DIST.RANGE IMCOSH IMCOT IMCSC " |
| 530 | "IMCSCH IMSEC IMSECH IMSINH IMTAN QUERYSTRING".split() |
| 531 | ) |
| 532 | |
| 533 | |
| 534 | def _attr_re(name): |
| 535 | return re.compile(rb"\s" + name + rb"""\s*=\s*(?:"([^"]*)"|'([^']*)')""") |
| 536 | |
| 537 | |
| 538 | _R_RE, _T_RE, _REF_RE, _SI_RE = _attr_re(b"r"), _attr_re(b"t"), _attr_re(b"ref"), _attr_re(b"si") |
| 539 | |
| 540 | |
| 541 | def _attr(pattern, attrs): |
| 542 | m = pattern.search(attrs) |
| 543 | if m is None: |
| 544 | return None |
| 545 | return m[1] if m[1] is not None else m[2] |
| 546 | |
| 547 | |
| 548 | def _sheet_data_span(xml): |
| 549 | if b"<!" in xml: |
| 550 | return None |
| 551 | parser = expat.ParserCreate(namespace_separator="}") |
| 552 | depth, found = [0], [] |
| 553 | |
| 554 | def start(name, _attributes): |
| 555 | depth[0] += 1 |
| 556 | if depth[0] == 2 and name == _MAIN_NS[1:] + "sheetData" and not found: |
| 557 | found.append(parser.CurrentByteIndex) |
| 558 | |
| 559 | def end(name): |
| 560 | if depth[0] == 2 and name == _MAIN_NS[1:] + "sheetData" and len(found) == 1: |
| 561 | found.append(parser.CurrentByteIndex) |
| 562 | depth[0] -= 1 |
| 563 | |
| 564 | parser.StartElementHandler, parser.EndElementHandler = start, end |
| 565 | parser.Parse(xml, True) |
| 566 | return tuple(found) if len(found) == 2 else None |
| 567 | |
| 568 | |
| 569 | def _cells(xml): |
| 570 | span = _sheet_data_span(xml) |
| 571 | row = column = 0 |
| 572 | for m in _ROW_OR_CELL_RE.finditer(xml, *span) if span else (): |
| 573 | if m[3] is None: |
| 574 | number = _attr(_R_RE, m[2]) |
| 575 | row, column = int(number) if number else row + 1, 0 |
| 576 | continue |
| 577 | ref = _attr(_R_RE, m[3]) |
| 578 | if ref: |
| 579 | row, column = _row_major(ref.decode()) |
| 580 | else: |
| 581 | column += 1 |
| 582 | yield row, column, m |
| 583 | |
| 584 | |
| 585 | def _sheet_xml(archive, part_name): |
| 586 | xml = archive.read(part_name) |
| 587 | _utf8_or_refuse(xml, part_name) |
| 588 | body = xml[3:] if xml.startswith(b"\xef\xbb\xbf") else xml |
| 589 | if b"<!" in xml or body.count(b"<?") > bool(re.match(rb"<\?xml\s", body)): |
| 590 | raise ValueError( |
| 591 | f"{part_name} holds a comment, CDATA, a DTD or a processing instruction, which this " |
| 592 | "script cannot edit. Load and save the workbook with openpyxl first, or leave it as is" |
| 593 | ) |
| 594 | try: |
| 595 | expat.ParserCreate().Parse(xml, True) |
| 596 | except expat.ExpatError as e: |
| 597 | raise ValueError(f"{part_name} is not well-formed XML: {e}") from None |
| 598 | return xml |
| 599 | |
| 600 | |
| 601 | def _array_cells(xml, budget): |
| 602 | cells = {} |
| 603 | for f in _F_RE.finditer(xml): |
| 604 | if _attr(_T_RE, f[1]) not in (b"array", b"dataTable"): |
| 605 | continue |
| 606 | first, _, last = (_attr(_REF_RE, f[1]) or b"").decode().partition(":") |
| 607 | if not last: |
| 608 | continue |
| 609 | (top, left), (bottom, right) = _row_major(first), _row_major(last) |
| 610 | if bottom < top or right < left: |
| 611 | continue |
| 612 | if len(cells) + (bottom - top + 1) * (right - left + 1) > budget: |
| 613 | continue |
| 614 | cells.update( |
| 615 | ((r, c), (top, left)) for r in range(top, bottom + 1) for c in range(left, right + 1) |
| 616 | ) |
| 617 | return cells |
| 618 | |
| 619 | |
| 620 | def _computed(copy_path, array_cells, names): |
| 621 | computed, lacked = {}, {} |
| 622 | with zipfile.ZipFile(copy_path) as archive: |
| 623 | strings = None |
| 624 | its_names = _sheet_names(archive) |
| 625 | by_name = {ours.casefold(): ours for ours in names} |
| 626 | ours = {its: by_name[its.casefold()] for its in its_names if its.casefold() in by_name} |
| 627 | if len(its_names) == len(names): |
| 628 | for its, in_that_place in zip(its_names, names): |
| 629 | if its not in ours and in_that_place not in ours.values(): |
| 630 | ours[its] = in_that_place |
| 631 | for name, part_name in _worksheets(archive): |
| 632 | name = ours.get(name, name) |
| 633 | cells, lacks = computed.setdefault(name, {}), lacked.setdefault(name, set()) |
| 634 | wanted = array_cells.get(name, ()) |
| 635 | for row, column, m in _cells(archive.read(part_name)): |
| 636 | content = m[4] or b"" |
| 637 | if (row, column) not in wanted and not _F_RE.search(content): |
| 638 | continue |
| 639 | v = _V_RE.search(content) |
| 640 | kind, text = _attr(_T_RE, m[3]) or b"n", v and v[1] |
| 641 | if text is not None and kind == b"s": |
| 642 | if strings is None: |
| 643 | shared = _xml(archive.read("xl/sharedStrings.xml")) |
| 644 | strings = [_rich_text(si) for si in shared.iter(f"{_MAIN_NS}si")] |
| 645 | kind, text = b"str", html.escape(strings[int(text)], quote=False).encode() |
| 646 | f = _F_RE.search(content) |
| 647 | its_formula = (f and f[2]) or b"" |
| 648 | if re.search(rb"[a-z]", its_formula): |
| 649 | called = [_PREFIX_RE.sub("", n) for n in _called(_text(its_formula))] |
| 650 | if any(n != n.upper() and n.upper() in LIBREOFFICE_LACKS for n in called): |
| 651 | lacks.add((row, column)) |
| 652 | if _calls_its_own(_text(its_formula)): |
| 653 | kind, text = _NAME_ERROR |
| 654 | if text is not None and (kind == b"str" or (text and kind in (b"n", b"b", b"e"))): |
| 655 | cells[row, column] = (kind, text) |
| 656 | return computed, lacked |
| 657 | |
| 658 | |
| 659 | def _same_value(old_kind, old, kind, text): |
| 660 | if old is None: |
| 661 | return False |
| 662 | if (old_kind, old) == (kind, text): |
| 663 | return True |
| 664 | if {old_kind, kind} <= {b"n", b"b"}: |
| 665 | try: |
| 666 | return math.isclose(float(old), float(text), rel_tol=1e-14, abs_tol=1e-12) |
| 667 | except ValueError: |
| 668 | return False |
| 669 | return old_kind == kind and html.unescape(old.decode()) == html.unescape(text.decode()) |
| 670 | |
| 671 | |
| 672 | def _cell_with_value(m, f, kind, text): |
| 673 | p = m[1] or b"" |
| 674 | attrs = _T_OR_VM_RE.sub(b"", m[3]) |
| 675 | if kind != b"n": |
| 676 | attrs += b' t="' + kind + b'"' |
| 677 | kept = b"" if f is None else m[4][: f.end()] |
| 678 | ext_lst = _EXT_LST_RE.search(m[4] or b"") |
| 679 | rest = ext_lst[0] if ext_lst else b"" |
| 680 | return b"<%sc%s>%s<%sv>%s</%sv>%s</%sc>" % (p, attrs, kept, p, text, p, rest, p) |
| 681 | |
| 682 | |
| 683 | def _coordinate(row, column): |
| 684 | letters = "" |
| 685 | while column: |
| 686 | column, index = divmod(column - 1, 26) |
| 687 | letters = chr(ord("A") + index) + letters |
| 688 | return f"{letters}{row}" |
| 689 | |
| 690 | |
| 691 | def _text(formula): |
| 692 | text = formula.decode() |
| 693 | for entity, character in (("<", "<"), (">", ">"), (""", '"'), ("'", "'")): |
| 694 | text = text.replace(entity, character) |
| 695 | return text.replace("&", "&") |
| 696 | |
| 697 | |
| 698 | def _called(formula): |
| 699 | names = _CALL_RE.findall(_QUOTED_RE.sub("", formula)) |
| 700 | return [name for name in names if not name.lower().startswith("_xlpm.")] |
| 701 | |
| 702 | |
| 703 | def _lacking(name): |
| 704 | bare = _PREFIX_RE.sub("", name) |
| 705 | if bare.upper() not in LIBREOFFICE_LACKS: |
| 706 | return None |
| 707 | return bare != name or bare.upper() in _STORED_BARE |
| 708 | |
| 709 | |
| 710 | def _calls_its_own(formula): |
| 711 | names = [_PREFIX_RE.sub("", name) for name in _called(formula)] |
| 712 | return any(name != name.upper() and name != name.lower() for name in names) |
| 713 | |
| 714 | |
| 715 | def _unbalanced(formula): |
| 716 | bare = _QUOTED_RE.sub("", formula) |
| 717 | return bare.count("(") != bare.count(")") |
| 718 | |
| 719 | |
| 720 | def _reads_another_workbook(formula, reaching): |
| 721 | plain = _STRING_RE.sub("", formula) |
| 722 | if _EXTERNAL_REF_RE.search(plain): |
| 723 | return True |
| 724 | words = _WORD_RE.findall(_QUOTED_RE.sub("", plain)) if reaching else () |
| 725 | return any(word.lower() in reaching for word in words) |
| 726 | |
| 727 | |
| 728 | def _names_reaching_another_workbook(archive): |
| 729 | reaching, used_by = set(), {} |
| 730 | for name in _workbook_xml(archive).iter(f"{_MAIN_NS}definedName"): |
| 731 | key, plain = name.get("name", "").lower(), _STRING_RE.sub("", name.text or "") |
| 732 | if _EXTERNAL_REF_RE.search(plain): |
| 733 | reaching.add(key) |
| 734 | for word in _WORD_RE.findall(_QUOTED_RE.sub("", plain)): |
| 735 | used_by.setdefault(word.lower(), set()).add(key) |
| 736 | todo = list(reaching) |
| 737 | while todo: |
| 738 | for user in used_by.get(todo.pop(), ()): |
| 739 | if user not in reaching: |
| 740 | reaching.add(user) |
| 741 | todo.append(user) |
| 742 | return reaching |
| 743 | |
| 744 | |
| 745 | def _verdict(formula, reaching=frozenset()): |
| 746 | lacking = [_lacking(name) for name in _called(formula)] |
| 747 | if False in lacking: |
| 748 | return "mistake" |
| 749 | if _reads_another_workbook(formula, reaching): |
| 750 | return "link" |
| 751 | return "lacks" if True in lacking else None |
| 752 | |
| 753 | |
| 754 | def _splice(xml, computed, lacked, array_cells, sheet_name, reaching, found): |
| 755 | out, done = [], 0 |
| 756 | filling, filled, shared = set(), set(), {} |
| 757 | for row, column, m in _cells(xml): |
| 758 | content = m[4] or b"" |
| 759 | f = _F_RE.search(content) |
| 760 | if f is None and array_cells.get((row, column)) not in filling: |
| 761 | continue |
| 762 | v = _V_RE.search(content, f.end() if f else 0) |
| 763 | old = v and (v[1] or b"") |
| 764 | kind = _attr(_T_RE, m[3]) or b"n" |
| 765 | new = computed.get((row, column)) |
| 766 | verdict = None |
| 767 | if f is None: |
| 768 | filled.add((row, column)) |
| 769 | else: |
| 770 | where = f"{sheet_name}!{_coordinate(row, column)}" |
| 771 | text, si = _text(f[2] or b""), _attr(_SI_RE, f[1]) |
| 772 | verdict = _verdict(text, reaching) if text else shared.get(si) |
| 773 | if text and si: |
| 774 | shared[si] = verdict |
| 775 | if verdict == "lacks" and (row, column) not in lacked: |
| 776 | verdict = None |
| 777 | if _unbalanced(text): |
| 778 | found[UNBALANCED].append(where) |
| 779 | if verdict or new is None or new == _NAME_ERROR: |
| 780 | if f is not None: |
| 781 | has_value = old or (old is not None and kind == b"str") |
| 782 | held = has_value and (kind, old) != _NAME_ERROR |
| 783 | no_value_held = not verdict and new == _NAME_ERROR and not held |
| 784 | mistake = verdict == "mistake" or no_value_held |
| 785 | found["#NAME?" if mistake else "not_computed"].append(where) |
| 786 | continue |
| 787 | if f is not None: |
| 788 | filling.add((row, column)) |
| 789 | if _same_value(kind, old, *new): |
| 790 | continue |
| 791 | out += [xml[done : m.start()], _cell_with_value(m, f, *new)] |
| 792 | done = m.end() |
| 793 | for cell, first in array_cells.items(): |
| 794 | new = computed.get(cell) |
| 795 | held_by_the_sheet = cell == first or cell in filled |
| 796 | if first in filling and not held_by_the_sheet and new and new[0] == b"e": |
| 797 | error = new[1].decode() |
| 798 | if error != "#NAME?" and error in EXCEL_ERRORS: |
| 799 | found.setdefault(error, []).append(f"{sheet_name}!{_coordinate(*cell)}") |
| 800 | if not out: |
| 801 | return xml |
| 802 | out.append(xml[done:]) |
| 803 | return b"".join(out) |
| 804 | |
| 805 | |
| 806 | def _replace_parts(path, parts): |
| 807 | handle, new_path = tempfile.mkstemp( |
| 808 | dir=os.path.dirname(path), prefix=".recalc-", suffix=Path(path).suffix |
| 809 | ) |
| 810 | try: |
| 811 | with ( |
| 812 | os.fdopen(handle, "wb") as out, |
| 813 | zipfile.ZipFile(path) as old, |
| 814 | zipfile.ZipFile(out, "w") as new, |
| 815 | ): |
| 816 | new.comment = old.comment |
| 817 | for item in old.infolist(): |
| 818 | if item.filename in parts: |
| 819 | new.writestr(item, parts[item.filename]) |
| 820 | continue |
| 821 | with old.open(item) as source, new.open(copy.copy(item), "w") as target: |
| 822 | shutil.copyfileobj(source, target) |
| 823 | status = os.stat(path) |
| 824 | with contextlib.suppress(OSError, AttributeError): |
| 825 | os.chown(new_path, status.st_uid, status.st_gid) |
| 826 | shutil.copystat(path, new_path) |
| 827 | os.utime(new_path) |
| 828 | os.replace(new_path, path) |
| 829 | except BaseException: |
| 830 | with contextlib.suppress(OSError): |
| 831 | os.unlink(new_path) |
| 832 | raise |
| 833 | |
| 834 | |
| 835 | def _write_values(path, copy_path): |
| 836 | with zipfile.ZipFile(path) as archive: |
| 837 | sheets = _worksheets(archive) |
| 838 | reaching = _names_reaching_another_workbook(archive) |
| 839 | array_cells = {} |
| 840 | for name, part_name in sheets: |
| 841 | budget = MAX_ARRAY_CELLS - sum(map(len, array_cells.values())) |
| 842 | array_cells[name] = _array_cells(_sheet_xml(archive, part_name), budget) |
| 843 | computed, lacked = _computed(copy_path, array_cells, _sheet_names(archive)) |
| 844 | parts, found = {}, {"#NAME?": [], UNBALANCED: [], "not_computed": []} |
| 845 | for name, part_name in sheets: |
| 846 | xml = archive.read(part_name) |
| 847 | if name not in computed and _F_RE.search(xml): |
| 848 | raise ValueError( |
| 849 | f"LibreOffice's copy has no sheet called {name!r}: it renames or drops some " |
| 850 | "sheets, such as one whose name is over 31 characters, so this sheet's " |
| 851 | "formulas cannot be recalculated" |
| 852 | ) |
| 853 | cells, lacks = computed.get(name, {}), lacked.get(name, ()) |
| 854 | new = _splice(xml, cells, lacks, array_cells[name], name, reaching, found) |
| 855 | if new is not xml: |
| 856 | try: |
| 857 | expat.ParserCreate().Parse(new, True) |
| 858 | except expat.ExpatError as e: |
| 859 | raise ValueError(f"editing {part_name} as text broke its XML ({e})") from None |
| 860 | parts[part_name] = new |
| 861 | if parts: |
| 862 | _replace_parts(path, parts) |
| 863 | return found |
| 864 | |
| 865 | |
| 866 | def main(): |
| 867 | signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) |
| 868 | args = [a for a in sys.argv[1:] if a != "--force"] |
| 869 | force = "--force" in sys.argv[1:] |
| 870 | |
| 871 | if not args: |
| 872 | print("Usage: python recalc.py <excel_file> [timeout_seconds] [--force]") |
| 873 | print("\nRecalculates all formulas in an Excel file using LibreOffice") |
| 874 | print("LibreOffice works on a copy; only the values it computes are written into the file.") |
| 875 | print("\nReturns JSON with error details:") |
| 876 | print(" - status: 'success' or 'errors_found'") |
| 877 | print(" - total_errors: Total number of Excel errors found") |
| 878 | print(" - total_formulas: Number of formulas in the file") |
| 879 | print(" - error_summary: Breakdown by error type with locations") |
| 880 | print(" - #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, #NUM!, #N/A, unbalanced brackets") |
| 881 | print(" - not_computed: only if LibreOffice could not compute some formulas: a function") |
| 882 | print(" it lacks, or a link to another workbook. Those cells are left as they were, and") |
| 883 | print(" Excel computes them when it opens a file openpyxl saved. A sound formula that") |
| 884 | print(" depends on one of them reports #NAME? too") |
| 885 | print("\nOn any failure the JSON has an 'error' key and no 'status'.") |
| 886 | print("--force is accepted and ignored.") |
| 887 | sys.exit(1) |
| 888 | |
| 889 | filename = args[0] |
| 890 | try: |
| 891 | timeout = int(args[1]) if len(args) > 1 else 30 |
| 892 | except ValueError: |
| 893 | result = {"error": f"timeout must be an integer number of seconds, got {args[1]!r}"} |
| 894 | print(json.dumps(result, indent=2)) |
| 895 | sys.exit(1) |
| 896 | |
| 897 | result = recalc(filename, timeout, force=force) |
| 898 | print(json.dumps(result, indent=2)) |
| 899 | sys.exit(1 if "error" in result else 0) |
| 900 | |
| 901 | |
| 902 | if __name__ == "__main__": |
| 903 | main() |