SPB Git

spb/wp42_uqo

Public
1.8 KB · 33 lines python
1"""Evaluator-side office helpers (controller): recalculate spreadsheet formulas with LibreOffice headless so that cached values exist2whatever tool produced the workbook (openpyxl writes formulas without cached values). Arm-neutral: applied to every run's deliverables3before deterministic evaluation and before judging; the raw archive is never modified."""4from __future__ import annotations5import os, shutil, subprocess, tempfile67SOFFICE = "/Applications/LibreOffice.app/Contents/MacOS/soffice"89def recalc_xlsx(path: str, timeout=120) -> bool:10    """Replace `path` by a LibreOffice-recalculated copy. Returns True if it succeeded."""11    if not os.path.isfile(SOFFICE) or not path.lower().endswith((".xlsx", ".xlsm")): return False12    try:13        with open(path, "rb") as f:14            if f.read(2) != b"PK": return False   # not an OOXML zip (e.g. a text file named .xlsx): leave it as is, the evaluator must see garbage as garbage15    except OSError: return False16    with tempfile.TemporaryDirectory() as td, tempfile.TemporaryDirectory() as profile:17        try:18            r = subprocess.run([SOFFICE, f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", "xlsx:Calc MS Excel 2007 XML", "--outdir", td, path],19                               capture_output=True, text=True, timeout=timeout)20            out = os.path.join(td, os.path.basename(path))21            if r.returncode == 0 and os.path.isfile(out) and os.path.getsize(out) > 0:22                shutil.copy2(out, path); return True23        except Exception:  # noqa: BLE00124            pass25    return False2627def recalc_tree(root: str) -> dict:28    res = {}29    for dp, _, fns in os.walk(root):30        for fn in fns:31            if fn.lower().endswith((".xlsx", ".xlsm")): res[os.path.relpath(os.path.join(dp, fn), root)] = recalc_xlsx(os.path.join(dp, fn))32    return res33
Files · main
Menu

Theme