ectype-data 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.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""The profile report: a self-contained HTML page describing a fingerprint (ADR-0016).
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
import ectype
|
|
6
|
+
|
|
7
|
+
rep = ectype.report("customers.dfp") # or a loaded Fingerprint
|
|
8
|
+
print(rep.summary())
|
|
9
|
+
rep.to_html("customers-report.html")
|
|
10
|
+
|
|
11
|
+
The page is built from the fingerprint alone: :mod:`ectype.reporting.adapter` turns it into a
|
|
12
|
+
plain :class:`~ectype.reporting.view.ReportView`, :mod:`~ectype.reporting.findings` says what is
|
|
13
|
+
worth saying and :mod:`~ectype.reporting.render` draws the page. This module joins them and
|
|
14
|
+
keeps the page within a size budget by drawing columns in less detail.
|
|
15
|
+
|
|
16
|
+
Two fingerprints give a comparison page instead (what drifted between them, side by side)::
|
|
17
|
+
|
|
18
|
+
from ectype.reporting import compare_report
|
|
19
|
+
|
|
20
|
+
compare_report("january.dfp", "february.dfp").to_html("jan-feb-report.html")
|
|
21
|
+
|
|
22
|
+
Engine imports stay lazy and go through the adapter only (``tests/report/
|
|
23
|
+
test_report_boundary.py``): ``import ectype.reporting`` loads no part of the engine.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
import math
|
|
30
|
+
import os
|
|
31
|
+
import sys
|
|
32
|
+
from collections.abc import Sequence
|
|
33
|
+
from dataclasses import asdict, dataclass, field
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
36
|
+
|
|
37
|
+
from ectype.reporting import findings
|
|
38
|
+
from ectype.reporting import render as _render
|
|
39
|
+
from ectype.reporting.findings import Alert
|
|
40
|
+
from ectype.reporting.select import select_columns
|
|
41
|
+
from ectype.reporting.view import VIEW_VERSION, DriftView, ReportView
|
|
42
|
+
|
|
43
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
44
|
+
from ectype.fingerprint.core import Fingerprint
|
|
45
|
+
|
|
46
|
+
#: the page's default size budget, in UTF-8 bytes
|
|
47
|
+
DEFAULT_MAX_BYTES = 5_000_000
|
|
48
|
+
#: the smallest budget accepted
|
|
49
|
+
MIN_MAX_BYTES = 100_000
|
|
50
|
+
#: values of ``detail``: ``auto`` chooses from the number of columns and the budget
|
|
51
|
+
DETAIL_CHOICES = ("auto", "full", "compact", "list")
|
|
52
|
+
#: ``auto``: full detail up to this many columns
|
|
53
|
+
FULL_MAX_COLUMNS = 200
|
|
54
|
+
#: ``auto``: compact detail up to this many columns, a list beyond
|
|
55
|
+
COMPACT_MAX_COLUMNS = 1000
|
|
56
|
+
|
|
57
|
+
_LEVELS = _render.DETAILS # ("full", "compact", "list"), most detailed first
|
|
58
|
+
_LEVEL_WORDS = {
|
|
59
|
+
"compact": "in compact detail",
|
|
60
|
+
"list": "as one row of a list, without a chart,",
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _budget(n: int) -> str:
|
|
65
|
+
"""A budget in words: ``5 MB``, ``2.5 MB``, ``100 KB``."""
|
|
66
|
+
return f"{n / 1_000_000:g} MB" if n >= 1_000_000 else f"{n / 1000:g} KB"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _mb(n: int, budget: int | None = None) -> str:
|
|
70
|
+
"""A page size in words (``7.2 MB``, ``312 KB``), one decimal finer when it would read the
|
|
71
|
+
same as ``budget``."""
|
|
72
|
+
unit, name, places = (1_000_000, "MB", 1) if n >= 1_000_000 else (1000, "KB", 0)
|
|
73
|
+
shown = round(n / unit, places)
|
|
74
|
+
if budget is not None and n > budget and shown * unit <= budget:
|
|
75
|
+
places += 2 if name == "MB" else 1
|
|
76
|
+
return f"{n / unit:.{places}f} {name}"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _auto_level(n_columns: int) -> str:
|
|
80
|
+
if n_columns <= FULL_MAX_COLUMNS:
|
|
81
|
+
return "full"
|
|
82
|
+
if n_columns <= COMPACT_MAX_COLUMNS:
|
|
83
|
+
return "compact"
|
|
84
|
+
return "list"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _level_warning(level: str, n_columns: int, *, by_size: tuple[str, int] | None,
|
|
88
|
+
max_bytes: int, subject: str) -> str:
|
|
89
|
+
"""The sentence that says why an ``auto`` page is drawn below full detail.
|
|
90
|
+
|
|
91
|
+
``by_size`` is ``(level, size)`` of the page one level up when that page was over the
|
|
92
|
+
budget, or ``None`` when the number of columns alone set the level."""
|
|
93
|
+
how = _LEVEL_WORDS.get(level, f"in {level} detail")
|
|
94
|
+
if by_size is not None:
|
|
95
|
+
why = (f"At {by_size[0]} detail the page would be {_mb(by_size[1], max_bytes)}, over the "
|
|
96
|
+
f"{_budget(max_bytes)} budget, so each column is drawn {how} instead.")
|
|
97
|
+
else:
|
|
98
|
+
why = (f"{subject} has {n_columns:,} columns, so each column is drawn {how} to keep "
|
|
99
|
+
"the page small.")
|
|
100
|
+
return (f"{why} For full detail on some of them, select them (`ectype report FILE "
|
|
101
|
+
"--columns A,B,C`, or `columns=[...]`), or force it with `--detail full`.")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _size_warning(size: int, max_bytes: int, level: str) -> str:
|
|
105
|
+
advice = ("Report on fewer columns with `--columns`, or raise the budget with "
|
|
106
|
+
"`--max-bytes`." if level == "list" else
|
|
107
|
+
"Report on fewer columns with `--columns`, or use `--detail list`.")
|
|
108
|
+
return f"The page is {_mb(size, max_bytes)}, over the {_budget(max_bytes)} budget. {advice}"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _render_within(view: ReportView, detail: str, max_bytes: int, *,
|
|
112
|
+
alerts: Sequence[Alert] | None = None, title: str | None = None,
|
|
113
|
+
notices: Sequence[str] = (), subject: str = "This table",
|
|
114
|
+
) -> tuple[str, str, list[str]]:
|
|
115
|
+
"""Render ``view`` within ``max_bytes``: ``(page, level rendered, warnings)``.
|
|
116
|
+
|
|
117
|
+
``detail="auto"`` starts at the level the number of columns calls for and steps down while
|
|
118
|
+
the page is over the budget and a lower level exists. A forced level is rendered as asked.
|
|
119
|
+
Each warning is also shown on the page, after ``notices``.
|
|
120
|
+
"""
|
|
121
|
+
n = len(view.columns)
|
|
122
|
+
|
|
123
|
+
def draw(level: str, warns: Sequence[str]) -> tuple[str, int]:
|
|
124
|
+
page = _render.render(view, detail=level, alerts=alerts, title=title,
|
|
125
|
+
notices=[*notices, *warns])
|
|
126
|
+
return page, len(page.encode("utf-8"))
|
|
127
|
+
|
|
128
|
+
if detail != "auto":
|
|
129
|
+
page, size = draw(detail, [])
|
|
130
|
+
if size <= max_bytes:
|
|
131
|
+
return page, detail, []
|
|
132
|
+
warns = [_size_warning(size, max_bytes, detail)]
|
|
133
|
+
page, size = draw(detail, warns)
|
|
134
|
+
return page, detail, [_size_warning(size, max_bytes, detail)]
|
|
135
|
+
|
|
136
|
+
level = _auto_level(n)
|
|
137
|
+
too_big: tuple[str, int] | None = None # the level above and its size, once over
|
|
138
|
+
while True:
|
|
139
|
+
warns = ([] if level == "full" else
|
|
140
|
+
[_level_warning(level, n, by_size=too_big, max_bytes=max_bytes,
|
|
141
|
+
subject=subject)])
|
|
142
|
+
page, size = draw(level, warns)
|
|
143
|
+
lower = _LEVELS.index(level) + 1
|
|
144
|
+
if size <= max_bytes or lower >= len(_LEVELS):
|
|
145
|
+
break
|
|
146
|
+
too_big = (level, size)
|
|
147
|
+
level = _LEVELS[lower]
|
|
148
|
+
if size > max_bytes:
|
|
149
|
+
warns = [*warns, _size_warning(size, max_bytes, level)]
|
|
150
|
+
page, size = draw(level, warns)
|
|
151
|
+
warns[-1] = _size_warning(size, max_bytes, level)
|
|
152
|
+
return page, level, list(warns)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _finite(x: Any) -> Any:
|
|
156
|
+
"""``x`` with every non-finite float replaced by ``None`` (strict JSON)."""
|
|
157
|
+
if isinstance(x, float):
|
|
158
|
+
return x if math.isfinite(x) else None
|
|
159
|
+
if isinstance(x, dict):
|
|
160
|
+
return {k: _finite(val) for k, val in x.items()}
|
|
161
|
+
if isinstance(x, list | tuple):
|
|
162
|
+
return [_finite(val) for val in x]
|
|
163
|
+
return x
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass
|
|
167
|
+
class ProfileReport:
|
|
168
|
+
"""A profile report: the view of a fingerprint, its alerts and the page drawn from them.
|
|
169
|
+
|
|
170
|
+
``detail`` is the level actually rendered (``"full"``, ``"compact"`` or ``"list"``);
|
|
171
|
+
``warnings`` are sentences about how the page was cut to its budget (also shown on it).
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
view: ReportView
|
|
175
|
+
alerts: list[Alert] = field(default_factory=list)
|
|
176
|
+
detail: str = "full"
|
|
177
|
+
warnings: list[str] = field(default_factory=list)
|
|
178
|
+
title: str | None = field(default=None, repr=False)
|
|
179
|
+
notices: list[str] = field(default_factory=list, repr=False)
|
|
180
|
+
_html: str | None = field(default=None, init=False, repr=False, compare=False)
|
|
181
|
+
|
|
182
|
+
def summary(self, *, warnings: bool = True) -> str:
|
|
183
|
+
"""The short terminal summary, then one ``warning: ...`` line per warning (left out
|
|
184
|
+
with ``warnings=False``)."""
|
|
185
|
+
lines = [findings.summary(self.view, self.alerts)]
|
|
186
|
+
if warnings:
|
|
187
|
+
lines += [f"warning: {w}" for w in self.warnings]
|
|
188
|
+
return "\n".join(lines)
|
|
189
|
+
|
|
190
|
+
def to_html_string(self) -> str:
|
|
191
|
+
"""The page as one HTML document (rendered once, then cached)."""
|
|
192
|
+
if self._html is None:
|
|
193
|
+
self._html = _render.render(self.view, detail=self.detail, alerts=self.alerts,
|
|
194
|
+
title=self.title,
|
|
195
|
+
notices=[*self.notices, *self.warnings])
|
|
196
|
+
return self._html
|
|
197
|
+
|
|
198
|
+
@property
|
|
199
|
+
def size_bytes(self) -> int:
|
|
200
|
+
"""Size of the page in UTF-8 bytes."""
|
|
201
|
+
return len(self.to_html_string().encode("utf-8"))
|
|
202
|
+
|
|
203
|
+
def to_html(self, path: str | os.PathLike[str]) -> Path:
|
|
204
|
+
"""Write the page (UTF-8), creating parent folders; returns the path."""
|
|
205
|
+
p = Path(path)
|
|
206
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
207
|
+
p.write_text(self.to_html_string(), encoding="utf-8")
|
|
208
|
+
return p
|
|
209
|
+
|
|
210
|
+
def to_dict(self) -> dict[str, Any]:
|
|
211
|
+
"""The report as plain data (strict JSON: no NaN or infinity)."""
|
|
212
|
+
return _finite({
|
|
213
|
+
"report": "profile",
|
|
214
|
+
"view_version": getattr(self.view, "view_version", VIEW_VERSION),
|
|
215
|
+
"detail": self.detail,
|
|
216
|
+
"warnings": list(self.warnings),
|
|
217
|
+
"alerts": [{**asdict(a), "text": a.text} for a in self.alerts],
|
|
218
|
+
"view": self.view.to_dict(),
|
|
219
|
+
})
|
|
220
|
+
|
|
221
|
+
def to_json(self, path: str | os.PathLike[str], *, indent: int = 2) -> Path:
|
|
222
|
+
"""Write :meth:`to_dict` as JSON (UTF-8), creating parent folders; returns the path."""
|
|
223
|
+
p = Path(path)
|
|
224
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
225
|
+
p.write_text(json.dumps(self.to_dict(), indent=indent, ensure_ascii=False,
|
|
226
|
+
allow_nan=False) + "\n", encoding="utf-8")
|
|
227
|
+
return p
|
|
228
|
+
|
|
229
|
+
def __str__(self) -> str:
|
|
230
|
+
return self.summary()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _view_of(source: Any) -> ReportView:
|
|
234
|
+
if isinstance(source, str | os.PathLike):
|
|
235
|
+
from ectype.reporting.adapter import load_view
|
|
236
|
+
|
|
237
|
+
return load_view(source)
|
|
238
|
+
# A Fingerprint can only exist once its module is loaded: look it up without importing it.
|
|
239
|
+
core = sys.modules.get("ectype.fingerprint.core")
|
|
240
|
+
cls = getattr(core, "Fingerprint", None) if core is not None else None
|
|
241
|
+
if isinstance(cls, type) and isinstance(source, cls):
|
|
242
|
+
from ectype.reporting.adapter import build_view
|
|
243
|
+
|
|
244
|
+
return build_view(cast("Fingerprint", source))
|
|
245
|
+
raise TypeError("report() takes a Fingerprint or the path to a .dfp file, not "
|
|
246
|
+
f"{type(source).__module__}.{type(source).__qualname__}")
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def report(source: Fingerprint | str | os.PathLike[str], *, detail: str = "auto",
|
|
250
|
+
columns: Sequence[str] | None = None, max_bytes: int = DEFAULT_MAX_BYTES,
|
|
251
|
+
title: str | None = None) -> ProfileReport:
|
|
252
|
+
"""The profile report of a fingerprint (a loaded :class:`Fingerprint` or a ``.dfp`` path).
|
|
253
|
+
|
|
254
|
+
``detail`` is ``"auto"`` (full detail up to :data:`FULL_MAX_COLUMNS` columns, compact up
|
|
255
|
+
to :data:`COMPACT_MAX_COLUMNS`, a list beyond, and one level lower while the page is over
|
|
256
|
+
``max_bytes``) or a level to render as asked: ``"full"``, ``"compact"`` or ``"list"``.
|
|
257
|
+
``columns`` reports on a selection of the columns. ``title`` replaces the page's heading.
|
|
258
|
+
|
|
259
|
+
Raises :class:`ValueError` for an unknown ``detail``, a ``max_bytes`` below 100,000 or an
|
|
260
|
+
unknown column; :class:`TypeError` for a source that is neither a fingerprint nor a path.
|
|
261
|
+
Errors of loading a ``.dfp`` (:class:`~ectype.errors.EctypeError`) propagate.
|
|
262
|
+
"""
|
|
263
|
+
if detail not in DETAIL_CHOICES:
|
|
264
|
+
raise ValueError(f"detail must be one of {', '.join(DETAIL_CHOICES)}, not {detail!r}")
|
|
265
|
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int):
|
|
266
|
+
raise TypeError(f"max_bytes must be an integer, not {type(max_bytes).__name__}")
|
|
267
|
+
if max_bytes < MIN_MAX_BYTES:
|
|
268
|
+
raise ValueError(f"max_bytes must be at least {MIN_MAX_BYTES:,}, not {max_bytes:,}")
|
|
269
|
+
if title is not None and not isinstance(title, str):
|
|
270
|
+
raise TypeError(f"title must be a string, not {type(title).__name__}")
|
|
271
|
+
if columns is not None and isinstance(columns, str):
|
|
272
|
+
raise TypeError("columns must be a list of column names, not a single string")
|
|
273
|
+
|
|
274
|
+
view = _view_of(source)
|
|
275
|
+
notices: list[str] = []
|
|
276
|
+
subject = "This table"
|
|
277
|
+
if columns is not None:
|
|
278
|
+
total = view.overview.columns if view.overview.columns else len(view.columns)
|
|
279
|
+
view = select_columns(view, list(columns))
|
|
280
|
+
notices.append(f"Showing {len(view.columns):,} of {total:,} columns.")
|
|
281
|
+
subject = "This selection"
|
|
282
|
+
alerts = findings.alerts(view)
|
|
283
|
+
page, level, warns = _render_within(view, detail, max_bytes, alerts=alerts, title=title,
|
|
284
|
+
notices=notices, subject=subject)
|
|
285
|
+
out = ProfileReport(view=view, alerts=alerts, detail=level, warnings=warns, title=title,
|
|
286
|
+
notices=notices)
|
|
287
|
+
out._html = page
|
|
288
|
+
return out
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
#: charts drawn for at most this many changed columns, tried in turn while a comparison page
|
|
292
|
+
#: is over its budget (``None``: every changed column has a chart)
|
|
293
|
+
_CARD_STEPS: tuple[int | None, ...] = (None, 200, 100, 50, 20, 0)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@dataclass
|
|
297
|
+
class ComparisonReport:
|
|
298
|
+
"""A comparison report: the view of two fingerprints side by side and the page drawn from
|
|
299
|
+
it. The first fingerprint is the reference, the second the one compared with it.
|
|
300
|
+
|
|
301
|
+
``charted`` is the number of changed columns drawn with a chart (``None``: all of them);
|
|
302
|
+
``warnings`` are sentences about how the page was cut to its budget (also shown on it).
|
|
303
|
+
"""
|
|
304
|
+
|
|
305
|
+
view: DriftView
|
|
306
|
+
warnings: list[str] = field(default_factory=list)
|
|
307
|
+
charted: int | None = None
|
|
308
|
+
title: str | None = field(default=None, repr=False)
|
|
309
|
+
_html: str | None = field(default=None, init=False, repr=False, compare=False)
|
|
310
|
+
|
|
311
|
+
@property
|
|
312
|
+
def verdict(self) -> str:
|
|
313
|
+
"""``"drift"``, ``"none"`` or ``"inconclusive"``."""
|
|
314
|
+
return self.view.verdict
|
|
315
|
+
|
|
316
|
+
def summary(self, *, warnings: bool = True) -> str:
|
|
317
|
+
"""The short terminal summary, then one ``warning: ...`` line per warning (left out
|
|
318
|
+
with ``warnings=False``)."""
|
|
319
|
+
from ectype.reporting import drift
|
|
320
|
+
|
|
321
|
+
lines = [drift.summary(self.view)]
|
|
322
|
+
if warnings:
|
|
323
|
+
lines += [f"warning: {w}" for w in self.warnings]
|
|
324
|
+
return "\n".join(lines)
|
|
325
|
+
|
|
326
|
+
def to_html_string(self) -> str:
|
|
327
|
+
"""The page as one HTML document (rendered once, then cached)."""
|
|
328
|
+
if self._html is None:
|
|
329
|
+
from ectype.reporting import drift
|
|
330
|
+
|
|
331
|
+
self._html = drift.render_drift(self.view, title=self.title,
|
|
332
|
+
notices=self.warnings, max_cards=self.charted)
|
|
333
|
+
return self._html
|
|
334
|
+
|
|
335
|
+
@property
|
|
336
|
+
def size_bytes(self) -> int:
|
|
337
|
+
"""Size of the page in UTF-8 bytes."""
|
|
338
|
+
return len(self.to_html_string().encode("utf-8"))
|
|
339
|
+
|
|
340
|
+
def to_html(self, path: str | os.PathLike[str]) -> Path:
|
|
341
|
+
"""Write the page (UTF-8), creating parent folders; returns the path."""
|
|
342
|
+
p = Path(path)
|
|
343
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
344
|
+
p.write_text(self.to_html_string(), encoding="utf-8")
|
|
345
|
+
return p
|
|
346
|
+
|
|
347
|
+
def to_dict(self) -> dict[str, Any]:
|
|
348
|
+
"""The report as plain data (strict JSON: no NaN or infinity)."""
|
|
349
|
+
return _finite({
|
|
350
|
+
"report": "comparison",
|
|
351
|
+
"view_version": getattr(self.view, "view_version", VIEW_VERSION),
|
|
352
|
+
"verdict": self.view.verdict,
|
|
353
|
+
"charted": self.charted,
|
|
354
|
+
"warnings": list(self.warnings),
|
|
355
|
+
"view": self.view.to_dict(),
|
|
356
|
+
})
|
|
357
|
+
|
|
358
|
+
def to_json(self, path: str | os.PathLike[str], *, indent: int = 2) -> Path:
|
|
359
|
+
"""Write :meth:`to_dict` as JSON (UTF-8), creating parent folders; returns the path."""
|
|
360
|
+
p = Path(path)
|
|
361
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
362
|
+
p.write_text(json.dumps(self.to_dict(), indent=indent, ensure_ascii=False,
|
|
363
|
+
allow_nan=False) + "\n", encoding="utf-8")
|
|
364
|
+
return p
|
|
365
|
+
|
|
366
|
+
def __str__(self) -> str:
|
|
367
|
+
return self.summary()
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _comparable(source: Any, which: str) -> Any:
|
|
371
|
+
"""``source`` when it is a path or a loaded fingerprint; ``TypeError`` otherwise."""
|
|
372
|
+
if isinstance(source, str | os.PathLike):
|
|
373
|
+
return source
|
|
374
|
+
core = sys.modules.get("ectype.fingerprint.core")
|
|
375
|
+
cls = getattr(core, "Fingerprint", None) if core is not None else None
|
|
376
|
+
if isinstance(cls, type) and isinstance(source, cls):
|
|
377
|
+
return source
|
|
378
|
+
raise TypeError(f"compare_report() takes two fingerprints or .dfp paths; the {which} is "
|
|
379
|
+
f"{type(source).__module__}.{type(source).__qualname__}")
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def compare_report(a: Fingerprint | str | os.PathLike[str],
|
|
383
|
+
b: Fingerprint | str | os.PathLike[str], *,
|
|
384
|
+
sensitivity: str | float = "standard", max_bytes: int = DEFAULT_MAX_BYTES,
|
|
385
|
+
title: str | None = None) -> ComparisonReport:
|
|
386
|
+
"""The comparison report of two fingerprints: ``a`` the reference, ``b`` the one compared
|
|
387
|
+
with it (each a loaded :class:`Fingerprint` or a ``.dfp`` path).
|
|
388
|
+
|
|
389
|
+
The decision of what drifted is the engine's (:func:`ectype.compare`, with the same
|
|
390
|
+
``sensitivity``); the page shows it column by column, both fingerprints on one axis.
|
|
391
|
+
While the page is over ``max_bytes``, fewer of the changed columns are drawn with a chart
|
|
392
|
+
and the rest are listed in a table.
|
|
393
|
+
|
|
394
|
+
Raises :class:`ValueError` for an unknown ``sensitivity`` or a ``max_bytes`` below
|
|
395
|
+
100,000; :class:`TypeError` for a source that is neither a fingerprint nor a path. Errors
|
|
396
|
+
of loading a ``.dfp`` (:class:`~ectype.errors.EctypeError`) propagate.
|
|
397
|
+
"""
|
|
398
|
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int):
|
|
399
|
+
raise TypeError(f"max_bytes must be an integer, not {type(max_bytes).__name__}")
|
|
400
|
+
if max_bytes < MIN_MAX_BYTES:
|
|
401
|
+
raise ValueError(f"max_bytes must be at least {MIN_MAX_BYTES:,}, not {max_bytes:,}")
|
|
402
|
+
if title is not None and not isinstance(title, str):
|
|
403
|
+
raise TypeError(f"title must be a string, not {type(title).__name__}")
|
|
404
|
+
a, b = _comparable(a, "first"), _comparable(b, "second")
|
|
405
|
+
from ectype.reporting import drift
|
|
406
|
+
from ectype.reporting.adapter import compare_view
|
|
407
|
+
|
|
408
|
+
view = compare_view(a, b, sensitivity=sensitivity)
|
|
409
|
+
n_changed = sum(1 for c in view.columns if c.status in ("drifted", "changed"))
|
|
410
|
+
page, size, first_size = "", 0, 0
|
|
411
|
+
warns: list[str] = []
|
|
412
|
+
charted: int | None = None
|
|
413
|
+
for step in _CARD_STEPS:
|
|
414
|
+
if step is not None and step >= n_changed:
|
|
415
|
+
continue
|
|
416
|
+
charted = step
|
|
417
|
+
warns = [] if step is None else [
|
|
418
|
+
f"With a chart for each of the {n_changed:,} changed columns the page would be "
|
|
419
|
+
f"{_mb(first_size, max_bytes)}, over the {_budget(max_bytes)} budget, so "
|
|
420
|
+
+ (f"only the {step:,} most changed are drawn" if step else "none is drawn")
|
|
421
|
+
+ " and the rest are listed in a table. Raise the budget with `--max-bytes` "
|
|
422
|
+
"(`max_bytes=`) to draw them all."]
|
|
423
|
+
page = drift.render_drift(view, title=title, notices=warns, max_cards=step)
|
|
424
|
+
size = len(page.encode("utf-8"))
|
|
425
|
+
if step is None:
|
|
426
|
+
first_size = size
|
|
427
|
+
if size <= max_bytes:
|
|
428
|
+
break
|
|
429
|
+
else:
|
|
430
|
+
warns = [*warns, f"The page is {_mb(size, max_bytes)}, over the {_budget(max_bytes)} "
|
|
431
|
+
"budget. Raise the budget with `--max-bytes` (`max_bytes=`)."]
|
|
432
|
+
page = drift.render_drift(view, title=title, notices=warns, max_cards=charted)
|
|
433
|
+
out = ComparisonReport(view=view, warnings=warns, charted=charted, title=title)
|
|
434
|
+
out._html = page
|
|
435
|
+
return out
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
__all__ = ["COMPACT_MAX_COLUMNS", "DEFAULT_MAX_BYTES", "DETAIL_CHOICES", "FULL_MAX_COLUMNS",
|
|
439
|
+
"ComparisonReport", "ProfileReport", "compare_report", "report", "select_columns"]
|