-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSpreadsheet_LLM_Encoder.py
More file actions
2141 lines (1849 loc) · 78.3 KB
/
Copy pathSpreadsheet_LLM_Encoder.py
File metadata and controls
2141 lines (1849 loc) · 78.3 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import openpyxl
import json
import logging
import importlib
import re
from fnmatch import fnmatch
from copy import copy
from temp_helpers import (
infer_cell_data_type,
categorize_number_format,
get_number_format_string,
detect_semantic_type,
)
from collections import defaultdict
from openpyxl.utils import get_column_letter
import sys
import paper_serializers
from tokenizer import count_tokens, DEFAULT_MODEL, tokenizer_metadata
logger = logging.getLogger(__name__)
EXCEL_ERROR_VALUES = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
SPARSE_TEXT_MAX_RATIO = 0.5
MAX_TRAILING_NOTE_ROWS = 2
MAX_SPARSE_COLUMN_RATIO = 0.5
MAX_DETAILED_ANCHOR_DIMENSION = 10
HEADER_AT_TOP_BONUS = 30
HEADER_AFTER_TITLE_BONUS = 24
MAX_BODY_ROW_BONUS = 10
MAX_WIDTH_BONUS = 8
BODY_DENSITY_WEIGHT = 25
RANGE_DENSITY_WEIGHT = 8
YEAR_OR_DATE_WEIGHT = 4
MAX_POPULATED_CELL_BONUS = 12
BODY_ROW_BONUS = 2
TITLE_ROW_BONUS = 2
NOTE_ROW_BONUS = 1
EXTRA_ROW_PENALTY = 2
OVERLAP_IOU_SUPPRESSION_THRESHOLD = 0.5
OVERLAP_CONTAINMENT_SUPPRESSION_THRESHOLD = 0.85
_FORMULA_REF_RE = re.compile(
r"(?<![A-Za-z0-9_])"
r"(?:(?:'(?P<quoted_sheet>[^']+)'|(?P<sheet>[A-Za-z_][A-Za-z0-9_ .]*))!)?"
r"\$?(?P<col>[A-Z]{1,3})\$?(?P<row>\d+)"
r"(?::\$?(?P<end_col>[A-Z]{1,3})\$?(?P<end_row>\d+))?",
re.IGNORECASE,
)
def _is_xlsb_path(excel_path: str) -> bool:
return os.path.splitext(str(excel_path))[1].lower() == ".xlsb"
def _load_xlsb_workbook(excel_path: str):
"""Load ``.xlsb`` sheets into an in-memory openpyxl workbook.
Values are preserved, but style fidelity from binary workbooks is limited.
"""
try:
pyxlsb = importlib.import_module("pyxlsb")
except ModuleNotFoundError as exc:
raise ModuleNotFoundError(
"Reading .xlsb files requires optional dependency 'pyxlsb'. "
"Install it with: pip install pyxlsb"
) from exc
workbook = openpyxl.Workbook()
workbook.remove(workbook.active)
with pyxlsb.open_workbook(excel_path) as xlsb_workbook:
for sheet_name in xlsb_workbook.sheets:
sheet = workbook.create_sheet(title=sheet_name)
with xlsb_workbook.get_sheet(sheet_name) as xlsb_sheet:
for row in xlsb_sheet.rows():
for cell in row:
if cell is None:
continue
row_idx = getattr(cell, "r", None)
col_idx = getattr(cell, "c", None)
value = getattr(cell, "v", None)
if row_idx is None or col_idx is None or value is None:
continue
sheet.cell(row=row_idx + 1, column=col_idx + 1, value=value)
return workbook
def _load_workbook_for_vanilla(excel_path: str):
if _is_xlsb_path(excel_path):
return _load_xlsb_workbook(excel_path)
return openpyxl.load_workbook(excel_path, data_only=True)
def _load_workbooks_for_encoding(excel_path: str, data_only: bool):
if _is_xlsb_path(excel_path):
workbook = _load_xlsb_workbook(excel_path)
return workbook, workbook, workbook
workbook = openpyxl.load_workbook(excel_path, data_only=data_only)
formula_workbook = openpyxl.load_workbook(excel_path, data_only=False)
cached_workbook = workbook if data_only else openpyxl.load_workbook(excel_path, data_only=True)
return workbook, formula_workbook, cached_workbook
def calculate_compression_ratio(original_tokens: int, compressed_tokens: int) -> float:
"""Return the compression ratio given original and compressed token counts."""
if compressed_tokens == 0:
return 0.0
if original_tokens == 0:
return 1.0
return original_tokens / compressed_tokens
def _normalize_formula_reference(match, current_sheet: str) -> str:
sheet = match.group("quoted_sheet") or match.group("sheet") or current_sheet
col = match.group("col").upper()
row = match.group("row")
end_col = match.group("end_col")
end_row = match.group("end_row")
if end_col and end_row:
return f"{sheet}!{col}{row}:{end_col.upper()}{end_row}"
return f"{sheet}!{col}{row}"
def extract_formula_references(formula: str, current_sheet: str) -> list:
"""Return normalized workbook references used by an Excel formula."""
refs = []
seen = set()
for match in _FORMULA_REF_RE.finditer(formula or ""):
ref = _normalize_formula_reference(match, current_sheet)
if ref not in seen:
refs.append(ref)
seen.add(ref)
return refs
def _formula_pattern(formula: str, current_sheet: str) -> str:
"""Collapse references in a formula so fill-down families can be grouped."""
def repl(match):
ref = _normalize_formula_reference(match, current_sheet)
return "<RANGE>" if ":" in ref else "<REF>"
return _FORMULA_REF_RE.sub(repl, formula or "")
def _json_safe_value(value):
if value is None or isinstance(value, (str, int, float, bool)):
return value
if hasattr(value, "isoformat"):
return value.isoformat()
return str(value)
def extract_formula_graph(formula_sheet, cached_sheet=None) -> dict:
"""Extract lightweight formula dependencies and spreadsheet error cells.
``formula_sheet`` must be loaded with ``data_only=False`` so formula text is
available. ``cached_sheet`` should be the same worksheet loaded with
``data_only=True`` when cached formula results are available.
"""
formulas = []
formula_errors = []
exact_groups = defaultdict(list)
pattern_groups = defaultdict(list)
sheet_name = formula_sheet.title
for row in range(1, formula_sheet.max_row + 1):
for col in range(1, formula_sheet.max_column + 1):
formula_cell = formula_sheet.cell(row=row, column=col)
value = formula_cell.value
ref = f"{get_column_letter(col)}{row}"
qualified_ref = f"{sheet_name}!{ref}"
cached_value = None
if cached_sheet is not None:
cached_value = cached_sheet.cell(row=row, column=col).value
if isinstance(value, str) and value in EXCEL_ERROR_VALUES:
formula_errors.append({"cell": qualified_ref, "error": value})
if not (isinstance(value, str) and value.startswith("=")):
continue
references = extract_formula_references(value, sheet_name)
cross_sheet_references = [
reference
for reference in references
if reference.split("!", 1)[0] != sheet_name
]
errors = []
if isinstance(cached_value, str) and cached_value in EXCEL_ERROR_VALUES:
errors.append(cached_value)
formulas.append({
"cell": qualified_ref,
"formula": value,
"cached_value": _json_safe_value(cached_value),
"references": references,
"cross_sheet_references": cross_sheet_references,
"errors": errors,
})
exact_groups[value].append(qualified_ref)
pattern_groups[_formula_pattern(value, sheet_name)].append(qualified_ref)
repeated_formula_summaries = []
for formula, cells in sorted(exact_groups.items()):
if len(cells) > 1:
repeated_formula_summaries.append({
"kind": "exact",
"formula": formula,
"count": len(cells),
"cells": cells,
})
for pattern, cells in sorted(pattern_groups.items()):
if len(cells) > 1:
repeated_formula_summaries.append({
"kind": "pattern",
"formula_pattern": pattern,
"count": len(cells),
"cells": cells,
})
return {
"formulas": formulas,
"formula_errors": formula_errors,
"repeated_formula_summaries": repeated_formula_summaries,
}
def _limit_to_positive_int(value, label):
if value is None:
return None
value = int(value)
if value <= 0:
raise ValueError(f"{label} must be a positive integer")
return value
def _bounded_dimensions(
rows,
cols,
max_rows_per_sheet=None,
max_cols_per_sheet=None,
max_cells_per_sheet=None,
):
"""Return bounded ``(rows, cols)`` while preserving full size by default."""
effective_rows = rows
effective_cols = cols
if max_rows_per_sheet is not None:
effective_rows = min(effective_rows, max_rows_per_sheet)
if max_cols_per_sheet is not None:
effective_cols = min(effective_cols, max_cols_per_sheet)
if max_cells_per_sheet is not None and effective_rows * effective_cols > max_cells_per_sheet:
if effective_cols > max_cells_per_sheet:
effective_cols = max_cells_per_sheet
effective_rows = 1
else:
effective_rows = max(1, max_cells_per_sheet // max(1, effective_cols))
return max(1, effective_rows), max(1, effective_cols)
def _validate_and_normalize_filter_list(values, parameter_name):
if values is None:
return []
if isinstance(values, str):
values = [values]
normalized = []
for value in values:
text = str(value).strip()
if not text:
raise ValueError(f"{parameter_name} entries must be non-empty")
normalized.append(text)
return normalized
def _compile_sheet_regexes(patterns, parameter_name):
"""Compile sheet-name regex filters as ``(pattern, compiled_regex)`` tuples."""
compiled = []
for pattern in patterns:
try:
compiled.append((pattern, re.compile(pattern)))
except re.error as exc:
raise ValueError(f"Invalid {parameter_name} pattern '{pattern}': {exc}") from exc
return compiled
def _sheet_selection_decision(
sheet_name,
include_names,
include_globs,
include_regexes,
exclude_names,
exclude_globs,
exclude_regexes,
):
include_filters_active = bool(include_names or include_globs or include_regexes)
include_matches = (
sheet_name in include_names
or any(fnmatch(sheet_name, pattern) for pattern in include_globs)
or any(regex.search(sheet_name) for _, regex in include_regexes)
)
if include_filters_active and not include_matches:
return False, "sheet not matched by include filters"
if sheet_name in exclude_names:
return False, "sheet excluded by name filter"
for pattern in exclude_globs:
if fnmatch(sheet_name, pattern):
return False, f"sheet excluded by glob filter '{pattern}'"
for pattern, regex in exclude_regexes:
if regex.search(sheet_name):
return False, f"sheet excluded by regex filter '{pattern}'"
return True, None
def _copy_bounded_sheet(source_sheet, max_row, max_col):
"""Copy a bounded top-left worksheet region into a normal worksheet."""
wb = openpyxl.Workbook()
target = wb.active
target.title = source_sheet.title
for row in range(1, max_row + 1):
for col in range(1, max_col + 1):
source_cell = source_sheet.cell(row=row, column=col)
target_cell = target.cell(row=row, column=col, value=source_cell.value)
if source_cell.has_style:
target_cell.font = copy(source_cell.font)
target_cell.fill = copy(source_cell.fill)
target_cell.border = copy(source_cell.border)
target_cell.alignment = copy(source_cell.alignment)
target_cell.protection = copy(source_cell.protection)
target_cell.number_format = source_cell.number_format
for merged_range in source_sheet.merged_cells.ranges:
if merged_range.max_row <= max_row and merged_range.max_col <= max_col:
target.merge_cells(str(merged_range))
return target
def _sheet_processing_plan(
sheet,
*,
max_rows_per_sheet=None,
max_cols_per_sheet=None,
max_cells_per_sheet=None,
sheet_limit_action="truncate",
):
if sheet_limit_action not in {"truncate", "skip", "error"}:
raise ValueError("sheet_limit_action must be 'truncate', 'skip', or 'error'")
original_rows = sheet.max_row or 1
original_cols = sheet.max_column or 1
effective_rows, effective_cols = _bounded_dimensions(
original_rows,
original_cols,
max_rows_per_sheet=max_rows_per_sheet,
max_cols_per_sheet=max_cols_per_sheet,
max_cells_per_sheet=max_cells_per_sheet,
)
truncated = effective_rows < original_rows or effective_cols < original_cols
metadata = {
"status": "encoded",
"limit_action": sheet_limit_action,
"truncated": truncated,
"original_rows": original_rows,
"original_cols": original_cols,
"original_cells": original_rows * original_cols,
"effective_rows": effective_rows,
"effective_cols": effective_cols,
"effective_cells": effective_rows * effective_cols,
"encoded_range": f"A1:{get_column_letter(effective_cols)}{effective_rows}",
}
if truncated:
metadata["reason"] = "sheet exceeds configured row/column/cell limits"
if sheet_limit_action == "skip":
metadata["status"] = "skipped"
metadata["encoded_range"] = None
elif sheet_limit_action == "error":
raise ValueError(
f"Sheet '{sheet.title}' exceeds configured limits: "
f"{original_rows}x{original_cols} -> {effective_rows}x{effective_cols}"
)
return effective_rows, effective_cols, metadata
def spreadsheet_llm_encode(
excel_path,
output_path=None,
k=4,
vanilla=False,
compress_homogeneous=True,
paper_strict=False,
data_only=True,
tokenizer_model=DEFAULT_MODEL,
max_rows_per_sheet=None,
max_cols_per_sheet=None,
max_cells_per_sheet=None,
sheet_limit_action="truncate",
include_sheets=None,
exclude_sheets=None,
include_sheet_globs=None,
exclude_sheet_globs=None,
include_sheet_regexes=None,
exclude_sheet_regexes=None,
):
"""
Convert an Excel file to SpreadsheetLLM format or a vanilla markdown-like format.
Args:
excel_path (str): Path to the Excel file.
output_path (str, optional): Path to save the output. Defaults to None.
k (int, optional): Neighborhood distance for structural anchors.
Defaults to 4 (paper's best ablation setting).
vanilla (bool, optional): If True, produce vanilla encoding instead of compressed.
Defaults to False.
compress_homogeneous (bool, optional): Drop fully-homogeneous rows/cols
after anchor extraction. Defaults to True. Set False for strict
paper-aligned skeleton retention.
paper_strict (bool, optional): Apply paper-faithful behavior where it
differs from pragmatic defaults. Currently this disables
post-anchor homogeneous row/column pruning. Defaults to False.
data_only (bool, optional): Load cached formula values instead of formula
text. Defaults to True (paper expects user-visible values).
tokenizer_model (str, optional): Model name for tokenizer-based
compression metrics. Defaults to ``"gpt-4"``.
max_rows_per_sheet (int, optional): When set, cap each sheet to this
many rows in bounded mode.
max_cols_per_sheet (int, optional): When set, cap each sheet to this
many columns in bounded mode.
max_cells_per_sheet (int, optional): When set, cap each sheet to this
many cells by reducing the effective row count after row/column
caps are applied.
sheet_limit_action (str, optional): What to do when a sheet exceeds
the configured caps: ``"truncate"`` (default), ``"skip"``, or
``"error"``.
include_sheets (Iterable[str] | str, optional): Exact sheet names to
include. When provided, only matching sheets are encoded.
exclude_sheets (Iterable[str] | str, optional): Exact sheet names to
exclude from encoding.
include_sheet_globs (Iterable[str] | str, optional): Glob patterns
for sheets to include.
exclude_sheet_globs (Iterable[str] | str, optional): Glob patterns
for sheets to exclude.
include_sheet_regexes (Iterable[str] | str, optional): Regex patterns
for sheets to include.
exclude_sheet_regexes (Iterable[str] | str, optional): Regex patterns
for sheets to exclude.
Returns:
dict: The SpreadsheetLLM encoding of the Excel file.
"""
if paper_strict:
compress_homogeneous = False
max_rows_per_sheet = _limit_to_positive_int(max_rows_per_sheet, "max_rows_per_sheet")
max_cols_per_sheet = _limit_to_positive_int(max_cols_per_sheet, "max_cols_per_sheet")
max_cells_per_sheet = _limit_to_positive_int(max_cells_per_sheet, "max_cells_per_sheet")
include_sheets = _validate_and_normalize_filter_list(include_sheets, "include_sheets")
exclude_sheets = _validate_and_normalize_filter_list(exclude_sheets, "exclude_sheets")
include_sheet_globs = _validate_and_normalize_filter_list(include_sheet_globs, "include_sheet_globs")
exclude_sheet_globs = _validate_and_normalize_filter_list(exclude_sheet_globs, "exclude_sheet_globs")
include_sheet_regexes = _validate_and_normalize_filter_list(include_sheet_regexes, "include_sheet_regexes")
exclude_sheet_regexes = _validate_and_normalize_filter_list(exclude_sheet_regexes, "exclude_sheet_regexes")
if vanilla:
return vanilla_encode(
excel_path,
output_path,
include_sheets=include_sheets,
exclude_sheets=exclude_sheets,
include_sheet_globs=include_sheet_globs,
exclude_sheet_globs=exclude_sheet_globs,
include_sheet_regexes=include_sheet_regexes,
exclude_sheet_regexes=exclude_sheet_regexes,
)
include_sheet_regexes_compiled = _compile_sheet_regexes(
include_sheet_regexes,
"include_sheet_regexes",
)
exclude_sheet_regexes_compiled = _compile_sheet_regexes(
exclude_sheet_regexes,
"exclude_sheet_regexes",
)
if sheet_limit_action not in {"truncate", "skip", "error"}:
raise ValueError("sheet_limit_action must be 'truncate', 'skip', or 'error'")
logger.info(f"Processing Excel file: {excel_path}")
try:
workbook, formula_workbook, cached_workbook = _load_workbooks_for_encoding(
excel_path,
data_only=data_only,
)
logger.info(
f"Found {len(workbook.sheetnames)} sheets: {', '.join(workbook.sheetnames)}"
)
except FileNotFoundError:
logger.warning(f"Error: File not found: {excel_path}")
return None
except Exception as e:
logger.warning(f"Error loading Excel file: {e}")
return None
sheets_encoding = {}
compression_metrics = {
"tokenizer": tokenizer_metadata(tokenizer_model),
"sheets": {},
}
sheet_processing = {
"mode": (
"bounded"
if any(v is not None for v in (max_rows_per_sheet, max_cols_per_sheet, max_cells_per_sheet))
else "full"
),
"limits": {
"max_rows_per_sheet": max_rows_per_sheet,
"max_cols_per_sheet": max_cols_per_sheet,
"max_cells_per_sheet": max_cells_per_sheet,
"sheet_limit_action": sheet_limit_action,
},
"selection": {
"include_sheets": include_sheets,
"exclude_sheets": exclude_sheets,
"include_sheet_globs": include_sheet_globs,
"exclude_sheet_globs": exclude_sheet_globs,
"include_sheet_regexes": include_sheet_regexes,
"exclude_sheet_regexes": exclude_sheet_regexes,
"included_sheets": [],
"skipped_sheets": [],
},
"sheets": {},
}
overall_orig = overall_anchor = overall_index = overall_format = overall_final = 0
for sheet_name in workbook.sheetnames:
logger.info(f"\\nProcessing sheet: {sheet_name}")
original_sheet = workbook[sheet_name]
include_sheet, selection_reason = _sheet_selection_decision(
sheet_name,
include_sheets,
include_sheet_globs,
include_sheet_regexes_compiled,
exclude_sheets,
exclude_sheet_globs,
exclude_sheet_regexes_compiled,
)
if not include_sheet:
sheet_processing["sheets"][sheet_name] = {
"status": "skipped",
"reason": selection_reason,
"limit_action": sheet_limit_action,
"truncated": False,
"original_rows": original_sheet.max_row or 1,
"original_cols": original_sheet.max_column or 1,
"original_cells": (original_sheet.max_row or 1) * (original_sheet.max_column or 1),
"effective_rows": 0,
"effective_cols": 0,
"effective_cells": 0,
"encoded_range": None,
}
sheet_processing["selection"]["skipped_sheets"].append(
{"sheet_name": sheet_name, "reason": selection_reason}
)
logger.info("Skipping sheet '%s': %s", sheet_name, selection_reason)
continue
if original_sheet.max_row <= 1 and original_sheet.max_column <= 1:
logger.info(f"Sheet '{sheet_name}' appears to be empty. Skipping.")
sheet_processing["sheets"][sheet_name] = {
"status": "skipped",
"reason": "sheet appears empty",
"limit_action": sheet_limit_action,
"truncated": False,
"original_rows": original_sheet.max_row or 1,
"original_cols": original_sheet.max_column or 1,
"original_cells": (original_sheet.max_row or 1) * (original_sheet.max_column or 1),
"effective_rows": 0,
"effective_cols": 0,
"effective_cells": 0,
"encoded_range": None,
}
sheet_processing["selection"]["skipped_sheets"].append(
{"sheet_name": sheet_name, "reason": "sheet appears empty"}
)
continue
effective_rows, effective_cols, processing_meta = _sheet_processing_plan(
original_sheet,
max_rows_per_sheet=max_rows_per_sheet,
max_cols_per_sheet=max_cols_per_sheet,
max_cells_per_sheet=max_cells_per_sheet,
sheet_limit_action=sheet_limit_action,
)
sheet_processing["sheets"][sheet_name] = processing_meta
if processing_meta["status"] == "skipped":
sheet_processing["selection"]["skipped_sheets"].append(
{
"sheet_name": sheet_name,
"reason": processing_meta.get(
"reason",
"sheet skipped (reason not recorded)",
),
}
)
logger.info(
"Skipping sheet '%s' because it exceeds configured limits: %s rows x %s cols",
sheet_name,
processing_meta["original_rows"],
processing_meta["original_cols"],
)
continue
sheet = original_sheet
formula_sheet = formula_workbook[sheet_name] if sheet_name in formula_workbook.sheetnames else None
cached_sheet = cached_workbook[sheet_name] if sheet_name in cached_workbook.sheetnames else None
if processing_meta["truncated"]:
logger.info(
"Truncating sheet '%s' from %s rows x %s cols to %s rows x %s cols",
sheet_name,
processing_meta["original_rows"],
processing_meta["original_cols"],
effective_rows,
effective_cols,
)
sheet = _copy_bounded_sheet(original_sheet, effective_rows, effective_cols)
if formula_sheet is not None:
formula_sheet = _copy_bounded_sheet(formula_sheet, effective_rows, effective_cols)
if cached_sheet is not None:
cached_sheet = _copy_bounded_sheet(cached_sheet, effective_rows, effective_cols)
logger.info(
f"Sheet dimensions: {sheet.max_row} rows × {sheet.max_column} columns"
)
# print memory usage
logger.info(f"Estimated memory usage: {sys.getsizeof(sheet)} bytes")
# --- gather original tokens via the paper's vanilla prompt format ---
# The paper baseline encodes every cell (including empty ones) in the
# bounding box as ``A1,value|...`` row-major pairs, then counts tokens
# with the model tokenizer.
vanilla_prompt = paper_serializers.to_paper_vanilla_prompt(sheet)
original_tokens = count_tokens(vanilla_prompt, model=tokenizer_model)
row_anchors, col_anchors = find_structural_anchors(sheet, k)
logger.info(
f"Found {len(row_anchors)} row anchors and {len(col_anchors)} column anchors"
)
kept_rows, kept_cols = extract_cells_near_anchors(sheet, row_anchors, col_anchors, 0)
if compress_homogeneous:
kept_rows, kept_cols = compress_homogeneous_regions(sheet, kept_rows, kept_cols)
logger.info(
f"After compression: {len(kept_rows)} rows and {len(kept_cols)} columns kept"
)
# Anchor-stage tokens: the vanilla pair-string restricted to retained
# rows/cols. Empty cells inside the retained skeleton are still emitted
# so the count is comparable to the paper's vanilla baseline.
anchor_parts = []
for r in kept_rows:
for c in kept_cols:
ref = f"{get_column_letter(c)}{r}"
val = sheet.cell(row=r, column=c).value
text = "" if val is None else str(val).replace("|", " ").replace("\n", " ")
anchor_parts.append(f"{ref},{text}")
anchor_prompt = "|".join(anchor_parts)
anchor_tokens = count_tokens(anchor_prompt, model=tokenizer_model)
inverted_index, format_map = create_inverted_index(
sheet, kept_rows, kept_cols, format_mode="paper"
)
logger.info(
f"Created inverted index with {len(inverted_index)} unique values"
)
merged_index = create_inverted_index_translation(inverted_index)
logger.info(
f"Merged values into {len(merged_index)} range groups"
)
# Inverted-index stage tokens: rendered as paper tuples
# ``(value|range)`` (no format substitution yet).
index_only_encoding = {"cells": merged_index, "formats": {}}
index_prompt = paper_serializers.to_paper_compressed_prompt(index_only_encoding)
index_tokens = count_tokens(index_prompt, model=tokenizer_model)
# Create a paper-format map from semantic keys to cell references. Older
# callers may still pass rich-style keys, so keep a compatibility path.
type_nfs_map = defaultdict(list)
for fmt_key, cells in format_map.items():
try:
fmt = json.loads(fmt_key)
except Exception:
fmt = {}
if set(("type", "nfs")).issubset(fmt.keys()):
type_nfs_map[fmt_key].extend(cells)
continue
for cell_ref in cells:
try:
cell = sheet[cell_ref]
except Exception:
continue
type_nfs_map[_paper_format_key(cell)].append(cell_ref)
aggregated_formats = aggregate_regions_dfs(sheet, type_nfs_map)
logger.info(
f"Aggregated {len(aggregated_formats)} format regions"
)
numeric_map = {
fmt: cells
for fmt, cells in type_nfs_map.items()
if json.loads(fmt).get("type") in ["numeric", "integer", "float"]
}
numeric_ranges = aggregate_regions_dfs(sheet, numeric_map)
logger.info(f"Clustered {len(numeric_ranges)} numeric format ranges")
# Coordinate remapping (paper Section 3.3.1): retained rows/cols are
# remapped to a continuous compact grid so the LLM sees A1, A2, … with
# no gaps. The inverse map lets predicted compact ranges round-trip
# back to original workbook addresses.
coord_map = paper_serializers.build_coord_map(kept_rows, kept_cols)
sheet_encoding = {
"structural_anchors": {
"rows": row_anchors,
"columns": [get_column_letter(c) for c in col_anchors]
},
"cells": merged_index,
"formats": aggregated_formats,
"numeric_ranges": numeric_ranges,
"coord_map": coord_map,
"encoding_mode": "paper_strict" if paper_strict else "pragmatic",
}
if formula_sheet is not None:
formula_graph = extract_formula_graph(
formula_sheet,
cached_sheet,
)
if (
formula_graph["formulas"]
or formula_graph["formula_errors"]
or formula_graph["repeated_formula_summaries"]
):
sheet_encoding["formula_graph"] = formula_graph
# Final stage tokens: the paper-faithful compressed prompt with format
# substitution and compact-coordinate remapping applied.
final_prompt = paper_serializers.to_paper_compressed_prompt(
sheet_encoding, coord_map=coord_map
)
format_tokens = count_tokens(
paper_serializers.to_paper_compressed_prompt(sheet_encoding),
model=tokenizer_model,
)
final_tokens = count_tokens(final_prompt, model=tokenizer_model)
ratio_anchor = calculate_compression_ratio(original_tokens, anchor_tokens)
ratio_index = calculate_compression_ratio(original_tokens, index_tokens)
ratio_format = calculate_compression_ratio(original_tokens, format_tokens)
ratio_final = calculate_compression_ratio(original_tokens, final_tokens)
compression_metrics["sheets"][sheet_name] = {
"original_tokens": original_tokens,
"after_anchor_tokens": anchor_tokens,
"after_inverted_index_tokens": index_tokens,
"after_format_tokens": format_tokens,
"final_tokens": final_tokens,
"anchor_ratio": ratio_anchor,
"inverted_index_ratio": ratio_index,
"format_ratio": ratio_format,
"overall_ratio": ratio_final,
}
logger.info(
f"{sheet_name} compression - Anchors: {ratio_anchor:.2f}x, "
f"Index: {ratio_index:.2f}x, Formats: {ratio_format:.2f}x, "
f"Overall: {ratio_final:.2f}x"
)
sheets_encoding[sheet_name] = sheet_encoding
sheet_processing["selection"]["included_sheets"].append(sheet_name)
overall_orig += original_tokens
overall_anchor += anchor_tokens
overall_index += index_tokens
overall_format += format_tokens
overall_final += final_tokens
compression_metrics["overall"] = {
"original_tokens": overall_orig,
"after_anchor_tokens": overall_anchor,
"after_inverted_index_tokens": overall_index,
"after_format_tokens": overall_format,
"final_tokens": overall_final,
"anchor_ratio": calculate_compression_ratio(overall_orig, overall_anchor),
"inverted_index_ratio": calculate_compression_ratio(overall_orig, overall_index),
"format_ratio": calculate_compression_ratio(overall_orig, overall_format),
"overall_ratio": calculate_compression_ratio(overall_orig, overall_final),
}
logger.info(
f"Overall compression: {compression_metrics['overall']['overall_ratio']:.2f}x"
)
full_encoding = {
"file_name": os.path.basename(excel_path),
"sheets": sheets_encoding,
"compression_metrics": compression_metrics,
"sheet_processing": sheet_processing,
}
if output_path:
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(full_encoding, f, indent=2, ensure_ascii=False)
logger.info(f"Saved SpreadsheetLLM encoding to {output_path}")
return full_encoding
def get_cell_style_key(cell):
"""Creates a hashable key representing a cell's style for comparison."""
if not cell:
return "no_cell"
font = cell.font
border = cell.border
fill = cell.fill
alignment = cell.alignment
# Create a tuple of style attributes. Tuples are hashable.
style_tuple = (
(font.bold, font.italic, font.underline, font.sz, str(font.color.rgb if font.color else None)),
(border.left.style, border.right.style, border.top.style, border.bottom.style),
(fill.patternType, str(fill.fgColor.rgb if fill.fgColor else None)),
(alignment.horizontal, alignment.vertical, alignment.wrap_text)
)
return style_tuple
def _is_year_like(value):
"""Return True for common spreadsheet header years."""
if isinstance(value, int):
return 1900 <= value <= 2100
if isinstance(value, float) and value.is_integer():
return 1900 <= int(value) <= 2100
if isinstance(value, str) and value.strip().isdigit():
return 1900 <= int(value.strip()) <= 2100
return False
def is_header_row(sheet, row_idx):
"""More robust heuristics to detect header rows, as per Appendix C."""
num_populated = 0
num_bold = 0
num_all_caps = 0
num_strings = 0
num_centered = 0
num_numeric = 0
num_year_or_date = 0
unique_values = set()
for c in range(1, sheet.max_column + 1):
cell = sheet.cell(row=row_idx, column=c)
if cell.value is None or str(cell.value).strip() == "":
continue
num_populated += 1
unique_values.add(str(cell.value).strip())
if cell.font and cell.font.bold:
num_bold += 1
if cell.alignment and cell.alignment.horizontal == 'center':
num_centered += 1
sem_type = detect_semantic_type(cell)
if sem_type in {"numeric", "integer", "float", "percentage", "currency"}:
num_numeric += 1
if sem_type in {"year", "date", "datetime"} or _is_year_like(cell.value):
num_year_or_date += 1
if isinstance(cell.value, str):
num_strings += 1
if cell.value.isupper() and len(cell.value) > 1:
num_all_caps += 1
if num_populated == 0:
return False
# A high proportion of bolded, centered, or all-caps text cells are strong indicators.
if num_bold / num_populated > 0.6:
return True
if num_centered / num_populated > 0.6:
return True
if num_strings > 0 and num_all_caps / num_strings > 0.6:
return True
# Plain text headers in benchmark spreadsheets are often not styled.
# Require at least two populated cells so single-cell titles/notes do not
# become table headers just because they contain text.
if (
num_populated >= 2
and num_strings / num_populated >= 0.5
# Plain text headers should not accept ordinary data rows such as
# ["West", 100, "Mia"], but should still accept rare numeric/date labels.
and (
num_numeric == 0
or num_numeric / num_populated <= 0.1
or (num_year_or_date > 0 and num_numeric / num_populated <= 0.5)
)
and len(unique_values) > 1
):
return True
# Year/date rows are common spreadsheet headers even when values are typed
# as numbers or dates rather than strings.
if num_populated >= 2 and num_year_or_date / num_populated >= 0.5:
return True
return False
def _cell_profile(cell, merged_coordinates):
"""Compact profile for structural boundary comparisons."""
value = cell.value
populated = value is not None and str(value).strip() != ""
text_shape = None
if isinstance(value, str):
stripped = value.strip()
if stripped.isupper() and len(stripped) > 1:
text_shape = "upper"
elif stripped.istitle():
text_shape = "title"
elif stripped:
text_shape = "text"
return (
populated,
detect_semantic_type(cell) if populated else "empty",
text_shape,
cell.coordinate in merged_coordinates,
get_cell_style_key(cell),
)
def _range_stats(sheet, r1, c1, r2, c2):
"""Return density and text/number proportions for a candidate range."""
total = (r2 - r1 + 1) * (c2 - c1 + 1)
populated = text = numeric = year_or_date = 0
for r in range(r1, r2 + 1):
for c in range(c1, c2 + 1):
cell = sheet.cell(row=r, column=c)
if cell.value is None or str(cell.value).strip() == "":
continue
populated += 1
sem_type = detect_semantic_type(cell)
if sem_type in {"numeric", "integer", "float", "percentage", "currency"}:
numeric += 1
if sem_type in {"year", "date", "datetime"} or _is_year_like(cell.value):
year_or_date += 1
if isinstance(cell.value, str):
text += 1
return {
"density": populated / total if total else 0,
"populated": populated,
"text_ratio": text / populated if populated else 0,
"numeric_ratio": numeric / populated if populated else 0,
"year_or_date_ratio": year_or_date / populated if populated else 0,
}
def _edge_density(sheet, r1, c1, r2, c2):
edge_cells = []
for c in range(c1, c2 + 1):
edge_cells.append(sheet.cell(row=r1, column=c))
if r2 != r1:
edge_cells.append(sheet.cell(row=r2, column=c))
for r in range(r1 + 1, r2):
edge_cells.append(sheet.cell(row=r, column=c1))
if c2 != c1:
edge_cells.append(sheet.cell(row=r, column=c2))
if not edge_cells:
return 0
populated = sum(
1 for cell in edge_cells
if cell.value is not None and str(cell.value).strip() != ""
)
return populated / len(edge_cells)
def is_populated_cell(cell):
return cell.value is not None and str(cell.value).strip() != ""
def _populated_count_in_row(sheet, row_idx, c1=None, c2=None):
start = c1 if c1 is not None else 1
end = c2 if c2 is not None else sheet.max_column