headroom/examples/tabular_compression_demo.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

161 lines
5.6 KiB
Python
Raw Normal View History

feat(transforms): tabular + spreadsheet (.xlsx/.xls) compression (#1128) ## Description Adds a content-type-aware path for **tabular data** — CSV/TSV, markdown tables, fixed-width text, and binary `.xlsx`/`.xls` spreadsheets — by routing them through the existing, battle-tested `SmartCrusher` instead of letting them fall through to `PLAIN_TEXT → Kompress`. The pipeline already compressed tables losslessly when handed a JSON array of records. This wires up the missing front door: detect tabular text (and ingest binary spreadsheets), convert to JSON records, and reuse `SmartCrusher.crush()`. No new compression algorithm. Closes # ## Type of Change - [ ] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - **Detection** (`content_detector.py`): new `ContentType.TABULAR` + `_try_detect_tabular()` for CSV/TSV, markdown tables, and fixed-width columns. Ordered after search/log (which also look "delimited") and before code, with a prose-rejection guard so it never steals `file:line:content` search output, `key: value` logs, or sentences with incidental commas. Rust backend returns `plain_text` for unknown types and the router already falls back to the Python detector, so **no Rust change**. - **Bridge** (`tabular_ingest.py`): stdlib parsers + `to_records()` + a `TabularCompressor` that parses → JSON records → `SmartCrusher` (lossless `csv-schema` first; lossy row-drop with reversible `<<ccr:HASH>>` markers stays SmartCrusher's built-in fallback). Only adopts a result when it actually saves bytes. - **Spreadsheets** (`spreadsheet_ingest.py`): `.xlsx`/`.xls` → per-sheet CSV text at the SDK boundary. Optional deps (`pip install headroom-ai[spreadsheet]`) fail loudly with an install hint, never silently degrade. - **Routing** (`content_router.py`): `CompressionStrategy.TABULAR`, `enable_tabular_compressor` flag, lazy getter, apply branch, strategy maps, Kompress fallback eligibility. - **SDK** (`compress.py`): `compress_spreadsheet(path, ...)` helper (one message per sheet). - **Packaging** (`pyproject.toml`): new `[spreadsheet]` extra; `openpyxl` added to `[dev]` so the xlsx path is exercised in CI. - **Docs/demo**: `examples/tabular_compression_demo.py` + README entry. ### Design note: lossless-only Compact, all-unique tables with no query yield ~0 savings — this is correct, not a bug. SmartCrusher returns `skip:unique_entities_no_signal` and won't drop unique rows without a duplicate/relevance signal. Real wins come from verbose/redundant tables and query-driven selection. A pressure-driven lossy row sampler was considered and intentionally not added. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ python -m pytest tests/test_transforms_tabular.py -q collected 20 items tests/test_transforms_tabular.py .................... [100%] ============================== 20 passed in 7.15s ============================== $ ruff check headroom/transforms/tabular_ingest.py headroom/transforms/spreadsheet_ingest.py All checks passed! $ mypy headroom/transforms/tabular_ingest.py headroom/transforms/spreadsheet_ingest.py Success: no issues found in 2 source files ``` `tests/test_transforms_tabular.py` (20 tests): detection true positives + no-misroute negatives (search/log/JSON/prose), parser units (incl. fixed-width), the CSV→SmartCrusher bridge, router routing + disable flag, and `.xlsx` ingestion (skipif openpyxl missing) + error paths. `spreadsheet_ingest` 100% / `tabular_ingest` 90% line coverage. ## Real Behavior Proof - **Environment:** local checkout of `feat/tabular-compression`, Python 3.x, `pip install -e ".[dev]"`. - **Exact command / steps:** `python examples/tabular_compression_demo.py` (no API key required). - **Observed result:** ```text === Raw tabular text (ContentRouter, char-level) === compact unique CSV strat=tabular chars 1306 -> 1072 ( 17.9% saved) redundant CSV strat=tabular chars 2661 -> 1350 ( 49.3% saved) verbose markdown strat=tabular chars 2019 -> 1580 ( 21.7% saved) === Full pipeline (real tokenizer) === redundant CSV tokens 768 -> 394 ( 48.7% saved) === Binary spreadsheet (.xlsx) === 2-sheet workbook tokens 1092 -> 683 ( 37.5% saved) ``` - **Not tested:** legacy `.xls` binary path (needs optional `xlrd` + binary fixture; `# pragma: no cover`); base64-embedded `.xlsx` inside multimodal blocks (out of scope, noted as a follow-up). ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Additional Notes - CHANGELOG/version are intentionally untouched: this repo uses **release-please**, which bumps the version and CHANGELOG via automated `chore: release main` PRs, not per-feature PRs. - The `.xls` path is `# pragma: no cover` (legacy, needs optional `xlrd` + a binary fixture). - Follow-up (out of scope): base64-embedded `.xlsx` inside tool-result/multimodal blocks; porting tabular parsers into the Rust core for parity. --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 09:30:20 -07:00
#!/usr/bin/env python3
"""Demo / test harness for tabular + spreadsheet compression.
Generates representative sample data and runs it through Headroom's tabular
compressor so you can see where it helps (verbose / redundant tables, and
query-driven selection) and where it correctly does nothing (compact, all-unique
data with no signal to compress against).
Usage:
python examples/tabular_compression_demo.py # run all scenarios
python examples/tabular_compression_demo.py --write DIR # also save sample files
The .xlsx scenario requires the spreadsheet extra:
pip install headroom-ai[spreadsheet]
"""
from __future__ import annotations
import argparse
import importlib.util
from pathlib import Path
import headroom
from headroom.transforms.content_router import ContentRouter
_HAS_OPENPYXL = importlib.util.find_spec("openpyxl") is not None
# ─── Sample data generators ─────────────────────────────────────────────────
def compact_unique_csv(rows: int = 60) -> str:
"""Minimal CSV, every row unique — nothing safely removable (~0 savings)."""
lines = ["id,name,age,city"]
lines += [f"{i},user_{i},{20 + i % 50},city_{i}" for i in range(rows)]
return "\n".join(lines)
def redundant_csv(rows: int = 120) -> str:
"""Highly repetitive rows — SmartCrusher can dedupe (big savings)."""
lines = ["region,product,status"]
lines += ["EMEA,widget-A,shipped" for _ in range(rows)]
return "\n".join(lines)
def verbose_markdown(rows: int = 40) -> str:
"""A padded markdown table — verbose source, lossless compaction wins."""
header = "| name | age | city | status | dept |\n| --- | --- | --- | --- | --- |"
body = "\n".join(
f"| user_{i} | {20 + i} | city_{i % 5} | active | engineering |" for i in range(rows)
)
return f"{header}\n{body}"
# ─── Runners ────────────────────────────────────────────────────────────────
def _run_router(label: str, content: str) -> None:
"""Compress raw tabular text through the ContentRouter."""
result = ContentRouter().compress(content)
before = len(content)
after = len(result.compressed)
pct = 100 * (before - after) / before if before else 0.0
print(
f"{label:24s} strat={result.strategy_used.value:9s} "
f"chars {before:6d} -> {after:6d} ({pct:5.1f}% saved)"
)
def _run_messages(label: str, content: str) -> None:
"""Compress via the full pipeline (real tokenizer accounting)."""
res = headroom.compress(
[{"role": "user", "content": content}],
compress_user_messages=True,
)
pct = 100 * res.tokens_saved / res.tokens_before if res.tokens_before else 0.0
print(
f"{label:24s} tokens {res.tokens_before:6d} -> "
f"{res.tokens_after:6d} ({pct:5.1f}% saved)"
)
def _run_xlsx(label: str, path: Path) -> None:
res = headroom.compress_spreadsheet(str(path))
pct = 100 * res.tokens_saved / res.tokens_before if res.tokens_before else 0.0
print(
f"{label:24s} tokens {res.tokens_before:6d} -> "
f"{res.tokens_after:6d} ({pct:5.1f}% saved)"
)
def _build_xlsx(path: Path) -> None:
import openpyxl
wb = openpyxl.Workbook()
unique = wb.active
unique.title = "Unique"
unique.append(["id", "name", "dept"])
for i in range(60):
unique.append([i, f"user_{i}", ["eng", "sales", "ops"][i % 3]])
redundant = wb.create_sheet("Redundant")
redundant.append(["region", "product", "status"])
for _ in range(120):
redundant.append(["EMEA", "widget-A", "shipped"])
wb.save(path)
# ─── Main ───────────────────────────────────────────────────────────────────
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--write",
metavar="DIR",
help="Also write the generated sample files (.csv/.md/.xlsx) to DIR",
)
args = parser.parse_args()
samples = {
"compact_unique.csv": compact_unique_csv(),
"redundant.csv": redundant_csv(),
"verbose_table.md": verbose_markdown(),
}
print("=== Raw tabular text (ContentRouter, char-level) ===")
_run_router("compact unique CSV", samples["compact_unique.csv"])
_run_router("redundant CSV", samples["redundant.csv"])
_run_router("verbose markdown", samples["verbose_table.md"])
print("\n=== Full pipeline (real tokenizer) ===")
_run_messages("redundant CSV", samples["redundant.csv"])
print("\n=== Binary spreadsheet (.xlsx) ===")
if not _HAS_OPENPYXL:
print(" skipped — install: pip install headroom-ai[spreadsheet]")
else:
out_dir = Path(args.write) if args.write else Path("/tmp")
out_dir.mkdir(parents=True, exist_ok=True)
xlsx_path = out_dir / "demo.xlsx"
_build_xlsx(xlsx_path)
_run_xlsx("2-sheet workbook", xlsx_path)
if args.write:
out = Path(args.write)
out.mkdir(parents=True, exist_ok=True)
for name, content in samples.items():
(out / name).write_text(content)
print(f"\nSample files written to {out.resolve()}")
print(
"\nTakeaway: redundant/verbose tables compress; compact all-unique data "
"correctly passes through (lossless-only — nothing safely removable)."
)
if __name__ == "__main__":
main()