Spaces:
Runtime error
Runtime error
Download app/refdata.py from bhyve/bhyve-workflow: direct link, hf CLI and curl.
- Browser
- Download file 2.05 kB
-
https://huggingface.co/spaces/bhyve/bhyve-workflow/resolve/main/app/refdata.py
- Command line
-
hf download hf://spaces/bhyve/bhyve-workflow/app/refdata.py
-
curl -L -o refdata.py https://huggingface.co/spaces/bhyve/bhyve-workflow/resolve/main/app/refdata.py
2.05 kB
| """Load an uploaded reference sheet (e.g. the client master) into a simple | |
| {name, columns, rows} dict that the enrich block matches against.""" | |
| import io | |
| import openpyxl | |
| # Safety bound: a reference sheet won't realistically exceed this. It also stops a | |
| # runaway if a file reports an inflated used-range (whole-column/-sheet formatting). | |
| _MAX_REF_ROWS = 100_000 | |
| def load_reference_xlsx(content: bytes, name: str, sheet: str | None = None) -> dict: | |
| # read_only streams the sheet and SKIPS the full non-streaming workbook parse, which | |
| # can hang for minutes on real-world xlsx whose styles/formatting span whole columns | |
| # (observed on a real client master). data_only returns cached values, not formulas. | |
| wb = openpyxl.load_workbook(io.BytesIO(content), data_only=True, read_only=True) | |
| try: | |
| # Assume a single-sheet master: default to the first sheet. (`sheet=` can target a | |
| # specific tab if a multi-sheet picker is added later.) | |
| ws = wb[sheet] if sheet else wb.worksheets[0] | |
| rows: list[list] = [] | |
| for r in ws.iter_rows(values_only=True): | |
| rows.append(list(r)) | |
| if len(rows) >= _MAX_REF_ROWS: | |
| break | |
| finally: | |
| wb.close() # read_only workbooks hold a file handle until closed | |
| if not rows: | |
| return {"name": name, "columns": [], "rows": []} | |
| # Header row = the row with the most non-empty cells among the first few | |
| # (skips a title row sitting above the real headers). | |
| scan = min(5, len(rows)) | |
| hdr_idx = max(range(scan), key=lambda i: sum(1 for c in rows[i] if c not in (None, ""))) | |
| headers = [] | |
| for j, c in enumerate(rows[hdr_idx]): | |
| h = str(c).strip() if c not in (None, "") else "" | |
| headers.append(h or f"col{j + 1}") | |
| data = [] | |
| for r in rows[hdr_idx + 1:]: | |
| if all(c in (None, "") for c in r): | |
| continue | |
| data.append({headers[j]: (r[j] if j < len(r) else None) for j in range(len(headers))}) | |
| return {"name": name, "columns": headers, "rows": data} | |