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 +16 -0
- textray/core/__init__.py +5 -0
- textray/core/analyzer.py +616 -0
- textray/core/cv.py +215 -0
- textray/core/html_assets.py +133 -0
- textray/core/result.py +348 -0
- textray/core/text_utils.py +295 -0
- textray/core/validation.py +247 -0
- textray/datasets/__init__.py +5 -0
- textray/datasets/synthetic.py +147 -0
- textray/diagnostics/__init__.py +1 -0
- textray/diagnostics/artifacts.py +477 -0
- textray/diagnostics/duplicates.py +301 -0
- textray/diagnostics/embeddings.py +466 -0
- textray/diagnostics/lexical.py +718 -0
- textray/diagnostics/model_errors.py +466 -0
- textray/diagnostics/pos.py +365 -0
- textray/diagnostics/summary.py +226 -0
- textray/diagnostics/surrogates.py +485 -0
- textray/report/__init__.py +5 -0
- textray/report/builder.py +208 -0
- textray/report/templates/report.html.j2 +199 -0
- textray/visuals/__init__.py +23 -0
- textray/visuals/artifact_charts.py +280 -0
- textray/visuals/embedding_charts.py +113 -0
- textray/visuals/error_charts.py +243 -0
- textray/visuals/lexical_charts.py +491 -0
- textray/visuals/theme.py +179 -0
- textray/visuals/tree_chart.py +290 -0
- textray-0.1.0.dist-info/METADATA +483 -0
- textray-0.1.0.dist-info/RECORD +33 -0
- textray-0.1.0.dist-info/WHEEL +4 -0
- textray-0.1.0.dist-info/licenses/LICENSE +21 -0
textray/core/cv.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Shared cross-validation helpers and the per-analyzer baseline cache.
|
|
2
|
+
|
|
3
|
+
Every "leak-free" score in textray (metadata canary, TF-IDF / BoW baselines, ablations,
|
|
4
|
+
surrogate CV AUCs) goes through :func:`oof_predict`, so they all use the same folds and the
|
|
5
|
+
same fallbacks. :class:`BaselineCache` lets one ``TextRay`` reuse the expensive baselines
|
|
6
|
+
across diagnostics, so the report shows one consistent "baseline AUC".
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable, Hashable
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import pandas as pd
|
|
17
|
+
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
|
|
18
|
+
from sklearn.linear_model import LogisticRegression
|
|
19
|
+
from sklearn.model_selection import StratifiedKFold
|
|
20
|
+
from sklearn.pipeline import Pipeline
|
|
21
|
+
from sklearn.preprocessing import StandardScaler
|
|
22
|
+
|
|
23
|
+
from textray.core.text_utils import VECTORIZER_TOKEN_PATTERN
|
|
24
|
+
|
|
25
|
+
# One setting for every TF-IDF / BoW baseline, so all sections report the same number.
|
|
26
|
+
BASELINE_MAX_FEATURES = 10000
|
|
27
|
+
BASELINE_NGRAM_RANGE: tuple[int, int] = (1, 2)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def can_cross_validate(y: np.ndarray) -> bool:
|
|
31
|
+
"""True when there are enough documents of each class for stratified CV."""
|
|
32
|
+
return len(y) >= 4 and int(min((y == 1).sum(), (y == 0).sum())) >= 2
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def n_cv_splits(y: np.ndarray, max_splits: int = 5) -> int:
|
|
36
|
+
min_class = int(min((y == 1).sum(), (y == 0).sum()))
|
|
37
|
+
return max(2, min(max_splits, min_class))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def oof_predict(
|
|
41
|
+
y: np.ndarray,
|
|
42
|
+
fit_predict: Callable[[np.ndarray, np.ndarray], np.ndarray],
|
|
43
|
+
random_state: int = 42,
|
|
44
|
+
) -> np.ndarray:
|
|
45
|
+
"""Out-of-fold P(positive) using stratified K-fold.
|
|
46
|
+
|
|
47
|
+
``fit_predict(train_idx, valid_idx)`` must fit on the train rows and return probabilities
|
|
48
|
+
for the validation rows. A fold that raises ``ValueError`` (e.g. empty vocabulary) scores
|
|
49
|
+
0.5. Returns all-0.5 when there is too little data to cross-validate.
|
|
50
|
+
"""
|
|
51
|
+
if not can_cross_validate(y):
|
|
52
|
+
return np.full(len(y), 0.5)
|
|
53
|
+
cv = StratifiedKFold(n_splits=n_cv_splits(y), shuffle=True, random_state=random_state)
|
|
54
|
+
oof = np.full(len(y), 0.5, dtype=float)
|
|
55
|
+
for tr, va in cv.split(np.zeros(len(y)), y):
|
|
56
|
+
try:
|
|
57
|
+
oof[va] = fit_predict(tr, va)
|
|
58
|
+
except ValueError:
|
|
59
|
+
oof[va] = 0.5
|
|
60
|
+
return oof
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def make_text_vectorizer(
|
|
64
|
+
n_train_docs: int,
|
|
65
|
+
stopwords: frozenset[str],
|
|
66
|
+
ngram_range: tuple[int, int] = BASELINE_NGRAM_RANGE,
|
|
67
|
+
use_tfidf: bool = True,
|
|
68
|
+
max_features: int = BASELINE_MAX_FEATURES,
|
|
69
|
+
) -> TfidfVectorizer | CountVectorizer:
|
|
70
|
+
kwargs: dict[str, Any] = {
|
|
71
|
+
"ngram_range": ngram_range,
|
|
72
|
+
"stop_words": sorted(stopwords) if stopwords else None,
|
|
73
|
+
"min_df": 2 if n_train_docs >= 15 else 1,
|
|
74
|
+
"max_features": max_features,
|
|
75
|
+
"token_pattern": VECTORIZER_TOKEN_PATTERN,
|
|
76
|
+
}
|
|
77
|
+
return TfidfVectorizer(**kwargs) if use_tfidf else CountVectorizer(**kwargs)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def oof_text_baseline(
|
|
81
|
+
texts: pd.Series,
|
|
82
|
+
y: np.ndarray,
|
|
83
|
+
stopwords: frozenset[str],
|
|
84
|
+
*,
|
|
85
|
+
ngram_range: tuple[int, int] = BASELINE_NGRAM_RANGE,
|
|
86
|
+
use_tfidf: bool = True,
|
|
87
|
+
mask_top_k_in_fold: int = 0,
|
|
88
|
+
random_state: int = 42,
|
|
89
|
+
) -> np.ndarray:
|
|
90
|
+
"""Out-of-fold probabilities from a TF-IDF (or BoW) + LogisticRegression baseline.
|
|
91
|
+
|
|
92
|
+
``mask_top_k_in_fold`` drops the K strongest terms of each training fold before the final
|
|
93
|
+
fit, which measures how much the baseline depends on a handful of keywords.
|
|
94
|
+
"""
|
|
95
|
+
arr = texts.to_numpy()
|
|
96
|
+
|
|
97
|
+
def _fit_predict(tr: np.ndarray, va: np.ndarray) -> np.ndarray:
|
|
98
|
+
vec = make_text_vectorizer(len(tr), stopwords, ngram_range, use_tfidf)
|
|
99
|
+
X_tr = vec.fit_transform(arr[tr])
|
|
100
|
+
X_va = vec.transform(arr[va])
|
|
101
|
+
if mask_top_k_in_fold > 0 and X_tr.shape[1] > mask_top_k_in_fold:
|
|
102
|
+
probe = LogisticRegression(max_iter=1000, C=1.0, random_state=random_state)
|
|
103
|
+
probe.fit(X_tr, y[tr])
|
|
104
|
+
top_idx = np.argsort(np.abs(probe.coef_[0]))[::-1][:mask_top_k_in_fold]
|
|
105
|
+
keep = np.ones(X_tr.shape[1], dtype=bool)
|
|
106
|
+
keep[top_idx] = False
|
|
107
|
+
X_tr, X_va = X_tr[:, keep], X_va[:, keep]
|
|
108
|
+
clf = LogisticRegression(max_iter=1000, C=1.0, random_state=random_state)
|
|
109
|
+
clf.fit(X_tr, y[tr])
|
|
110
|
+
return clf.predict_proba(X_va)[:, 1]
|
|
111
|
+
|
|
112
|
+
return oof_predict(y, _fit_predict, random_state=random_state)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass(frozen=True)
|
|
116
|
+
class CanaryResult:
|
|
117
|
+
"""Metadata-only canary: out-of-fold probabilities, ROC-AUC and mean coefficients."""
|
|
118
|
+
|
|
119
|
+
oof: np.ndarray
|
|
120
|
+
auc: float
|
|
121
|
+
coefs: np.ndarray
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def metadata_canary(
|
|
125
|
+
surface_df: pd.DataFrame,
|
|
126
|
+
y: np.ndarray,
|
|
127
|
+
random_state: int = 42,
|
|
128
|
+
) -> CanaryResult:
|
|
129
|
+
"""Leak-free CV of a LogisticRegression trained only on non-semantic surface features."""
|
|
130
|
+
from sklearn.metrics import roc_auc_score
|
|
131
|
+
|
|
132
|
+
X = surface_df.to_numpy(dtype=float)
|
|
133
|
+
if not can_cross_validate(y):
|
|
134
|
+
return CanaryResult(np.full(len(y), 0.5), 0.5, np.zeros(X.shape[1]))
|
|
135
|
+
|
|
136
|
+
n_splits = n_cv_splits(y)
|
|
137
|
+
coefs = np.zeros(X.shape[1], dtype=float)
|
|
138
|
+
|
|
139
|
+
def _fit_predict(tr: np.ndarray, va: np.ndarray) -> np.ndarray:
|
|
140
|
+
nonlocal coefs
|
|
141
|
+
pipe = Pipeline(
|
|
142
|
+
[
|
|
143
|
+
("scaler", StandardScaler()),
|
|
144
|
+
("clf", LogisticRegression(max_iter=1000, C=1.0, random_state=random_state)),
|
|
145
|
+
]
|
|
146
|
+
)
|
|
147
|
+
pipe.fit(X[tr], y[tr])
|
|
148
|
+
coefs = coefs + pipe.named_steps["clf"].coef_[0] / n_splits
|
|
149
|
+
return pipe.predict_proba(X[va])[:, 1]
|
|
150
|
+
|
|
151
|
+
oof = oof_predict(y, _fit_predict, random_state=random_state)
|
|
152
|
+
return CanaryResult(oof=oof, auc=float(roc_auc_score(y, oof)), coefs=coefs)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class BaselineCache:
|
|
156
|
+
"""Memoises expensive, deterministic baseline computations for one ``TextRay``.
|
|
157
|
+
|
|
158
|
+
Keys must capture every input that changes the result (stopwords, random_state, ...).
|
|
159
|
+
"""
|
|
160
|
+
|
|
161
|
+
def __init__(self) -> None:
|
|
162
|
+
self._store: dict[Hashable, Any] = {}
|
|
163
|
+
|
|
164
|
+
def get_or_compute(self, key: Hashable, compute: Callable[[], Any]) -> Any:
|
|
165
|
+
if key not in self._store:
|
|
166
|
+
self._store[key] = compute()
|
|
167
|
+
return self._store[key]
|
|
168
|
+
|
|
169
|
+
def clear(self) -> None:
|
|
170
|
+
self._store.clear()
|
|
171
|
+
|
|
172
|
+
def __len__(self) -> int:
|
|
173
|
+
return len(self._store)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def cached_text_baseline(
|
|
177
|
+
cache: BaselineCache | None,
|
|
178
|
+
texts: pd.Series,
|
|
179
|
+
y: np.ndarray,
|
|
180
|
+
stopwords: frozenset[str],
|
|
181
|
+
*,
|
|
182
|
+
use_tfidf: bool = True,
|
|
183
|
+
ngram_range: tuple[int, int] = BASELINE_NGRAM_RANGE,
|
|
184
|
+
random_state: int = 42,
|
|
185
|
+
) -> np.ndarray:
|
|
186
|
+
"""OOF baseline on the analyzer's full corpus, reused across diagnostics when cached."""
|
|
187
|
+
|
|
188
|
+
def _compute() -> np.ndarray:
|
|
189
|
+
return oof_text_baseline(
|
|
190
|
+
texts,
|
|
191
|
+
y,
|
|
192
|
+
stopwords,
|
|
193
|
+
ngram_range=ngram_range,
|
|
194
|
+
use_tfidf=use_tfidf,
|
|
195
|
+
random_state=random_state,
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
if cache is None:
|
|
199
|
+
return _compute()
|
|
200
|
+
key = ("text_baseline", use_tfidf, ngram_range, stopwords, random_state)
|
|
201
|
+
return cache.get_or_compute(key, _compute)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def cached_metadata_canary(
|
|
205
|
+
cache: BaselineCache | None,
|
|
206
|
+
surface_df: pd.DataFrame,
|
|
207
|
+
y: np.ndarray,
|
|
208
|
+
random_state: int = 42,
|
|
209
|
+
) -> CanaryResult:
|
|
210
|
+
if cache is None:
|
|
211
|
+
return metadata_canary(surface_df, y, random_state=random_state)
|
|
212
|
+
return cache.get_or_compute(
|
|
213
|
+
("metadata_canary", random_state),
|
|
214
|
+
lambda: metadata_canary(surface_df, y, random_state=random_state),
|
|
215
|
+
)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Chart JavaScript and safe JSON embedding shared by the HTML report and result pages.
|
|
2
|
+
|
|
3
|
+
Reports inline the Vega / Vega-Lite / Vega-Embed JavaScript (from ``vl-convert-python``) so a
|
|
4
|
+
saved file renders with no internet access. Chart specs contain document text, so they are
|
|
5
|
+
escaped before going inside a ``<script>`` element.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from functools import lru_cache
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import altair as alt
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def script_safe_json(json_text: str) -> str:
|
|
18
|
+
"""Make JSON safe to place inside an HTML ``<script>`` element.
|
|
19
|
+
|
|
20
|
+
A document containing ``</script>`` would otherwise end the script block early and
|
|
21
|
+
turn the rest of its text into live HTML. ``<``, ``>`` and ``&`` only occur inside JSON
|
|
22
|
+
strings, where the ``\\uXXXX`` escapes decode to the same characters.
|
|
23
|
+
"""
|
|
24
|
+
return (
|
|
25
|
+
json_text.replace("<", "\\u003c")
|
|
26
|
+
.replace(">", "\\u003e")
|
|
27
|
+
.replace("&", "\\u0026")
|
|
28
|
+
.replace("
", "\\u2028")
|
|
29
|
+
.replace("
", "\\u2029")
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _vl_convert_version() -> str:
|
|
34
|
+
# vl-convert names Vega-Lite versions like "v6_4"; Altair reports "v6.4.1".
|
|
35
|
+
return "_".join(alt.SCHEMA_VERSION.split(".")[:2])
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@lru_cache(maxsize=1)
|
|
39
|
+
def inline_vega_bundle() -> str | None:
|
|
40
|
+
"""Vega + Vega-Lite + Vega-Embed as one script, or ``None`` if vl-convert is missing."""
|
|
41
|
+
try:
|
|
42
|
+
import vl_convert
|
|
43
|
+
except ImportError:
|
|
44
|
+
return None
|
|
45
|
+
vlc: Any = vl_convert # its type stubs wrongly mark the optional snippet as required
|
|
46
|
+
try:
|
|
47
|
+
bundle = vlc.javascript_bundle(None, vl_version=_vl_convert_version())
|
|
48
|
+
except Exception:
|
|
49
|
+
try:
|
|
50
|
+
bundle = vlc.javascript_bundle(None)
|
|
51
|
+
except Exception:
|
|
52
|
+
return None
|
|
53
|
+
return str(bundle).replace("</script", "<\\/script").replace("</SCRIPT", "<\\/SCRIPT")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def cdn_script_tags() -> str:
|
|
57
|
+
"""Script tags loading the Vega versions that match the installed Altair from jsDelivr."""
|
|
58
|
+
versions = {
|
|
59
|
+
"vega": alt.VEGA_VERSION,
|
|
60
|
+
"vega-lite": alt.VEGALITE_VERSION,
|
|
61
|
+
"vega-embed": alt.VEGAEMBED_VERSION,
|
|
62
|
+
}
|
|
63
|
+
return "\n".join(
|
|
64
|
+
f'<script src="https://cdn.jsdelivr.net/npm/{name}@{version}"></script>'
|
|
65
|
+
for name, version in versions.items()
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def vega_script_block(inline: bool = True) -> tuple[str, bool]:
|
|
70
|
+
"""HTML that defines ``window.vegaEmbed``, and whether it works offline.
|
|
71
|
+
|
|
72
|
+
The inline bundle runs inside a function so it can appear more than once on a page
|
|
73
|
+
(e.g. several notebook outputs) without redeclaring its top-level names.
|
|
74
|
+
"""
|
|
75
|
+
bundle = inline_vega_bundle() if inline else None
|
|
76
|
+
if bundle:
|
|
77
|
+
return (
|
|
78
|
+
"<script>if (!window.vegaEmbed) { (function () {\n" + bundle + "\n})(); }</script>",
|
|
79
|
+
True,
|
|
80
|
+
)
|
|
81
|
+
return cdn_script_tags(), False
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def vega_embed_call(element_id: str, spec_json: str) -> str:
|
|
85
|
+
"""JavaScript statement rendering ``spec_json`` into the element with ``element_id``.
|
|
86
|
+
|
|
87
|
+
Works immediately when ``window.vegaEmbed`` is already defined (inline offline bundle),
|
|
88
|
+
and polls briefly if scripts are still loading asynchronously from a CDN.
|
|
89
|
+
"""
|
|
90
|
+
target = json.dumps("#" + element_id)
|
|
91
|
+
safe_spec = script_safe_json(spec_json)
|
|
92
|
+
return (
|
|
93
|
+
"(function(){"
|
|
94
|
+
f"var el={target},spec={safe_spec},tries=0;"
|
|
95
|
+
"function run(){"
|
|
96
|
+
"if(window.vegaEmbed){"
|
|
97
|
+
"window.vegaEmbed(el,spec,{actions:true}).catch(function(err){"
|
|
98
|
+
"var n=document.querySelector(el);"
|
|
99
|
+
"if(n){n.innerHTML='<div style=\"color:#991B1B;background:#FEF2F2;padding:8px 12px;"
|
|
100
|
+
"border-radius:6px;font-size:12px;\">Chart render error: '+String(err)+'</div>';}"
|
|
101
|
+
"});"
|
|
102
|
+
"}else if(tries++<100){setTimeout(run,50);}"
|
|
103
|
+
"else{var n=document.querySelector(el);"
|
|
104
|
+
"if(n){n.innerHTML='<div style=\"color:#92400E;background:#FFFBEB;padding:8px 12px;"
|
|
105
|
+
'border-radius:6px;font-size:12px;">Vega-Embed failed to load. Check network access '
|
|
106
|
+
"or install vl-convert-python for offline rendering.</div>';}}"
|
|
107
|
+
"}run();})();"
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
OFFLINE_HELP = (
|
|
112
|
+
"Charts in this file load their JavaScript from the internet (cdn.jsdelivr.net) and "
|
|
113
|
+
"will be blank offline. Install vl-convert-python and rebuild to embed it."
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
PRINT_CSS = """
|
|
117
|
+
@media print {
|
|
118
|
+
@page { margin: 14mm; }
|
|
119
|
+
body { background: #FFFFFF !important; color: #000000; }
|
|
120
|
+
.no-print, .vega-actions { display: none !important; }
|
|
121
|
+
.card, section, .chart-wrap, .chart-box, .alert { break-inside: avoid; box-shadow: none !important; }
|
|
122
|
+
header.hero { background: #FFFFFF !important; color: #000000 !important; border: 1px solid #CBD5E1; }
|
|
123
|
+
header.hero .hero-meta, header.hero .badge { color: #000000 !important; background: none !important; }
|
|
124
|
+
a { color: inherit; text-decoration: none; }
|
|
125
|
+
.chart-wrap, .table-scroll { overflow: visible !important; }
|
|
126
|
+
}
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
# Expand collapsed data tables when printing / saving as PDF.
|
|
130
|
+
PRINT_JS = (
|
|
131
|
+
"window.addEventListener('beforeprint', function () {"
|
|
132
|
+
" document.querySelectorAll('details').forEach(function (d) { d.open = true; }); });"
|
|
133
|
+
)
|
textray/core/result.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""Unified result and warning containers returned by all textray diagnostics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import json
|
|
7
|
+
import uuid
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
import altair as alt
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
from textray.core.html_assets import (
|
|
16
|
+
OFFLINE_HELP,
|
|
17
|
+
PRINT_CSS,
|
|
18
|
+
vega_embed_call,
|
|
19
|
+
vega_script_block,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
Severity = Literal["info", "warning", "critical"]
|
|
23
|
+
|
|
24
|
+
_SEVERITY_COLORS: dict[str, tuple[str, str, str]] = {
|
|
25
|
+
"critical": ("#FEF2F2", "#DC2626", "#991B1B"),
|
|
26
|
+
"warning": ("#FFFBEB", "#D97706", "#92400E"),
|
|
27
|
+
"info": ("#EFF6FF", "#2563EB", "#1E40AF"),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class DiagnosticWarning:
|
|
33
|
+
"""Structured diagnostic finding or leakage/artifact alert."""
|
|
34
|
+
|
|
35
|
+
severity: Severity
|
|
36
|
+
category: str
|
|
37
|
+
message: str
|
|
38
|
+
evidence: dict[str, Any] = field(default_factory=dict)
|
|
39
|
+
|
|
40
|
+
def to_dict(self) -> dict[str, Any]:
|
|
41
|
+
return {
|
|
42
|
+
"severity": self.severity,
|
|
43
|
+
"category": self.category,
|
|
44
|
+
"message": self.message,
|
|
45
|
+
"evidence": self.evidence,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class DiagnosticResult:
|
|
51
|
+
"""Unified return object for every textray diagnostic method.
|
|
52
|
+
|
|
53
|
+
Attributes
|
|
54
|
+
----------
|
|
55
|
+
name:
|
|
56
|
+
Machine-readable diagnostic identifier (e.g. ``"dividing_terms"``).
|
|
57
|
+
title:
|
|
58
|
+
Human-readable title shown in notebooks and HTML reports.
|
|
59
|
+
chart:
|
|
60
|
+
Interactive Altair chart (``None`` for table-only diagnostics like ``context``).
|
|
61
|
+
data:
|
|
62
|
+
Primary tidy :class:`pandas.DataFrame` backing the diagnostic.
|
|
63
|
+
metrics:
|
|
64
|
+
Key scalar summary metrics computed by the diagnostic.
|
|
65
|
+
warnings:
|
|
66
|
+
Structured :class:`DiagnosticWarning` alerts triggered by this check.
|
|
67
|
+
extras:
|
|
68
|
+
Auxiliary DataFrames (e.g. trimmed outliers, leaf snippets, duplicate pairs).
|
|
69
|
+
description:
|
|
70
|
+
Short explanatory note shown below the title in reports and notebooks.
|
|
71
|
+
error:
|
|
72
|
+
Set when the diagnostic failed inside :meth:`TextRay.report`; the report shows an
|
|
73
|
+
error card for it instead of stopping.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
name: str
|
|
77
|
+
title: str
|
|
78
|
+
chart: alt.TopLevelMixin | None = None
|
|
79
|
+
data: pd.DataFrame = field(default_factory=pd.DataFrame)
|
|
80
|
+
metrics: dict[str, Any] = field(default_factory=dict)
|
|
81
|
+
warnings: list[DiagnosticWarning] = field(default_factory=list)
|
|
82
|
+
extras: dict[str, pd.DataFrame] = field(default_factory=dict)
|
|
83
|
+
description: str = ""
|
|
84
|
+
error: str | None = None
|
|
85
|
+
|
|
86
|
+
def __repr__(self) -> str:
|
|
87
|
+
n_rows, n_cols = self.data.shape
|
|
88
|
+
n_warn = len(self.warnings)
|
|
89
|
+
chart_status = "yes" if self.chart is not None else "no"
|
|
90
|
+
metric_preview = ", ".join(
|
|
91
|
+
f"{k}={_format_metric_value(v)}" for k, v in list(self.metrics.items())[:4]
|
|
92
|
+
)
|
|
93
|
+
return (
|
|
94
|
+
f"DiagnosticResult(name={self.name!r}, rows={n_rows}x{n_cols}, "
|
|
95
|
+
f"chart={chart_status}, warnings={n_warn}"
|
|
96
|
+
+ (f", {metric_preview}" if metric_preview else "")
|
|
97
|
+
+ ")"
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
def chart_spec(self) -> dict[str, Any] | None:
|
|
101
|
+
"""Return the Vega-Lite specification dictionary if a chart is present."""
|
|
102
|
+
if self.chart is None:
|
|
103
|
+
return None
|
|
104
|
+
return self.chart.to_dict()
|
|
105
|
+
|
|
106
|
+
def save(self, path: str | Path, **kwargs: Any) -> Path:
|
|
107
|
+
"""Save the diagnostic result to disk.
|
|
108
|
+
|
|
109
|
+
Supported extensions:
|
|
110
|
+
- ``.html``: Self-contained interactive HTML page.
|
|
111
|
+
- ``.json``: Vega-Lite JSON specification (requires a chart).
|
|
112
|
+
- ``.csv``: Primary ``data`` table as CSV.
|
|
113
|
+
- ``.png`` / ``.svg`` / ``.pdf``: Static chart export (requires ``vl-convert-python``).
|
|
114
|
+
"""
|
|
115
|
+
out = Path(path)
|
|
116
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
117
|
+
suffix = out.suffix.lower()
|
|
118
|
+
|
|
119
|
+
if suffix == ".csv":
|
|
120
|
+
self.data.to_csv(out, index=False, **kwargs)
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
if suffix == ".html":
|
|
124
|
+
out.write_text(self._to_standalone_html(), encoding="utf-8")
|
|
125
|
+
return out
|
|
126
|
+
|
|
127
|
+
if suffix == ".json":
|
|
128
|
+
if self.chart is None:
|
|
129
|
+
payload = {
|
|
130
|
+
"name": self.name,
|
|
131
|
+
"title": self.title,
|
|
132
|
+
"metrics": self.metrics,
|
|
133
|
+
"warnings": [w.to_dict() for w in self.warnings],
|
|
134
|
+
"data": self.data.to_dict(orient="records"),
|
|
135
|
+
}
|
|
136
|
+
out.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8")
|
|
137
|
+
else:
|
|
138
|
+
out.write_text(self.chart.to_json(indent=2), encoding="utf-8")
|
|
139
|
+
return out
|
|
140
|
+
|
|
141
|
+
if suffix in {".png", ".svg", ".pdf"}:
|
|
142
|
+
if self.chart is None:
|
|
143
|
+
raise ValueError(
|
|
144
|
+
f"Cannot export {suffix} because diagnostic '{self.name}' has no chart."
|
|
145
|
+
)
|
|
146
|
+
try:
|
|
147
|
+
self.chart.save(str(out), **kwargs)
|
|
148
|
+
except Exception as exc: # pragma: no cover - depends on optional vl-convert
|
|
149
|
+
raise RuntimeError(
|
|
150
|
+
f"Exporting to {suffix} requires `vl-convert-python`. "
|
|
151
|
+
"Install it with: `pip install textray[export]`"
|
|
152
|
+
) from exc
|
|
153
|
+
return out
|
|
154
|
+
|
|
155
|
+
raise ValueError(
|
|
156
|
+
f"Unsupported export extension '{suffix}'. "
|
|
157
|
+
"Use one of: .html, .json, .csv, .png, .svg, .pdf."
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def _render_warnings_html(self) -> str:
|
|
161
|
+
if not self.warnings:
|
|
162
|
+
return ""
|
|
163
|
+
items = []
|
|
164
|
+
for w in self.warnings:
|
|
165
|
+
bg, border, fg = _SEVERITY_COLORS.get(w.severity, _SEVERITY_COLORS["info"])
|
|
166
|
+
badge = html.escape(w.severity.upper())
|
|
167
|
+
cat = html.escape(w.category)
|
|
168
|
+
msg = html.escape(w.message)
|
|
169
|
+
items.append(
|
|
170
|
+
f'<div style="background:{bg};border-left:4px solid {border};color:{fg};'
|
|
171
|
+
f'padding:8px 12px;margin:6px 0;border-radius:4px;font-size:13px;">'
|
|
172
|
+
f"<strong>[{badge}] {cat}:</strong> {msg}</div>"
|
|
173
|
+
)
|
|
174
|
+
return "".join(items)
|
|
175
|
+
|
|
176
|
+
def _render_metrics_html(self) -> str:
|
|
177
|
+
if not self.metrics:
|
|
178
|
+
return ""
|
|
179
|
+
pills = []
|
|
180
|
+
for k, v in self.metrics.items():
|
|
181
|
+
label = html.escape(k.replace("_", " ").title())
|
|
182
|
+
val = html.escape(_format_metric_value(v))
|
|
183
|
+
pills.append(
|
|
184
|
+
'<div style="background:#F8FAFC;border:1px solid #E2E8F0;border-radius:6px;'
|
|
185
|
+
'padding:6px 10px;min-width:110px;">'
|
|
186
|
+
f'<div style="font-size:11px;color:#64748B;text-transform:uppercase;'
|
|
187
|
+
f'letter-spacing:0.04em;">{label}</div>'
|
|
188
|
+
f'<div style="font-size:15px;font-weight:600;color:#0F172A;">{val}</div>'
|
|
189
|
+
"</div>"
|
|
190
|
+
)
|
|
191
|
+
return (
|
|
192
|
+
'<div style="display:flex;flex-wrap:wrap;gap:8px;margin:10px 0 14px 0;">'
|
|
193
|
+
+ "".join(pills)
|
|
194
|
+
+ "</div>"
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def _render_table_html(self, max_rows: int = 25) -> str:
|
|
198
|
+
if self.data.empty:
|
|
199
|
+
return (
|
|
200
|
+
'<div style="background:#FFFFFF;color:#64748B;border:1px solid #E2E8F0;'
|
|
201
|
+
'border-radius:8px;padding:12px 16px;font-size:13px;">No rows to display.</div>'
|
|
202
|
+
)
|
|
203
|
+
preview = self.data.head(max_rows)
|
|
204
|
+
table_html = preview.to_html(index=False, border=0, classes="textray-table", escape=True)
|
|
205
|
+
note = ""
|
|
206
|
+
if len(self.data) > max_rows:
|
|
207
|
+
note = (
|
|
208
|
+
f'<p style="color:#64748B;font-size:12px;margin:8px 0 0 0;">'
|
|
209
|
+
f"Showing {max_rows} of {len(self.data):,} rows. Access full table via <code>.data</code>.</p>"
|
|
210
|
+
)
|
|
211
|
+
return (
|
|
212
|
+
"<style>"
|
|
213
|
+
".textray-table{border-collapse:collapse;width:100%;font-size:13px;background:#FFFFFF;}"
|
|
214
|
+
".textray-table th{background:#F1F5F9;color:#0F172A;text-align:left;padding:7px 10px;"
|
|
215
|
+
"border-bottom:2px solid #CBD5E1;font-weight:600;}"
|
|
216
|
+
".textray-table td{background:#FFFFFF;padding:6px 10px;border-bottom:1px solid #E2E8F0;"
|
|
217
|
+
"color:#1E293B;vertical-align:top;}"
|
|
218
|
+
".textray-table tr:hover td{background:#F8FAFC;}"
|
|
219
|
+
"</style>"
|
|
220
|
+
'<div style="background:#FFFFFF;color:#0F172A;border:1px solid #E2E8F0;'
|
|
221
|
+
'border-radius:8px;padding:12px 14px;overflow-x:auto;">'
|
|
222
|
+
f"{table_html}{note}</div>"
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
def _header_html(self, *, as_card: bool = True) -> str:
|
|
226
|
+
"""Title, description, warnings and metrics (everything except the chart/table)."""
|
|
227
|
+
desc = (
|
|
228
|
+
f'<p style="margin:0 0 8px 0;color:#475569;font-size:13px;">'
|
|
229
|
+
f"{html.escape(self.description)}</p>"
|
|
230
|
+
if self.description
|
|
231
|
+
else ""
|
|
232
|
+
)
|
|
233
|
+
card_style = (
|
|
234
|
+
"font-family:system-ui,-apple-system,sans-serif;background:#FFFFFF;color:#0F172A;"
|
|
235
|
+
"border:1px solid #E2E8F0;border-radius:8px;padding:14px 16px;margin-bottom:8px;"
|
|
236
|
+
if as_card
|
|
237
|
+
else "font-family:system-ui,-apple-system,sans-serif;color:#0F172A;"
|
|
238
|
+
)
|
|
239
|
+
return (
|
|
240
|
+
f'<div style="{card_style}">'
|
|
241
|
+
f'<h3 style="margin:0 0 4px 0;font-size:17px;color:#0F172A;">{html.escape(self.title)}</h3>'
|
|
242
|
+
f"{desc}{self._render_warnings_html()}{self._render_metrics_html()}</div>"
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
def _ipython_display_(self) -> None:
|
|
246
|
+
"""Notebook display for VS Code code cells, JupyterLab, and classic Notebook.
|
|
247
|
+
|
|
248
|
+
- If the user has explicitly selected a non-default Altair renderer (e.g.
|
|
249
|
+
``alt.renderers.enable("svg")`` or ``"png"``), displays the styled header card
|
|
250
|
+
and delegates the chart to Altair.
|
|
251
|
+
- Otherwise, renders a single self-contained light card using the bundled offline
|
|
252
|
+
Vega/Vega-Lite JavaScript (from ``vl-convert-python``), so charts render reliably
|
|
253
|
+
in VS Code Dark/Light themes with zero internet access.
|
|
254
|
+
"""
|
|
255
|
+
from IPython.display import HTML, display
|
|
256
|
+
|
|
257
|
+
if self.chart is None:
|
|
258
|
+
display(HTML(self._header_html(as_card=True) + self._render_table_html()))
|
|
259
|
+
return
|
|
260
|
+
|
|
261
|
+
active_renderer = getattr(alt.renderers, "active", "default")
|
|
262
|
+
if active_renderer != "default":
|
|
263
|
+
display(HTML(self._header_html(as_card=True)))
|
|
264
|
+
display(self.chart)
|
|
265
|
+
return
|
|
266
|
+
|
|
267
|
+
script_block, offline = vega_script_block(inline=True)
|
|
268
|
+
if offline:
|
|
269
|
+
display(HTML(self._render_inline_card_html(script_block)))
|
|
270
|
+
else:
|
|
271
|
+
display(HTML(self._header_html(as_card=True)))
|
|
272
|
+
display(self.chart)
|
|
273
|
+
|
|
274
|
+
def _render_inline_card_html(self, script_block: str) -> str:
|
|
275
|
+
assert self.chart is not None
|
|
276
|
+
div_id = f"textray-chart-{uuid.uuid4().hex[:10]}"
|
|
277
|
+
return (
|
|
278
|
+
'<div style="font-family:system-ui,-apple-system,sans-serif;background:#FFFFFF;'
|
|
279
|
+
'color:#0F172A;border:1px solid #E2E8F0;border-radius:8px;padding:14px 16px;">'
|
|
280
|
+
f"{self._header_html(as_card=False)}"
|
|
281
|
+
f'<div id="{div_id}" style="margin-top:8px;overflow-x:auto;"></div>'
|
|
282
|
+
f"{script_block}"
|
|
283
|
+
f"<script>{vega_embed_call(div_id, self.chart.to_json())}</script>"
|
|
284
|
+
"</div>"
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def _repr_html_(self) -> str:
|
|
288
|
+
"""Self-contained HTML for front-ends that don't use IPython's display hooks."""
|
|
289
|
+
if self.chart is None:
|
|
290
|
+
return self._header_html(as_card=True) + self._render_table_html()
|
|
291
|
+
script_block, _ = vega_script_block(inline=True)
|
|
292
|
+
return self._render_inline_card_html(script_block)
|
|
293
|
+
|
|
294
|
+
def _to_standalone_html(self, inline_js: bool = True) -> str:
|
|
295
|
+
div_id = f"textray-chart-{uuid.uuid4().hex[:10]}"
|
|
296
|
+
script_block, offline = vega_script_block(inline=inline_js)
|
|
297
|
+
chart_block = ""
|
|
298
|
+
if self.chart is not None:
|
|
299
|
+
chart_block = (
|
|
300
|
+
f'<div id="{div_id}" class="chart-box"></div>'
|
|
301
|
+
f"<script>{vega_embed_call(div_id, self.chart.to_json())}</script>"
|
|
302
|
+
)
|
|
303
|
+
notice = (
|
|
304
|
+
""
|
|
305
|
+
if offline or self.chart is None
|
|
306
|
+
else f'<p class="no-print" style="color:#92400E;font-size:13px;">{OFFLINE_HELP}</p>'
|
|
307
|
+
)
|
|
308
|
+
table_block = self._render_table_html(max_rows=50)
|
|
309
|
+
return f"""<!DOCTYPE html>
|
|
310
|
+
<html lang="en">
|
|
311
|
+
<head>
|
|
312
|
+
<meta charset="utf-8" />
|
|
313
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
314
|
+
<title>{html.escape(self.title)} — textray</title>
|
|
315
|
+
{script_block}
|
|
316
|
+
<style>
|
|
317
|
+
body {{ font-family: system-ui, -apple-system, sans-serif; max-width: 1180px; margin: 28px auto;
|
|
318
|
+
padding: 0 24px; color: #0F172A; background: #FFFFFF; line-height: 1.5; }}
|
|
319
|
+
.chart-box {{ margin: 18px 0 24px 0; overflow-x: auto; }}
|
|
320
|
+
h1 {{ font-size: 22px; margin-bottom: 4px; }}
|
|
321
|
+
h2 {{ font-size: 16px; margin-top: 24px; color: #334155; }}
|
|
322
|
+
{PRINT_CSS}
|
|
323
|
+
</style>
|
|
324
|
+
</head>
|
|
325
|
+
<body>
|
|
326
|
+
<h1>{html.escape(self.title)}</h1>
|
|
327
|
+
<p style="color:#475569;margin-top:0;">{html.escape(self.description)}</p>
|
|
328
|
+
{notice}
|
|
329
|
+
{self._render_warnings_html()}
|
|
330
|
+
{self._render_metrics_html()}
|
|
331
|
+
{chart_block}
|
|
332
|
+
<h2>Data Table</h2>
|
|
333
|
+
{table_block}
|
|
334
|
+
</body>
|
|
335
|
+
</html>
|
|
336
|
+
"""
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _format_metric_value(value: Any) -> str:
|
|
340
|
+
if isinstance(value, bool):
|
|
341
|
+
return str(value)
|
|
342
|
+
if isinstance(value, int):
|
|
343
|
+
return f"{value:,}"
|
|
344
|
+
if isinstance(value, float):
|
|
345
|
+
if abs(value) >= 100:
|
|
346
|
+
return f"{value:,.1f}"
|
|
347
|
+
return f"{value:.3f}"
|
|
348
|
+
return str(value)
|