-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhook.py
More file actions
executable file
·1426 lines (1190 loc) · 48.9 KB
/
hook.py
File metadata and controls
executable file
·1426 lines (1190 loc) · 48.9 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
#!/usr/bin/env python3
"""Codex hook prototype for deterministic context-format selection.
This hook is intentionally conservative:
- It only optimizes files explicitly referenced in the user prompt.
- It only emits lossless representations for JSON/CSV/TSV input.
- It chooses the lowest model-token count from a fixed candidate set.
The selector is deterministic. Better token counters can be plugged in without
changing the selection contract.
"""
from __future__ import annotations
import csv
import hashlib
import io
import json
import os
import re
import shlex
import sys
import time
import tomllib
from dataclasses import asdict, dataclass
from functools import lru_cache
from pathlib import Path
from typing import Any, Iterable
SUPPORTED_EXTENSIONS = {".json", ".jsonl", ".csv", ".tsv"}
STANDARD_CANDIDATES = {"raw", "compact-json", "csv", "tsv"}
SCHEMA_VERSION = "context-selector/v1"
DEFAULT_MAX_BYTES = 5_000_000
DEFAULT_INLINE_MAX_CHARS = 12_000
DEFAULT_MIN_SAVINGS_RATIO = 0.05
DEFAULT_MIN_SAVED_TOKENS = 128
DEFAULT_PROVIDER_INPUT_TOKENS_PER_SECOND = 0.0
DEFAULT_MIN_NET_LATENCY_SAVED_MS = 0.0
RAW_INTENT_RE = re.compile(
r"\b("
r"exact bytes|verbatim|original formatting|whitespace|line numbers?|raw text|"
r"show (?:me )?the file|quote the file|as-is|line-by-line|delimiter|comma|tab|json syntax"
r")\b",
re.I,
)
try:
csv.field_size_limit(sys.maxsize)
except OverflowError:
csv.field_size_limit(2**31 - 1)
@dataclass(frozen=True)
class SourceData:
path: Path
kind: str
value: Any
raw_text: str
@dataclass(frozen=True)
class Candidate:
name: str
text: str
reversible: bool
instructions: str
notes: tuple[str, ...] = ()
@dataclass(frozen=True)
class ModelProfile:
slug: str
provider: str
tokenizer_family: str
token_counter: str
context_window: int | None
auto_compact_token_limit: int | None
source: str
@dataclass(frozen=True)
class Choice:
source: Path
candidate: Candidate
raw_tokens: int
payload_tokens: int
instruction_tokens: int
total_tokens: int
savings_ratio: float
output_path: Path
@dataclass(frozen=True)
class RewritePlan:
choices: tuple[Choice, ...]
updated_command: str
def main() -> int:
try:
payload = json.load(sys.stdin)
except Exception as exc:
return emit_error(f"Invalid hook JSON: {exc}")
event_name = payload.get("hook_event_name") or payload.get("hookEventName")
if event_name == "UserPromptSubmit":
return handle_user_prompt_submit(payload)
if event_name == "PreToolUse":
return handle_pre_tool_use(payload)
return emit_noop()
def handle_user_prompt_submit(payload: dict[str, Any]) -> int:
if os.environ.get("CONTEXT_OPTIMIZER_VISIBLE_PROMPT_INJECTION") != "1":
return emit_noop()
prompt = str(payload.get("prompt") or "")
cwd = Path(str(payload.get("cwd") or os.getcwd())).expanduser().resolve()
model = str(payload.get("model") or payload.get("model_id") or "unknown")
model_profile = resolve_model_profile(model, payload, cwd)
max_bytes = int(os.environ.get("CONTEXT_OPTIMIZER_MAX_BYTES", DEFAULT_MAX_BYTES))
inline_max_chars = int(os.environ.get("CONTEXT_OPTIMIZER_INLINE_MAX_CHARS", DEFAULT_INLINE_MAX_CHARS))
policy = savings_policy_from_env()
report_skips = os.environ.get("CONTEXT_OPTIMIZER_REPORT_SKIPS") == "1"
if prompt_requests_raw_file(prompt):
return emit_noop()
paths = discover_paths(prompt, cwd)
choices: list[Choice] = []
skipped: list[str] = []
cache_dir = cwd / ".codex" / "context-cache"
cache_dir.mkdir(parents=True, exist_ok=True)
for path in paths:
try:
if path.stat().st_size > max_bytes:
skipped.append(f"{path}: skipped; over {max_bytes} bytes")
continue
source = load_source(path)
choice = choose_best(source, model_profile, cache_dir)
if should_inject(choice, policy):
choices.append(choice)
elif report_skips:
skipped.append(
f"{path}: no injection; best={choice.candidate.name}, savings={choice.savings_ratio:.1%}"
)
except Exception as exc:
if report_skips:
skipped.append(f"{path}: skipped; {exc}")
if not choices and not skipped:
return emit_noop()
context = build_additional_context(choices, skipped, model_profile, inline_max_chars)
print(
json.dumps(
{
"hookSpecificOutput": {
"hookEventName": "UserPromptSubmit",
"additionalContext": context,
}
},
ensure_ascii=False,
)
)
return 0
def handle_pre_tool_use(payload: dict[str, Any]) -> int:
tool_name = str(payload.get("tool_name") or payload.get("toolName") or "")
if tool_name != "Bash":
return emit_noop()
tool_input = payload.get("tool_input") or payload.get("toolInput") or {}
if not isinstance(tool_input, dict):
return emit_noop()
command = str(tool_input.get("command") or "")
cwd = Path(str(payload.get("cwd") or os.getcwd())).expanduser().resolve()
paths = plain_cat_paths(command, cwd)
if not paths:
return emit_noop()
try:
plan = build_rewrite_plan(paths, payload, cwd)
if plan is None:
return emit_noop()
except Exception:
return emit_noop()
model = str(payload.get("model") or payload.get("model_id") or "unknown")
model_profile = resolve_model_profile(model, payload, cwd)
report_path = write_hook_report(plan.choices, cwd, model_profile, "codex-pre-tool-use")
if not verify_hook_report(report_path):
return emit_noop()
hook_output: dict[str, Any] = {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"updatedInput": {"command": plan.updated_command},
}
if os.environ.get("CONTEXT_OPTIMIZER_EXPLAIN_REWRITES") == "1":
summary = "; ".join(rewrite_summary(choice) for choice in plan.choices)
hook_output["additionalContext"] = (
"Context optimizer rewrote a whole-file context read to optimized sidecar file(s). "
f"{summary}"
)
print(
json.dumps(
{
"hookSpecificOutput": hook_output
},
ensure_ascii=False,
)
)
return 0
def emit_noop() -> int:
print("{}")
return 0
def emit_error(message: str) -> int:
print(f"Context optimizer hook error: {message}", file=sys.stderr)
return emit_noop()
def prompt_requests_raw_file(prompt: str) -> bool:
return bool(RAW_INTENT_RE.search(prompt))
def discover_paths(prompt: str, cwd: Path) -> list[Path]:
"""Find plausible local data paths mentioned in the prompt."""
candidates: set[Path] = set()
quoted = re.findall(r"""['"`]([^'"`\n]+\.(?:jsonl?|csv|tsv))['"`]""", prompt, flags=re.I)
bare = re.findall(r"""(?<![\w:/.-])((?:\./|\.\./|/|[A-Za-z0-9_.-]+/)?[A-Za-z0-9_./-]+\.(?:jsonl?|csv|tsv))(?![\w.-])""", prompt, flags=re.I)
for raw in [*quoted, *bare]:
raw = raw.strip()
if not raw:
continue
path = Path(raw).expanduser()
if not path.is_absolute():
path = cwd / path
try:
resolved = path.resolve()
except OSError:
continue
if resolved.exists() and resolved.is_file() and resolved.suffix.lower() in SUPPORTED_EXTENSIONS:
candidates.add(resolved)
return sorted(candidates)
def plain_cat_paths(command: str, cwd: Path) -> list[Path]:
try:
parts = shlex.split(command)
except ValueError:
return []
if len(parts) >= 3 and parts[0] == "cat" and parts[1] == "--":
raw_paths = parts[2:]
elif len(parts) >= 2 and parts[0] == "cat":
raw_paths = parts[1:]
else:
return []
paths: list[Path] = []
for raw_path in raw_paths:
if raw_path.startswith("-"):
return []
path = Path(raw_path).expanduser()
if not path.is_absolute():
path = cwd / path
try:
resolved = path.resolve()
except OSError:
return []
if not (
resolved.exists()
and resolved.is_file()
and resolved.suffix.lower() in SUPPORTED_EXTENSIONS
):
return []
paths.append(resolved)
return paths
def build_rewrite_plan(paths: list[Path], payload: dict[str, Any], cwd: Path) -> RewritePlan | None:
if not paths:
return None
started_at = time.perf_counter()
max_bytes = int(os.environ.get("CONTEXT_OPTIMIZER_MAX_BYTES", DEFAULT_MAX_BYTES))
policy = savings_policy_from_env()
model = str(payload.get("model") or payload.get("model_id") or "unknown")
model_profile = resolve_model_profile(model, payload, cwd)
cache_dir = cwd / ".codex" / "context-cache"
cache_dir.mkdir(parents=True, exist_ok=True)
choices: list[Choice] = []
for path in paths:
if path.stat().st_size > max_bytes:
return None
source = load_source(path)
choice = choose_best(source, model_profile, cache_dir)
if not should_inject(choice, policy):
return None
choices.append(choice)
local_milliseconds = elapsed_milliseconds(started_at)
if not should_rewrite_for_latency(choices, local_milliseconds, latency_policy_from_env()):
return None
updated_command = "cat -- " + " ".join(shlex.quote(str(choice.output_path)) for choice in choices)
return RewritePlan(tuple(choices), updated_command)
def rewrite_summary(choice: Choice) -> str:
percent = round(choice.savings_ratio * 100, 1)
return (
f"Source: {choice.source}. Optimized: {choice.output_path}. "
f"Selected format: {choice.candidate.name}. "
f"{token_count_label(choice)}: {choice.total_tokens} vs raw {choice.raw_tokens} ({percent}% savings)."
)
def write_hook_report(
choices: tuple[Choice, ...],
cwd: Path,
model_profile: ModelProfile,
adapter: str,
) -> Path:
report_dir = cwd / ".codex" / "context-cache" / "reports"
report_dir.mkdir(parents=True, exist_ok=True)
digest_input = "\n".join(
f"{choice.source}\0{choice.output_path}\0{choice.total_tokens}"
for choice in choices
)
digest = hashlib.sha256(digest_input.encode("utf-8")).hexdigest()[:16]
report_path = report_dir / f"{adapter}.{digest}.json"
raw_tokens = sum(choice.raw_tokens for choice in choices)
selected_tokens = sum(choice.total_tokens for choice in choices)
report = {
"schema_version": SCHEMA_VERSION,
"adapter": adapter,
"cwd": str(cwd),
"out_dir": str(cwd / ".codex" / "context-cache"),
"model_profile": asdict(model_profile),
"policy": {
"supported_extensions": sorted(SUPPORTED_EXTENSIONS),
"max_bytes": int(os.environ.get("CONTEXT_OPTIMIZER_MAX_BYTES", DEFAULT_MAX_BYTES)),
**savings_policy_from_env(),
**latency_policy_from_env(),
"include_candidates": False,
},
"summary": {
"files": len(choices),
"selected_files": len(choices),
"raw_tokens": raw_tokens,
"selected_tokens": selected_tokens,
"saved_tokens": raw_tokens - selected_tokens,
"savings_ratio": 0.0 if raw_tokens == 0 else 1.0 - (selected_tokens / raw_tokens),
},
"results": [choice_report(choice, model_profile) for choice in choices],
}
report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return report_path
def verify_hook_report(report_path: Path) -> bool:
try:
from verify_selector_report import validate_report
report = json.loads(report_path.read_text(encoding="utf-8"))
errors = validate_report(report, check_files=True)
except Exception:
return False
return not errors
def choice_report(choice: Choice, model_profile: ModelProfile) -> dict[str, Any]:
return {
"source": str(choice.source),
"source_name": choice.source.name,
"selected": True,
"decision": "selected",
"read_path": str(choice.output_path),
"kind": choice.source.suffix.lower().lstrip("."),
"bytes": choice.source.stat().st_size,
"sha256": sha256_file(choice.source),
"raw_tokens": choice.raw_tokens,
"selected_format": choice.candidate.name,
"selected_tokens": choice.total_tokens,
"payload_tokens": choice.payload_tokens,
"instruction_tokens": choice.instruction_tokens,
"saved_tokens": choice.raw_tokens - choice.total_tokens,
"savings_ratio": choice.savings_ratio,
"token_counter_label": "estimated" if model_profile.token_counter == "deterministic-fallback" else "exact",
"output_path": str(choice.output_path),
"output_sha256": sha256_file(choice.output_path),
"notes": list(choice.candidate.notes),
}
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def load_source(path: Path) -> SourceData:
suffix = path.suffix.lower()
text = path.read_text(encoding="utf-8-sig")
if suffix == ".json":
return SourceData(path=path, kind="json", value=json.loads(text), raw_text=text)
if suffix == ".jsonl":
rows = [json.loads(line) for line in text.splitlines() if line.strip()]
return SourceData(path=path, kind="jsonl", value=rows, raw_text=text)
if suffix in {".csv", ".tsv"}:
delimiter = "\t" if suffix == ".tsv" else ","
reader = csv.DictReader(io.StringIO(text), delimiter=delimiter)
rows = [dict(row) for row in reader]
return SourceData(path=path, kind=suffix[1:], value=rows, raw_text=text)
raise ValueError(f"unsupported extension {suffix}")
def choose_best(source: SourceData, model_profile: ModelProfile, cache_dir: Path) -> Choice:
raw_tokens = count_tokens(source.raw_text, model_profile)
candidates = candidates_for_profile(source, model_profile)
if not candidates:
raise ValueError("no safe candidates generated")
ranked = sorted(
candidates,
key=lambda c: (
count_tokens(candidate_blob(c), model_profile),
count_tokens(c.text, model_profile),
len(c.text),
c.name,
),
)
best = ranked[0]
best_tokens = count_tokens(best.text, model_profile)
instruction_tokens = count_tokens(best.instructions, model_profile)
total_tokens = count_tokens(candidate_blob(best), model_profile)
digest = hashlib.sha256((str(source.path) + "\0" + best.text).encode("utf-8")).hexdigest()[:16]
output_path = cache_dir / f"{source.path.stem}.{digest}.{best.name}.txt"
output_path.write_text(candidate_blob(best), encoding="utf-8")
savings_ratio = 0.0 if raw_tokens == 0 else 1.0 - (total_tokens / raw_tokens)
return Choice(
source=source.path,
candidate=best,
raw_tokens=raw_tokens,
payload_tokens=best_tokens,
instruction_tokens=instruction_tokens,
total_tokens=total_tokens,
savings_ratio=savings_ratio,
output_path=output_path,
)
def savings_policy_from_env() -> dict[str, float | int]:
return {
"min_savings_ratio": float(os.environ.get("CONTEXT_OPTIMIZER_MIN_SAVINGS_RATIO", DEFAULT_MIN_SAVINGS_RATIO)),
"min_saved_tokens": int(os.environ.get("CONTEXT_OPTIMIZER_MIN_SAVED_TOKENS", DEFAULT_MIN_SAVED_TOKENS)),
}
def latency_policy_from_env() -> dict[str, float | bool]:
provider_tps = float(
os.environ.get(
"CONTEXT_OPTIMIZER_PROVIDER_INPUT_TOKENS_PER_SECOND",
DEFAULT_PROVIDER_INPUT_TOKENS_PER_SECOND,
)
)
min_net_saved_ms = float(
os.environ.get(
"CONTEXT_OPTIMIZER_MIN_NET_LATENCY_SAVED_MS",
DEFAULT_MIN_NET_LATENCY_SAVED_MS,
)
)
return {
"latency_gate_enabled": provider_tps > 0,
"provider_input_tokens_per_second": provider_tps,
"min_net_latency_saved_milliseconds": min_net_saved_ms,
}
def should_inject(choice: Choice, policy: dict[str, float | int]) -> bool:
saved_tokens = choice.raw_tokens - choice.total_tokens
return (
choice.candidate.name != "raw"
and choice.savings_ratio >= float(policy["min_savings_ratio"])
and saved_tokens >= int(policy["min_saved_tokens"])
)
def should_rewrite_for_latency(
choices: list[Choice],
local_milliseconds: float,
policy: dict[str, float | bool],
) -> bool:
provider_tps = float(policy["provider_input_tokens_per_second"])
if provider_tps <= 0:
return True
saved_tokens = sum(choice.raw_tokens - choice.total_tokens for choice in choices)
projected_saved_ms = saved_tokens * 1000.0 / provider_tps
return projected_saved_ms - local_milliseconds >= float(policy["min_net_latency_saved_milliseconds"])
def elapsed_milliseconds(started_at: float) -> float:
return (time.perf_counter() - started_at) * 1000.0
def with_fallback_note(candidates: list[Candidate]) -> list[Candidate]:
return [
Candidate(
candidate.name,
candidate.text,
candidate.reversible,
candidate.instructions,
(*candidate.notes, "fallback token estimate"),
)
for candidate in candidates
]
def candidates_for_profile(source: SourceData, model_profile: ModelProfile) -> list[Candidate]:
candidates = validated_candidates(source)
if model_profile.token_counter != "deterministic-fallback":
return candidates
return with_fallback_note(
[candidate for candidate in candidates if candidate.name in STANDARD_CANDIDATES]
)
def generate_candidates(source: SourceData) -> list[Candidate]:
value = source.value
candidates = [
Candidate(
"raw",
source.raw_text,
True,
"",
("original bytes normalized as UTF-8 text",),
),
Candidate(
"compact-json",
compact_json(value),
True,
"Minified JSON.",
("lossless parsed data",),
),
]
rows = rows_from_value(value)
if rows:
headers = stable_headers(rows)
if headers and rows_are_uniform(rows, headers):
candidates.append(
Candidate(
"column-json",
column_json_text(rows, headers),
True,
"JSON [columns,rows].",
("lossless columnar JSON",),
)
)
codebook_json = codebook_json_text(rows, headers)
if codebook_json:
candidates.append(
Candidate(
"codebook-json",
codebook_json,
True,
"JSON [cols,dicts,rows]; dicts=[col,values]; codes=indexes.",
("lossless columnar JSON with categorical dictionaries",),
)
)
typed_columns = infer_typed_columns(rows, headers)
if typed_columns:
candidates.extend(
[
Candidate(
"typed-csv",
typed_table_text(rows, headers, typed_columns, ","),
True,
"Types: i=int n=num b=bool s=str ?=nullable ~=null.",
("lossless typed table",),
),
Candidate(
"typed-tsv",
typed_table_text(rows, headers, typed_columns, "\t"),
True,
"Types: i=int n=num b=bool s=str ?=nullable ~=null.",
("lossless typed table",),
),
]
)
if safe_unquoted_headers(headers):
candidates.append(
Candidate(
"typed-codebook-row",
typed_codebook_row_text(rows, headers, typed_columns),
True,
"Types: i=int n=num b=bool s=str ?=nullable ~=null. d:col code=value r=CSV rows.",
("lossless typed table with categorical dictionaries",),
)
)
candidates.extend(
[
Candidate(
"csv",
table_text(rows, headers, ","),
True,
"Cells=JSON CSV.",
("lossless parsed table",),
),
Candidate(
"tsv",
table_text(rows, headers, "\t"),
True,
"Cells=JSON TSV.",
("lossless parsed table",),
),
]
)
if safe_unquoted_headers(headers):
candidates.extend(
[
Candidate(
"codebook-row",
codebook_row_text(rows, headers),
True,
"c=cols d:col code=JSON r=CSV rows; \\ escapes |.",
("lossless codebook row table",),
),
]
)
return dedupe_candidates(candidates)
def validated_candidates(source: SourceData) -> list[Candidate]:
verified: list[Candidate] = []
for candidate in generate_candidates(source):
if not candidate.reversible:
continue
if candidate_matches_source(source, candidate):
verified.append(
Candidate(
candidate.name,
candidate.text,
candidate.reversible,
candidate.instructions,
(*candidate.notes, "roundtrip verified"),
)
)
return verified
def candidate_matches_source(source: SourceData, candidate: Candidate) -> bool:
try:
return decode_candidate_value(candidate.name, candidate.text, source.kind) == source.value
except Exception:
return False
def candidate_blob(candidate: Candidate) -> str:
if not candidate.instructions:
return candidate.text
return candidate.instructions + "\n" + candidate.text
def rows_from_value(value: Any) -> list[dict[str, Any]]:
if isinstance(value, list) and all(isinstance(item, dict) for item in value):
return [dict(item) for item in value]
if isinstance(value, dict):
for key in ("rows", "data", "items", "records", "results"):
nested = value.get(key)
if isinstance(nested, list) and all(isinstance(item, dict) for item in nested):
return [dict(item) for item in nested]
return []
def stable_headers(rows: list[dict[str, Any]]) -> list[str]:
seen: dict[str, None] = {}
for row in rows:
for key in row:
seen.setdefault(str(key), None)
return list(seen.keys())
def rows_are_uniform(rows: list[dict[str, Any]], headers: list[str]) -> bool:
expected = set(headers)
return all(set(str(key) for key in row) == expected for row in rows)
def safe_unquoted_headers(headers: list[str]) -> bool:
return all(re.match(r"^[A-Za-z_][A-Za-z0-9_. -]*$", header) for header in headers)
def compact_json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=False)
def table_text(rows: list[dict[str, Any]], headers: list[str], delimiter: str) -> str:
output = io.StringIO()
writer = csv.writer(output, delimiter=delimiter, lineterminator="\n")
writer.writerow(headers)
for row in rows:
writer.writerow([cell_json(row.get(header)) for header in headers])
return output.getvalue().rstrip("\n")
def column_json_text(rows: list[dict[str, Any]], headers: list[str]) -> str:
return json.dumps(
[headers, [[row.get(header) for header in headers] for row in rows]],
ensure_ascii=False,
separators=(",", ":"),
)
def codebook_json_text(rows: list[dict[str, Any]], headers: list[str]) -> str | None:
cell_rows = [[cell_json(row.get(header)) for header in headers] for row in rows]
dictionaries = build_json_cell_dictionaries(cell_rows, headers)
if not dictionaries:
return None
dicts: list[list[Any]] = []
for index, header in enumerate(headers):
mapping = dictionaries.get(header)
if not mapping:
continue
values: list[Any] = [None] * len(mapping)
for raw, code in mapping.items():
values[code] = json.loads(raw)
dicts.append([index, values])
encoded_rows: list[list[Any]] = []
for row, cell_row in zip(rows, cell_rows):
encoded_row: list[Any] = []
for index, header in enumerate(headers):
mapping = dictionaries.get(header)
encoded_row.append(mapping[cell_row[index]] if mapping else row.get(header))
encoded_rows.append(encoded_row)
return json.dumps([headers, dicts, encoded_rows], ensure_ascii=False, separators=(",", ":"))
def build_json_cell_dictionaries(rows: list[list[str]], headers: list[str]) -> dict[str, dict[str, int]]:
dictionaries: dict[str, dict[str, int]] = {}
for index, header in enumerate(headers):
values = [row[index] for row in rows]
unique = list(dict.fromkeys(values))
if len(unique) == len(values):
continue
mapping = {value: code for code, value in enumerate(unique)}
raw_len = sum(len(value) for value in values)
encoded_len = sum(len(str(mapping[value])) for value in values)
dict_values = [json.loads(value) for value in unique]
dict_entry_len = len(json.dumps([index, dict_values], ensure_ascii=False, separators=(",", ":")))
if raw_len > encoded_len + dict_entry_len + 1:
dictionaries[header] = mapping
return dictionaries
def typed_table_text(
rows: list[dict[str, Any]],
headers: list[str],
typed_columns: dict[str, str],
delimiter: str,
) -> str:
output = io.StringIO()
output.write("t:" + ",".join(typed_columns[header] for header in headers) + "\n")
writer = csv.writer(output, delimiter=delimiter, lineterminator="\n")
writer.writerow(headers)
for row in rows:
writer.writerow([typed_cell(row.get(header), typed_columns[header]) for header in headers])
return output.getvalue().rstrip("\n")
def infer_typed_columns(rows: list[dict[str, Any]], headers: list[str]) -> dict[str, str] | None:
typed: dict[str, str] = {}
for header in headers:
values = [row.get(header) for row in rows]
kind = infer_column_type(values)
if kind is None:
return None
typed[header] = kind
return typed
def infer_column_type(values: list[Any]) -> str | None:
non_null = [value for value in values if value is not None]
nullable = len(non_null) != len(values)
suffix = "?" if nullable else ""
if not non_null:
return "s?"
if all(isinstance(value, bool) for value in non_null):
return "b" + suffix
if all(isinstance(value, int) and not isinstance(value, bool) for value in non_null):
return "i" + suffix
if all(is_number(value) for value in non_null):
return "n" + suffix
if all(isinstance(value, str) for value in non_null):
if nullable and any(value == "~" for value in non_null):
return None
return "s" + suffix
return None
def is_number(value: Any) -> bool:
if isinstance(value, bool):
return False
if not isinstance(value, (int, float)):
return False
return value == value and value not in (float("inf"), float("-inf"))
def typed_cell(value: Any, kind: str) -> str:
base = kind.removesuffix("?")
if value is None:
return "~"
if base == "b":
return "1" if value else "0"
return str(value)
def codebook_row_text(rows: list[dict[str, Any]], headers: list[str]) -> str:
dictionaries = build_dictionaries(rows, headers)
encoded_rows = encode_rows(rows, headers, dictionaries)
output = io.StringIO()
output.write("c:" + ",".join(headers) + "\n")
for header, mapping in dictionaries.items():
pairs = [f"{code}={escape_atom(value)}" for value, code in mapping.items()]
output.write(f"d:{header} " + "|".join(pairs) + "\n")
output.write("r:\n")
writer = csv.writer(output, lineterminator="\n")
writer.writerows(encoded_rows)
return output.getvalue().rstrip("\n")
def typed_codebook_row_text(
rows: list[dict[str, Any]],
headers: list[str],
typed_columns: dict[str, str],
) -> str:
typed_rows = [[typed_cell(row.get(header), typed_columns[header]) for header in headers] for row in rows]
dictionaries = build_cell_dictionaries(typed_rows, headers)
output = io.StringIO()
output.write("t:" + ",".join(typed_columns[header] for header in headers) + "\n")
output.write("c:" + ",".join(headers) + "\n")
for header, mapping in dictionaries.items():
pairs = [f"{code}={escape_atom(value)}" for value, code in mapping.items()]
output.write(f"d:{header} " + "|".join(pairs) + "\n")
output.write("r:\n")
writer = csv.writer(output, lineterminator="\n")
for typed_row in typed_rows:
writer.writerow([encode_cell(value, header, dictionaries) for value, header in zip(typed_row, headers)])
return output.getvalue().rstrip("\n")
def build_dictionaries(rows: list[dict[str, Any]], headers: list[str]) -> dict[str, dict[str, int]]:
cell_rows = [[cell_json(row.get(header)) for header in headers] for row in rows]
return build_cell_dictionaries(cell_rows, headers)
def build_cell_dictionaries(rows: list[list[str]], headers: list[str]) -> dict[str, dict[str, int]]:
dictionaries: dict[str, dict[str, int]] = {}
row_count = max(1, len(rows))
for index, header in enumerate(headers):
values = [row[index] for row in rows]
unique = list(dict.fromkeys(values))
if not unique:
continue
avg_len = sum(len(value) for value in values) / row_count
repeated = len(unique) <= min(64, max(2, row_count // 2))
worthwhile = avg_len >= 4 and sum(len(value) for value in values) > sum(len(value) for value in unique) + row_count
if repeated and worthwhile:
dictionaries[header] = {value: index for index, value in enumerate(unique)}
return dictionaries
def encode_cell(value: str, header: str, dictionaries: dict[str, dict[str, int]]) -> str:
mapping = dictionaries.get(header)
return str(mapping[value]) if mapping else value
def encode_rows(
rows: list[dict[str, Any]],
headers: list[str],
dictionaries: dict[str, dict[str, int]],
) -> list[list[str]]:
encoded: list[list[str]] = []
for row in rows:
encoded_row: list[str] = []
for header in headers:
value = cell_json(row.get(header))
mapping = dictionaries.get(header)
encoded_row.append(str(mapping[value]) if mapping else value)
encoded.append(encoded_row)
return encoded
def cell_json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=False)
def escape_atom(value: str) -> str:
return value.replace("\\", "\\\\").replace("\n", "\\n").replace("|", "\\|").replace(",", "\\,")
def unescape_atom(value: str) -> str:
output: list[str] = []
escaped = False
for char in value:
if escaped:
output.append("\n" if char == "n" else char)
escaped = False
elif char == "\\":
escaped = True
else:
output.append(char)
if escaped:
output.append("\\")
return "".join(output)
def split_escaped(value: str, delimiter: str) -> list[str]:
parts: list[str] = []
current: list[str] = []
escaped = False
for char in value:
if escaped:
current.extend(["\\", char])
escaped = False
elif char == "\\":
escaped = True
elif char == delimiter:
parts.append("".join(current))
current = []
else:
current.append(char)
if escaped:
current.append("\\")
parts.append("".join(current))
return parts
def decode_candidate_value(name: str, text: str, source_kind: str) -> Any:
if name == "raw":
return decode_raw_value(text, source_kind)
if name == "compact-json":
return json.loads(text)
if name == "column-json":
return decode_column_json(text)
if name == "codebook-json":
return decode_codebook_json(text)
if name == "csv":
return decode_json_table(text, ",")
if name == "tsv":
return decode_json_table(text, "\t")
if name == "typed-csv":
return decode_typed_table(text, ",")
if name == "typed-tsv":
return decode_typed_table(text, "\t")
if name == "codebook-row":
return decode_codebook_row(text)
if name == "typed-codebook-row":
return decode_typed_codebook_row(text)
raise ValueError(f"unsupported candidate {name}")
def decode_raw_value(text: str, source_kind: str) -> Any:
if source_kind == "json":
return json.loads(text)