textray 0.1.0__tar.gz

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.
Files changed (42) hide show
  1. textray-0.1.0/.gitignore +34 -0
  2. textray-0.1.0/CHANGELOG.md +18 -0
  3. textray-0.1.0/LICENSE +21 -0
  4. textray-0.1.0/PKG-INFO +483 -0
  5. textray-0.1.0/README.md +431 -0
  6. textray-0.1.0/pyproject.toml +110 -0
  7. textray-0.1.0/src/textray/__init__.py +16 -0
  8. textray-0.1.0/src/textray/core/__init__.py +5 -0
  9. textray-0.1.0/src/textray/core/analyzer.py +616 -0
  10. textray-0.1.0/src/textray/core/cv.py +215 -0
  11. textray-0.1.0/src/textray/core/html_assets.py +133 -0
  12. textray-0.1.0/src/textray/core/result.py +348 -0
  13. textray-0.1.0/src/textray/core/text_utils.py +295 -0
  14. textray-0.1.0/src/textray/core/validation.py +247 -0
  15. textray-0.1.0/src/textray/datasets/__init__.py +5 -0
  16. textray-0.1.0/src/textray/datasets/synthetic.py +147 -0
  17. textray-0.1.0/src/textray/diagnostics/__init__.py +1 -0
  18. textray-0.1.0/src/textray/diagnostics/artifacts.py +477 -0
  19. textray-0.1.0/src/textray/diagnostics/duplicates.py +301 -0
  20. textray-0.1.0/src/textray/diagnostics/embeddings.py +466 -0
  21. textray-0.1.0/src/textray/diagnostics/lexical.py +718 -0
  22. textray-0.1.0/src/textray/diagnostics/model_errors.py +466 -0
  23. textray-0.1.0/src/textray/diagnostics/pos.py +365 -0
  24. textray-0.1.0/src/textray/diagnostics/summary.py +226 -0
  25. textray-0.1.0/src/textray/diagnostics/surrogates.py +485 -0
  26. textray-0.1.0/src/textray/report/__init__.py +5 -0
  27. textray-0.1.0/src/textray/report/builder.py +208 -0
  28. textray-0.1.0/src/textray/report/templates/report.html.j2 +199 -0
  29. textray-0.1.0/src/textray/visuals/__init__.py +23 -0
  30. textray-0.1.0/src/textray/visuals/artifact_charts.py +280 -0
  31. textray-0.1.0/src/textray/visuals/embedding_charts.py +113 -0
  32. textray-0.1.0/src/textray/visuals/error_charts.py +243 -0
  33. textray-0.1.0/src/textray/visuals/lexical_charts.py +491 -0
  34. textray-0.1.0/src/textray/visuals/theme.py +179 -0
  35. textray-0.1.0/src/textray/visuals/tree_chart.py +290 -0
  36. textray-0.1.0/tests/conftest.py +36 -0
  37. textray-0.1.0/tests/test_artifacts.py +42 -0
  38. textray-0.1.0/tests/test_errors_and_report.py +65 -0
  39. textray-0.1.0/tests/test_lexical.py +82 -0
  40. textray-0.1.0/tests/test_regressions.py +634 -0
  41. textray-0.1.0/tests/test_surrogates_embeddings.py +66 -0
  42. textray-0.1.0/tests/test_validation.py +73 -0
@@ -0,0 +1,34 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Packaging / build
7
+ build/
8
+ dist/
9
+ *.egg-info/
10
+ .eggs/
11
+
12
+ # Virtual environments & lockfiles
13
+ .venv/
14
+ venv/
15
+ env/
16
+ uv.lock
17
+
18
+ # Test / lint / typecheck caches
19
+ .pytest_cache/
20
+ .mypy_cache/
21
+ .ruff_cache/
22
+ .coverage
23
+ htmlcov/
24
+
25
+ # Jupyter
26
+ .ipynb_checkpoints/
27
+
28
+ # Generated artifacts
29
+ *.html
30
+ !src/textray/report/templates/*.html.j2
31
+
32
+ # OS
33
+ .DS_Store
34
+ Thumbs.db
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ All notable changes to `textray` will be documented in this file.
4
+
5
+ ## [0.1.0] - 2026-11-29
6
+
7
+ ### Added
8
+ - Initial public release of `textray` for binary text classification diagnostics and leakage auditing.
9
+ - Cohesive stateful `TextRay` analyzer (`textray.analyze(...)`) and unified `DiagnosticResult` objects with offline VS Code / Jupyter rendering and dark-mode safe light cards.
10
+ - Lexical & Yellowbrick-inspired Altair visualizers: `dividing_terms` (Fightin' Words `log_odds`, `tfidf`, `counts`, `chi2`, `pmi` with diverging bars & non-overlapping Scattertext-style scatter), `term_frequency`, `dispersion` (`corpus` & `document` modes), `word_correlation` (`all` & `diff` modes), `pos_distribution`, and `context` (KWIC).
11
+ - Stopword presets (`"short"`, `"english"`, `"long"`, `None`, or custom list) plus per-call `stopwords=` override on `dividing_terms()`.
12
+ - Artifact & leakage auditing: `surface_audit` (fast structural extraction + metadata-only canary CV), `pattern_audit` (precision date/month regexes, page numbers, IDs, headers/footers), `shortcut_ablation`, and `duplicates` (analytical exact counts + TF-IDF near-duplicates, `flag_conflicts=True`, `extras["conflicting_docs"]`, and cross-split leakage).
13
+ - Interpretable surrogates: custom Altair `decision_tree` (auto-sized non-overlapping rounded cards) and version-aware L1/L2 `linear_drivers`.
14
+ - Interactive 2D `embedding_map` (UMAP / t-SNE / PCA) supporting `tfidf-svd` (default, no downloads), local/cached Sentence-Transformers (`local_files_only=True` offline support + `pathlib.Path`), precomputed embeddings, `percent_rows_embed`, optional quantile outlier trimming, and interactive click-to-isolate class legend (including marginal density view).
15
+ - Optional model error diagnostics (`error_analysis`, `label_issues`, `model_vs_baseline`) with shared leak-free `BaselineCache` and automatic non-training `eval_splits` scoring when `split_col` is provided.
16
+ - Self-contained offline HTML `report()` (via embedded Vega JS from `vl-convert-python`, print CSS, error-isolated section cards, full HTML/script escaping, progress logging, and compact `ReportHTML` notebook summary card).
17
+ - Preserves original DataFrame index labels in `doc_index` / `doc_idx_a` / `doc_idx_b` across all diagnostics.
18
+ - Built-in synthetic benchmark generator `make_leaky_dataset()`.
textray-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MLResearch42
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
textray-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,483 @@
1
+ Metadata-Version: 2.5
2
+ Name: textray
3
+ Version: 0.1.0
4
+ Summary: Interactive diagnostic visualizations and leakage auditing for binary text classification.
5
+ Project-URL: Homepage, https://github.com/MLResearch42/textray
6
+ Project-URL: Repository, https://github.com/MLResearch42/textray
7
+ Project-URL: Issues, https://github.com/MLResearch42/textray/issues
8
+ Author-email: MLResearch42 <MLResearch42@users.noreply.github.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: altair,data-leakage,diagnostics,explainability,machine-learning,nlp,text-classification,visualization
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Scientific/Engineering :: Visualization
23
+ Classifier: Topic :: Text Processing :: Linguistic
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: altair>=5.2
26
+ Requires-Dist: jinja2>=3.1
27
+ Requires-Dist: numpy>=1.24
28
+ Requires-Dist: pandas>=2.0
29
+ Requires-Dist: scikit-learn>=1.3
30
+ Requires-Dist: scipy>=1.11
31
+ Requires-Dist: vl-convert-python>=1.8
32
+ Provides-Extra: all
33
+ Requires-Dist: nltk>=3.8; extra == 'all'
34
+ Requires-Dist: sentence-transformers>=2.6; extra == 'all'
35
+ Requires-Dist: spacy>=3.7; extra == 'all'
36
+ Requires-Dist: umap-learn>=0.5.5; extra == 'all'
37
+ Provides-Extra: dev
38
+ Requires-Dist: mypy>=1.10; extra == 'dev'
39
+ Requires-Dist: pandas-stubs>=2.0; extra == 'dev'
40
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
41
+ Requires-Dist: pytest>=8.0; extra == 'dev'
42
+ Requires-Dist: ruff>=0.4; extra == 'dev'
43
+ Provides-Extra: embeddings
44
+ Requires-Dist: sentence-transformers>=2.6; extra == 'embeddings'
45
+ Requires-Dist: umap-learn>=0.5.5; extra == 'embeddings'
46
+ Provides-Extra: export
47
+ Requires-Dist: vl-convert-python>=1.8; extra == 'export'
48
+ Provides-Extra: pos
49
+ Requires-Dist: nltk>=3.8; extra == 'pos'
50
+ Requires-Dist: spacy>=3.7; extra == 'pos'
51
+ Description-Content-Type: text/markdown
52
+
53
+ <p align="center">
54
+ <img src="https://raw.githubusercontent.com/MLResearch42/textray/main/assets/textray-banner.jpg" alt="TEXTRAY — Binary Text Classification Diagnostics & Leakage Auditing" width="100%" />
55
+ </p>
56
+
57
+ # textray
58
+
59
+ **X-ray diagnostics, leakage auditing, and interactive Altair visualizations for binary text classification.**
60
+
61
+ `textray` is a one-stop Python diagnostic toolkit for NLP practitioners and data scientists. Give it a `pandas.DataFrame` with your text column and binary labels (plus optional model predictions `y_pred` / `y_proba`), and immediately uncover:
62
+
63
+ - **What lexically separates your classes** (unigrams, bigrams, trigrams via Fightin' Words log-odds, TF-IDF, counts, chi-squared, and PMI)
64
+ - **Hidden leakage and spurious shortcuts** (date imbalances like `"August"`, PDF page numbers, headers/footers, document-length bias, metadata-only canary AUC, and feature-masking ablations)
65
+ - **Yellowbrick-inspired text visualizations rebuilt natively in interactive Altair** (token frequency distributions, lexical dispersion across corpus order and document position, word co-occurrence heatmaps, POS tag distributions, UMAP & t-SNE maps)
66
+ - **Interpretable surrogate splits** (clean shallow decision trees & sparse linear drivers with one-parameter `exclude_terms` ablation)
67
+ - **Semantic embedding overlap & outliers** (interactive 2D UMAP/t-SNE/PCA with click-legend class isolation; TF-IDF+SVD embeddings by default, Sentence-Transformers optional, optional quantile outlier trimming)
68
+ - **Model error slicing & suspected label noise** (FP/FN trigger terms, high-confidence label disagreements, and model-vs-baseline benchmarks)
69
+ - **Self-contained interactive HTML reports** that work offline (the chart JavaScript is embedded), ready to share with stakeholders or attach to model reviews.
70
+
71
+ ---
72
+
73
+ ## Installation
74
+
75
+ ```bash
76
+ pip install textray
77
+ ```
78
+
79
+ The core install has no downloads at run time: reports embed their chart JavaScript, and
80
+ embeddings default to TF-IDF + SVD.
81
+
82
+ Optional extras:
83
+
84
+ ```bash
85
+ pip install "textray[embeddings]" # sentence-transformers + umap-learn
86
+ pip install "textray[pos]" # spaCy + NLTK part-of-speech taggers
87
+ pip install "textray[all]" # everything
88
+ ```
89
+
90
+ Without `[pos]`, `pos_distribution()` falls back to a small built-in tagger. spaCy's
91
+ `en_core_web_sm` model is not on PyPI; install it with `python -m spacy download en_core_web_sm`
92
+ (or its wheel file on an offline machine).
93
+
94
+ ---
95
+
96
+ ## Quickstart
97
+
98
+ ```python
99
+ import textray as tr
100
+
101
+ # Try on the built-in synthetic dataset with planted date/footer/length leakage
102
+ df = tr.make_leaky_dataset(n_samples=400)
103
+
104
+ ray = tr.analyze(
105
+ df,
106
+ text_col="text",
107
+ label_col="label",
108
+ positive_label="urgent",
109
+ y_pred="y_pred", # optional
110
+ y_proba="y_proba", # optional
111
+ split_col="split", # optional (checks train/test duplicate leakage)
112
+ stopwords="english", # "short", "english" (default), "long", None, or your own list
113
+ )
114
+
115
+ # 1. Corpus health, class balance & row-order stability
116
+ ray.summary()
117
+
118
+ # 2. Diverging unigrams, bigrams & trigrams (Fightin' Words log-odds, TF-IDF, counts, chi2, PMI)
119
+ ray.dividing_terms(ngrams=(1, 2, 3), metric="log_odds", view="both")
120
+ ray.dividing_terms(metric="tfidf", stopwords="short") # override the stopword list per call
121
+
122
+ # 3. Inspect any suspicious term directly in context (KWIC)
123
+ ray.context("august", n=10)
124
+
125
+ # 4. Hunt for non-semantic leakage & shortcuts
126
+ ray.surface_audit() # Metadata-only canary ROC-AUC + feature shifts
127
+ ray.pattern_audit() # Dates, years, page numbers, IDs + header/footer tokens
128
+ ray.shortcut_ablation() # CV ROC-AUC drop when masking dates, digits, headers, or top-K terms
129
+ ray.duplicates() # Exact/near duplicates, opposite-label conflicts, split leaks
130
+ # (contradictory docs listed in res.extras["conflicting_docs"])
131
+
132
+ # 5. Interpretable tree & linear surrogates ("peel the onion" via exclude_terms)
133
+ ray.decision_tree(max_depth=3)
134
+ ray.decision_tree(max_depth=3, exclude_terms=["august", "internal escalation"])
135
+ ray.linear_drivers(penalty="l1")
136
+
137
+ # 6. Yellowbrick-inspired Altair text visualizers
138
+ ray.term_frequency(compare_stopwords=True)
139
+ ray.dispersion(terms=["august", "page", "outage"], mode="document")
140
+ ray.word_correlation(mode="diff")
141
+ ray.pos_distribution()
142
+
143
+ # 7. Interactive 2D semantic embedding map (click legend to isolate classes)
144
+ ray.embedding_map(
145
+ method="umap", # "umap", "tsne", or "pca"
146
+ model="tfidf-svd", # default; or a sentence-transformers name / local path
147
+ percent_rows_embed=20, # embed a stratified 20% of rows (default: up to sample_n=5000)
148
+ outlier_quantile=0.0, # default 0; e.g. 0.05 hides the furthest 5% (res.extras["outliers"])
149
+ show_density=True,
150
+ )
151
+
152
+ # 8. Optional model error & label noise diagnostics
153
+ ray.error_analysis()
154
+ ray.label_issues()
155
+ ray.model_vs_baseline() # with split_col, scored on non-training rows only
156
+ ray.model_vs_baseline(eval_splits=["test"])
157
+
158
+ # 9. Export everything into one self-contained interactive HTML report.
159
+ # Prints progress per section; a section that fails becomes an error card.
160
+ ray.report("diagnostic_report.html")
161
+ ```
162
+
163
+ Every method returns a unified `DiagnosticResult` that renders directly in Jupyter notebooks and exposes:
164
+
165
+ - `res.chart` — interactive `altair.Chart`
166
+ - `res.data` — tidy `pandas.DataFrame` backing the chart
167
+ (`doc_index` columns hold your DataFrame's index labels, so `df.loc[res.data["doc_index"]]` returns the original rows)
168
+ - `res.metrics` — `dict` of key scalar summary metrics
169
+ - `res.warnings` — list of structured `DiagnosticWarning` leakage/artifact alerts
170
+ - `res.extras` — auxiliary DataFrames (e.g., trimmed outliers, header/footer tables, leaf rules)
171
+ - `res.save("chart.html" | "spec.json" | "table.csv" | "chart.png")`
172
+
173
+ textray's charts carry their own styling and data, so using textray never changes your global
174
+ Altair theme or row limit. To use the textray look on your own charts, call
175
+ `textray.visuals.register_theme(enable=True)`.
176
+
177
+ ### VS Code Code Cells & Offline Environments
178
+
179
+ - **Zero-internet interactive charts in VS Code:** By default in Jupyter / VS Code notebooks and `# %%` Interactive Window cells, `DiagnosticResult` renders inside a self-contained light card (legible in both Dark and Light VS Code themes) using the bundled offline Vega/Vega-Lite JavaScript from `vl-convert-python`—no CDN or internet access required.
180
+ - **Custom Altair renderers:** If you prefer static SVG/PNG output (e.g. for smaller saved `.ipynb` files or untrusted workspaces), call `alt.renderers.enable("svg")` or `alt.renderers.enable("png")`; `textray` automatically respects any non-default Altair renderer.
181
+ - **Offline Sentence-Transformers:** Pass either a local folder path (`model="/path/to/all-MiniLM-L6-v2"` or a `pathlib.Path`) or a locally cached model name; `textray` tries `local_files_only=True` first so it never blocks on Hugging Face Hub checks.
182
+
183
+ ---
184
+
185
+ ## Cheat Sheet
186
+
187
+ Everything textray can do, with every argument and its default. You only ever need the
188
+ first two arguments of `analyze()`; everything else is optional.
189
+
190
+ ### 1. Start here: `tr.analyze()`
191
+
192
+ ```python
193
+ import textray as tr
194
+
195
+ ray = tr.analyze(
196
+ df, # your pandas DataFrame
197
+ text_col="text", # column with the documents
198
+ label_col="label", # column with the two class labels
199
+ positive_label=None, # which label is "positive"; guessed if None
200
+ y_pred=None, # optional: model predictions (column name or array)
201
+ y_proba=None, # optional: model P(positive) (column name or array)
202
+ split_col=None, # optional: column with "train"/"test"/... split names
203
+ stopwords="english", # "short" | "english" | "long" | None | your own list
204
+ exclude_terms=None, # words/phrases to hide from every check, e.g. ["august"]
205
+ random_state=42, # makes sampling and cross-validation repeatable
206
+ )
207
+ ```
208
+
209
+ | Argument | Default | What it does |
210
+ | :--- | :--- | :--- |
211
+ | `df` | required | DataFrame with one row per document. Rows with a missing label are skipped. |
212
+ | `text_col` | required | Name of the text column. |
213
+ | `label_col` | required | Name of the label column. It must have exactly two distinct values. |
214
+ | `positive_label` | `None` | The label to treat as "positive" (e.g. `"spam"`). If `None`, textray guesses from common names like `1`, `True`, `"spam"`, `"fraud"`, `"urgent"`. |
215
+ | `y_pred` | `None` | Your model's predicted labels. Needed for `error_analysis()` and `model_vs_baseline()`. |
216
+ | `y_proba` | `None` | Your model's probability of the positive class. Used for AUC and by `label_issues()`. |
217
+ | `split_col` | `None` | Split names per row. Enables train/test leak checks, and model metrics then use only non-training rows. |
218
+ | `stopwords` | `"english"` | Common words to ignore. `"short"` (~40 words, keeps "not"/"you"), `"english"` (318 words), `"long"` (`"english"` + contractions and filler like "thanks"), `None`, or a list. |
219
+ | `exclude_terms` | `None` | Words or phrases masked out of every check. Use it to "peel the onion": hide an obvious leak and see what is left. |
220
+ | `random_state` | `42` | Seed for sampling and cross-validation. |
221
+
222
+ Useful properties: `ray.pos_name`, `ray.neg_name`, `ray.has_predictions`.
223
+
224
+ ### 2. What every method returns
225
+
226
+ Every method returns a `DiagnosticResult`. In a notebook it displays itself (header, warnings, metrics and chart).
227
+
228
+ | Attribute / method | What it is |
229
+ | :--- | :--- |
230
+ | `res.chart` | Interactive Altair chart (`None` for table-only checks such as `context()`). |
231
+ | `res.data` | The main table behind the chart (a pandas DataFrame). |
232
+ | `res.metrics` | Dict of headline numbers, e.g. `{"metadata_canary_auc": 0.94}`. |
233
+ | `res.warnings` | List of findings, each with `.severity` (`"critical"`, `"warning"`, `"info"`), `.category`, `.message`, `.evidence`. |
234
+ | `res.extras` | Dict of extra tables (listed per method below). |
235
+ | `res.chart_spec()` | The chart as a Vega-Lite dict. |
236
+ | `res.save(path)` | Save by file extension: `.html` (offline page), `.csv` (the `data` table), `.json` (chart spec), `.png` / `.svg` / `.pdf` (static chart). |
237
+
238
+ > **Finding the original rows:** any `doc_index` (or `doc_idx_a` / `doc_idx_b`) column holds
239
+ > your DataFrame's own index labels, so `df.loc[res.data["doc_index"]]` returns those documents.
240
+
241
+ ### 3. Which check answers my question?
242
+
243
+ | I want to know… | Use |
244
+ | :--- | :--- |
245
+ | Is my data healthy? Class balance, empty docs, does the label drift with row order? | `summary()` |
246
+ | Which words and phrases separate the two classes? | `dividing_terms()` |
247
+ | How is a specific word actually used in each class? | `context("word")` |
248
+ | Could the model cheat using length, digits, CAPS or punctuation instead of meaning? | `surface_audit()` |
249
+ | Are dates, page numbers, IDs, headers or footers giving the label away? | `pattern_audit()` |
250
+ | How much does accuracy drop if I remove dates, digits or the top keywords? | `shortcut_ablation()` |
251
+ | Are there duplicate documents, contradictory labels, or train/test leaks? | `duplicates()` |
252
+ | What simple rules would a tiny model learn? | `decision_tree()`, `linear_drivers()` |
253
+ | Do the classes overlap in meaning? Are there odd clusters? | `embedding_map()` |
254
+ | Which documents might be mislabeled? | `label_issues()` |
255
+ | What do my model's false positives and false negatives have in common? | `error_analysis()` *(needs `y_pred`)* |
256
+ | Is my model better than simple keyword baselines? | `model_vs_baseline()` *(needs `y_pred`)* |
257
+ | Most common words, where words appear, which words co-occur, grammar differences | `term_frequency()`, `dispersion()`, `word_correlation()`, `pos_distribution()` |
258
+ | Everything at once, as one shareable file | `report("audit.html")` |
259
+
260
+ ### 4. Every method and argument
261
+
262
+ Defaults are shown in each call, so `ray.summary()` behaves exactly like
263
+ `ray.summary(n_bins=10)`. Many methods take `exclude_terms`: those words are hidden for that
264
+ call only, on top of any set in `analyze()`.
265
+
266
+ #### Overview
267
+
268
+ **`ray.summary(n_bins=10)`**: corpus health: class balance, empty or very short docs, vocabulary overlap between classes, and whether the label share drifts across row order.
269
+
270
+ | Argument | Default | What it does |
271
+ | :--- | :--- | :--- |
272
+ | `n_bins` | `10` | Number of row-order chunks used to check for label drift. |
273
+
274
+ Extras: `row_order_drift`.
275
+
276
+ **`ray.context(term, n=10, window=70)`**: shows `term` in context (keyword-in-context), balanced across both classes.
277
+
278
+ | Argument | Default | What it does |
279
+ | :--- | :--- | :--- |
280
+ | `term` | required | Word or phrase to look up (case-insensitive, whole words). |
281
+ | `n` | `10` | Number of documents to show, split evenly between classes (fewer if fewer match). |
282
+ | `window` | `70` | Characters of context shown on each side of the match. |
283
+
284
+ #### Words that separate the classes
285
+
286
+ **`ray.dividing_terms(ngrams=(1, 2, 3), metric="log_odds", top_n=20, view="bars", exclude_terms=None, min_df=2, stopwords="default")`**: the most class-distinctive single words, word pairs and word triples.
287
+
288
+ | Argument | Default | What it does |
289
+ | :--- | :--- | :--- |
290
+ | `ngrams` | `(1, 2, 3)` | Phrase lengths to score: 1 = single words, 2 = pairs, 3 = triples. |
291
+ | `metric` | `"log_odds"` | How to score a term: `"log_odds"` (robust default), `"tfidf"`, `"counts"`, `"chi2"`, `"pmi"`. |
292
+ | `top_n` | `20` | Terms shown per class, per phrase length. |
293
+ | `view` | `"bars"` | `"bars"`, `"scatter"` (frequency vs. distinctiveness) or `"both"`. |
294
+ | `exclude_terms` | `None` | Extra words/phrases to hide for this call. |
295
+ | `min_df` | `2` | Ignore terms found in fewer documents than this. |
296
+ | `stopwords` | `"default"` | Override the stopword list for this call only (`"short"`, `"english"`, `"long"`, `None`, a list). `"default"` keeps the `analyze()` setting. |
297
+
298
+ **`ray.term_frequency(top_n=30, by_class=True, compare_stopwords=False, exclude_terms=None)`**: the most frequent words.
299
+
300
+ | Argument | Default | What it does |
301
+ | :--- | :--- | :--- |
302
+ | `top_n` | `30` | Number of words shown. |
303
+ | `by_class` | `True` | Split each bar by class. |
304
+ | `compare_stopwords` | `False` | Also show the counts before stopwords were removed, side by side. |
305
+ | `exclude_terms` | `None` | Extra words/phrases to hide for this call. |
306
+
307
+ **`ray.dispersion(terms=None, mode="corpus", top_n_auto=8, exclude_terms=None, max_points=5000)`**: where words appear.
308
+
309
+ | Argument | Default | What it does |
310
+ | :--- | :--- | :--- |
311
+ | `terms` | `None` | Words to plot. `None` picks the most class-distinctive words automatically. |
312
+ | `mode` | `"corpus"` | `"corpus"`: position across your rows (spots batch or date drift). `"document"`: position inside each document, 0–100% (spots headers and footers). |
313
+ | `top_n_auto` | `8` | How many words to pick when `terms=None`. |
314
+ | `exclude_terms` | `None` | Extra words/phrases to hide for this call. |
315
+ | `max_points` | `5000` | Cap on plotted points (all are kept in `res.data`). |
316
+
317
+ **`ray.word_correlation(terms=None, top_n=16, mode="all", exclude_terms=None)`**: which words tend to appear together.
318
+
319
+ | Argument | Default | What it does |
320
+ | :--- | :--- | :--- |
321
+ | `terms` | `None` | Words to compare. `None` picks distinctive words from both classes. |
322
+ | `top_n` | `16` | How many words to pick when `terms=None`. |
323
+ | `mode` | `"all"` | `"all"`: co-occurrence over all documents. `"diff"`: positive-class minus negative-class co-occurrence. |
324
+ | `exclude_terms` | `None` | Extra words/phrases to hide for this call. |
325
+
326
+ **`ray.pos_distribution(backend="auto", spacy_model="en_core_web_sm", normalize=True, sample_n=2000, auto_download=True)`**: compares grammar (nouns, verbs, numbers, …) between classes.
327
+
328
+ | Argument | Default | What it does |
329
+ | :--- | :--- | :--- |
330
+ | `backend` | `"auto"` | `"spacy"`, `"nltk"`, or `"auto"` (spaCy, then NLTK, then a built-in tagger). spaCy/NLTK need `pip install "textray[pos]"`. |
331
+ | `spacy_model` | `"en_core_web_sm"` | spaCy model name (install it with `python -m spacy download en_core_web_sm`). |
332
+ | `normalize` | `True` | Show percentages of tokens instead of raw counts. |
333
+ | `sample_n` | `2000` | Number of documents tagged (balanced across classes). |
334
+ | `auto_download` | `True` | Let NLTK download its tagger if missing. Set `False` offline to skip a possible 2-minute wait. |
335
+
336
+ #### Leakage and shortcuts
337
+
338
+ **`ray.surface_audit(sample_n=3000)`**: can the label be predicted from formatting alone (length, digits, capitals, punctuation, newlines, URLs) without any words? A high "canary" AUC means leakage.
339
+
340
+ | Argument | Default | What it does |
341
+ | :--- | :--- | :--- |
342
+ | `sample_n` | `3000` | Documents plotted in the distribution charts (scores use all rows). |
343
+
344
+ Extras: `document_features` (the formatting features of every document).
345
+
346
+ **`ray.pattern_audit(boundary_tokens=5)`**: how often dates, years, times, page numbers, money, URLs, e-mails, IDs, ALL-CAPS words and `[bracketed tags]` appear in each class, plus words that cluster at the start or end of documents.
347
+
348
+ | Argument | Default | What it does |
349
+ | :--- | :--- | :--- |
350
+ | `boundary_tokens` | `5` | How many words at the start (header) and end (footer) of each document to inspect. |
351
+
352
+ Extras: `header_terms`, `footer_terms`.
353
+
354
+ **`ray.shortcut_ablation(exclude_terms=None, top_k_terms=10, boundary_tokens=5)`**: retrains a simple classifier with dates, digits, headers/footers or the top keywords removed, and shows how much AUC drops. A big drop means the classes are separated by a shortcut.
355
+
356
+ | Argument | Default | What it does |
357
+ | :--- | :--- | :--- |
358
+ | `exclude_terms` | `None` | Also test the AUC drop when these words/phrases are removed. |
359
+ | `top_k_terms` | `10` | How many of the strongest keywords to remove in the "top keywords" test. |
360
+ | `boundary_tokens` | `5` | Words removed from each end in the header/footer test. |
361
+
362
+ **`ray.duplicates(near_threshold=0.95, max_pairs=2000, flag_conflicts=True)`**: exact and near-duplicate documents, duplicates with opposite labels, and duplicates split across train/test.
363
+
364
+ | Argument | Default | What it does |
365
+ | :--- | :--- | :--- |
366
+ | `near_threshold` | `0.95` | Similarity (0.5–1.0) above which two documents count as near-duplicates. `1.0` = exact only. |
367
+ | `max_pairs` | `2000` | Rows listed in `res.data` (contradictions first). Counts and warnings always cover every pair. |
368
+ | `flag_conflicts` | `True` | Raise a critical warning for duplicates with opposite labels and list them in `extras["conflicting_docs"]`. |
369
+
370
+ Extras: `summary`, `conflicting_docs`.
371
+
372
+ #### Simple "surrogate" models
373
+
374
+ **`ray.decision_tree(max_depth=3, representation="tfidf", ngram_range=(1, 2), exclude_terms=None, min_samples_leaf=5)`**: a small decision tree showing which words split the classes first.
375
+
376
+ | Argument | Default | What it does |
377
+ | :--- | :--- | :--- |
378
+ | `max_depth` | `3` | Number of question levels in the tree. |
379
+ | `representation` | `"tfidf"` | `"tfidf"` (weighted word scores) or `"count"` (word present / absent). |
380
+ | `ngram_range` | `(1, 2)` | Phrase lengths used: `(1, 2)` = single words and pairs. |
381
+ | `exclude_terms` | `None` | Hide words to see the next-best splits. |
382
+ | `min_samples_leaf` | `5` | Smallest number of documents allowed in an end node. |
383
+
384
+ Extras: `nodes`, `edges`. `res.data` lists one rule per end node.
385
+
386
+ **`ray.linear_drivers(top_n=20, penalty="l2", ngram_range=(1, 2), C=1.0, exclude_terms=None)`**: the words a logistic regression leans on most for each class.
387
+
388
+ | Argument | Default | What it does |
389
+ | :--- | :--- | :--- |
390
+ | `top_n` | `20` | Words shown per class. |
391
+ | `penalty` | `"l2"` | `"l2"` keeps all words with small weights; `"l1"` keeps only a few strong words. |
392
+ | `ngram_range` | `(1, 2)` | Phrase lengths used. |
393
+ | `C` | `1.0` | Inverse regularization strength: smaller `C` = simpler model with fewer strong words. |
394
+ | `exclude_terms` | `None` | Hide words to see the next drivers. |
395
+
396
+ #### Meaning (embeddings)
397
+
398
+ **`ray.embedding_map(method="umap", model="tfidf-svd", embeddings=None, normalize=True, outlier_quantile=0.0, metric="cosine", sample_n=5000, show_density=False, exclude_terms=None, percent_rows_embed=None)`**: a 2-D map of documents by meaning. Click the legend to show one class.
399
+
400
+ | Argument | Default | What it does |
401
+ | :--- | :--- | :--- |
402
+ | `method` | `"umap"` | `"umap"`, `"tsne"` or `"pca"`. UMAP needs `textray[embeddings]` (falls back to t-SNE). |
403
+ | `model` | `"tfidf-svd"` | `"tfidf-svd"` works offline with no download. Or a sentence-transformers name / local folder path (needs `textray[embeddings]`), or any object with `.encode(texts)`. |
404
+ | `embeddings` | `None` | Your own precomputed vectors, shape `(rows, dims)`. |
405
+ | `normalize` | `True` | Scale every vector to length 1. |
406
+ | `outlier_quantile` | `0.0` | Hide this share of the most distant points (e.g. `0.05`); hidden points go to `extras["outliers"]`. |
407
+ | `metric` | `"cosine"` | Distance used for neighbours and UMAP: `"cosine"` or `"euclidean"`. |
408
+ | `sample_n` | `5000` | Maximum documents embedded (a class-balanced sample). |
409
+ | `show_density` | `False` | Add density curves along both axes. |
410
+ | `exclude_terms` | `None` | Words hidden before embedding. |
411
+ | `percent_rows_embed` | `None` | Embed this percentage of rows (0–100) instead of using `sample_n`. |
412
+
413
+ Extras: `outliers`.
414
+
415
+ #### Your model's mistakes and label noise
416
+
417
+ **`ray.label_issues(top_n=25)`**: documents whose label looks wrong. Uses your `y_proba` if given, otherwise a cross-validated baseline model.
418
+
419
+ | Argument | Default | What it does |
420
+ | :--- | :--- | :--- |
421
+ | `top_n` | `25` | Number of suspects listed in `res.data`. |
422
+
423
+ Extras: `all_scores` (a score for every document).
424
+
425
+ **`ray.error_analysis(top_n=15, exclude_terms=None, eval_splits=None)`** *(needs `y_pred`)*: counts of true/false positives/negatives and the words behind each error type.
426
+
427
+ | Argument | Default | What it does |
428
+ | :--- | :--- | :--- |
429
+ | `top_n` | `15` | Words shown per error type. |
430
+ | `exclude_terms` | `None` | Extra words/phrases to hide for this call. |
431
+ | `eval_splits` | `None` | Splits to evaluate on, e.g. `["test"]`. Default: all rows, or every non-training split when `split_col` is set. |
432
+
433
+ Extras: `confusion`, `fp_terms`, `fn_terms`.
434
+
435
+ **`ray.model_vs_baseline(eval_splits=None)`** *(needs `y_pred`)*: compares your model with three simple baselines (formatting-only, word counts, TF-IDF). If a baseline nearly matches your model, the model may rely on keywords or leakage.
436
+
437
+ | Argument | Default | What it does |
438
+ | :--- | :--- | :--- |
439
+ | `eval_splits` | `None` | Splits to score on, e.g. `["test"]`. Default: every non-training split when `split_col` is set. |
440
+
441
+ ### 5. The full report
442
+
443
+ ```python
444
+ ray.report(
445
+ "audit.html", # where to save; None = just return the HTML
446
+ title=None, # report title; default "… Audit: <pos> vs <neg>"
447
+ include_embeddings=True, # include the embedding map
448
+ include_pos=True, # include the grammar (POS) check
449
+ embedding_method="umap", # "umap" | "tsne" | "pca"
450
+ embedding_model="tfidf-svd", # same choices as embedding_map(model=...)
451
+ outlier_quantile=0.0, # same as embedding_map
452
+ percent_rows_embed=None, # same as embedding_map
453
+ inline_js=True, # True: works offline (~1 MB bigger); False: loads charts from the internet
454
+ progress=True, # print one line per section while it runs
455
+ )
456
+ ```
457
+
458
+ Runs every check above (the model checks only when `y_pred` was given) and writes one HTML
459
+ file. A check that fails shows as an error card; the rest of the report still builds.
460
+
461
+ ### 6. Helpers
462
+
463
+ | Function | What it does |
464
+ | :--- | :--- |
465
+ | `tr.make_leaky_dataset(n_samples=400, random_state=42, include_predictions=True, include_splits=True)` | Synthetic data with planted leaks (dates, footers, length) for trying textray out. Columns: `text`, `label`, plus `split`, `y_pred`, `y_proba`. |
466
+ | `textray.visuals.register_theme(enable=False)` | Register textray's chart style with Altair for your own charts; `enable=True` also makes it the active theme. |
467
+
468
+ ---
469
+
470
+ ## Development
471
+
472
+ ```bash
473
+ git clone https://github.com/MLResearch42/textray.git
474
+ cd textray
475
+ uv sync --extra dev
476
+ uv run pytest
477
+ uv run ruff check src tests
478
+ uv run mypy src/textray
479
+ ```
480
+
481
+ ## License
482
+
483
+ MIT — see [LICENSE](LICENSE).