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.
textray/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """textray: Interactive diagnostic visualizations and leakage auditing for binary text classification."""
2
+
3
+ from textray.core.analyzer import TextRay, analyze
4
+ from textray.core.result import DiagnosticResult, DiagnosticWarning
5
+ from textray.datasets.synthetic import make_leaky_dataset
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "DiagnosticResult",
11
+ "DiagnosticWarning",
12
+ "TextRay",
13
+ "__version__",
14
+ "analyze",
15
+ "make_leaky_dataset",
16
+ ]
@@ -0,0 +1,5 @@
1
+ """Core data structures, validation, text utilities, and orchestrator."""
2
+
3
+ from textray.core.result import DiagnosticResult, DiagnosticWarning
4
+
5
+ __all__ = ["DiagnosticResult", "DiagnosticWarning"]
@@ -0,0 +1,616 @@
1
+ """Stateful TextRay analyzer orchestrating all diagnostics with smart lazy caching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import time
7
+ import traceback
8
+ import warnings
9
+ from collections.abc import Callable, Iterable, Sequence
10
+ from pathlib import Path
11
+ from typing import Any, Literal
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+
16
+ from textray.core.cv import BaselineCache
17
+ from textray.core.result import DiagnosticResult, DiagnosticWarning
18
+ from textray.core.text_utils import merge_exclude_terms, resolve_stopwords
19
+ from textray.core.validation import ValidatedDataset, validate_inputs
20
+ from textray.diagnostics.artifacts import (
21
+ extract_surface_features,
22
+ run_pattern_audit,
23
+ run_shortcut_ablation,
24
+ run_surface_audit,
25
+ )
26
+ from textray.diagnostics.duplicates import run_duplicates
27
+ from textray.diagnostics.embeddings import (
28
+ DEFAULT_EMBEDDING_MODEL,
29
+ ProjectionMethod,
30
+ embedding_sample_size,
31
+ run_embedding_map,
32
+ )
33
+ from textray.diagnostics.lexical import (
34
+ DividingMetric,
35
+ run_context,
36
+ run_dispersion,
37
+ run_dividing_terms,
38
+ run_term_frequency,
39
+ run_word_correlation,
40
+ )
41
+ from textray.diagnostics.model_errors import (
42
+ run_error_analysis,
43
+ run_label_issues,
44
+ run_model_vs_baseline,
45
+ )
46
+ from textray.diagnostics.pos import PosBackend, run_pos_distribution
47
+ from textray.diagnostics.summary import run_summary
48
+ from textray.diagnostics.surrogates import run_decision_tree, run_linear_drivers
49
+ from textray.report.builder import build_html_report
50
+
51
+
52
+ class TextRay:
53
+ """One-stop diagnostic explorer for binary text classification datasets and models.
54
+
55
+ Prefer constructing via :func:`textray.analyze` or directly with ``TextRay(df, text_col, label_col)``.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ df: pd.DataFrame,
61
+ text_col: str,
62
+ label_col: str,
63
+ *,
64
+ positive_label: Any = None,
65
+ y_pred: str | Sequence[Any] | np.ndarray | pd.Series | None = None,
66
+ y_proba: str | Sequence[float] | np.ndarray | pd.Series | None = None,
67
+ split_col: str | None = None,
68
+ stopwords: str | Iterable[str] | None = "english",
69
+ exclude_terms: Iterable[str] | None = None,
70
+ random_state: int = 42,
71
+ ) -> None:
72
+ """
73
+ Parameters
74
+ ----------
75
+ stopwords:
76
+ ``"english"`` (default, scikit-learn's 318 words), ``"short"`` (~40 function
77
+ words; keeps negations and pronouns), ``"long"`` (``"english"`` plus contractions
78
+ and conversational filler), ``None`` for no removal, or your own list of words.
79
+ """
80
+ self.dataset: ValidatedDataset = validate_inputs(
81
+ df=df,
82
+ text_col=text_col,
83
+ label_col=label_col,
84
+ positive_label=positive_label,
85
+ y_pred=y_pred,
86
+ y_proba=y_proba,
87
+ split_col=split_col,
88
+ )
89
+ self.text_col = text_col
90
+ self.label_col = label_col
91
+ self.stopwords: frozenset[str] = resolve_stopwords(stopwords)
92
+ self.exclude_terms: tuple[str, ...] = merge_exclude_terms(exclude_terms, None)
93
+ self.random_state = random_state
94
+
95
+ # Internal lazy caches
96
+ self._surface_df: pd.DataFrame | None = None
97
+ self._embedding_cache: dict[tuple[Any, ...], tuple[np.ndarray, np.ndarray, str]] = {}
98
+ # Shared CV baselines (TF-IDF, BoW, metadata canary) reused across diagnostics
99
+ self._baselines = BaselineCache()
100
+
101
+ @property
102
+ def pos_name(self) -> str:
103
+ return self.dataset.pos_name
104
+
105
+ @property
106
+ def neg_name(self) -> str:
107
+ return self.dataset.neg_name
108
+
109
+ @property
110
+ def has_predictions(self) -> bool:
111
+ return self.dataset.y_pred is not None
112
+
113
+ def __repr__(self) -> str:
114
+ pred_flag = "yes" if self.has_predictions else "no"
115
+ return (
116
+ f"TextRay(n_docs={len(self.dataset.texts):,}, "
117
+ f"positive={self.pos_name!r}, negative={self.neg_name!r}, "
118
+ f"predictions={pred_flag})"
119
+ )
120
+
121
+ def _get_surface_df(self) -> pd.DataFrame:
122
+ if self._surface_df is None:
123
+ self._surface_df = extract_surface_features(self.dataset.texts)
124
+ return self._surface_df
125
+
126
+ def _effective_exclude(self, exclude_terms: Iterable[str] | None) -> tuple[str, ...]:
127
+ return merge_exclude_terms(self.exclude_terms, exclude_terms)
128
+
129
+ # ------------------------------------------------------------------
130
+ # Overview & Context
131
+ # ------------------------------------------------------------------
132
+ def summary(self, n_bins: int = 10) -> DiagnosticResult:
133
+ """Corpus health summary: class balance, vocabulary overlap, and row-order drift."""
134
+ return run_summary(self.dataset, stopwords=self.stopwords, n_bins=n_bins)
135
+
136
+ def context(self, term: str, n: int = 10, window: int = 70) -> DiagnosticResult:
137
+ """Key-Word-In-Context (KWIC) concordance table split across Positive and Negative docs."""
138
+ return run_context(self.dataset, term=term, n=n, window=window)
139
+
140
+ # ------------------------------------------------------------------
141
+ # Lexical & Yellowbrick-Inspired Visuals
142
+ # ------------------------------------------------------------------
143
+ def dividing_terms(
144
+ self,
145
+ ngrams: Sequence[int] = (1, 2, 3),
146
+ metric: DividingMetric = "log_odds",
147
+ top_n: int = 20,
148
+ view: Literal["bars", "scatter", "both"] = "bars",
149
+ exclude_terms: Iterable[str] | None = None,
150
+ min_df: int = 2,
151
+ stopwords: str | Iterable[str] | None = "default",
152
+ ) -> DiagnosticResult:
153
+ """Side-by-side diverging charts & statistics for unigrams, bigrams, and trigrams.
154
+
155
+ ``stopwords`` overrides the analyzer's list for this call only: ``"short"``,
156
+ ``"english"``, ``"long"``, ``None`` or a custom list. ``"default"`` keeps the
157
+ analyzer's setting.
158
+ """
159
+ call_stopwords = (
160
+ self.stopwords
161
+ if isinstance(stopwords, str) and stopwords == "default"
162
+ else resolve_stopwords(stopwords)
163
+ )
164
+ return run_dividing_terms(
165
+ dataset=self.dataset,
166
+ ngrams=ngrams,
167
+ metric=metric,
168
+ top_n=top_n,
169
+ stopwords=call_stopwords,
170
+ exclude_terms=self._effective_exclude(exclude_terms),
171
+ view=view,
172
+ min_df=min_df,
173
+ )
174
+
175
+ def term_frequency(
176
+ self,
177
+ top_n: int = 30,
178
+ by_class: bool = True,
179
+ compare_stopwords: bool = False,
180
+ exclude_terms: Iterable[str] | None = None,
181
+ ) -> DiagnosticResult:
182
+ """Yellowbrick FreqDistVisualizer equivalent: corpus token frequency distribution."""
183
+ return run_term_frequency(
184
+ dataset=self.dataset,
185
+ top_n=top_n,
186
+ by_class=by_class,
187
+ compare_stopwords=compare_stopwords,
188
+ stopwords=self.stopwords,
189
+ exclude_terms=self._effective_exclude(exclude_terms),
190
+ )
191
+
192
+ def dispersion(
193
+ self,
194
+ terms: Sequence[str] | None = None,
195
+ mode: Literal["corpus", "document"] = "corpus",
196
+ top_n_auto: int = 8,
197
+ exclude_terms: Iterable[str] | None = None,
198
+ max_points: int = 5000,
199
+ ) -> DiagnosticResult:
200
+ """Yellowbrick DispersionPlot upgraded for binary classification (corpus or within-doc)."""
201
+ return run_dispersion(
202
+ dataset=self.dataset,
203
+ terms=terms,
204
+ mode=mode,
205
+ stopwords=self.stopwords,
206
+ exclude_terms=self._effective_exclude(exclude_terms),
207
+ top_n_auto=top_n_auto,
208
+ max_points=max_points,
209
+ )
210
+
211
+ def word_correlation(
212
+ self,
213
+ terms: Sequence[str] | None = None,
214
+ top_n: int = 16,
215
+ mode: Literal["all", "diff"] = "all",
216
+ exclude_terms: Iterable[str] | None = None,
217
+ ) -> DiagnosticResult:
218
+ """Yellowbrick WordCorrelationPlot: co-occurrence heatmap (overall or class-difference)."""
219
+ return run_word_correlation(
220
+ dataset=self.dataset,
221
+ terms=terms,
222
+ top_n=top_n,
223
+ mode=mode,
224
+ stopwords=self.stopwords,
225
+ exclude_terms=self._effective_exclude(exclude_terms),
226
+ )
227
+
228
+ def pos_distribution(
229
+ self,
230
+ backend: PosBackend = "auto",
231
+ spacy_model: str = "en_core_web_sm",
232
+ normalize: bool = True,
233
+ sample_n: int = 2000,
234
+ auto_download: bool = True,
235
+ ) -> DiagnosticResult:
236
+ """Yellowbrick PosTagVisualizer equivalent comparing Universal POS tags across classes."""
237
+ return run_pos_distribution(
238
+ dataset=self.dataset,
239
+ backend=backend,
240
+ spacy_model=spacy_model,
241
+ normalize=normalize,
242
+ sample_n=sample_n,
243
+ auto_download=auto_download,
244
+ random_state=self.random_state,
245
+ )
246
+
247
+ # ------------------------------------------------------------------
248
+ # Artifact, Leakage & Duplicate Audits
249
+ # ------------------------------------------------------------------
250
+ def surface_audit(self, sample_n: int = 3000) -> DiagnosticResult:
251
+ """Non-semantic structural feature audit + metadata-only canary classifier."""
252
+ return run_surface_audit(
253
+ dataset=self.dataset,
254
+ surface_df=self._get_surface_df(),
255
+ random_state=self.random_state,
256
+ sample_n=sample_n,
257
+ cache=self._baselines,
258
+ )
259
+
260
+ def pattern_audit(self, boundary_tokens: int = 5) -> DiagnosticResult:
261
+ """Regex artifact scanner (dates, numbers, IDs) + header/footer boundary check."""
262
+ return run_pattern_audit(
263
+ dataset=self.dataset,
264
+ boundary_tokens=boundary_tokens,
265
+ stopwords=self.stopwords,
266
+ )
267
+
268
+ def shortcut_ablation(
269
+ self,
270
+ exclude_terms: Iterable[str] | None = None,
271
+ top_k_terms: int = 10,
272
+ boundary_tokens: int = 5,
273
+ ) -> DiagnosticResult:
274
+ """Measure CV ROC-AUC drop when masking dates, digits, boundaries, or top-K terms."""
275
+ return run_shortcut_ablation(
276
+ dataset=self.dataset,
277
+ stopwords=self.stopwords,
278
+ exclude_terms=self._effective_exclude(exclude_terms),
279
+ top_k_terms=top_k_terms,
280
+ boundary_tokens=boundary_tokens,
281
+ surface_df=self._get_surface_df(),
282
+ random_state=self.random_state,
283
+ cache=self._baselines,
284
+ )
285
+
286
+ def duplicates(
287
+ self,
288
+ near_threshold: float = 0.95,
289
+ max_pairs: int = 2000,
290
+ flag_conflicts: bool = True,
291
+ ) -> DiagnosticResult:
292
+ """Detect exact/near duplicates, opposite-label conflicts, and cross-split leakage.
293
+
294
+ Counts cover every pair; ``max_pairs`` only limits the rows listed in ``.data``.
295
+ ``flag_conflicts=True`` raises a critical warning for contradictory pairs (same text,
296
+ opposite labels) and lists every document involved in ``.extras["conflicting_docs"]``.
297
+ """
298
+ return run_duplicates(
299
+ dataset=self.dataset,
300
+ near_threshold=near_threshold,
301
+ max_pairs=max_pairs,
302
+ flag_conflicts=flag_conflicts,
303
+ )
304
+
305
+ # ------------------------------------------------------------------
306
+ # Interpretable Surrogates
307
+ # ------------------------------------------------------------------
308
+ def decision_tree(
309
+ self,
310
+ max_depth: int = 3,
311
+ representation: Literal["tfidf", "count"] = "tfidf",
312
+ ngram_range: tuple[int, int] = (1, 2),
313
+ exclude_terms: Iterable[str] | None = None,
314
+ min_samples_leaf: int = 5,
315
+ ) -> DiagnosticResult:
316
+ """Fit a shallow decision tree and render a clean interactive Altair tree diagram."""
317
+ return run_decision_tree(
318
+ dataset=self.dataset,
319
+ max_depth=max_depth,
320
+ representation=representation,
321
+ ngram_range=ngram_range,
322
+ stopwords=self.stopwords,
323
+ exclude_terms=self._effective_exclude(exclude_terms),
324
+ min_samples_leaf=min_samples_leaf,
325
+ random_state=self.random_state,
326
+ )
327
+
328
+ def linear_drivers(
329
+ self,
330
+ top_n: int = 20,
331
+ penalty: Literal["l1", "l2"] = "l2",
332
+ ngram_range: tuple[int, int] = (1, 2),
333
+ C: float = 1.0,
334
+ exclude_terms: Iterable[str] | None = None,
335
+ ) -> DiagnosticResult:
336
+ """Fit a sparse regularized linear surrogate to expose top positive/negative term drivers."""
337
+ return run_linear_drivers(
338
+ dataset=self.dataset,
339
+ top_n=top_n,
340
+ penalty=penalty,
341
+ ngram_range=ngram_range,
342
+ C=C,
343
+ stopwords=self.stopwords,
344
+ exclude_terms=self._effective_exclude(exclude_terms),
345
+ random_state=self.random_state,
346
+ )
347
+
348
+ # ------------------------------------------------------------------
349
+ # Semantic Embeddings (Yellowbrick UMAP + t-SNE + Outlier Trimming)
350
+ # ------------------------------------------------------------------
351
+ def embedding_map(
352
+ self,
353
+ method: ProjectionMethod = "umap",
354
+ model: str | Any = DEFAULT_EMBEDDING_MODEL,
355
+ embeddings: np.ndarray | None = None,
356
+ normalize: bool = True,
357
+ outlier_quantile: float = 0.0,
358
+ metric: Literal["cosine", "euclidean"] = "cosine",
359
+ sample_n: int = 5000,
360
+ show_density: bool = False,
361
+ exclude_terms: Iterable[str] | None = None,
362
+ percent_rows_embed: float | None = None,
363
+ ) -> DiagnosticResult:
364
+ """Interactive 2D UMAP/t-SNE/PCA semantic map with class isolation.
365
+
366
+ Only a class-stratified sample is embedded: ``percent_rows_embed`` percent of rows
367
+ (0-100] when given, otherwise up to ``sample_n`` rows. The default ``model`` is
368
+ ``"tfidf-svd"``, which needs no download; pass a sentence-transformers model name or
369
+ local path for neural embeddings. ``outlier_quantile`` > 0 hides the furthest points.
370
+ """
371
+ eff_exclude = self._effective_exclude(exclude_terms)
372
+ n_embed = embedding_sample_size(len(self.dataset.texts), sample_n, percent_rows_embed)
373
+ model_key = str(model) if isinstance(model, (str, Path)) else f"obj:{id(model)}"
374
+ cache_key = (
375
+ model_key,
376
+ normalize,
377
+ eff_exclude,
378
+ n_embed,
379
+ )
380
+ cached = self._embedding_cache.get(cache_key) if embeddings is None else None
381
+
382
+ result, computed = run_embedding_map(
383
+ dataset=self.dataset,
384
+ method=method,
385
+ model=model,
386
+ embeddings=embeddings,
387
+ normalize=normalize,
388
+ outlier_quantile=outlier_quantile,
389
+ metric=metric,
390
+ sample_n=sample_n,
391
+ show_density=show_density,
392
+ stopwords=self.stopwords,
393
+ exclude_terms=eff_exclude,
394
+ cached_embeddings=cached,
395
+ random_state=self.random_state,
396
+ percent_rows_embed=percent_rows_embed,
397
+ )
398
+ if embeddings is None and computed[1].shape[0] > 0:
399
+ self._embedding_cache[cache_key] = computed
400
+ return result
401
+
402
+ # ------------------------------------------------------------------
403
+ # Model & Error Diagnostics
404
+ # ------------------------------------------------------------------
405
+ def error_analysis(
406
+ self,
407
+ top_n: int = 15,
408
+ exclude_terms: Iterable[str] | None = None,
409
+ eval_splits: Sequence[str] | None = None,
410
+ ) -> DiagnosticResult:
411
+ """Slice TP/FP/TN/FN outcomes and find n-grams driving False Positives & False Negatives.
412
+
413
+ With ``split_col``, only non-training rows are scored unless ``eval_splits`` names
414
+ the splits to use (e.g. ``["test"]``).
415
+ """
416
+ return run_error_analysis(
417
+ dataset=self.dataset,
418
+ top_n=top_n,
419
+ stopwords=self.stopwords,
420
+ exclude_terms=self._effective_exclude(exclude_terms),
421
+ eval_splits=eval_splits,
422
+ )
423
+
424
+ def label_issues(self, top_n: int = 25) -> DiagnosticResult:
425
+ """Surface highest-confidence label disagreements (works with or without y_proba)."""
426
+ return run_label_issues(
427
+ dataset=self.dataset,
428
+ top_n=top_n,
429
+ stopwords=self.stopwords,
430
+ random_state=self.random_state,
431
+ cache=self._baselines,
432
+ )
433
+
434
+ def model_vs_baseline(self, eval_splits: Sequence[str] | None = None) -> DiagnosticResult:
435
+ """Benchmark user predictions against metadata canary, BoW, and TF-IDF baselines.
436
+
437
+ With ``split_col``, every model is scored on non-training rows only, unless
438
+ ``eval_splits`` names the splits to use (e.g. ``["test"]``).
439
+ """
440
+ return run_model_vs_baseline(
441
+ dataset=self.dataset,
442
+ stopwords=self.stopwords,
443
+ surface_df=self._get_surface_df(),
444
+ random_state=self.random_state,
445
+ cache=self._baselines,
446
+ eval_splits=eval_splits,
447
+ )
448
+
449
+ # ------------------------------------------------------------------
450
+ # Full HTML Diagnostic Report
451
+ # ------------------------------------------------------------------
452
+ def report(
453
+ self,
454
+ path: str | Path | None = None,
455
+ *,
456
+ title: str | None = None,
457
+ include_embeddings: bool = True,
458
+ include_pos: bool = True,
459
+ embedding_method: ProjectionMethod = "umap",
460
+ embedding_model: str | Any = DEFAULT_EMBEDDING_MODEL,
461
+ outlier_quantile: float = 0.0,
462
+ percent_rows_embed: float | None = None,
463
+ inline_js: bool = True,
464
+ progress: bool = True,
465
+ ) -> str:
466
+ """Run the full diagnostic suite and generate a self-contained interactive HTML report.
467
+
468
+ A section that raises is shown as an error card instead of stopping the report.
469
+ ``progress=True`` prints one line per section with its run time. ``inline_js=True``
470
+ embeds the chart JavaScript so the file works offline; ``False`` loads it from a CDN
471
+ (smaller file, needs internet to view).
472
+ """
473
+ steps: list[tuple[str, str, Callable[[], DiagnosticResult]]] = [
474
+ ("summary", "Corpus Summary", self.summary),
475
+ (
476
+ "dividing_terms",
477
+ "Class-Dividing Terms",
478
+ lambda: self.dividing_terms(ngrams=(1, 2, 3), view="both"),
479
+ ),
480
+ ("surface_audit", "Surface & Metadata Leakage Audit", self.surface_audit),
481
+ ("pattern_audit", "Pattern & Positional Boundary Audit", self.pattern_audit),
482
+ ("shortcut_ablation", "Shortcut Sensitivity Ablation", self.shortcut_ablation),
483
+ ("duplicates", "Duplicate & Leakage Audit", self.duplicates),
484
+ ("decision_tree", "Decision Tree Surrogate", self.decision_tree),
485
+ ("linear_drivers", "Linear Feature Drivers", self.linear_drivers),
486
+ (
487
+ "term_frequency",
488
+ "Token Frequency Distribution",
489
+ lambda: self.term_frequency(compare_stopwords=True),
490
+ ),
491
+ ("dispersion", "Lexical Dispersion", lambda: self.dispersion(mode="document")),
492
+ (
493
+ "word_correlation",
494
+ "Word Co-Occurrence Correlation",
495
+ lambda: self.word_correlation(mode="all"),
496
+ ),
497
+ ("label_issues", "Suspected Label Noise", self.label_issues),
498
+ ]
499
+ if include_pos:
500
+ steps.append(("pos_distribution", "Part-of-Speech Distribution", self.pos_distribution))
501
+ if include_embeddings:
502
+ steps.append(
503
+ (
504
+ "embedding_map",
505
+ "Semantic Embedding Map",
506
+ lambda: self.embedding_map(
507
+ method=embedding_method,
508
+ model=embedding_model,
509
+ outlier_quantile=outlier_quantile,
510
+ percent_rows_embed=percent_rows_embed,
511
+ ),
512
+ )
513
+ )
514
+ if self.has_predictions:
515
+ steps.append(("error_analysis", "Model Error Analysis", self.error_analysis))
516
+ steps.append(("model_vs_baseline", "Model vs. Baselines", self.model_vs_baseline))
517
+
518
+ results: list[DiagnosticResult] = []
519
+ n_steps = len(steps)
520
+ report_start = time.perf_counter()
521
+ for i, (name, label, run) in enumerate(steps, start=1):
522
+ if progress:
523
+ print(
524
+ f"[textray {i:>2}/{n_steps}] {label} ...", end="", file=sys.stderr, flush=True
525
+ )
526
+ started = time.perf_counter()
527
+ try:
528
+ result = run()
529
+ status = f"done in {time.perf_counter() - started:.1f}s"
530
+ except Exception as exc: # one broken section must not lose the whole report
531
+ result = _failed_section_result(name, label, exc)
532
+ status = f"FAILED ({type(exc).__name__}: {exc})"
533
+ if progress:
534
+ print(f" {status}", file=sys.stderr, flush=True)
535
+ if result.error is not None:
536
+ warnings.warn(
537
+ f"textray report: section '{name}' failed and is shown as an error card: "
538
+ f"{result.error}",
539
+ RuntimeWarning,
540
+ stacklevel=2,
541
+ )
542
+ results.append(result)
543
+
544
+ report_title = (
545
+ title or f"Binary Text Classification Audit: {self.pos_name} vs {self.neg_name}"
546
+ )
547
+ html_out = build_html_report(
548
+ results=results,
549
+ title=report_title,
550
+ pos_name=self.pos_name,
551
+ neg_name=self.neg_name,
552
+ n_docs=len(self.dataset.texts),
553
+ output_path=path,
554
+ inline_js=inline_js,
555
+ )
556
+ if progress:
557
+ where = f" -> {path}" if path is not None else ""
558
+ print(
559
+ f"[textray] report built in {time.perf_counter() - report_start:.1f}s{where}",
560
+ file=sys.stderr,
561
+ flush=True,
562
+ )
563
+ return html_out
564
+
565
+
566
+ def _failed_section_result(name: str, label: str, exc: BaseException) -> DiagnosticResult:
567
+ """Placeholder result rendered as an error card when a report section raises."""
568
+ tb = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)[-3:])
569
+ return DiagnosticResult(
570
+ name=name,
571
+ title=f"{label} (failed)",
572
+ chart=None,
573
+ data=pd.DataFrame(),
574
+ metrics={},
575
+ warnings=[
576
+ DiagnosticWarning(
577
+ severity="warning",
578
+ category="Section Failed",
579
+ message=(
580
+ f"This check could not run: {type(exc).__name__}: {exc}. "
581
+ "The rest of the report is unaffected."
582
+ ),
583
+ evidence={"error_type": type(exc).__name__, "traceback": tb},
584
+ )
585
+ ],
586
+ description="",
587
+ error=f"{type(exc).__name__}: {exc}",
588
+ )
589
+
590
+
591
+ def analyze(
592
+ df: pd.DataFrame,
593
+ text_col: str,
594
+ label_col: str,
595
+ *,
596
+ positive_label: Any = None,
597
+ y_pred: str | Sequence[Any] | np.ndarray | pd.Series | None = None,
598
+ y_proba: str | Sequence[float] | np.ndarray | pd.Series | None = None,
599
+ split_col: str | None = None,
600
+ stopwords: str | Iterable[str] | None = "english",
601
+ exclude_terms: Iterable[str] | None = None,
602
+ random_state: int = 42,
603
+ ) -> TextRay:
604
+ """Create a :class:`TextRay` diagnostic analyzer for a binary text classification DataFrame."""
605
+ return TextRay(
606
+ df=df,
607
+ text_col=text_col,
608
+ label_col=label_col,
609
+ positive_label=positive_label,
610
+ y_pred=y_pred,
611
+ y_proba=y_proba,
612
+ split_col=split_col,
613
+ stopwords=stopwords,
614
+ exclude_terms=exclude_terms,
615
+ random_state=random_state,
616
+ )