textray 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,477 @@
1
+ """Surface metadata canary, regex pattern/boundary audit, and shortcut ablation diagnostics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Iterable
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ from sklearn.metrics import roc_auc_score
11
+
12
+ from textray.core.cv import (
13
+ BaselineCache,
14
+ CanaryResult,
15
+ cached_metadata_canary,
16
+ cached_text_baseline,
17
+ oof_text_baseline,
18
+ )
19
+ from textray.core.result import DiagnosticResult, DiagnosticWarning, Severity
20
+ from textray.core.text_utils import ARTIFACT_PATTERNS, mask_terms_series, strip_dates
21
+ from textray.core.validation import ValidatedDataset
22
+ from textray.diagnostics.lexical import compute_dividing_terms_table
23
+ from textray.visuals.artifact_charts import (
24
+ build_pattern_audit_chart,
25
+ build_shortcut_ablation_chart,
26
+ build_surface_audit_chart,
27
+ )
28
+
29
+ _PUNCT_RE = re.compile(r"[^\w\s]")
30
+ # A sentence = a run between . ! ? that contains at least one visible character.
31
+ _SENTENCE_RE = re.compile(r"[^.!?]*[^.!?\s][^.!?]*")
32
+ _DIGIT_RE = re.compile(r"\d")
33
+ _URL_RE = ARTIFACT_PATTERNS["urls"]
34
+ _EMAIL_RE = ARTIFACT_PATTERNS["emails"]
35
+
36
+ # Byte sets for the fast path on pure-ASCII documents (the common case). Counting with
37
+ # bytes.translate runs in C; the definitions match Python's str methods / re classes.
38
+ _ASCII = [chr(c) for c in range(128)]
39
+ _ASCII_UPPER = "".join(c for c in _ASCII if c.isupper()).encode()
40
+ _ASCII_ALPHA = "".join(c for c in _ASCII if c.isalpha()).encode()
41
+ _ASCII_DIGIT = "".join(c for c in _ASCII if c.isdigit()).encode()
42
+ _ASCII_SPACE = "".join(c for c in _ASCII if c.isspace()).encode()
43
+ _ASCII_PUNCT = "".join(c for c in _ASCII if not (c.isalnum() or c == "_" or c.isspace())).encode()
44
+
45
+
46
+ def _count_bytes(raw: bytes, chars: bytes) -> int:
47
+ return len(raw) - len(raw.translate(None, chars))
48
+
49
+
50
+ def _char_counts(text: str) -> tuple[int, int, int, int, int, int]:
51
+ """(visible, digits, upper, letters, punctuation, non_ascii) character counts."""
52
+ if text.isascii():
53
+ raw = text.encode("ascii")
54
+ return (
55
+ len(raw) - _count_bytes(raw, _ASCII_SPACE),
56
+ _count_bytes(raw, _ASCII_DIGIT),
57
+ _count_bytes(raw, _ASCII_UPPER),
58
+ _count_bytes(raw, _ASCII_ALPHA),
59
+ _count_bytes(raw, _ASCII_PUNCT),
60
+ 0,
61
+ )
62
+ return (
63
+ sum(1 for c in text if not c.isspace()),
64
+ len(_DIGIT_RE.findall(text)),
65
+ sum(1 for c in text if c.isupper()),
66
+ sum(1 for c in text if c.isalpha()),
67
+ len(_PUNCT_RE.findall(text)),
68
+ sum(1 for c in text if ord(c) > 127),
69
+ )
70
+
71
+
72
+ def extract_surface_features(texts: pd.Series) -> pd.DataFrame:
73
+ """Compute non-semantic structural & formatting features for every document."""
74
+ s = texts.astype(str)
75
+ counts = np.array([_char_counts(t) for t in s], dtype=float).reshape(-1, 6)
76
+ n_visible, n_digits, n_upper, n_alpha, n_punct, n_non_ascii = counts.T
77
+ n_chars = s.str.len().to_numpy(dtype=float)
78
+ denom_chars = np.maximum(n_chars, 1.0)
79
+ n_words = np.array([len(t.split()) for t in s], dtype=float)
80
+ n_sents = s.str.count(_SENTENCE_RE.pattern).to_numpy(dtype=float)
81
+ n_sents = np.where(n_chars > 0, np.maximum(n_sents, 1.0), 0.0)
82
+
83
+ # URL/e-mail regexes are slow per character, so only run them where they can match.
84
+ url_candidates = s.str.contains("://", regex=False) | s.str.contains("www.", regex=False)
85
+ url_count = s.where(url_candidates, "").str.count(_URL_RE.pattern, flags=_URL_RE.flags)
86
+ email_count = s.where(s.str.contains("@", regex=False), "").str.count(
87
+ _EMAIL_RE.pattern, flags=_EMAIL_RE.flags
88
+ )
89
+
90
+ return pd.DataFrame(
91
+ {
92
+ "char_count": n_chars,
93
+ "word_count": n_words,
94
+ "sentence_count": n_sents,
95
+ "avg_word_len": np.where(n_words > 0, n_visible / np.maximum(n_words, 1.0), 0.0),
96
+ "digit_ratio": n_digits / denom_chars,
97
+ "uppercase_ratio": n_upper / np.maximum(n_alpha, 1.0),
98
+ "punctuation_ratio": n_punct / denom_chars,
99
+ "newline_count": s.str.count("\n").to_numpy(dtype=float),
100
+ "non_ascii_ratio": n_non_ascii / denom_chars,
101
+ "url_email_count": (url_count + email_count).to_numpy(dtype=float),
102
+ },
103
+ index=texts.index,
104
+ )
105
+
106
+
107
+ def compute_metadata_canary_auc(
108
+ surface_df: pd.DataFrame,
109
+ y: np.ndarray,
110
+ random_state: int = 42,
111
+ ) -> tuple[float, np.ndarray]:
112
+ """Leak-free stratified CV ROC-AUC and mean coefficients of the metadata-only canary."""
113
+ canary = cached_metadata_canary(None, surface_df, y, random_state=random_state)
114
+ return canary.auc, canary.coefs
115
+
116
+
117
+ def _auc(y: np.ndarray, proba: np.ndarray) -> float:
118
+ return float(roc_auc_score(y, proba))
119
+
120
+
121
+ def run_surface_audit(
122
+ dataset: ValidatedDataset,
123
+ surface_df: pd.DataFrame | None = None,
124
+ random_state: int = 42,
125
+ sample_n: int = 3000,
126
+ cache: BaselineCache | None = None,
127
+ ) -> DiagnosticResult:
128
+ """Audit non-semantic structural features and train a metadata-only leakage canary."""
129
+ feat_df = surface_df if surface_df is not None else extract_surface_features(dataset.texts)
130
+ y = dataset.y
131
+
132
+ canary: CanaryResult = cached_metadata_canary(cache, feat_df, y, random_state=random_state)
133
+ canary_auc, mean_coefs = canary.auc, canary.coefs
134
+
135
+ rows = []
136
+ pos_mask = y == 1
137
+ neg_mask = y == 0
138
+ for col, coef in zip(feat_df.columns, mean_coefs, strict=False):
139
+ pos_vals = feat_df.loc[pos_mask, col].to_numpy()
140
+ neg_vals = feat_df.loc[neg_mask, col].to_numpy()
141
+ pos_mean = float(np.mean(pos_vals))
142
+ neg_mean = float(np.mean(neg_vals))
143
+ pooled_std = float(np.sqrt(0.5 * (np.var(pos_vals) + np.var(neg_vals))))
144
+ cohens_d = (pos_mean - neg_mean) / pooled_std if pooled_std > 1e-12 else 0.0
145
+ rows.append(
146
+ {
147
+ "feature": col,
148
+ "pos_mean": round(pos_mean, 4),
149
+ "neg_mean": round(neg_mean, 4),
150
+ "pos_median": round(float(np.median(pos_vals)), 4),
151
+ "neg_median": round(float(np.median(neg_vals)), 4),
152
+ "cohens_d": round(cohens_d, 3),
153
+ "canary_weight": round(float(coef), 4),
154
+ "abs_effect": round(abs(cohens_d), 3),
155
+ }
156
+ )
157
+
158
+ summary_df = (
159
+ pd.DataFrame(rows).sort_values("abs_effect", ascending=False).reset_index(drop=True)
160
+ )
161
+
162
+ warnings: list[DiagnosticWarning] = []
163
+ if canary_auc >= 0.70:
164
+ sev: Severity = "critical" if canary_auc >= 0.80 else "warning"
165
+ top_feats = summary_df.head(3)["feature"].tolist()
166
+ warnings.append(
167
+ DiagnosticWarning(
168
+ severity=sev,
169
+ category="Metadata-Only Leakage Canary",
170
+ message=(
171
+ f"A classifier using ONLY non-semantic surface features (no words) achieved "
172
+ f"ROC-AUC = {canary_auc:.3f}. Top structural drivers: {', '.join(top_feats)}."
173
+ ),
174
+ evidence={"metadata_canary_auc": round(canary_auc, 4), "top_features": top_feats},
175
+ )
176
+ )
177
+
178
+ # Sample document-level feature frame for distribution plots
179
+ doc_feat_df = feat_df.copy()
180
+ doc_feat_df["class_label"] = dataset.class_labels.values
181
+ if len(doc_feat_df) > sample_n:
182
+ doc_feat_df = doc_feat_df.sample(n=sample_n, random_state=random_state)
183
+
184
+ top_dist_features = summary_df.head(4)["feature"].tolist()
185
+ chart = build_surface_audit_chart(
186
+ summary_df=summary_df,
187
+ doc_feat_df=doc_feat_df,
188
+ top_features=top_dist_features,
189
+ pos_name=dataset.pos_name,
190
+ neg_name=dataset.neg_name,
191
+ canary_auc=canary_auc,
192
+ )
193
+
194
+ return DiagnosticResult(
195
+ name="surface_audit",
196
+ title="Surface & Metadata Leakage Audit (Non-Semantic Canary)",
197
+ chart=chart,
198
+ data=summary_df,
199
+ metrics={
200
+ "metadata_canary_auc": round(canary_auc, 4),
201
+ "top_structural_feature": str(summary_df.iloc[0]["feature"]),
202
+ "top_cohens_d": float(summary_df.iloc[0]["cohens_d"]),
203
+ },
204
+ warnings=warnings,
205
+ extras={"document_features": feat_df},
206
+ description=(
207
+ "Tests whether purely structural signals (length, digits, casing, punctuation) predict the label."
208
+ ),
209
+ )
210
+
211
+
212
+ def run_pattern_audit(
213
+ dataset: ValidatedDataset,
214
+ boundary_tokens: int = 5,
215
+ stopwords: frozenset[str] = frozenset(),
216
+ ) -> DiagnosticResult:
217
+ """Scan spurious regex patterns (dates, page numbers, IDs) and header/footer boundaries."""
218
+ texts = dataset.texts
219
+ y = dataset.y
220
+ pos_mask = y == 1
221
+ neg_mask = y == 0
222
+ n_pos = max(int(pos_mask.sum()), 1)
223
+ n_neg = max(int(neg_mask.sum()), 1)
224
+
225
+ pattern_rows = []
226
+ for name, pat in ARTIFACT_PATTERNS.items():
227
+ has_pat = texts.str.contains(pat, regex=True).to_numpy()
228
+ pos_pct = float(has_pat[pos_mask].sum()) / n_pos * 100.0
229
+ neg_pct = float(has_pat[neg_mask].sum()) / n_neg * 100.0
230
+ gap = pos_pct - neg_pct
231
+ pattern_rows.append(
232
+ {
233
+ "pattern": name,
234
+ "pos_pct": round(pos_pct, 2),
235
+ "neg_pct": round(neg_pct, 2),
236
+ "pct_gap": round(gap, 2),
237
+ "abs_gap": round(abs(gap), 2),
238
+ "total_matches": int(has_pat.sum()),
239
+ }
240
+ )
241
+
242
+ pattern_df = (
243
+ pd.DataFrame(pattern_rows).sort_values("abs_gap", ascending=False).reset_index(drop=True)
244
+ )
245
+
246
+ # Header (first N tokens) and Footer (last N tokens) boundary comparison
247
+ headers = texts.apply(lambda s: " ".join(s.split()[:boundary_tokens]))
248
+ footers = texts.apply(lambda s: " ".join(s.split()[-boundary_tokens:]))
249
+
250
+ header_terms = compute_dividing_terms_table(
251
+ headers,
252
+ y,
253
+ dataset.pos_name,
254
+ dataset.neg_name,
255
+ ngram_range=(1, 2),
256
+ metric="log_odds",
257
+ stopwords=stopwords,
258
+ min_df=2,
259
+ )
260
+ footer_terms = compute_dividing_terms_table(
261
+ footers,
262
+ y,
263
+ dataset.pos_name,
264
+ dataset.neg_name,
265
+ ngram_range=(1, 2),
266
+ metric="log_odds",
267
+ stopwords=stopwords,
268
+ min_df=2,
269
+ )
270
+
271
+ warnings: list[DiagnosticWarning] = []
272
+ leaky_patterns = pattern_df[pattern_df["abs_gap"] >= 20.0]
273
+ for _, row in leaky_patterns.head(4).iterrows():
274
+ sev: Severity = "critical" if float(row["abs_gap"]) >= 35.0 else "warning"
275
+ warnings.append(
276
+ DiagnosticWarning(
277
+ severity=sev,
278
+ category="Pattern Artifact Imbalance",
279
+ message=(
280
+ f"Pattern '{row['pattern']}' appears in {row['pos_pct']:.1f}% of {dataset.pos_name} "
281
+ f"vs {row['neg_pct']:.1f}% of {dataset.neg_name} docs ({row['pct_gap']:+.1f}pp gap)."
282
+ ),
283
+ evidence={
284
+ "pattern": str(row["pattern"]),
285
+ "pos_pct": float(row["pos_pct"]),
286
+ "neg_pct": float(row["neg_pct"]),
287
+ },
288
+ )
289
+ )
290
+
291
+ for b_label, b_df in [("Header", header_terms), ("Footer", footer_terms)]:
292
+ if not b_df.empty:
293
+ extreme = b_df[b_df["doc_pct_gap"].abs() >= 30.0]
294
+ if not extreme.empty:
295
+ top_terms = extreme.head(4)["term"].tolist()
296
+ warnings.append(
297
+ DiagnosticWarning(
298
+ severity="warning",
299
+ category=f"{b_label} Boilerplate Leakage",
300
+ message=(
301
+ f"Strong class-skewed tokens found in document {b_label.lower()}s "
302
+ f"(first/last {boundary_tokens} tokens): {', '.join(repr(t) for t in top_terms)}."
303
+ ),
304
+ evidence={"location": b_label.lower(), "terms": top_terms},
305
+ )
306
+ )
307
+
308
+ chart = build_pattern_audit_chart(
309
+ pattern_df=pattern_df,
310
+ header_df=header_terms,
311
+ footer_df=footer_terms,
312
+ pos_name=dataset.pos_name,
313
+ neg_name=dataset.neg_name,
314
+ boundary_tokens=boundary_tokens,
315
+ )
316
+
317
+ return DiagnosticResult(
318
+ name="pattern_audit",
319
+ title="Pattern & Positional Boundary Audit (Dates, Numbers, Headers & Footers)",
320
+ chart=chart,
321
+ data=pattern_df,
322
+ metrics={
323
+ "max_pattern_gap_pp": float(pattern_df.iloc[0]["abs_gap"])
324
+ if not pattern_df.empty
325
+ else 0.0,
326
+ "top_skewed_pattern": str(pattern_df.iloc[0]["pattern"])
327
+ if not pattern_df.empty
328
+ else "n/a",
329
+ "flagged_patterns": len(leaky_patterns),
330
+ },
331
+ warnings=warnings,
332
+ extras={"header_terms": header_terms.head(40), "footer_terms": footer_terms.head(40)},
333
+ description=(
334
+ "Compares hit rates of common non-semantic artifact patterns and inspects document "
335
+ f"headers (first {boundary_tokens} tokens) and footers (last {boundary_tokens} tokens)."
336
+ ),
337
+ )
338
+
339
+
340
+ def run_shortcut_ablation(
341
+ dataset: ValidatedDataset,
342
+ stopwords: frozenset[str] = frozenset(),
343
+ exclude_terms: Iterable[str] | None = None,
344
+ top_k_terms: int = 10,
345
+ boundary_tokens: int = 5,
346
+ surface_df: pd.DataFrame | None = None,
347
+ random_state: int = 42,
348
+ cache: BaselineCache | None = None,
349
+ ) -> DiagnosticResult:
350
+ """Measure CV ROC-AUC sensitivity when masking dates, digits, headers/footers, and top-K terms."""
351
+ texts = dataset.texts
352
+ y = dataset.y
353
+
354
+ def _cv_text_auc(variant: pd.Series, mask_top_k_in_fold: int = 0) -> float:
355
+ return _auc(
356
+ y,
357
+ oof_text_baseline(
358
+ variant,
359
+ y,
360
+ stopwords,
361
+ mask_top_k_in_fold=mask_top_k_in_fold,
362
+ random_state=random_state,
363
+ ),
364
+ )
365
+
366
+ base_auc = _auc(y, cached_text_baseline(cache, texts, y, stopwords, random_state=random_state))
367
+ no_dates_auc = _cv_text_auc(strip_dates(texts))
368
+ no_digits_auc = _cv_text_auc(texts.str.replace(r"\d+", " ", regex=True))
369
+
370
+ def _strip_boundaries(s: str) -> str:
371
+ toks = s.split()
372
+ if len(toks) <= 2 * boundary_tokens:
373
+ return s
374
+ return " ".join(toks[boundary_tokens:-boundary_tokens])
375
+
376
+ no_bounds = texts.apply(_strip_boundaries)
377
+ no_bounds_auc = _cv_text_auc(no_bounds)
378
+ no_topk_auc = _cv_text_auc(texts, mask_top_k_in_fold=top_k_terms)
379
+
380
+ feat_df = surface_df if surface_df is not None else extract_surface_features(texts)
381
+ meta_auc = cached_metadata_canary(cache, feat_df, y, random_state=random_state).auc
382
+
383
+ scenarios: list[dict[str, object]] = [
384
+ {
385
+ "scenario": "Full Text (Baseline)",
386
+ "roc_auc": round(base_auc, 4),
387
+ "delta_auc": 0.0,
388
+ "kind": "baseline",
389
+ },
390
+ {
391
+ "scenario": "Without Dates / Months / Years",
392
+ "roc_auc": round(no_dates_auc, 4),
393
+ "delta_auc": round(no_dates_auc - base_auc, 4),
394
+ "kind": "ablation",
395
+ },
396
+ {
397
+ "scenario": "Without Digits / Numbers",
398
+ "roc_auc": round(no_digits_auc, 4),
399
+ "delta_auc": round(no_digits_auc - base_auc, 4),
400
+ "kind": "ablation",
401
+ },
402
+ {
403
+ "scenario": f"Without First/Last {boundary_tokens} Tokens",
404
+ "roc_auc": round(no_bounds_auc, 4),
405
+ "delta_auc": round(no_bounds_auc - base_auc, 4),
406
+ "kind": "ablation",
407
+ },
408
+ {
409
+ "scenario": f"Without Top-{top_k_terms} Predictive Terms",
410
+ "roc_auc": round(no_topk_auc, 4),
411
+ "delta_auc": round(no_topk_auc - base_auc, 4),
412
+ "kind": "ablation",
413
+ },
414
+ ]
415
+
416
+ if exclude_terms:
417
+ masked = mask_terms_series(texts, exclude_terms)
418
+ masked_auc = _cv_text_auc(masked)
419
+ scenarios.append(
420
+ {
421
+ "scenario": "Without Custom exclude_terms",
422
+ "roc_auc": round(masked_auc, 4),
423
+ "delta_auc": round(masked_auc - base_auc, 4),
424
+ "kind": "ablation",
425
+ }
426
+ )
427
+
428
+ scenarios.append(
429
+ {
430
+ "scenario": "Metadata-Only Canary (No Words)",
431
+ "roc_auc": round(meta_auc, 4),
432
+ "delta_auc": round(meta_auc - base_auc, 4),
433
+ "kind": "canary",
434
+ }
435
+ )
436
+
437
+ ablation_df = pd.DataFrame(scenarios)
438
+ warnings: list[DiagnosticWarning] = []
439
+ ablation_only = ablation_df[ablation_df["kind"] == "ablation"]
440
+ if not ablation_only.empty:
441
+ worst_idx = ablation_only["delta_auc"].idxmin()
442
+ worst_row = ablation_df.loc[worst_idx]
443
+ if float(worst_row["delta_auc"]) <= -0.05:
444
+ warnings.append(
445
+ DiagnosticWarning(
446
+ severity="warning" if float(worst_row["delta_auc"]) > -0.12 else "critical",
447
+ category="Shortcut Sensitivity",
448
+ message=(
449
+ f"'{worst_row['scenario']}' dropped baseline CV ROC-AUC by "
450
+ f"{abs(float(worst_row['delta_auc'])):.3f} (from {base_auc:.3f} to {float(worst_row['roc_auc']):.3f})."
451
+ ),
452
+ evidence={
453
+ "scenario": str(worst_row["scenario"]),
454
+ "delta_auc": float(worst_row["delta_auc"]),
455
+ },
456
+ )
457
+ )
458
+
459
+ chart = build_shortcut_ablation_chart(ablation_df=ablation_df, base_auc=base_auc)
460
+
461
+ return DiagnosticResult(
462
+ name="shortcut_ablation",
463
+ title="Shortcut Sensitivity & Feature-Masking Ablation",
464
+ chart=chart,
465
+ data=ablation_df,
466
+ metrics={
467
+ "baseline_auc": round(base_auc, 4),
468
+ "no_dates_delta": round(no_dates_auc - base_auc, 4),
469
+ "no_topk_delta": round(no_topk_auc - base_auc, 4),
470
+ "metadata_canary_auc": round(meta_auc, 4),
471
+ },
472
+ warnings=warnings,
473
+ description=(
474
+ "Quantifies how strongly a cross-validated text classifier relies on dates, digits, "
475
+ "header/footer tokens, or a handful of narrow keywords."
476
+ ),
477
+ )