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.
Files changed (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,902 @@
1
+ """The comparison page: two fingerprints side by side, as one self-contained HTML document.
2
+
3
+ ADR-0016, section 7. The page is drawn from a :class:`~ectype.reporting.view.DriftView`, which
4
+ ``adapter.compare_view`` builds from the engine's drift comparison; this module imports only
5
+ the standard library and ``ectype.reporting.{view, fmt, charts, findings, style, render}``. It
6
+ keeps the rules of :mod:`ectype.reporting.render` and reuses its helpers: every string of the
7
+ view is escaped, every optional field may be ``None``, every part of the page is drawn inside
8
+ its own guard, ids and links are built from integers and fixed words only.
9
+
10
+ The colour rule of the product: purple is the first fingerprint (the reference), teal the
11
+ second. The two never differ by colour alone: the first is drawn as filled bars, the second as
12
+ an outline, and every chart has a legend line under it.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Callable, Sequence
18
+ from functools import partial
19
+
20
+ from ectype.reporting import charts, fmt
21
+ from ectype.reporting.render import (
22
+ FOOTER,
23
+ _axis_formatter,
24
+ _e,
25
+ _f,
26
+ _fitted,
27
+ _guard,
28
+ _nochart_text,
29
+ _notice,
30
+ _quantile,
31
+ _section,
32
+ _sentence,
33
+ _table,
34
+ _unread_li,
35
+ )
36
+ from ectype.reporting.style import CSS, SCRIPT
37
+ from ectype.reporting.view import (
38
+ ColumnView,
39
+ DriftColumn,
40
+ DriftPair,
41
+ DriftView,
42
+ Histogram,
43
+ Levels,
44
+ Privacy,
45
+ ReportView,
46
+ )
47
+
48
+ #: section ids in page order, with their rail labels
49
+ SECTIONS = (
50
+ ("overview", "Overview"),
51
+ ("changed", "What changed"),
52
+ ("relationships", "Relationships"),
53
+ ("schema", "Schema and policy"),
54
+ ("steady", "Steady columns"),
55
+ ("reading", "How to read this page"),
56
+ )
57
+
58
+ #: drifted pairs listed before the rest are folded into a ``<details>``
59
+ PAIRS_VISIBLE = 12
60
+ #: columns named in the lede
61
+ LEDE_NAMES = 5
62
+
63
+ #: metric names in words; any other is printed as stored
64
+ METRIC_WORDS = {
65
+ "univariate.ks": "shape of the distribution",
66
+ "univariate.wasserstein": "location and spread",
67
+ "univariate.mean_std": "mean and spread",
68
+ "univariate.frequencies": "category frequencies",
69
+ "univariate.missing_rate": "share of empty cells",
70
+ "univariate.quantiles": "quantiles",
71
+ "univariate.tail": "the extreme values (the tails)",
72
+ "univariate.granularity": "rounding of the values",
73
+ "temporal.acf": "how a value follows the ones before it",
74
+ "temporal.trend": "trend over time",
75
+ "temporal.spectrum": "cycles over time",
76
+ "temporal.seasonal_profile": "seasonal pattern",
77
+ "temporal.interarrival": "gaps between events",
78
+ "temporal.burstiness": "how events cluster in time",
79
+ "temporal.transition": "moves from one state to the next",
80
+ "multivariate.energy": "joint distribution of several columns",
81
+ "multivariate.c2st": "joint distribution of several columns",
82
+ "bivariate.spearman": "correlation",
83
+ "bivariate.pearson": "correlation",
84
+ "bivariate.kendall": "correlation",
85
+ "bivariate.cramers_v": "association",
86
+ "bivariate.correlation_ratio": "group differences",
87
+ "bivariate.mutual_information": "mutual information",
88
+ "bivariate.mutual_info": "mutual information",
89
+ "bivariate.contingency": "joint frequencies",
90
+ }
91
+
92
+ #: the adapter's sentence for a pseudonymised column starts with this; it is not a change
93
+ _STAND_IN_PREFIX = "category sets are not compared"
94
+
95
+ #: policy fields compared when the two policies differ
96
+ _POLICY_FIELDS: tuple[tuple[str, str], ...] = (
97
+ ("policy", "Policy"),
98
+ ("sensitive", "Marked as sensitive"),
99
+ ("min_category_support", "Fewest rows a stored value needs"),
100
+ ("quantile_resolution", "Stored quantiles"),
101
+ ("tail_clip", "Tails clipped at"),
102
+ ("rare_cell_min", "Fewest rows a stored pair cell needs"),
103
+ ("significant_digits", "Significant digits"),
104
+ ("identifiers", "Identifiers"),
105
+ )
106
+
107
+ _DEFS = (
108
+ ("A fingerprint", "A file that Ectype fits to a table once: a model of each column and of "
109
+ "how columns move together, with no rows. This page compares two of them "
110
+ "and reads neither table."),
111
+ ("A measured property", "One thing a fingerprint records about a column or a pair of "
112
+ "columns: the shape of a distribution, its location and spread, "
113
+ "the share of empty cells, the strength of an association."),
114
+ ("First and second", "The first fingerprint is the reference (the original); the second is "
115
+ "the one compared with it."),
116
+ ("Purple bars, teal outline", "In every chart the first fingerprint is drawn as purple "
117
+ "filled bars and the second as a teal outline, with a legend "
118
+ "line under the chart."),
119
+ ("Drifted", "A measured property of a column, or of a pair of columns, moved by more than "
120
+ "sampling noise explains."),
121
+ ("Sampling noise and the threshold", "Two samples of one population never agree exactly. "
122
+ "Each property has a threshold set from the noise of "
123
+ "two samples of these sizes; the page says how many "
124
+ "times its threshold a property moved."),
125
+ ("False-discovery rate", "Of the properties called drifted, at most this share is expected "
126
+ "to be noise."),
127
+ ("Stand-in tokens", "A pseudonymised column's labels are replaced independently in each "
128
+ "fingerprint, so equal labels mean nothing: the column is compared by "
129
+ "its profile (how concentrated it is), not by its labels."),
130
+ )
131
+
132
+ _CANNOT = (
133
+ "The rows themselves.",
134
+ "The targets the validator holds back (sealed): only how far each moved is used.",
135
+ "Whether a change matters for your use of the data.",
136
+ "Why a column changed.",
137
+ )
138
+
139
+
140
+ # -- small words ------------------------------------------------------------------------------
141
+
142
+
143
+ def metric_words(metric: str | None) -> str:
144
+ """A metric name in words (``univariate.ks`` -> ``shape of the distribution``)."""
145
+ if not metric or not isinstance(metric, str):
146
+ return "a property"
147
+ return METRIC_WORDS.get(metric, metric)
148
+
149
+
150
+ def _times(ratio: float | None) -> str:
151
+ r = _f(ratio)
152
+ if r is None:
153
+ return "beyond its threshold"
154
+ if r >= 100:
155
+ return f"{fmt.count(round(r))} times its threshold"
156
+ return f"{r:.1f} times its threshold"
157
+
158
+
159
+ def _score(x: object) -> str:
160
+ v = _f(x)
161
+ if v is None:
162
+ return "–"
163
+ return f"{v:.2f}" if v < 100 else fmt.number(v)
164
+
165
+
166
+ def _type_of(c: ColumnView | None) -> str:
167
+ if c is None or not c.logical_type:
168
+ return "type not recorded"
169
+ return fmt.type_label(c.logical_type, c.is_date)
170
+
171
+
172
+ def _is_change(sentence: str) -> bool:
173
+ return bool(sentence) and not sentence.startswith(_STAND_IN_PREFIX)
174
+
175
+
176
+ def _status_words(dc: DriftColumn) -> str:
177
+ bits = []
178
+ if dc.status == "drifted":
179
+ bits.append("drifted")
180
+ for s in dc.changes or []:
181
+ if not isinstance(s, str) or not _is_change(s):
182
+ continue
183
+ if s.startswith("type changed"):
184
+ w = "type changed"
185
+ elif s.startswith("role changed"):
186
+ w = "role changed"
187
+ elif "categor" in s:
188
+ w = "categories changed"
189
+ else:
190
+ w = "changed"
191
+ if w not in bits:
192
+ bits.append(w)
193
+ if not bits:
194
+ bits.append({"added": "added", "removed": "removed", "changed": "changed"}.get(
195
+ dc.status, dc.status or "steady"))
196
+ return ", ".join(bits)
197
+
198
+
199
+ # -- the page context -------------------------------------------------------------------------
200
+
201
+
202
+ class _Ctx:
203
+ """What every part of the page needs: the view, the names of the two sides, anchors."""
204
+
205
+ def __init__(self, view: DriftView) -> None:
206
+ self.view = view
207
+ self.a: ReportView = view.a if isinstance(view.a, ReportView) else ReportView()
208
+ self.b: ReportView = view.b if isinstance(view.b, ReportView) else ReportView()
209
+ self.cols: list[DriftColumn] = [c for c in view.columns or []
210
+ if isinstance(c, DriftColumn)]
211
+ self.anchors: dict[str, str] = {}
212
+ for k, c in enumerate(self.cols):
213
+ if c.status in ("drifted", "changed", "added") and isinstance(c.name, str) \
214
+ and c.name not in self.anchors:
215
+ self.anchors[c.name] = f"col-{k}"
216
+ self.na = self._name(self.a)
217
+ self.nb = self._name(self.b)
218
+ same = self.na == self.nb
219
+ da, db = self._date(self.a), self._date(self.b)
220
+ if same and da and db and da != db:
221
+ self.la, self.lb = f"first, fitted {da}", f"second, fitted {db}"
222
+ elif same or not self.na or not self.nb:
223
+ self.la, self.lb = "first", "second"
224
+ else:
225
+ self.la, self.lb = f"first: {self.na}", f"second: {self.nb}"
226
+ self._uid = 0
227
+ self._a_cols = {c.name: c for c in self.a.columns if isinstance(c.name, str)}
228
+ self._b_cols = {c.name: c for c in self.b.columns if isinstance(c.name, str)}
229
+
230
+ @staticmethod
231
+ def _name(v: ReportView) -> str:
232
+ n = v.overview.name
233
+ return n if isinstance(n, str) else ""
234
+
235
+ @staticmethod
236
+ def _date(v: ReportView) -> str:
237
+ c = v.overview.created
238
+ return _fitted(c) if isinstance(c, str) and c else ""
239
+
240
+ def uid(self) -> str:
241
+ self._uid += 1
242
+ return f"d{self._uid}"
243
+
244
+ def link(self, name: object) -> str:
245
+ text = _e(name) if name not in (None, "") else "(unnamed column)"
246
+ h = self.anchors.get(name) if isinstance(name, str) else None
247
+ return f'<a href="#{h}">{text}</a>' if h else text
248
+
249
+ def col_a(self, name: str) -> ColumnView | None:
250
+ return self._a_cols.get(name)
251
+
252
+ def col_b(self, name: str) -> ColumnView | None:
253
+ return self._b_cols.get(name)
254
+
255
+ def legend(self, first: bool = True, second: bool = True) -> str:
256
+ bits = []
257
+ if first:
258
+ bits.append(f'<span><i class="sw sw1"></i>{_e(self.la)}</span>')
259
+ if second:
260
+ bits.append(f'<span><i class="sw sw2"></i>{_e(self.lb)}</span>')
261
+ return f'<p class="legend">{"".join(bits)}</p>'
262
+
263
+ def by_status(self, *status: str) -> list[DriftColumn]:
264
+ return [c for c in self.cols if c.status in status]
265
+
266
+
267
+ # -- overview ---------------------------------------------------------------------------------
268
+
269
+
270
+ def _verdict(p: _Ctx) -> tuple[str, str]:
271
+ """The verdict's class and sentence (plain text, "Head: rest")."""
272
+ v = p.view
273
+ fm, fn = _f(v.n_targets), _f(v.n_drifted)
274
+ m = int(fm) if fm is not None else None
275
+ n = int(fn) if fn is not None else None
276
+ noise = "by more than sampling noise explains"
277
+ if v.verdict == "drift":
278
+ if n:
279
+ of = (f"{fmt.count(m)} measured {'property' if m == 1 else 'properties'}"
280
+ if m is not None else "the measured properties")
281
+ return "v-drift", f"Drift found: {fmt.count(n)} of {of} moved {noise}."
282
+ schema = []
283
+ n_changed = len([c for c in p.cols if c.status in ("changed", "drifted")
284
+ and any(_is_change(s) for s in c.changes or [])])
285
+ for k, word in ((len(p.by_status("added")), "added"),
286
+ (len(p.by_status("removed")), "removed"), (n_changed, "changed")):
287
+ if k:
288
+ schema.append(f"{fmt.plural(k, 'column')} {word}")
289
+ what = fmt.join(schema, 3) if schema else "columns, types or categories differ"
290
+ if m == 0:
291
+ return "v-drift", (f"Drift found: the schema changed ({what}); the two "
292
+ "fingerprints share no measured property to compare.")
293
+ rest = ("none of the measured properties moved" if m is None
294
+ else f"none of the {fmt.plural(m, 'measured property', 'measured properties')} "
295
+ "moved")
296
+ return "v-drift", f"Drift found: the schema changed ({what}); {rest} {noise}."
297
+ if v.verdict == "none":
298
+ if m is None:
299
+ return "v-none", f"No drift found: no measured property moved {noise}."
300
+ if m == 1:
301
+ return "v-none", f"No drift found: the 1 measured property did not move {noise}."
302
+ return "v-none", (f"No drift found: none of the {fmt.count(m)} measured properties "
303
+ f"moved {noise}.")
304
+ failed = any(u.where == "comparison" for u in v.unread or [])
305
+ if v.verdict == "inconclusive" and not failed and v.n_errors:
306
+ k = int(v.n_errors)
307
+ what = "1 property" if k == 1 else f"{fmt.count(k)} properties"
308
+ return "v-inconclusive", (f"Inconclusive: {what} could not be compared; no drift was "
309
+ "found among the rest.")
310
+ if v.verdict == "inconclusive" or failed:
311
+ return "v-inconclusive", ("Inconclusive: the comparison could not be completed, so no "
312
+ "verdict is given. The two fingerprints are described side "
313
+ "by side below.")
314
+ return "v-inconclusive", "No verdict: this comparison holds no result."
315
+
316
+
317
+ def _heading(p: _Ctx, title: str | None) -> str:
318
+ if title:
319
+ return title
320
+ if p.na and p.nb and p.na != p.nb:
321
+ return f"{p.na} compared with {p.nb}"
322
+ if p.na or p.nb:
323
+ return f"Two fingerprints of {p.na or p.nb}"
324
+ return "Two fingerprints compared"
325
+
326
+
327
+ def _lede(p: _Ctx) -> str:
328
+ drifted = p.by_status("drifted")
329
+ changed = p.by_status("changed")
330
+ added, removed = p.by_status("added"), p.by_status("removed")
331
+ n = len(p.cols)
332
+ if not n:
333
+ return ""
334
+ parts = []
335
+ if drifted:
336
+ parts.append(f"{fmt.count(len(drifted))} drifted")
337
+ if changed:
338
+ parts.append(f"{fmt.count(len(changed))} changed type, role or categories")
339
+ if added:
340
+ parts.append(f"{fmt.count(len(added))} {'was' if len(added) == 1 else 'were'} added")
341
+ if removed:
342
+ parts.append(f"{fmt.count(len(removed))} {'was' if len(removed) == 1 else 'were'} "
343
+ "removed")
344
+ s = [f"Of the {fmt.plural(n, 'column')} of either fingerprint, "
345
+ + (fmt.join(parts, 4) + "." if parts else "none drifted, changed, appeared or "
346
+ "disappeared.")]
347
+ top = [c.name for c in [*drifted, *changed] if isinstance(c.name, str)][:LEDE_NAMES]
348
+ if top:
349
+ word = "The most changed" if len(top) > 1 else "The one that moved"
350
+ s.append(f"{word}: {fmt.join(top, LEDE_NAMES)}.")
351
+ ra, rb = _f(p.a.overview.rows), _f(p.b.overview.rows)
352
+ if ra is not None and rb is not None:
353
+ s.append(f"The first holds {fmt.plural(ra, 'row')}, the second "
354
+ f"{fmt.plural(rb, 'row')}.")
355
+ return " ".join(s)
356
+
357
+
358
+ def _facts_table(p: _Ctx) -> str:
359
+ def facts(v: ReportView) -> list[str]:
360
+ o = v.overview
361
+ n_cols = o.columns if _f(o.columns) is not None else (len(v.columns) or None)
362
+ policy = o.policy or v.privacy.policy or ""
363
+ if v.privacy.sensitive:
364
+ policy = (policy or "not recorded") + ", sensitive"
365
+ return [
366
+ o.name if isinstance(o.name, str) else "",
367
+ fmt.count(o.rows) if _f(o.rows) is not None else "",
368
+ fmt.count(n_cols) if n_cols is not None else "",
369
+ policy,
370
+ o.format_version or "",
371
+ o.engine_version or "",
372
+ _fitted(o.created) if isinstance(o.created, str) and o.created else "",
373
+ o.content_id or "",
374
+ ]
375
+
376
+ labels = ("Name", "Rows", "Columns", "Policy", "Format", "Engine", "Fitted", "Fingerprint id")
377
+ fa, fb = facts(p.a), facts(p.b)
378
+ rows = []
379
+ for i, label in enumerate(labels):
380
+ cls = ' class="mono"' if label == "Fingerprint id" else ""
381
+ rows.append(f'<tr><th scope="row">{label}</th><td{cls}>{_e(fa[i]) or "–"}</td>'
382
+ f"<td{cls}>{_e(fb[i]) or '–'}</td></tr>")
383
+ return _table("The two fingerprints", ("", "First", "Second"), rows,
384
+ "The two fingerprints", cls="two")
385
+
386
+
387
+ def _decision(p: _Ctx) -> str:
388
+ v = p.view
389
+ q = _f(v.q)
390
+ ra, rb = _f(p.a.overview.rows), _f(p.b.overview.rows)
391
+ sizes = (f" ({fmt.plural(ra, 'row')} and {fmt.plural(rb, 'row')})"
392
+ if ra is not None and rb is not None else "")
393
+ rate = f"{q:g}" if q is not None else "the chosen level"
394
+ sens = f" (sensitivity {v.sensitivity})" if v.sensitivity else ""
395
+ text = (f"How the decision is made: each measured property is compared against the "
396
+ f"sampling noise of two samples of these sizes{sizes}, and all of them are tested "
397
+ f"together with the false-discovery rate held at {rate}{sens}.")
398
+ if v.only_a or v.only_b:
399
+ text += (f" {fmt.plural(v.only_a, 'property', 'properties')} measured only in the "
400
+ f"first and {fmt.count(v.only_b)} only in the second could not be compared.")
401
+ return f'<p class="decision">{_e(text)}</p>'
402
+
403
+
404
+ def _overview(p: _Ctx, heading: str, notices: Sequence[str]) -> str:
405
+ out = [f'<section id="overview" aria-labelledby="overview-h"><h1 id="overview-h">'
406
+ f"{_e(heading)}</h1>"]
407
+ cls, sentence = _verdict(p)
408
+ head, _, rest = sentence.partition(": ")
409
+ out.append(f'<p class="verdict {cls}"><span class="mark" aria-hidden="true"></span>'
410
+ f"<span><b>{_e(head)}:</b> {_e(rest)}</span></p>")
411
+ lede = _lede(p)
412
+ if lede:
413
+ out.append(f'<p class="lede">{_e(lede)}</p>')
414
+ for n in notices or ():
415
+ out.append(f'<p class="notice">{_notice(n)}</p>')
416
+ for w in p.view.policy_warnings or []:
417
+ out.append(f'<p class="notice serious">{_e(w)}</p>')
418
+ out.append(_guard(lambda: _facts_table(p), "table"))
419
+ out.append(_decision(p))
420
+ out.append("</section>")
421
+ return "".join(out)
422
+
423
+
424
+ # -- what changed -----------------------------------------------------------------------------
425
+
426
+
427
+ def _usable_hist(c: ColumnView | None) -> Histogram | None:
428
+ if c is None or c.histogram is None or not charts.has_data(c.histogram):
429
+ return None
430
+ return c.histogram
431
+
432
+
433
+ def _usable_levels(c: ColumnView | None) -> Levels | None:
434
+ if c is None or c.levels is None or not charts.has_data(c.levels):
435
+ return None
436
+ return c.levels
437
+
438
+
439
+ def _missing(c: ColumnView | None) -> str:
440
+ m = None if c is None else _f(c.missing)
441
+ return fmt.share(m) if m is not None else "–"
442
+
443
+
444
+ def _hist_figures(h: Histogram | None) -> dict[str, str]:
445
+ if h is None:
446
+ return {}
447
+ f = _axis_formatter(h)
448
+ out = {}
449
+ q25, q50, q75 = _quantile(h, 0.25), _quantile(h, 0.5), _quantile(h, 0.75)
450
+ if q50 is not None:
451
+ out["Median"] = f(q50)
452
+ if q25 is not None and q75 is not None:
453
+ out["Middle half"] = f"{f(q25)} to {f(q75)}"
454
+ return out
455
+
456
+
457
+ def _level_figures(lv: Levels | None) -> dict[str, str]:
458
+ if lv is None:
459
+ return {}
460
+ out = {}
461
+ if _f(lv.n_levels) is not None:
462
+ out["Number of values"] = fmt.count(lv.n_levels)
463
+ plain = [b for b in lv.bars or [] if b.kind == "level" and _f(b.share) is not None]
464
+ if plain:
465
+ top = max(plain, key=lambda b: _f(b.share) or 0.0)
466
+ label = "a stand-in token" if lv.stand_ins else fmt.truncate(str(top.label), 30)
467
+ out["Most common"] = f"{label} ({fmt.share(top.share)})"
468
+ return out
469
+
470
+
471
+ def _key_figures(p: _Ctx, name: str, ca: ColumnView | None, cb: ColumnView | None) -> str:
472
+ ha, hb = _usable_hist(ca), _usable_hist(cb)
473
+ la, lb = _usable_levels(ca), _usable_levels(cb)
474
+ fa = {**_hist_figures(ha), **_level_figures(la if ha is None else None)}
475
+ fb = {**_hist_figures(hb), **_level_figures(lb if hb is None else None)}
476
+ keys: list[str] = []
477
+ for k in [*fa, *fb]:
478
+ if k not in keys:
479
+ keys.append(k)
480
+ rows = [f'<tr><th scope="row">{_e(k)}</th><td>{_e(fa.get(k, "–"))}</td>'
481
+ f'<td>{_e(fb.get(k, "–"))}</td></tr>' for k in keys]
482
+ rows.append(f'<tr><th scope="row">Empty cells</th><td>{_e(_missing(ca))}</td>'
483
+ f"<td>{_e(_missing(cb))}</td></tr>")
484
+ cap = f"Key figures of {_e(fmt.truncate(name, 80))}"
485
+ return ('<div class="kfw">' + _table(cap, ("", "First", "Second"), rows, cap, cls="kf")
486
+ + "</div>")
487
+
488
+
489
+ def _one_chart(p: _Ctx, c: ColumnView, title: str, compact: bool) -> str:
490
+ h, lv = _usable_hist(c), _usable_levels(c)
491
+ if h is not None:
492
+ return charts.histogram(h, uid=p.uid(), title=title, compact=compact)
493
+ if lv is not None:
494
+ return charts.levels(lv, uid=p.uid(), title=title, max_bars=4 if compact else 8,
495
+ compact=compact)
496
+ return ""
497
+
498
+
499
+ def _charts(p: _Ctx, name: str, ca: ColumnView | None, cb: ColumnView | None) -> str:
500
+ title = name if len(name) <= 120 else fmt.truncate(name, 120)
501
+ ha, hb = _usable_hist(ca), _usable_hist(cb)
502
+ la, lb = _usable_levels(ca), _usable_levels(cb)
503
+ if ha is not None and hb is not None and (ha.axis or "number") == (hb.axis or "number"):
504
+ svg = charts.histogram(ha, uid=p.uid(), title=f"{title}: first and second", second=hb)
505
+ return svg + p.legend()
506
+ if ha is None and hb is None and la is not None and lb is not None:
507
+ svg = charts.levels_pair(la, lb, uid=p.uid(), title=f"{title}: first and second")
508
+ return svg + p.legend()
509
+ out = []
510
+ drawn = {side: _one_chart(p, c, f"{title}: {side.lower()}", compact=False)
511
+ for c, side in ((ca, "First"), (cb, "Second")) if c is not None}
512
+ why = {side: _nochart_text(c) for c, side in ((ca, "First"), (cb, "Second"))
513
+ if c is not None and not drawn[side]}
514
+ if len(why) == 2 and why["First"] == why["Second"]:
515
+ # neither side has a distribution, for one reason: say it once
516
+ return f'<p class="side">No chart. {_e(why["First"])}</p>'
517
+ for c, side, first in ((ca, "First", True), (cb, "Second", False)):
518
+ if c is None:
519
+ continue
520
+ svg = drawn[side]
521
+ if not svg:
522
+ out.append(f'<p class="side">{side}: no chart. {_e(why[side])}</p>')
523
+ continue
524
+ if side == "Second":
525
+ # a lone chart of the second is drawn as the outline it has everywhere else
526
+ svg = svg.replace('class="bar"', 'class="bar second"')
527
+ out.append(f'<p class="side">{side}</p>{svg}'
528
+ + p.legend(first=first, second=not first))
529
+ return "".join(out)
530
+
531
+
532
+ def _card(p: _Ctx, k: int, dc: DriftColumn) -> str:
533
+ name = dc.name if isinstance(dc.name, str) else str(dc.name)
534
+ ca, cb = p.col_a(name), p.col_b(name)
535
+ ta, tb = _type_of(ca), _type_of(cb)
536
+ kind = ta if ta == tb else f"{ta}, then {tb}"
537
+ out = [f'<article class="col dcol" id="col-{k}"><header><h3>'
538
+ f'{_e(name) or "(unnamed column)"}</h3><p class="kind"><span>{_e(kind)}</span>'
539
+ f"<span>{_e(_status_words(dc))}</span></p></header>"]
540
+ if dc.status == "drifted" or dc.n_drifted:
541
+ bits = []
542
+ if dc.worst_metric:
543
+ r = _f(dc.worst_ratio)
544
+ where = f"at {_times(r)}" if r is not None else "beyond its threshold"
545
+ bits.append(f"worst property: {metric_words(dc.worst_metric)} {where}")
546
+ if dc.n_drifted:
547
+ n = int(dc.n_drifted)
548
+ bits.append(f"{fmt.plural(n, 'property', 'properties')} drifted")
549
+ if bits:
550
+ out.append(f'<p class="howfar">{_e(_sentence("; ".join(bits)))}.</p>')
551
+ out.append(_charts(p, name, ca, cb))
552
+ out.append(_key_figures(p, name, ca, cb))
553
+ changes = [s for s in dc.changes or [] if isinstance(s, str) and s]
554
+ if changes:
555
+ out.append('<ul class="changes">' + "".join(
556
+ f"<li>{_e(_sentence(s))}.</li>" for s in changes) + "</ul>")
557
+ out.append("</article>")
558
+ return "".join(out)
559
+
560
+
561
+ def _added_card(p: _Ctx, k: int, dc: DriftColumn) -> str:
562
+ name = dc.name if isinstance(dc.name, str) else str(dc.name)
563
+ cb = p.col_b(name)
564
+ out = [f'<article class="col compact dcol" id="col-{k}"><header><h3>'
565
+ f'{_e(name) or "(unnamed column)"}</h3><p class="kind"><span>{_e(_type_of(cb))}'
566
+ "</span><span>only in the second</span></p></header>"]
567
+ svg = "" if cb is None else _one_chart(p, cb, f"{fmt.truncate(name, 120)}: second", True)
568
+ if svg:
569
+ out.append(svg.replace('class="bar"', 'class="bar second"'))
570
+ out.append(p.legend(first=False))
571
+ else:
572
+ out.append('<p class="nochart">No distribution to draw.</p>')
573
+ out.append("</article>")
574
+ return "".join(out)
575
+
576
+
577
+ def _listed(p: _Ctx, rest: list[tuple[int, DriftColumn]]) -> str:
578
+ """The changed columns beyond ``max_cards``: one table row each, no chart."""
579
+ rows = []
580
+ for k, c in rest:
581
+ how = ""
582
+ if c.worst_metric:
583
+ r = _f(c.worst_ratio)
584
+ how = metric_words(c.worst_metric) + (f", {_times(r)}" if r is not None else "")
585
+ rows.append(f'<tr id="col-{k}"><th scope="row">{_e(c.name) or "(unnamed column)"}</th>'
586
+ f"<td>{_e(_status_words(c))}</td><td>{_e(how) or '–'}</td></tr>")
587
+ cap = "Changed columns listed without a chart"
588
+ return _table(cap, ("Column", "What changed", "Worst property"), rows, cap, cls="cols")
589
+
590
+
591
+ def _changed(p: _Ctx, max_cards: int | None = None) -> str:
592
+ moved = [(k, c) for k, c in enumerate(p.cols) if c.status in ("drifted", "changed")]
593
+ rest: list[tuple[int, DriftColumn]] = []
594
+ if max_cards is not None and len(moved) > max_cards:
595
+ moved, rest = moved[:max(0, max_cards)], moved[max(0, max_cards):]
596
+ added = [(k, c) for k, c in enumerate(p.cols) if c.status == "added"]
597
+ removed = [c for c in p.cols if c.status == "removed"]
598
+ out = []
599
+ if moved:
600
+ out.append('<p class="intro">Each column that drifted or changed, most changed first. '
601
+ "Its chart draws both fingerprints on one axis: the first as filled purple "
602
+ "bars, the second as a teal outline. Charts are rebuilt from the fitted "
603
+ "models, not from rows.</p>")
604
+ out.append('<div class="grid">')
605
+ for k, c in moved:
606
+ card = _guard(partial(_card, p, k, c), "column")
607
+ if not card.startswith("<article"):
608
+ card = (f'<article class="col dcol" id="col-{k}"><h3>{_e(c.name)}</h3>'
609
+ f"{card}</article>")
610
+ out.append(card)
611
+ out.append("</div>")
612
+ elif not rest:
613
+ out.append("<p>No column drifted or changed.</p>")
614
+ if rest:
615
+ out.append(f"<h3>{'Other changed' if moved else 'Changed'} columns "
616
+ f"({fmt.count(len(rest))})</h3>"
617
+ '<p class="intro">Listed without a chart to keep the page small, most '
618
+ "changed first.</p>")
619
+ out.append(_guard(partial(_listed, p, rest), "table"))
620
+ if added:
621
+ out.append(f"<h3>Added in the second ({fmt.count(len(added))})</h3>")
622
+ out.append('<div class="grid">')
623
+ for k, c in added:
624
+ card = _guard(partial(_added_card, p, k, c), "column")
625
+ if not card.startswith("<article"):
626
+ card = (f'<article class="col compact dcol" id="col-{k}"><h3>{_e(c.name)}</h3>'
627
+ f"{card}</article>")
628
+ out.append(card)
629
+ out.append("</div>")
630
+ if removed:
631
+ out.append(f"<h3>Only in the first ({fmt.count(len(removed))})</h3><ul>")
632
+ for c in removed:
633
+ out.append(f"<li>{_e(c.name) or '(unnamed column)'} "
634
+ f'<span class="num">({_e(_type_of(p.col_a(c.name)))})</span></li>')
635
+ out.append("</ul>")
636
+ return _section("changed", "What changed", "".join(out))
637
+
638
+
639
+ # -- relationships ----------------------------------------------------------------------------
640
+
641
+
642
+ def _pair_li(p: _Ctx, pr: DriftPair, peak: float) -> str:
643
+ s = _f(pr.score) or 0.0
644
+ width = f"{100 * min(max(s / peak, 0.0), 1.0):.1f}".rstrip("0").rstrip(".") + "%"
645
+ what = metric_words(pr.worst_metric) if pr.worst_metric else "joint behaviour"
646
+ more = ""
647
+ n = int(pr.n_drifted) if _f(pr.n_drifted) is not None else 0
648
+ if n > 1:
649
+ more = f" ({fmt.count(n)} properties drifted)"
650
+ return (f'<li><span class="meter"><span style="width:{width}"></span></span>'
651
+ f'<span class="num">{_e(_score(s))}</span><span class="say">{p.link(pr.a)} and '
652
+ f"{p.link(pr.b)}: their {_e(what)} moved{_e(more)}</span></li>")
653
+
654
+
655
+ def _relationships(p: _Ctx) -> str:
656
+ v = p.view
657
+ pairs = [x for x in v.pairs or [] if isinstance(x, DriftPair)]
658
+ if not pairs:
659
+ return _section("relationships", "Relationships",
660
+ "<p>No relationship between columns moved by more than sampling noise "
661
+ "explains.</p>")
662
+ peak = max((_f(x.score) or 0.0 for x in pairs), default=0.0) or 1.0
663
+ total = v.n_pairs if _f(v.n_pairs) is not None and v.n_pairs >= len(pairs) else len(pairs)
664
+ out = [f'<p class="intro">{_e(fmt.plural(total, "pair"))} of columns moved together '
665
+ "differently in the second. The number is the drift score: how far the pair's "
666
+ "properties moved beyond their thresholds, added up; the largest first.</p>"]
667
+ if total > len(pairs):
668
+ out.append(f"<p>Showing {fmt.count(len(pairs))} of {fmt.count(total)}.</p>")
669
+ out.append('<ol class="pairs">')
670
+ out += [_pair_li(p, x, peak) for x in pairs[:PAIRS_VISIBLE]]
671
+ out.append("</ol>")
672
+ rest = pairs[PAIRS_VISIBLE:]
673
+ if rest:
674
+ out.append(f'<details class="more"><summary>{fmt.plural(len(rest), "more pair")}'
675
+ f'</summary><ol class="pairs" start="{PAIRS_VISIBLE + 1}">')
676
+ out += [_pair_li(p, x, peak) for x in rest]
677
+ out.append("</ol></details>")
678
+ return _section("relationships", "Relationships", "".join(out))
679
+
680
+
681
+ # -- schema and policy ------------------------------------------------------------------------
682
+
683
+
684
+ def _policy_value(pv: Privacy, key: str) -> str:
685
+ val = getattr(pv, key, None)
686
+ if key == "tail_clip":
687
+ nums = [x for x in (_f(t) for t in val or []) if x is not None]
688
+ return " and ".join(fmt.share(x) for x in nums) if nums else ""
689
+ if isinstance(val, bool):
690
+ return "yes" if val else "no"
691
+ if val is None:
692
+ return ""
693
+ if isinstance(val, (int, float)) and not isinstance(val, bool):
694
+ return fmt.number(val) if _f(val) is not None else ""
695
+ return str(val)
696
+
697
+
698
+ def _policy_rows(p: _Ctx) -> list[str]:
699
+ pa, pb = p.a.privacy, p.b.privacy
700
+ rows = []
701
+ for key, label in _POLICY_FIELDS:
702
+ x, y = _policy_value(pa, key), _policy_value(pb, key)
703
+ if key == "policy":
704
+ x = x or p.a.overview.policy or ""
705
+ y = y or p.b.overview.policy or ""
706
+ if x != y:
707
+ rows.append(f'<tr><th scope="row">{label}</th><td>{_e(x) or "not recorded"}</td>'
708
+ f'<td>{_e(y) or "not recorded"}</td></tr>')
709
+ return rows
710
+
711
+
712
+ def _schema(p: _Ctx) -> str:
713
+ v = p.view
714
+ rows = []
715
+ for c in p.cols:
716
+ what = []
717
+ if c.status == "added":
718
+ what.append(f"added in the second ({_type_of(p.col_b(c.name))})")
719
+ elif c.status == "removed":
720
+ what.append(f"only in the first ({_type_of(p.col_a(c.name))})")
721
+ what += [s for s in c.changes or [] if isinstance(s, str) and _is_change(s)]
722
+ if what:
723
+ rows.append(f'<tr><th scope="row">{p.link(c.name)}</th>'
724
+ f"<td>{_e(_sentence('; '.join(what)))}</td></tr>")
725
+ policy = _policy_rows(p)
726
+ notes = [n for n in v.notes or [] if isinstance(n, str) and n]
727
+ out = []
728
+ if not rows and not policy:
729
+ out.append("<p>The two fingerprints have the same columns, types and policy.</p>")
730
+ if rows:
731
+ out.append(_table("Changes to the columns", ("Column", "What changed"), rows,
732
+ "Changes to the columns"))
733
+ if policy:
734
+ out.append("<p>The two fingerprints were made under different policies, so their "
735
+ "stored summaries are coarsened differently: a small difference can come "
736
+ "from the policy rather than the data.</p>")
737
+ out.append(_table("The policies that differ", ("Setting", "First", "Second"), policy,
738
+ "The policies that differ", cls="two"))
739
+ if notes:
740
+ out.append("<h3>Notes of the engine</h3>"
741
+ '<p class="small">What the comparison itself noted, quoted as written. '
742
+ "A name such as <code>bivariate.contingency:a|b</code> is one measured "
743
+ "property: the kind of measurement, then the column or columns.</p><ul>"
744
+ + "".join(f"<li>{_e(n)}</li>" for n in notes) + "</ul>")
745
+ return _section("schema", "Schema and policy", "".join(out))
746
+
747
+
748
+ # -- steady columns ---------------------------------------------------------------------------
749
+
750
+
751
+ def _summary_value(c: ColumnView | None) -> str:
752
+ if c is None:
753
+ return "–"
754
+ h = _usable_hist(c)
755
+ if h is not None:
756
+ q = _quantile(h, 0.5)
757
+ return f"median {_axis_formatter(h)(q)}" if q is not None else "–"
758
+ lv = _usable_levels(c)
759
+ if lv is not None:
760
+ top = _level_figures(lv).get("Most common")
761
+ return f"most common: {top}" if top else "–"
762
+ return "–"
763
+
764
+
765
+ def _steady(p: _Ctx) -> str:
766
+ steady = p.by_status("steady")
767
+ if not p.cols:
768
+ return _section("steady", "Steady columns", "<p>This comparison lists no columns.</p>")
769
+ if not steady:
770
+ return _section("steady", "Steady columns",
771
+ "<p>No column is steady: every column drifted, changed, was added or "
772
+ "was removed.</p>")
773
+ out = []
774
+ if p.view.verdict == "inconclusive":
775
+ out.append('<p class="intro">The comparison was inconclusive: these columns were not '
776
+ "found to move, which is not the same as having been shown to stay.</p>")
777
+ else:
778
+ out.append('<p class="intro">Columns in which no measured property moved by more than '
779
+ "sampling noise explains. They have no chart, which keeps a wide comparison "
780
+ "small.</p>")
781
+ rows = []
782
+ for c in steady:
783
+ name = c.name if isinstance(c.name, str) else str(c.name)
784
+ ca, cb = p.col_a(name), p.col_b(name)
785
+ rows.append(f'<tr><th scope="row">{_e(name) or "(unnamed column)"}</th>'
786
+ f"<td>{_e(_type_of(ca if ca is not None else cb))}</td>"
787
+ f"<td>{_e(_summary_value(ca))}</td><td>{_e(_summary_value(cb))}</td>"
788
+ f'<td class="num">{_e(_missing(ca))}</td>'
789
+ f'<td class="num">{_e(_missing(cb))}</td></tr>')
790
+ table = _table("Steady columns", ("Column", "Type", "First", "Second", "Empty, first",
791
+ "Empty, second"), rows, "Steady columns",
792
+ cls="cols wide", num_cols=(4, 5))
793
+ out.append(f'<details class="more"><summary>{fmt.plural(len(steady), "steady column")}'
794
+ f"</summary>{table}</details>")
795
+ return _section("steady", "Steady columns", "".join(out))
796
+
797
+
798
+ # -- how to read this page --------------------------------------------------------------------
799
+
800
+
801
+ def _reading(p: _Ctx) -> str:
802
+ out = ['<h3>Reading the page</h3><dl class="defs">']
803
+ out += [f"<dt>{k}</dt><dd>{d}</dd>" for k, d in _DEFS]
804
+ out.append("</dl><h3>What this page cannot show</h3><ul>")
805
+ out += [f"<li>{x}</li>" for x in _CANNOT]
806
+ out.append("</ul><h3>What this page does not describe</h3>")
807
+ items = [_unread_li(u) for u in p.view.unread or []]
808
+ for side, rv in (("In the first: ", p.a), ("In the second: ", p.b)):
809
+ for u in rv.all_unread():
810
+ li = _unread_li(u)
811
+ items.append("<li>" + side + li[4:])
812
+ for name in rv.extra_sections or []:
813
+ items.append(f"<li>{side}a {_e(name)} section, which this page does not cover</li>")
814
+ if items:
815
+ out.append("<ul>" + "".join(items) + "</ul>")
816
+ else:
817
+ out.append("<p>Everything in the two fingerprints and their comparison that the report "
818
+ "reads is described above.</p>")
819
+ return _section("reading", "How to read this page", "".join(out))
820
+
821
+
822
+ # -- the document -----------------------------------------------------------------------------
823
+
824
+
825
+ def summary(view: DriftView) -> str:
826
+ """The short terminal summary of a comparison: three to five plain lines."""
827
+ try:
828
+ p = _Ctx(view)
829
+ except Exception: # noqa: BLE001
830
+ p = _Ctx(DriftView())
831
+ lines = [_heading(p, None), _verdict(p)[1]]
832
+ counts = [(len(p.by_status(s)), s) for s in ("drifted", "changed", "added", "removed",
833
+ "steady")]
834
+ said = [f"{fmt.count(n)} {s}" for n, s in counts if n]
835
+ if said:
836
+ lines.append("Columns: " + ", ".join(said))
837
+ top = [c.name for c in p.by_status("drifted", "changed") if isinstance(c.name, str)]
838
+ if top:
839
+ lines.append("Most changed: " + fmt.join(top, LEDE_NAMES))
840
+ unread = [*(view.unread or []), *p.a.all_unread(), *p.b.all_unread()]
841
+ if unread:
842
+ lines.append(f"Not described: {fmt.plural(len(unread), 'item')} this version of the "
843
+ "report does not read")
844
+ return "\n".join(lines)
845
+
846
+
847
+ def render_drift(view: DriftView, *, title: str | None = None,
848
+ notices: Sequence[str] = (), max_cards: int | None = None) -> str:
849
+ """The comparison page as one HTML document. Never raises on a view of the documented
850
+ types (including ``DriftView()``). ``max_cards`` draws charts for at most that many
851
+ changed columns (the most changed) and lists the rest in a table."""
852
+ try:
853
+ p = _Ctx(view)
854
+ except Exception: # noqa: BLE001 - a malformed view still gives a page
855
+ p = _Ctx(DriftView())
856
+ try:
857
+ heading = _heading(p, title if isinstance(title, str) else None)
858
+ except Exception: # noqa: BLE001
859
+ heading = "Two fingerprints compared"
860
+ page_title = f"{heading}: comparison report" if not title else heading
861
+
862
+ counts = {"changed": len(p.by_status("drifted", "changed")),
863
+ "steady": len(p.by_status("steady"))}
864
+ rail = ['<nav class="rail" aria-label="Sections"><p class="brand">Ectype <span>comparison '
865
+ "report</span></p><ol>"]
866
+ for sid, label in SECTIONS:
867
+ count = f" <span>{fmt.count(counts[sid])}</span>" if sid in counts else ""
868
+ rail.append(f'<li><a href="#{sid}">{label}{count}</a></li>')
869
+ rail.append("</ol></nav>")
870
+
871
+ builders: list[Callable[[], str]] = [
872
+ lambda: _overview(p, heading, notices),
873
+ lambda: _changed(p, max_cards if isinstance(max_cards, int) else None),
874
+ lambda: _relationships(p),
875
+ lambda: _schema(p),
876
+ lambda: _steady(p),
877
+ lambda: _reading(p),
878
+ ]
879
+ sections = []
880
+ for (sid, label), build in zip(SECTIONS, builders, strict=True):
881
+ html_ = _guard(build, "overview" if sid == "overview" else "section")
882
+ if not html_.startswith("<section"):
883
+ head = (f'<h1 id="{sid}-h">{_e(heading)}</h1>' if sid == "overview"
884
+ else f'<h2 id="{sid}-h">{label}</h2>')
885
+ html_ = f'<section id="{sid}" aria-labelledby="{sid}-h">{head}{html_}</section>'
886
+ sections.append(html_)
887
+
888
+ return "".join([
889
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">'
890
+ '<meta name="viewport" content="width=device-width,initial-scale=1">'
891
+ '<meta name="color-scheme" content="light dark">'
892
+ '<meta name="generator" content="Ectype profile report">'
893
+ f"<title>{_e(page_title)}</title><style>{CSS}</style></head><body>"
894
+ '<a class="skip" href="#main">Skip to the report</a><div class="shell">',
895
+ "".join(rail),
896
+ '<main id="main">',
897
+ "".join(sections),
898
+ f"<footer><p>{FOOTER}</p></footer></main></div><script>{SCRIPT}</script></body></html>",
899
+ ])
900
+
901
+
902
+ __all__ = ["METRIC_WORDS", "SECTIONS", "metric_words", "render_drift", "summary"]