File size: 2,049 Bytes
74d4552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""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}