Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(spreadsheet): render an .xls cell the way the .xlsx loader renders it (#3616)
Lukas261796f9beb1
diff --git a/headroom/transforms/spreadsheet_ingest.py b/headroom/transforms/spreadsheet_ingest.pyindex 14d6c2e5c..0a185a361 100644--- a/headroom/transforms/spreadsheet_ingest.py+++ b/headroom/transforms/spreadsheet_ingest.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport csvimport io+from datetime import datetime, timefrom pathlib import Path__all__ = ["load_spreadsheet"]@@ -68,9 +69,40 @@ def _load_xlsx(path: Path) -> dict[str, str]:return sheets-def _load_xls(- path: Path,-) -> dict[str, str]: # pragma: no cover - legacy .xls; needs optional xlrd + binary fixture+def _xls_cell(cell: object, datemode: int) -> object:+ """Render one xlrd cell the way openpyxl renders the same cell in a .xlsx.++ xlrd hands back the raw storage rather than the value: a date is the serial+ number Excel keeps it as, a boolean is 1 or 0, and every number is a double,+ so a whole number arrives as ``12.0``. Left alone, the two loaders disagree+ about the same workbook -- ``45292.0`` here against ``2024-01-01 00:00:00``+ there -- and the date is not recoverable from the text.+ """+ import xlrd++ kind = cell.ctype # type: ignore[attr-defined]+ value = cell.value # type: ignore[attr-defined]++ if kind == xlrd.XL_CELL_DATE:+ try:+ year, month, day, hour, minute, second = xlrd.xldate_as_tuple(value, datemode)+ except (ValueError, xlrd.XLDateError):+ return value+ if (year, month, day) == (0, 0, 0):+ # A time-only cell has no date part; openpyxl reads one as a time.+ return time(hour, minute, second)+ return datetime(year, month, day, hour, minute, second)+ if kind == xlrd.XL_CELL_BOOLEAN:+ return bool(value)+ if kind == xlrd.XL_CELL_NUMBER and float(value).is_integer():+ return int(value)+ if kind == xlrd.XL_CELL_ERROR:+ # openpyxl with data_only=True gives the text Excel shows, e.g. #DIV/0!+ return xlrd.error_text_from_code.get(value, "")+ return value+++def _load_xls(path: Path) -> dict[str, str]:try:import xlrdexcept ImportError as e:@@ -82,7 +114,9 @@ def _load_xls(book = xlrd.open_workbook(str(path))sheets: dict[str, str] = {}for sheet in book.sheets():- rows = [sheet.row_values(i) for i in range(sheet.nrows)]+ rows = [+ [_xls_cell(cell, book.datemode) for cell in sheet.row(i)] for i in range(sheet.nrows)+ ]text = _rows_to_csv(rows)if text.strip():sheets[sheet.name] = textdiff --git a/pyproject.toml b/pyproject.tomlindex 3c0e7ef74..5441a6180 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -307,6 +307,8 @@ dev = ["sentence-transformers>=2.2.0,<7.0","numpy>=1.24.0","openpyxl>=3.1.0", # exercises spreadsheet_ingest (.xlsx) in the test suite+ "xlrd>=2.0.1", # exercises spreadsheet_ingest (.xls) in the test suite+ "xlwt>=1.3.0", # writes the legacy .xls fixtures for spreadsheet_ingest tests"respx>=0.20.0", # HTTP mock transport for passthrough handler tests]# All optional dependencies (everything you need).diff --git a/tests/test_transforms_tabular.py b/tests/test_transforms_tabular.pyindex 94341150d..fab7ca15d 100644--- a/tests/test_transforms_tabular.py+++ b/tests/test_transforms_tabular.py@@ -7,6 +7,7 @@ ingestion (spreadsheet_ingest / compress_spreadsheet).from __future__ import annotations+import datetimeimport importlib.utilimport pytest@@ -407,6 +408,104 @@ def test_compress_spreadsheet_empty_workbook_returns_empty(tmp_path) -> None:assert result.tokens_saved == 0+def test_load_xls_renders_cells_like_the_xlsx_loader(tmp_path) -> None:+ """xlrd hands back the raw storage, not the value.++ A date is the serial number Excel keeps it as, a boolean is 1 or 0, and+ every number is a double, so a whole number arrives as ``12.0``. The two+ loaders then disagree about the same workbook, and the date is no longer+ recoverable from the text.+ """+ xlwt = pytest.importorskip("xlwt")+ pytest.importorskip("xlrd")++ from headroom.transforms.spreadsheet_ingest import load_spreadsheet++ date_style = xlwt.XFStyle()+ date_style.num_format_str = "YYYY-MM-DD"++ book = xlwt.Workbook()+ sheet = book.add_sheet("Data")+ for column, heading in enumerate(["When", "Active", "Units", "Rate", "Text"]):+ sheet.write(0, column, heading)+ sheet.write(1, 0, datetime.date(2024, 1, 1), date_style)+ sheet.write(1, 1, True)+ sheet.write(1, 2, 12)+ sheet.write(1, 3, 1.5)+ sheet.write(1, 4, "ok")+ path = tmp_path / "legacy.xls"+ book.save(path)++ rows = load_spreadsheet(path)["Data"].splitlines()++ assert rows[0] == "When,Active,Units,Rate,Text"+ # 45292.0,1,12.0,1.5,ok before this.+ assert rows[1] == "2024-01-01 00:00:00,True,12,1.5,ok"+++def test_load_xls_renders_a_time_only_cell_as_a_time(tmp_path) -> None:+ """A time carries no date, so xlrd reports year, month and day as zero."""+ xlwt = pytest.importorskip("xlwt")+ pytest.importorskip("xlrd")+ openpyxl = pytest.importorskip("openpyxl")++ from headroom.transforms.spreadsheet_ingest import load_spreadsheet++ time_style = xlwt.XFStyle()+ time_style.num_format_str = "HH:MM:SS"++ book = xlwt.Workbook()+ sheet = book.add_sheet("Data")+ sheet.write(0, 0, "Starts")+ sheet.write(1, 0, datetime.time(12, 0, 0), time_style)+ xls_path = tmp_path / "legacy.xls"+ book.save(xls_path)++ workbook = openpyxl.Workbook()+ worksheet = workbook.active+ worksheet.title = "Data"+ worksheet.append(["Starts"])+ worksheet.append([datetime.time(12, 0, 0)])+ xlsx_path = tmp_path / "modern.xlsx"+ workbook.save(xlsx_path)++ # ValueError: year 0 is out of range before this.+ assert load_spreadsheet(xls_path)["Data"] == load_spreadsheet(xlsx_path)["Data"]+ assert load_spreadsheet(xls_path)["Data"].splitlines()[1] == "12:00:00"+++def test_load_xls_and_xlsx_agree_on_the_same_values(tmp_path) -> None:+ """The reference: openpyxl is what the .xls path is matching."""+ xlwt = pytest.importorskip("xlwt")+ pytest.importorskip("xlrd")+ openpyxl = pytest.importorskip("openpyxl")++ from headroom.transforms.spreadsheet_ingest import load_spreadsheet++ date_style = xlwt.XFStyle()+ date_style.num_format_str = "YYYY-MM-DD"+ book = xlwt.Workbook()+ sheet = book.add_sheet("Data")+ sheet.write(0, 0, "When")+ sheet.write(0, 1, "Active")+ sheet.write(0, 2, "Units")+ sheet.write(1, 0, datetime.date(2024, 1, 1), date_style)+ sheet.write(1, 1, True)+ sheet.write(1, 2, 12)+ xls_path = tmp_path / "legacy.xls"+ book.save(xls_path)++ workbook = openpyxl.Workbook()+ worksheet = workbook.active+ worksheet.title = "Data"+ worksheet.append(["When", "Active", "Units"])+ worksheet.append([datetime.date(2024, 1, 1), True, 12])+ xlsx_path = tmp_path / "modern.xlsx"+ workbook.save(xlsx_path)++ assert load_spreadsheet(xls_path) == load_spreadsheet(xlsx_path)++def test_load_spreadsheet_rejects_unknown_extension(tmp_path) -> None:from headroom.transforms.spreadsheet_ingest import load_spreadsheetdiff --git a/uv.lock b/uv.lockindex cd9154dbc..6cd2bc1c5 100644--- a/uv.lock+++ b/uv.lock@@ -1947,6 +1947,8 @@ dev = [{ name = "sqlite-vec" },{ name = "uvicorn" },{ name = "websockets" },+ { name = "xlrd" },+ { name = "xlwt" },]evals = [{ name = "anthropic" },@@ -2205,7 +2207,9 @@ requires-dist = [{ name = "watchdog", marker = "(python_full_version < '3.14' and extra == 'proxy') or (sys_platform != 'darwin' and extra == 'proxy')", specifier = ">=4.0.0" },{ name = "websockets", marker = "extra == 'dev'", specifier = ">=13.0" },{ name = "websockets", marker = "extra == 'proxy'", specifier = ">=13.0" },+ { name = "xlrd", marker = "extra == 'dev'", specifier = ">=2.0.1" },{ name = "xlrd", marker = "extra == 'spreadsheet'", specifier = ">=2.0.1" },+ { name = "xlwt", marker = "extra == 'dev'", specifier = ">=1.3.0" },{ name = "zstandard", marker = "extra == 'proxy'", specifier = ">=0.20.0" },]provides-extras = ["proxy", "proxy-prod", "code", "ml", "memory", "vector", "memory-stack", "pytorch-mps", "relevance", "image", "reports", "spreadsheet", "otel", "anyllm", "langchain", "langgraph", "agno", "strands", "crewai", "autogen", "mcp", "voice", "voice-train", "evals", "bedrock", "html", "dev", "all", "sandbox"]@@ -7780,6 +7784,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/1a/62/c8d562e7766786ba6587d09c5a8ba9f718ed3fa8af7f4553e8f91c36f302/xlrd-2.0.2-py2.py3-none-any.whl", hash = "sha256:ea762c3d29f4cca48d82df517b6d89fbce4db3107f9d78713e48cd321d5c9aa9", size = 96555, upload-time = "2025-06-14T08:46:37.766Z" },]+[[package]]+name = "xlwt"+version = "1.3.0"+source = { registry = "https://pypi.org/simple/" }+sdist = { url = "https://files.pythonhosted.org/packages/06/97/56a6f56ce44578a69343449aa5a0d98eefe04085d69da539f3034e2cd5c1/xlwt-1.3.0.tar.gz", hash = "sha256:c59912717a9b28f1a3c2a98fd60741014b06b043936dcecbc113eaaada156c88", size = 153929, upload-time = "2017-08-22T06:47:16.498Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/44/48/def306413b25c3d01753603b1a222a011b8621aed27cd7f89cbc27e6b0f4/xlwt-1.3.0-py2.py3-none-any.whl", hash = "sha256:a082260524678ba48a297d922cc385f58278b8aa68741596a87de01a9c628b2e", size = 99981, upload-time = "2017-08-22T06:47:15.281Z" },+]+[[package]]name = "xxhash"version = "3.6.0"