recalc.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. """xlsx formula recalculation using LibreOffice and openpyxl, returning a JSON error list.
  2. Part of the MiniMax xlsx skill (MIT). See LICENSE for terms.
  3. The CLI retains the upstream contract:
  4. python scripts/recalc.py <workbook> [timeout_seconds]
  5. JSON output fields are fixed: ``status`` / ``total_errors`` / ``total_formulas`` /
  6. ``error_summary``; the error path returns only ``{"error": "..."}``.
  7. """
  8. from __future__ import annotations
  9. import argparse
  10. import json
  11. import os
  12. import platform
  13. import signal
  14. import subprocess
  15. import sys
  16. from pathlib import Path
  17. from office.soffice import get_soffice_env
  18. from openpyxl import load_workbook
  19. # --- LibreOffice Basic module storage locations -------------------------------
  20. BASIC_DIR_DARWIN = "~/Library/Application Support/LibreOffice/4/user/basic/Standard"
  21. BASIC_DIR_LINUX = "~/.config/libreoffice/4/user/basic/Standard"
  22. BASIC_MODULE_FILE = "Module1.xba"
  23. # Note: Keep macro content and XML identical to upstream, or LibreOffice cannot find RecalculateAndSave.
  24. LO_RECALC_BASIC = """<?xml version="1.0" encoding="UTF-8"?>
  25. <!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
  26. <script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">
  27. Sub RecalculateAndSave()
  28. ThisComponent.calculateAll()
  29. ThisComponent.store()
  30. ThisComponent.close(True)
  31. End Sub
  32. </script:module>"""
  33. # List the seven common Excel error markers alphabetically, matching SKILL.md.
  34. XLSX_ERROR_TOKENS = (
  35. "#DIV/0!",
  36. "#N/A",
  37. "#NAME?",
  38. "#NULL!",
  39. "#NUM!",
  40. "#REF!",
  41. "#VALUE!",
  42. )
  43. _BASIC_INVOCATION = (
  44. "vnd.sun.star.script:Standard.Module1.RecalculateAndSave"
  45. "?language=Basic&location=application"
  46. )
  47. _MAX_LOCATIONS_PER_TOKEN = 20
  48. def _openpyxl_compat_hint(exc: Exception | str) -> str:
  49. """Return a user-facing hint for known openpyxl compatibility failures."""
  50. msg = str(exc)
  51. low = msg.lower()
  52. if "expected <class 'int'>" in msg or "merge" in low or "merged" in low:
  53. return (
  54. "openpyxl failed while parsing merged-cell metadata after LibreOffice "
  55. "saved the workbook. This is a known non-standard/rewritten mergeCell "
  56. "compatibility issue; recalc.py will use raw XML scanning, so do not "
  57. "retry blindly. If you need to read values later, use "
  58. "load_workbook(..., read_only=True, data_only=True) or raw XML."
  59. )
  60. if "chart" in low or "drawing" in low or "graphic" in low:
  61. return (
  62. "openpyxl failed while parsing chart/drawing metadata. Formula/error "
  63. "verification does not need chart objects, so recalc.py will bypass "
  64. "openpyxl and scan worksheet XML directly. Do not retry unless the "
  65. "raw-XML fallback also fails."
  66. )
  67. if "stylesheet" in low or "style" in low or "numberformat" in low:
  68. return (
  69. "openpyxl failed while parsing styles/number formats. Formula/error "
  70. "verification can continue via raw worksheet XML, but downstream code "
  71. "should avoid rewriting this workbook with openpyxl unless style "
  72. "round-trip has been tested."
  73. )
  74. return (
  75. "openpyxl could not parse this workbook, likely due to non-standard XLSX "
  76. "metadata. recalc.py will try a raw-XML scan that ignores charts, drawings, "
  77. "styles, and merged-cell objects and only verifies worksheet formulas/errors."
  78. )
  79. # --- subprocess helpers ------------------------------------------------------
  80. def has_coreutils_timeout() -> bool:
  81. """Use coreutils' ``gtimeout`` on macOS and the built-in ``timeout`` on Linux."""
  82. try:
  83. subprocess.run(
  84. ["gtimeout", "--version"],
  85. capture_output=True,
  86. timeout=1,
  87. check=False,
  88. )
  89. return True
  90. except (FileNotFoundError, subprocess.TimeoutExpired):
  91. return False
  92. def _wrap_with_timeout(cmd: list[str], timeout_sec: int) -> list[str]:
  93. sysname = platform.system()
  94. if sysname == "Linux":
  95. return ["timeout", str(timeout_sec), *cmd]
  96. if sysname == "Darwin" and has_coreutils_timeout():
  97. return ["gtimeout", str(timeout_sec), *cmd]
  98. return cmd
  99. def _build_soffice_cmdline(workbook_path: str) -> list[str]:
  100. return [
  101. "soffice",
  102. "--headless",
  103. "--norestore",
  104. _BASIC_INVOCATION,
  105. workbook_path,
  106. ]
  107. # --- LibreOffice Basic bootstrap --------------------------------------------
  108. def install_recalc_basic() -> bool:
  109. """Idempotently write the RecalculateAndSave macro to the LibreOffice user profile."""
  110. sysname = platform.system()
  111. basic_dir = os.path.expanduser(
  112. BASIC_DIR_DARWIN if sysname == "Darwin" else BASIC_DIR_LINUX
  113. )
  114. module_path = Path(basic_dir) / BASIC_MODULE_FILE
  115. # Already written and still contains the target Sub: consider it ready.
  116. if module_path.exists() and "RecalculateAndSave" in module_path.read_text():
  117. return True
  118. # If the user profile does not exist, cold-start soffice once to create its directories.
  119. if not module_path.parent.exists():
  120. subprocess.run(
  121. ["soffice", "--headless", "--terminate_after_init"],
  122. capture_output=True,
  123. timeout=10,
  124. env=get_soffice_env(),
  125. )
  126. module_path.parent.mkdir(parents=True, exist_ok=True)
  127. try:
  128. module_path.write_text(LO_RECALC_BASIC)
  129. return True
  130. except Exception:
  131. return False
  132. # --- Main flow ---------------------------------------------------------------
  133. def recalculate_workbook(
  134. workbook_path: str | os.PathLike,
  135. *,
  136. timeout_sec: int = 30,
  137. ) -> dict:
  138. """Recalculate all workbook formulas and return a JSON dictionary matching the upstream schema."""
  139. target = Path(workbook_path)
  140. if not target.exists():
  141. return {"error": f"workbook 不存在:{target}"}
  142. abs_path = str(target.resolve())
  143. if not install_recalc_basic():
  144. return {"error": "无法写入 LibreOffice Basic 回算模块"}
  145. cmd = _wrap_with_timeout(_build_soffice_cmdline(abs_path), timeout_sec)
  146. # Popen + start_new_session so the Python-side timeout fallback can
  147. # kill the whole process group. Without it, only the wrapper dies and
  148. # the LibreOffice child keeps the single-instance profile lock,
  149. # silently breaking every subsequent invocation.
  150. proc = subprocess.Popen(
  151. cmd,
  152. stdout=subprocess.PIPE,
  153. stderr=subprocess.PIPE,
  154. text=True,
  155. env=get_soffice_env(),
  156. start_new_session=True,
  157. )
  158. try:
  159. _stdout, stderr_text = proc.communicate(timeout=timeout_sec + 5)
  160. except subprocess.TimeoutExpired:
  161. try:
  162. os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
  163. except (ProcessLookupError, PermissionError):
  164. proc.kill()
  165. proc.wait()
  166. return {
  167. "error": (
  168. f"soffice exceeded {timeout_sec}s timeout; killed entire "
  169. "process group via Python-side fallback. On macOS install "
  170. "coreutils (`brew install coreutils`) so the gtimeout "
  171. "wrapper can cap soffice cleanly."
  172. )
  173. }
  174. # 124 is timeout's exit code; the document is already saved, so error scanning may continue.
  175. if proc.returncode not in (0, 124):
  176. stderr_text = stderr_text or "Unknown error during recalculation"
  177. if "Module1" in stderr_text or "RecalculateAndSave" not in stderr_text:
  178. return {"error": "LibreOffice Basic 模块未正确加载"}
  179. return {"error": stderr_text}
  180. # LibreOffice succeeded; openpyxl may still choke on rewritten merged
  181. # cells. Try the openpyxl path first, fall back to a raw-XML scan that
  182. # bypasses merged-cell parsing entirely.
  183. try:
  184. return _scan_for_errors(target)
  185. except Exception as exc:
  186. # openpyxl is strict about the full workbook package (merged cells,
  187. # chart drawings, styles, relationship targets). Recalc verification only
  188. # needs worksheet cached values and <f> formula nodes, so fall back to a
  189. # raw-XML scan for ANY openpyxl parse failure instead of crashing or
  190. # encouraging blind retries.
  191. try:
  192. return _scan_for_errors_via_xml(target, exc)
  193. except Exception as fallback_exc:
  194. return {
  195. "error": (
  196. "LibreOffice recalc completed, but workbook verification failed. "
  197. f"openpyxl_error={type(exc).__name__}: {exc}; "
  198. f"xml_fallback_error={type(fallback_exc).__name__}: {fallback_exc}. "
  199. "This is usually a non-standard XLSX package (merged cells, "
  200. "charts/drawings, styles, or relationships). Do not retry the "
  201. "same command blindly; inspect the workbook with "
  202. "scripts/office/unpack.py or use Excel/LibreOffice to resave it."
  203. ),
  204. "openpyxl_error": str(exc),
  205. "openpyxl_error_type": type(exc).__name__,
  206. "xml_fallback_error": str(fallback_exc),
  207. "xml_fallback_error_type": type(fallback_exc).__name__,
  208. "compatibility_hint": _openpyxl_compat_hint(exc),
  209. }
  210. def _scan_for_errors(target: Path) -> dict:
  211. """Read the workbook twice: computed values to find errors, then original formulas to count them."""
  212. findings: dict[str, list[str]] = {token: [] for token in XLSX_ERROR_TOKENS}
  213. error_count = 0
  214. book = load_workbook(target, data_only=True)
  215. try:
  216. for sheet_name in book.sheetnames:
  217. sheet = book[sheet_name]
  218. for row in sheet.iter_rows():
  219. for node in row:
  220. value = node.value
  221. if not isinstance(value, str):
  222. continue
  223. for token in XLSX_ERROR_TOKENS:
  224. if token in value:
  225. findings[token].append(
  226. f"{sheet_name}!{node.coordinate}"
  227. )
  228. error_count += 1
  229. break
  230. finally:
  231. book.close()
  232. summary: dict[str, dict] = {}
  233. for token, places in findings.items():
  234. if places:
  235. summary[token] = {
  236. "count": len(places),
  237. "locations": places[:_MAX_LOCATIONS_PER_TOKEN],
  238. }
  239. formula_total = _count_formulas(target)
  240. return {
  241. "status": "success" if error_count == 0 else "errors_found",
  242. "total_errors": error_count,
  243. "error_summary": summary,
  244. "total_formulas": formula_total,
  245. }
  246. def _count_formulas(target: Path) -> int:
  247. book = load_workbook(target, data_only=False)
  248. try:
  249. formula_total = 0
  250. for sheet_name in book.sheetnames:
  251. sheet = book[sheet_name]
  252. for row in sheet.iter_rows():
  253. for node in row:
  254. cv = node.value
  255. if isinstance(cv, str) and cv.startswith("="):
  256. formula_total += 1
  257. return formula_total
  258. finally:
  259. book.close()
  260. # --- raw-XML fallback --------------------------------------------------------
  261. # Trigger: LibreOffice expands a few original mergeCell entries to dozens of times their size;
  262. # openpyxl parses the generated ref with ``min_col == None`` and raises
  263. # ``TypeError: expected <class 'int'>``. This fallback avoids openpyxl,
  264. # using stdlib zipfile + ElementTree for the same statistics.
  265. _NS_MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
  266. _NS_PKG_REL = "http://schemas.openxmlformats.org/package/2006/relationships"
  267. _NS_DOC_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
  268. def _scan_for_errors_via_xml(target: Path, openpyxl_error: Exception | str) -> dict:
  269. """Pure-stdlib equivalent of :func:`_scan_for_errors`.
  270. Used when LibreOffice rewrites a workbook in a form openpyxl cannot
  271. re-read (typically merged-cell ``ref`` mutations that yield ``min_col``
  272. of ``None``). Walks ``xl/worksheets/sheet*.xml`` directly, counts
  273. ``<f>`` elements as formulas, and looks for the seven Excel error
  274. tokens inside cached ``<v>`` values. Returns the same JSON schema as
  275. the openpyxl path with an extra ``warning`` field so callers can tell
  276. which scanner produced the verdict.
  277. """
  278. import zipfile
  279. from xml.etree import ElementTree as ET
  280. findings: dict[str, list[str]] = {token: [] for token in XLSX_ERROR_TOKENS}
  281. formula_total = 0
  282. with zipfile.ZipFile(target, "r") as zf:
  283. sheet_display = _build_sheet_display_map(zf, ET)
  284. for entry in sorted(zf.namelist()):
  285. if not entry.startswith("xl/worksheets/sheet") or not entry.endswith(".xml"):
  286. continue
  287. display = sheet_display.get(entry, entry.split("/")[-1])
  288. tree = ET.fromstring(zf.read(entry))
  289. for cell in tree.iter(f"{{{_NS_MAIN}}}c"):
  290. if cell.find(f"{{{_NS_MAIN}}}f") is not None:
  291. formula_total += 1
  292. v_node = cell.find(f"{{{_NS_MAIN}}}v")
  293. if v_node is None or not v_node.text:
  294. continue
  295. vtext = v_node.text.strip()
  296. for token in XLSX_ERROR_TOKENS:
  297. if vtext.startswith(token):
  298. findings[token].append(
  299. f"{display}!{cell.get('r', '?')}"
  300. )
  301. break
  302. error_count = sum(len(places) for places in findings.values())
  303. summary: dict[str, dict] = {
  304. token: {
  305. "count": len(places),
  306. "locations": places[:_MAX_LOCATIONS_PER_TOKEN],
  307. }
  308. for token, places in findings.items()
  309. if places
  310. }
  311. return {
  312. "status": "success" if error_count == 0 else "errors_found",
  313. "total_errors": error_count,
  314. "error_summary": summary,
  315. "total_formulas": formula_total,
  316. "warning": (
  317. "openpyxl could not parse the post-recalc workbook "
  318. f"({type(openpyxl_error).__name__ if isinstance(openpyxl_error, Exception) else 'Error'}: {openpyxl_error}); "
  319. "verified via raw XML scan instead. LibreOffice did complete the recalculation."
  320. ),
  321. "scanner": "raw_xml_fallback",
  322. "openpyxl_error_type": type(openpyxl_error).__name__ if isinstance(openpyxl_error, Exception) else "Error",
  323. "openpyxl_error": str(openpyxl_error),
  324. "compatibility_hint": _openpyxl_compat_hint(openpyxl_error),
  325. }
  326. def _build_sheet_display_map(zf, et_module) -> dict[str, str]:
  327. """Map ``xl/worksheets/sheetN.xml`` → user-visible sheet name.
  328. Returns the underlying entry path keyed by display name so the JSON
  329. locations match what reviewers see in Excel rather than zip internals.
  330. """
  331. wb_root = et_module.fromstring(zf.read("xl/workbook.xml"))
  332. rels_root = et_module.fromstring(zf.read("xl/_rels/workbook.xml.rels"))
  333. rid_to_target: dict[str, str] = {}
  334. for rel in rels_root.findall(f"{{{_NS_PKG_REL}}}Relationship"):
  335. rid_to_target[rel.get("Id", "")] = rel.get("Target", "")
  336. display: dict[str, str] = {}
  337. for sheet_node in wb_root.findall(
  338. f"{{{_NS_MAIN}}}sheets/{{{_NS_MAIN}}}sheet"
  339. ):
  340. rid = sheet_node.get(f"{{{_NS_DOC_REL}}}id", "")
  341. target = rid_to_target.get(rid, "").lstrip("./").lstrip("/")
  342. if not target:
  343. continue
  344. entry = target if target.startswith("xl/") else f"xl/{target}"
  345. display[entry] = sheet_node.get("name") or entry
  346. return display
  347. # --- Compatibility wrapper: existing ``from recalc import recalc`` callers still work ---
  348. def recalc(filename, timeout=30):
  349. """Compatibility shim around :func:`recalculate_workbook`."""
  350. return recalculate_workbook(filename, timeout_sec=timeout)
  351. # --- CLI entry point ---------------------------------------------------------
  352. def _build_argparser() -> argparse.ArgumentParser:
  353. parser = argparse.ArgumentParser(
  354. prog="recalc.py",
  355. description=(
  356. "Recalculate every formula in an .xlsx workbook through LibreOffice "
  357. "and emit a JSON report of remaining error markers."
  358. ),
  359. epilog=(
  360. "Output JSON keys: status, total_errors, total_formulas, error_summary; "
  361. "or {\"error\": ...} on failure. Tokens scanned: "
  362. + ", ".join(XLSX_ERROR_TOKENS)
  363. + "."
  364. ),
  365. )
  366. parser.add_argument(
  367. "workbook_path",
  368. help="Path to the .xlsx (or .xlsm) file to recalculate.",
  369. )
  370. parser.add_argument(
  371. "timeout_seconds",
  372. nargs="?",
  373. type=int,
  374. default=30,
  375. help="LibreOffice subprocess timeout in seconds (default: 30).",
  376. )
  377. return parser
  378. def main(argv: list[str] | None = None) -> None:
  379. parser = _build_argparser()
  380. args = parser.parse_args(argv)
  381. payload = recalculate_workbook(
  382. args.workbook_path, timeout_sec=args.timeout_seconds
  383. )
  384. print(json.dumps(payload, indent=2))
  385. if "error" in payload and payload.get("status") is None:
  386. sys.exit(2)
  387. if __name__ == "__main__":
  388. main()