Skip to main content

TEXTRAY — Binary Text Classification Diagnostics & Leakage Auditing

textray

X-ray diagnostics, leakage auditing, and interactive Altair visualizations for binary text classification.

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:

  • What lexically separates your classes (unigrams, bigrams, trigrams via Fightin' Words log-odds, TF-IDF, counts, chi-squared, and PMI)
  • 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)
  • 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)
  • Interpretable surrogate splits (clean shallow decision trees & sparse linear drivers with one-parameter exclude_terms ablation)
  • 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)
  • Model error slicing & suspected label noise (FP/FN trigger terms, high-confidence label disagreements, and model-vs-baseline benchmarks)
  • Self-contained interactive HTML reports that work offline (the chart JavaScript is embedded), ready to share with stakeholders or attach to model reviews.

Installation

pip install textray

The core install has no downloads at run time: reports embed their chart JavaScript, and embeddings default to TF-IDF + SVD.

Optional extras:

pip install "textray[embeddings]"   # sentence-transformers + umap-learn
pip install "textray[pos]"          # spaCy + NLTK part-of-speech taggers
pip install "textray[all]"          # everything

Without [pos], pos_distribution() falls back to a small built-in tagger. spaCy's en_core_web_sm model is not on PyPI; install it with python -m spacy download en_core_web_sm (or its wheel file on an offline machine).


Quickstart

import textray as tr

# Try on the built-in synthetic dataset with planted date/footer/length leakage
df = tr.make_leaky_dataset(n_samples=400)

ray = tr.analyze(
    df,
    text_col="text",
    label_col="label",
    positive_label="urgent",
    y_pred="y_pred",      # optional
    y_proba="y_proba",    # optional
    split_col="split",    # optional (checks train/test duplicate leakage)
    stopwords="english",  # "short", "english" (default), "long", None, or your own list
)

# 1. Corpus health, class balance & row-order stability
ray.summary()

# 2. Diverging unigrams, bigrams & trigrams (Fightin' Words log-odds, TF-IDF, counts, chi2, PMI)
ray.dividing_terms(ngrams=(1, 2, 3), metric="log_odds", view="both")
ray.dividing_terms(metric="tfidf", stopwords="short")  # override the stopword list per call

# 3. Inspect any suspicious term directly in context (KWIC)
ray.context("august", n=10)

# 4. Hunt for non-semantic leakage & shortcuts
ray.surface_audit()       # Metadata-only canary ROC-AUC + feature shifts
ray.pattern_audit()       # Dates, years, page numbers, IDs + header/footer tokens
ray.shortcut_ablation()   # CV ROC-AUC drop when masking dates, digits, headers, or top-K terms
ray.duplicates()          # Exact/near duplicates, opposite-label conflicts, split leaks
                          # (contradictory docs listed in res.extras["conflicting_docs"])

# 5. Interpretable tree & linear surrogates ("peel the onion" via exclude_terms)
ray.decision_tree(max_depth=3)
ray.decision_tree(max_depth=3, exclude_terms=["august", "internal escalation"])
ray.linear_drivers(penalty="l1")

# 6. Yellowbrick-inspired Altair text visualizers
ray.term_frequency(compare_stopwords=True)
ray.dispersion(terms=["august", "page", "outage"], mode="document")
ray.word_correlation(mode="diff")
ray.pos_distribution()

# 7. Interactive 2D semantic embedding map (click legend to isolate classes)
ray.embedding_map(
    method="umap",                  # "umap", "tsne", or "pca"
    model="tfidf-svd",              # default; or a sentence-transformers name / local path
    percent_rows_embed=20,          # embed a stratified 20% of rows (default: up to sample_n=5000)
    outlier_quantile=0.0,           # default 0; e.g. 0.05 hides the furthest 5% (res.extras["outliers"])
    show_density=True,
)

# 8. Optional model error & label noise diagnostics
ray.error_analysis()
ray.label_issues()
ray.model_vs_baseline()          # with split_col, scored on non-training rows only
ray.model_vs_baseline(eval_splits=["test"])

# 9. Export everything into one self-contained interactive HTML report.
#    Prints progress per section; a section that fails becomes an error card.
ray.report("diagnostic_report.html")

Every method returns a unified DiagnosticResult that renders directly in Jupyter notebooks and exposes:

  • res.chart — interactive altair.Chart
  • res.data — tidy pandas.DataFrame backing the chart (doc_index columns hold your DataFrame's index labels, so df.loc[res.data["doc_index"]] returns the original rows)
  • res.metrics — dict of key scalar summary metrics
  • res.warnings — list of structured DiagnosticWarning leakage/artifact alerts
  • res.extras — auxiliary DataFrames (e.g., trimmed outliers, header/footer tables, leaf rules)
  • res.save("chart.html" | "spec.json" | "table.csv" | "chart.png")

textray's charts carry their own styling and data, so using textray never changes your global Altair theme or row limit. To use the textray look on your own charts, call textray.visuals.register_theme(enable=True).

VS Code Code Cells & Offline Environments

  • 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.
  • 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.
  • 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.

Cheat Sheet

Everything textray can do, with every argument and its default. You only ever need the first two arguments of analyze(); everything else is optional.

1. Start here: tr.analyze()

import textray as tr

ray = tr.analyze(
    df,                      # your pandas DataFrame
    text_col="text",         # column with the documents
    label_col="label",       # column with the two class labels
    positive_label=None,     # which label is "positive"; guessed if None
    y_pred=None,             # optional: model predictions (column name or array)
    y_proba=None,            # optional: model P(positive) (column name or array)
    split_col=None,          # optional: column with "train"/"test"/... split names
    stopwords="english",     # "short" | "english" | "long" | None | your own list
    exclude_terms=None,      # words/phrases to hide from every check, e.g. ["august"]
    random_state=42,         # makes sampling and cross-validation repeatable
)
Argument Default What it does
df required DataFrame with one row per document. Rows with a missing label are skipped.
text_col required Name of the text column.
label_col required Name of the label column. It must have exactly two distinct values.
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".
y_pred None Your model's predicted labels. Needed for error_analysis() and model_vs_baseline().
y_proba None Your model's probability of the positive class. Used for AUC and by label_issues().
split_col None Split names per row. Enables train/test leak checks, and model metrics then use only non-training rows.
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.
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.
random_state 42 Seed for sampling and cross-validation.

Useful properties: ray.pos_name, ray.neg_name, ray.has_predictions.

2. What every method returns

Every method returns a DiagnosticResult. In a notebook it displays itself (header, warnings, metrics and chart).

Attribute / method What it is
res.chart Interactive Altair chart (None for table-only checks such as context()).
res.data The main table behind the chart (a pandas DataFrame).
res.metrics Dict of headline numbers, e.g. {"metadata_canary_auc": 0.94}.
res.warnings List of findings, each with .severity ("critical", "warning", "info"), .category, .message, .evidence.
res.extras Dict of extra tables (listed per method below).
res.chart_spec() The chart as a Vega-Lite dict.
res.save(path) Save by file extension: .html (offline page), .csv (the data table), .json (chart spec), .png / .svg / .pdf (static chart).

Finding the original rows: any doc_index (or doc_idx_a / doc_idx_b) column holds your DataFrame's own index labels, so df.loc[res.data["doc_index"]] returns those documents.

3. Which check answers my question?

I want to know… Use
Is my data healthy? Class balance, empty docs, does the label drift with row order? summary()
Which words and phrases separate the two classes? dividing_terms()
How is a specific word actually used in each class? context("word")
Could the model cheat using length, digits, CAPS or punctuation instead of meaning? surface_audit()
Are dates, page numbers, IDs, headers or footers giving the label away? pattern_audit()
How much does accuracy drop if I remove dates, digits or the top keywords? shortcut_ablation()
Are there duplicate documents, contradictory labels, or train/test leaks? duplicates()
What simple rules would a tiny model learn? decision_tree(), linear_drivers()
Do the classes overlap in meaning? Are there odd clusters? embedding_map()
Which documents might be mislabeled? label_issues()
What do my model's false positives and false negatives have in common? error_analysis() (needs y_pred)
Is my model better than simple keyword baselines? model_vs_baseline() (needs y_pred)
Most common words, where words appear, which words co-occur, grammar differences term_frequency(), dispersion(), word_correlation(), pos_distribution()
Everything at once, as one shareable file report("audit.html")

4. Every method and argument

Defaults are shown in each call, so ray.summary() behaves exactly like ray.summary(n_bins=10). Many methods take exclude_terms: those words are hidden for that call only, on top of any set in analyze().

Overview

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.

Argument Default What it does
n_bins 10 Number of row-order chunks used to check for label drift.

Extras: row_order_drift.

ray.context(term, n=10, window=70): shows term in context (keyword-in-context), balanced across both classes.

Argument Default What it does
term required Word or phrase to look up (case-insensitive, whole words).
n 10 Number of documents to show, split evenly between classes (fewer if fewer match).
window 70 Characters of context shown on each side of the match.

Words that separate the classes

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.

Argument Default What it does
ngrams (1, 2, 3) Phrase lengths to score: 1 = single words, 2 = pairs, 3 = triples.
metric "log_odds" How to score a term: "log_odds" (robust default), "tfidf", "counts", "chi2", "pmi".
top_n 20 Terms shown per class, per phrase length.
view "bars" "bars", "scatter" (frequency vs. distinctiveness) or "both".
exclude_terms None Extra words/phrases to hide for this call.
min_df 2 Ignore terms found in fewer documents than this.
stopwords "default" Override the stopword list for this call only ("short", "english", "long", None, a list). "default" keeps the analyze() setting.

ray.term_frequency(top_n=30, by_class=True, compare_stopwords=False, exclude_terms=None): the most frequent words.

Argument Default What it does
top_n 30 Number of words shown.
by_class True Split each bar by class.
compare_stopwords False Also show the counts before stopwords were removed, side by side.
exclude_terms None Extra words/phrases to hide for this call.

ray.dispersion(terms=None, mode="corpus", top_n_auto=8, exclude_terms=None, max_points=5000): where words appear.

Argument Default What it does
terms None Words to plot. None picks the most class-distinctive words automatically.
mode "corpus" "corpus": position across your rows (spots batch or date drift). "document": position inside each document, 0–100% (spots headers and footers).
top_n_auto 8 How many words to pick when terms=None.
exclude_terms None Extra words/phrases to hide for this call.
max_points 5000 Cap on plotted points (all are kept in res.data).

ray.word_correlation(terms=None, top_n=16, mode="all", exclude_terms=None): which words tend to appear together.

Argument Default What it does
terms None Words to compare. None picks distinctive words from both classes.
top_n 16 How many words to pick when terms=None.
mode "all" "all": co-occurrence over all documents. "diff": positive-class minus negative-class co-occurrence.
exclude_terms None Extra words/phrases to hide for this call.

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.

Argument Default What it does
backend "auto" "spacy", "nltk", or "auto" (spaCy, then NLTK, then a built-in tagger). spaCy/NLTK need pip install "textray[pos]".
spacy_model "en_core_web_sm" spaCy model name (install it with python -m spacy download en_core_web_sm).
normalize True Show percentages of tokens instead of raw counts.
sample_n 2000 Number of documents tagged (balanced across classes).
auto_download True Let NLTK download its tagger if missing. Set False offline to skip a possible 2-minute wait.

Leakage and shortcuts

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.

Argument Default What it does
sample_n 3000 Documents plotted in the distribution charts (scores use all rows).

Extras: document_features (the formatting features of every document).

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.

Argument Default What it does
boundary_tokens 5 How many words at the start (header) and end (footer) of each document to inspect.

Extras: header_terms, footer_terms.

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.

Argument Default What it does
exclude_terms None Also test the AUC drop when these words/phrases are removed.
top_k_terms 10 How many of the strongest keywords to remove in the "top keywords" test.
boundary_tokens 5 Words removed from each end in the header/footer test.

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.

Argument Default What it does
near_threshold 0.95 Similarity (0.5–1.0) above which two documents count as near-duplicates. 1.0 = exact only.
max_pairs 2000 Rows listed in res.data (contradictions first). Counts and warnings always cover every pair.
flag_conflicts True Raise a critical warning for duplicates with opposite labels and list them in extras["conflicting_docs"].

Extras: summary, conflicting_docs.

Simple "surrogate" models

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.

Argument Default What it does
max_depth 3 Number of question levels in the tree.
representation "tfidf" "tfidf" (weighted word scores) or "count" (word present / absent).
ngram_range (1, 2) Phrase lengths used: (1, 2) = single words and pairs.
exclude_terms None Hide words to see the next-best splits.
min_samples_leaf 5 Smallest number of documents allowed in an end node.

Extras: nodes, edges. res.data lists one rule per end node.

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.

Argument Default What it does
top_n 20 Words shown per class.
penalty "l2" "l2" keeps all words with small weights; "l1" keeps only a few strong words.
ngram_range (1, 2) Phrase lengths used.
C 1.0 Inverse regularization strength: smaller C = simpler model with fewer strong words.
exclude_terms None Hide words to see the next drivers.

Meaning (embeddings)

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.

Argument Default What it does
method "umap" "umap", "tsne" or "pca". UMAP needs textray[embeddings] (falls back to t-SNE).
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).
embeddings None Your own precomputed vectors, shape (rows, dims).
normalize True Scale every vector to length 1.
outlier_quantile 0.0 Hide this share of the most distant points (e.g. 0.05); hidden points go to extras["outliers"].
metric "cosine" Distance used for neighbours and UMAP: "cosine" or "euclidean".
sample_n 5000 Maximum documents embedded (a class-balanced sample).
show_density False Add density curves along both axes.
exclude_terms None Words hidden before embedding.
percent_rows_embed None Embed this percentage of rows (0–100) instead of using sample_n.

Extras: outliers.

Your model's mistakes and label noise

ray.label_issues(top_n=25): documents whose label looks wrong. Uses your y_proba if given, otherwise a cross-validated baseline model.

Argument Default What it does
top_n 25 Number of suspects listed in res.data.

Extras: all_scores (a score for every document).

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.

Argument Default What it does
top_n 15 Words shown per error type.
exclude_terms None Extra words/phrases to hide for this call.
eval_splits None Splits to evaluate on, e.g. ["test"]. Default: all rows, or every non-training split when split_col is set.

Extras: confusion, fp_terms, fn_terms.

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.

Argument Default What it does
eval_splits None Splits to score on, e.g. ["test"]. Default: every non-training split when split_col is set.

5. The full report

ray.report(
    "audit.html",                 # where to save; None = just return the HTML
    title=None,                   # report title; default "… Audit: <pos> vs <neg>"
    include_embeddings=True,      # include the embedding map
    include_pos=True,             # include the grammar (POS) check
    embedding_method="umap",      # "umap" | "tsne" | "pca"
    embedding_model="tfidf-svd",  # same choices as embedding_map(model=...)
    outlier_quantile=0.0,         # same as embedding_map
    percent_rows_embed=None,      # same as embedding_map
    inline_js=True,               # True: works offline (~1 MB bigger); False: loads charts from the internet
    progress=True,                # print one line per section while it runs
)

Runs every check above (the model checks only when y_pred was given) and writes one HTML file. A check that fails shows as an error card; the rest of the report still builds.

6. Helpers

Function What it does
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.
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.

Development

git clone https://github.com/MLResearch42/textray.git
cd textray
uv sync --extra dev
uv run pytest
uv run ruff check src tests
uv run mypy src/textray

License

MIT — see LICENSE.

Metadata

Release files for textray 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for textray 0.1.0
File Size Uploaded Provenance Actions
textray-0.1.0.tar.gz 95.4 kB With provenance Details for textray-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for textray 0.1.0
File Interpreter ABI Platform Actions
textray-0.1.0-py3-none-any.whl Python 3 none any Details for textray-0.1.0-py3-none-any.whl

Total release size: 196.6 kB

Release files / textray-0.1.0.tar.gz

Download URL textray-0.1.0.tar.gz
Size 95.4 kB
Tags Source
SHA-256 checksum
How to use checksums
e41b1108d9cf3d77c10048874517b498c0cbf53ea80029d038a25f0168d988f4
BLAKE2b-256 checksum
How to use checksums
a839b06efb79c462de0b807cf59dd538c200a29d251febf5478aee625f8b5b33
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / textray-0.1.0-py3-none-any.whl

Download URL textray-0.1.0-py3-none-any.whl
Size 101.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d67971306b6cb5d21b73c282063f38f853e61e90ee321c6bdc4e152f575342c5
BLAKE2b-256 checksum
How to use checksums
e5134551d1f8403e21d0bb4b4cb970a48612f4906c2546538b2a234055876fe3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for textray 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for textray-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page