|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Quality eval for TextCrusher (Phase 2, #1171): does extractive compression |
| 3 | +preserve the answer-bearing content? No LLM/API calls -- fully local. |
| 4 | +
|
| 5 | +Part A -- SQuAD answer-retention (the strong, labeled metric): bury a real QA |
| 6 | +answer in a haystack of distractor paragraphs, compress to a target ratio, and |
| 7 | +measure whether the gold answer SURVIVES. TextCrusher (query-aware) vs truncate |
| 8 | +(keep-recent) vs random baselines. Mirrors kompress's published |
| 9 | +must_keep_recall (0.977 on its own labeled set). |
| 10 | +
|
| 11 | +Part B -- real-transcript fidelity: compress large text blocks from a real |
| 12 | +Claude Code transcript (ANONYMIZED), measuring ratio, speed, and salient-token |
| 13 | +retention (identifiers/numbers/errors -- the must-keep info in coding contexts). |
| 14 | +Only aggregate metrics are printed; raw content is never echoed. |
| 15 | +
|
| 16 | +Usage: python benchmarks/text_crusher_quality_eval.py [squad_dev.json] [transcript.jsonl] |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import glob |
| 22 | +import json |
| 23 | +import os |
| 24 | +import random |
| 25 | +import re |
| 26 | +import sys |
| 27 | +import time |
| 28 | + |
| 29 | +from headroom.transforms.text_crusher import TextCrusher |
| 30 | + |
| 31 | +_SEG = re.compile(r"(?<=[.!?])\s+|\n+") |
| 32 | +_SALIENT = re.compile( |
| 33 | + r"\b(?:error|exception|fail(?:ed|ure)?|warning|traceback|assert|todo|fixme)\b" |
| 34 | + r"|\b[A-Z]{2,}\b|\b[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*\b|\b\d+\b" |
| 35 | +) |
| 36 | + |
| 37 | +# --- anonymization (脱敏): scrub before any processing; never echo raw content --- |
| 38 | +_REDACT = [ |
| 39 | + (re.compile(r"/Users/[^/\s]+"), "/Users/USER"), |
| 40 | + (re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b"), "EMAIL"), |
| 41 | + (re.compile(r"\b(?:sk|pk|ghp|gho|xox[baprs])-[A-Za-z0-9_-]{10,}\b"), "TOKEN"), |
| 42 | + (re.compile(r"\bBearer\s+[A-Za-z0-9._-]{10,}"), "Bearer TOKEN"), |
| 43 | + (re.compile(r"\b[A-Fa-f0-9]{40,}\b"), "HEX"), |
| 44 | +] |
| 45 | + |
| 46 | + |
| 47 | +def anon(t: str) -> str: |
| 48 | + for rx, rep in _REDACT: |
| 49 | + t = rx.sub(rep, t) |
| 50 | + return t |
| 51 | + |
| 52 | + |
| 53 | +def norm(s: str) -> str: |
| 54 | + return re.sub(r"\s+", " ", s.lower()).strip() |
| 55 | + |
| 56 | + |
| 57 | +def _segs(text: str) -> list[str]: |
| 58 | + return [s for s in _SEG.split(text) if s.strip()] |
| 59 | + |
| 60 | + |
| 61 | +def truncate_keep_last(text: str, ratio: float) -> str: |
| 62 | + segs = _segs(text) |
| 63 | + budget = int(sum(len(s) for s in segs) * ratio) |
| 64 | + kept: list[str] = [] |
| 65 | + c = 0 |
| 66 | + for s in reversed(segs): |
| 67 | + if c >= budget: |
| 68 | + break |
| 69 | + kept.append(s) |
| 70 | + c += len(s) |
| 71 | + return "\n".join(reversed(kept)) |
| 72 | + |
| 73 | + |
| 74 | +def random_keep(text: str, ratio: float, seed: int) -> str: |
| 75 | + segs = _segs(text) |
| 76 | + idx = list(range(len(segs))) |
| 77 | + random.Random(seed).shuffle(idx) |
| 78 | + budget = int(sum(len(s) for s in segs) * ratio) |
| 79 | + kept: set[int] = set() |
| 80 | + c = 0 |
| 81 | + for i in idx: |
| 82 | + if c >= budget: |
| 83 | + break |
| 84 | + kept.add(i) |
| 85 | + c += len(segs[i]) |
| 86 | + return "\n".join(segs[i] for i in sorted(kept)) |
| 87 | + |
| 88 | + |
| 89 | +def eval_squad(path: str, n: int = 200, n_distract: int = 40, ratio: float = 0.3, seed: int = 0): |
| 90 | + data = json.load(open(path)) |
| 91 | + paras = [(p["context"], p["qas"]) for a in data["data"] for p in a["paragraphs"]] |
| 92 | + all_ctx = [c for c, _ in paras] |
| 93 | + examples = [ |
| 94 | + (ctx, qas[0]["question"], qas[0]["answers"][0]["text"]) |
| 95 | + for ctx, qas in paras |
| 96 | + if qas and qas[0]["answers"] |
| 97 | + ] |
| 98 | + rnd = random.Random(seed) |
| 99 | + rnd.shuffle(examples) |
| 100 | + examples = examples[:n] |
| 101 | + tc = TextCrusher() |
| 102 | + hit = {"text_crusher": 0, "truncate": 0, "random": 0} |
| 103 | + tc_ratios: list[float] = [] |
| 104 | + for gold_ctx, q, ans in examples: |
| 105 | + docs = rnd.sample(all_ctx, n_distract) + [gold_ctx] |
| 106 | + rnd.shuffle(docs) |
| 107 | + haystack = "\n\n".join(docs) |
| 108 | + a = norm(ans) |
| 109 | + out_tc = tc.compress(haystack, context=q, target_ratio=ratio).compressed |
| 110 | + hit["text_crusher"] += a in norm(out_tc) |
| 111 | + hit["truncate"] += a in norm(truncate_keep_last(haystack, ratio)) |
| 112 | + hit["random"] += a in norm(random_keep(haystack, ratio, seed)) |
| 113 | + tc_ratios.append(len(out_tc) / max(1, len(haystack))) |
| 114 | + nn = len(examples) |
| 115 | + print( |
| 116 | + f"\n=== Part A: SQuAD answer-retention (n={nn}, distractors={n_distract}, target_ratio={ratio}) ===" |
| 117 | + ) |
| 118 | + print( |
| 119 | + f" TextCrusher (query-aware): {hit['text_crusher'] / nn:6.1%} answer survives compression" |
| 120 | + ) |
| 121 | + print(f" Truncate (keep recent): {hit['truncate'] / nn:6.1%}") |
| 122 | + print(f" Random keep: {hit['random'] / nn:6.1%}") |
| 123 | + print( |
| 124 | + f" TextCrusher mean char-ratio: {sum(tc_ratios) / nn:.2f} (kept ~{sum(tc_ratios) / nn:.0%} of bytes)" |
| 125 | + ) |
| 126 | + print(" reference: kompress published must_keep_recall = 0.977 (its own labeled set)") |
| 127 | + |
| 128 | + |
| 129 | +def _block_texts(jsonl_path: str, min_words: int, limit: int) -> list[str]: |
| 130 | + out: list[str] = [] |
| 131 | + with open(jsonl_path) as fh: |
| 132 | + for line in fh: |
| 133 | + try: |
| 134 | + o = json.loads(line) |
| 135 | + except json.JSONDecodeError: |
| 136 | + continue |
| 137 | + m = o.get("message") or {} |
| 138 | + c = m.get("content") |
| 139 | + parts = ( |
| 140 | + [c] |
| 141 | + if isinstance(c, str) |
| 142 | + else [ |
| 143 | + p["text"] for p in c if isinstance(p, dict) and isinstance(p.get("text"), str) |
| 144 | + ] |
| 145 | + if isinstance(c, list) |
| 146 | + else [] |
| 147 | + ) |
| 148 | + for t in parts: |
| 149 | + if len(t.split()) >= min_words: |
| 150 | + out.append(anon(t)) |
| 151 | + if len(out) >= limit: |
| 152 | + break |
| 153 | + return out[:limit] |
| 154 | + |
| 155 | + |
| 156 | +def eval_transcript(jsonl_path: str, ratio: float = 0.4, min_words: int = 1500, limit: int = 40): |
| 157 | + blocks = _block_texts(jsonl_path, min_words, limit) |
| 158 | + if not blocks: |
| 159 | + print( |
| 160 | + f"\n=== Part B: no text blocks >= {min_words} words in {os.path.basename(jsonl_path)} ===" |
| 161 | + ) |
| 162 | + return |
| 163 | + tc = TextCrusher() |
| 164 | + ratios: list[float] = [] |
| 165 | + times: list[float] = [] |
| 166 | + retentions: list[float] = [] |
| 167 | + for b in blocks: |
| 168 | + sal_before = set(_SALIENT.findall(b)) |
| 169 | + t0 = time.perf_counter() |
| 170 | + out = tc.compress(b, target_ratio=ratio).compressed |
| 171 | + times.append((time.perf_counter() - t0) * 1000) |
| 172 | + sal_after = set(_SALIENT.findall(out)) |
| 173 | + retentions.append(len(sal_before & sal_after) / max(1, len(sal_before))) |
| 174 | + ratios.append(len(out.split()) / max(1, len(b.split()))) |
| 175 | + n = len(blocks) |
| 176 | + print( |
| 177 | + f"\n=== Part B: real transcript fidelity (n={n} large blocks, anonymized, target_ratio={ratio}) ===" |
| 178 | + ) |
| 179 | + print(f" mean token-ratio kept: {sum(ratios) / n:.2f}") |
| 180 | + print(f" mean speed: {sum(times) / n:.1f} ms/block") |
| 181 | + print( |
| 182 | + f" salient-token retention: {sum(retentions) / n:6.1%} (identifiers/numbers/errors kept)" |
| 183 | + ) |
| 184 | + print( |
| 185 | + f" -> keeps salient info at {sum(retentions) / n:.0%} while dropping to {sum(ratios) / n:.0%} of tokens" |
| 186 | + ) |
| 187 | + |
| 188 | + |
| 189 | +def eval_speed(scale_words: int = 250_000): |
| 190 | + # Reproducible throughput on a large synthetic prose block (no external data). |
| 191 | + text = " ".join( |
| 192 | + f"Sentence {i} discusses subsystem {i} and its failure mode {i % 7} in detail." |
| 193 | + for i in range(scale_words // 9) |
| 194 | + ) |
| 195 | + nwords = len(text.split()) |
| 196 | + tc = TextCrusher() |
| 197 | + t0 = time.perf_counter() |
| 198 | + out = tc.compress(text, target_ratio=0.3) |
| 199 | + ms = (time.perf_counter() - t0) * 1000 |
| 200 | + print(f"\n=== Part C: speed (synthetic, {nwords:,} words, fully reproducible) ===") |
| 201 | + print(f" TextCrusher compress: {ms:.0f} ms ({nwords / max(ms / 1000, 1e-6):,.0f} words/sec)") |
| 202 | + print(f" kept ratio: {out.compressed_tokens / max(1, out.original_tokens):.2f}") |
| 203 | + print(" reference: kompress (ModernBERT ONNX) ~272s for ~1M tokens (measured, query-blind)") |
| 204 | + print(" -> fast-vs-slow CONTRAST, not a same-input side-by-side run") |
| 205 | + |
| 206 | + |
| 207 | +if __name__ == "__main__": |
| 208 | + eval_speed() |
| 209 | + squad = sys.argv[1] if len(sys.argv) > 1 else "/tmp/squad_dev.json" |
| 210 | + tx = sys.argv[2] if len(sys.argv) > 2 else None |
| 211 | + if os.path.exists(squad): |
| 212 | + eval_squad(squad) |
| 213 | + else: |
| 214 | + print(f"SQuAD not found at {squad}; skipping Part A") |
| 215 | + if tx is None: |
| 216 | + found = glob.glob(os.path.expanduser("~/.claude/projects/*headroom*/*.jsonl")) |
| 217 | + tx = max(found, key=os.path.getsize) if found else None |
| 218 | + if tx and os.path.exists(tx): |
| 219 | + eval_transcript(tx) |
| 220 | + else: |
| 221 | + print("no transcript jsonl found; skipping Part B") |
0 commit comments