mintchip 0.2.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.
- mintchip/__init__.py +101 -0
- mintchip/__main__.py +7 -0
- mintchip/chips/__init__.py +7 -0
- mintchip/chips/bar.py +233 -0
- mintchip/chips/ci.py +194 -0
- mintchip/chips/delta.py +164 -0
- mintchip/chips/dist.py +384 -0
- mintchip/chips/funnel.py +129 -0
- mintchip/chips/gauge.py +197 -0
- mintchip/chips/num.py +55 -0
- mintchip/chips/rank.py +182 -0
- mintchip/chips/ratio.py +141 -0
- mintchip/chips/share.py +164 -0
- mintchip/chips/spark.py +278 -0
- mintchip/chips/strip.py +173 -0
- mintchip/chips/timeline.py +257 -0
- mintchip/chips/waterfall.py +212 -0
- mintchip/cli.py +691 -0
- mintchip/diff.py +645 -0
- mintchip/directives.py +782 -0
- mintchip/doctor.py +145 -0
- mintchip/fmt.py +135 -0
- mintchip/guide.py +189 -0
- mintchip/ingest.py +725 -0
- mintchip/prose.py +225 -0
- mintchip/render/__init__.py +1 -0
- mintchip/render/html.py +295 -0
- mintchip/render/svg_base.py +337 -0
- mintchip/render/text_base.py +215 -0
- mintchip/scales.py +117 -0
- mintchip/skill.py +332 -0
- mintchip/spec.py +659 -0
- mintchip/tables.py +1043 -0
- mintchip/themes.py +102 -0
- mintchip-0.2.0.dist-info/METADATA +274 -0
- mintchip-0.2.0.dist-info/RECORD +39 -0
- mintchip-0.2.0.dist-info/WHEEL +4 -0
- mintchip-0.2.0.dist-info/entry_points.txt +2 -0
- mintchip-0.2.0.dist-info/licenses/LICENSE +21 -0
mintchip/spec.py
ADDED
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
"""The chip record, the kind registry and the registration decorators.
|
|
2
|
+
|
|
3
|
+
A chip kind is one module in ``mintchip/chips/`` that registers three functions::
|
|
4
|
+
|
|
5
|
+
@chip("spark", question=..., have=..., params=(Param(...), ...), example={...}, size="m")
|
|
6
|
+
def spark(values, *, band=None, ...) -> Built: ... # validate, compute stats
|
|
7
|
+
|
|
8
|
+
@text_renderer("spark")
|
|
9
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut: ...
|
|
10
|
+
|
|
11
|
+
@svg_renderer("spark")
|
|
12
|
+
def _svg(chip: Chip, c: Canvas) -> None: ...
|
|
13
|
+
|
|
14
|
+
``@chip`` checks the function signature against ``params`` at import, and wraps it so that
|
|
15
|
+
every argument arrives already type-checked and normalised (see ``Param``), any ``ChipError``
|
|
16
|
+
names ``mintchip.<kind>``, and the returned ``Built`` becomes a ``Chip``.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import functools
|
|
22
|
+
import inspect
|
|
23
|
+
import json
|
|
24
|
+
import math
|
|
25
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
26
|
+
from dataclasses import dataclass, replace
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from .render import html as _html
|
|
31
|
+
from .render.svg_base import SIZES, Canvas, svg_root
|
|
32
|
+
from .render.text_base import TextOptions, TextOut, ansi, plain, to_ascii
|
|
33
|
+
from .themes import resolve_theme
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"CATALOG_ORDER",
|
|
37
|
+
"REGISTRY",
|
|
38
|
+
"Built",
|
|
39
|
+
"Chip",
|
|
40
|
+
"ChipError",
|
|
41
|
+
"Kind",
|
|
42
|
+
"Param",
|
|
43
|
+
"catalog",
|
|
44
|
+
"chip",
|
|
45
|
+
"domain_warnings",
|
|
46
|
+
"from_dict",
|
|
47
|
+
"own_scale",
|
|
48
|
+
"sibling_domain",
|
|
49
|
+
"svg_renderer",
|
|
50
|
+
"text_renderer",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
CATALOG_ORDER = (
|
|
54
|
+
"num", "spark", "ci", "dist", "bar", "gauge", "delta", "strip", "share", "ratio",
|
|
55
|
+
"timeline", "rank", "waterfall", "funnel",
|
|
56
|
+
) # fmt: skip
|
|
57
|
+
|
|
58
|
+
PARAM_TYPES = ("number", "int", "string", "bool", "numbers", "range", "strings", "values",
|
|
59
|
+
"mapping") # fmt: skip
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ChipError(ValueError):
|
|
63
|
+
"""A validation failure, with a ``fix_hint`` an agent or a person can act on."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, message: str, *, fix_hint: str | None = None) -> None:
|
|
66
|
+
self.message = message
|
|
67
|
+
self.fix_hint = fix_hint
|
|
68
|
+
super().__init__(f"{message} Fix: {fix_hint}" if fix_hint else message)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class Param:
|
|
73
|
+
"""One constructor argument. The CLI, JSON Schema and guide are generated from these.
|
|
74
|
+
|
|
75
|
+
Types, and what the constructor body receives after normalisation:
|
|
76
|
+
``number`` float · ``int`` int · ``string`` str · ``bool`` bool ·
|
|
77
|
+
``numbers`` list[float | None] (None or NaN is a gap) · ``range`` (lo, hi) tuple, lo ≤ hi ·
|
|
78
|
+
``strings`` list[str] · ``values`` list[bool | str | float | None] ·
|
|
79
|
+
``mapping`` dict[str, float | (float, float)] from a dict or a list of pairs.
|
|
80
|
+
Sequence types accept any iterable. None always means "not given".
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
name: str
|
|
84
|
+
type: str
|
|
85
|
+
help: str
|
|
86
|
+
required: bool = False
|
|
87
|
+
positional: bool = False
|
|
88
|
+
default: Any = None
|
|
89
|
+
choices: tuple[str, ...] | None = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class Built:
|
|
94
|
+
"""What a constructor body returns; ``@chip`` adds kind, args, label and unit."""
|
|
95
|
+
|
|
96
|
+
stats: Mapping[str, Any]
|
|
97
|
+
facts: Iterable[str]
|
|
98
|
+
alt: str
|
|
99
|
+
warnings: Iterable[str] = ()
|
|
100
|
+
domain: tuple[float, float] | None = None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class Kind:
|
|
105
|
+
"""A registered chip kind. ``fn`` is the public, validating constructor."""
|
|
106
|
+
|
|
107
|
+
name: str
|
|
108
|
+
fn: Callable[..., Chip]
|
|
109
|
+
question: str
|
|
110
|
+
have: str
|
|
111
|
+
params: tuple[Param, ...]
|
|
112
|
+
example: Mapping[str, Any]
|
|
113
|
+
size: str = "m"
|
|
114
|
+
text: Callable[[Chip, TextOptions], TextOut] | None = None
|
|
115
|
+
svg: Callable[[Chip, Canvas], None] | None = None
|
|
116
|
+
cuts: Callable[[Chip, tuple[float, float], bool], list[str]] | None = None
|
|
117
|
+
own_scale: bool = False # the natural scale is each chip's own total (bar)
|
|
118
|
+
|
|
119
|
+
def example_chip(self) -> Chip:
|
|
120
|
+
return self.fn(**self.example)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
REGISTRY: dict[str, Kind] = {}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# --- the record -----------------------------------------------------------------------------
|
|
127
|
+
@dataclass(frozen=True)
|
|
128
|
+
class Chip:
|
|
129
|
+
"""A chip is data: validated arguments, computed stats, facts and warnings. It holds no
|
|
130
|
+
theme, size or drawing; everything visual is a render argument."""
|
|
131
|
+
|
|
132
|
+
kind: str
|
|
133
|
+
args: Mapping[str, Any]
|
|
134
|
+
stats: Mapping[str, Any]
|
|
135
|
+
facts: tuple[str, ...]
|
|
136
|
+
warnings: tuple[str, ...]
|
|
137
|
+
alt: str
|
|
138
|
+
label: str | None = None
|
|
139
|
+
unit: str | None = None
|
|
140
|
+
domain: tuple[float, float] | None = None
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def _kind(self) -> Kind:
|
|
144
|
+
if self.kind not in REGISTRY:
|
|
145
|
+
raise ChipError(f"mintchip: unknown chip kind {self.kind!r}.", fix_hint=_kinds_hint())
|
|
146
|
+
return REGISTRY[self.kind]
|
|
147
|
+
|
|
148
|
+
def _domain(self, domain: Any) -> tuple[float, float] | None:
|
|
149
|
+
"""Render argument, then ``args["domain"]``, then ``chip.domain``."""
|
|
150
|
+
if domain is not None:
|
|
151
|
+
lo, hi = _range(f"{self.kind}.render", "domain", domain)
|
|
152
|
+
if not lo < hi:
|
|
153
|
+
raise ChipError(
|
|
154
|
+
f"mintchip.{self.kind}: domain must have lo < hi; got {domain!r}.",
|
|
155
|
+
fix_hint="Pass domain=(lo, hi), e.g. from mintchip.shared_domain(a, b).",
|
|
156
|
+
)
|
|
157
|
+
return lo, hi
|
|
158
|
+
if self.args.get("domain") is not None:
|
|
159
|
+
lo, hi = self.args["domain"]
|
|
160
|
+
return float(lo), float(hi)
|
|
161
|
+
return self.domain
|
|
162
|
+
|
|
163
|
+
def _text_out(
|
|
164
|
+
self, ascii: bool, compact: bool, domain: Any, decimals: int | None = None
|
|
165
|
+
) -> TextOut:
|
|
166
|
+
render = self._kind.text
|
|
167
|
+
if render is None:
|
|
168
|
+
raise ChipError(f"mintchip.{self.kind} has no text renderer.")
|
|
169
|
+
if decimals is not None and (isinstance(decimals, bool) or not isinstance(decimals, int)):
|
|
170
|
+
raise ChipError(
|
|
171
|
+
f"mintchip.{self.kind}: decimals must be a whole number; got {decimals!r}.",
|
|
172
|
+
fix_hint="Pass decimals=2, or leave it out for the chip's own precision.",
|
|
173
|
+
)
|
|
174
|
+
o = TextOptions(
|
|
175
|
+
ascii=ascii, compact=compact, domain=self._domain(domain), decimals=decimals
|
|
176
|
+
)
|
|
177
|
+
return render(self, o)
|
|
178
|
+
|
|
179
|
+
def text(
|
|
180
|
+
self,
|
|
181
|
+
*,
|
|
182
|
+
ascii: bool = False,
|
|
183
|
+
compact: bool = False,
|
|
184
|
+
value: bool = True,
|
|
185
|
+
color: bool = False,
|
|
186
|
+
domain: Any = None,
|
|
187
|
+
decimals: int | None = None,
|
|
188
|
+
) -> str:
|
|
189
|
+
"""``"{value} {glyph}"``. ``ascii`` is pure ASCII, ``compact`` shortens the value,
|
|
190
|
+
``color`` adds ANSI colour by ink role, ``domain`` imposes a shared scale, ``decimals``
|
|
191
|
+
sets the decimal places of the primary value (kinds whose value is a decimal number)."""
|
|
192
|
+
out = self._text_out(ascii, compact, domain, decimals)
|
|
193
|
+
glyph = ansi(out.glyph, ascii=ascii) if color else plain(out.glyph, ascii=ascii)
|
|
194
|
+
if not value:
|
|
195
|
+
return glyph
|
|
196
|
+
val = to_ascii(out.value) if ascii else out.value
|
|
197
|
+
return f"{val} {glyph}" if glyph else val
|
|
198
|
+
|
|
199
|
+
def value(
|
|
200
|
+
self, *, compact: bool = False, ascii: bool = False, decimals: int | None = None
|
|
201
|
+
) -> str:
|
|
202
|
+
"""The value part of ``text()`` alone, without the glyph: ``compact`` shortens it,
|
|
203
|
+
``ascii`` makes it pure ASCII, ``decimals`` sets the primary value's decimal places."""
|
|
204
|
+
v = self._text_out(ascii, compact, None, decimals).value
|
|
205
|
+
return to_ascii(v) if ascii else v
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
def value_text(self) -> str:
|
|
209
|
+
"""The value part of ``text()``, in full: ``value()`` with no options."""
|
|
210
|
+
return self.value()
|
|
211
|
+
|
|
212
|
+
def warnings_for(self, domain: Any = None) -> tuple[str, ...]:
|
|
213
|
+
"""The warnings that hold when the chip is drawn on ``domain``, as a table column or a
|
|
214
|
+
prose group imposes one: a shared scale can bring a clipped value back on scale, or cut
|
|
215
|
+
data the chip's own scale kept. ``warnings`` is the set for the chip's own scale, and
|
|
216
|
+
``warnings_for(None)`` returns it."""
|
|
217
|
+
cuts = self._kind.cuts
|
|
218
|
+
if domain is None or cuts is None:
|
|
219
|
+
return self.warnings
|
|
220
|
+
own = self._domain(None)
|
|
221
|
+
stale = set(cuts(self, own, self.args.get("domain") is None)) if own else set()
|
|
222
|
+
kept = tuple(w for w in self.warnings if w not in stale)
|
|
223
|
+
return kept + tuple(cuts(self, self._domain(domain), False))
|
|
224
|
+
|
|
225
|
+
def svg(
|
|
226
|
+
self,
|
|
227
|
+
*,
|
|
228
|
+
theme: Any = "auto",
|
|
229
|
+
accent: str | None = None,
|
|
230
|
+
domain: Any = None,
|
|
231
|
+
size: str | None = None,
|
|
232
|
+
standalone: bool = False,
|
|
233
|
+
) -> str:
|
|
234
|
+
"""Inline SVG, 1em tall. ``theme`` is auto (follows the text colour), light, dark or
|
|
235
|
+
mono; ``size`` is s, m or l; ``standalone`` embeds light/dark CSS for a .svg file.
|
|
236
|
+
Returns "" for kinds that have no graphic."""
|
|
237
|
+
k = self._kind
|
|
238
|
+
if k.svg is None:
|
|
239
|
+
return ""
|
|
240
|
+
try:
|
|
241
|
+
th = resolve_theme(theme, accent)
|
|
242
|
+
except (TypeError, ValueError) as e:
|
|
243
|
+
raise ChipError(f"mintchip.{self.kind}: {e}.", fix_hint="Use theme='auto'.") from None
|
|
244
|
+
size = size or k.size
|
|
245
|
+
if size not in SIZES:
|
|
246
|
+
raise ChipError(
|
|
247
|
+
f"mintchip.{self.kind}: unknown size {size!r}.", fix_hint="Use 's', 'm' or 'l'."
|
|
248
|
+
)
|
|
249
|
+
natural = domain is None and self.args.get("domain") is None
|
|
250
|
+
c = Canvas(SIZES[size], th, self._domain(domain), natural=natural)
|
|
251
|
+
k.svg(self, c)
|
|
252
|
+
return svg_root(
|
|
253
|
+
c, alt=self.alt, facts=self.facts, spec=self.to_dict(), standalone=standalone
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
def html(
|
|
257
|
+
self,
|
|
258
|
+
*,
|
|
259
|
+
theme: Any = "auto",
|
|
260
|
+
accent: str | None = None,
|
|
261
|
+
domain: Any = None,
|
|
262
|
+
value: bool = True,
|
|
263
|
+
label: bool = False,
|
|
264
|
+
details: bool = True,
|
|
265
|
+
detail: str | None = None,
|
|
266
|
+
compact: bool = True,
|
|
267
|
+
decimals: int | None = None,
|
|
268
|
+
) -> str:
|
|
269
|
+
"""Inline HTML, valid inside ``<p>`` and ``<td>``: the value in the text's own type,
|
|
270
|
+
then the SVG. ``compact`` shows the short value; ``decimals`` sets the primary value's
|
|
271
|
+
decimal places; ``details`` adds a no-JavaScript popover with the label, the full
|
|
272
|
+
value, the facts the sentence does not already show, the warnings that hold on this
|
|
273
|
+
``domain`` and ``detail`` (trusted HTML, appended)."""
|
|
274
|
+
full = self._text_out(False, False, domain, decimals).value
|
|
275
|
+
shown = self._text_out(False, True, domain, decimals).value if compact else full
|
|
276
|
+
return _html.chip_html(
|
|
277
|
+
self,
|
|
278
|
+
svg=self.svg(theme=theme, accent=accent, domain=domain),
|
|
279
|
+
value=shown if value else None,
|
|
280
|
+
full=full,
|
|
281
|
+
label=self.label if label else None,
|
|
282
|
+
details=details,
|
|
283
|
+
detail=detail,
|
|
284
|
+
warnings=self.warnings_for(domain),
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def markdown(self, *, compact: bool = False) -> str:
|
|
288
|
+
"""The text form in a code span."""
|
|
289
|
+
t = self.text(compact=compact)
|
|
290
|
+
return f"`` {t} ``" if "`" in t else f"`{t}`"
|
|
291
|
+
|
|
292
|
+
def to_dict(self) -> dict[str, Any]:
|
|
293
|
+
"""``{"chip": kind, **args}``: JSON-safe, and ``from_dict`` rebuilds the chip."""
|
|
294
|
+
return {"chip": self.kind, **json.loads(json.dumps(dict(self.args)))}
|
|
295
|
+
|
|
296
|
+
def summary(self) -> dict[str, Any]:
|
|
297
|
+
return {
|
|
298
|
+
"kind": self.kind,
|
|
299
|
+
"label": self.label,
|
|
300
|
+
"value": self.value_text,
|
|
301
|
+
"text": self.text(),
|
|
302
|
+
"alt": self.alt,
|
|
303
|
+
"facts": list(self.facts),
|
|
304
|
+
"warnings": list(self.warnings),
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
def save(self, path: str | Path, **render_options: Any) -> dict[str, Any]:
|
|
308
|
+
"""Write ``.svg`` (standalone), ``.html``, ``.txt`` or ``.json``; returns the summary."""
|
|
309
|
+
dest = Path(path)
|
|
310
|
+
suffix = dest.suffix.lower()
|
|
311
|
+
try:
|
|
312
|
+
if suffix == ".svg":
|
|
313
|
+
content = self.svg(standalone=True, **render_options)
|
|
314
|
+
if not content:
|
|
315
|
+
raise ChipError(
|
|
316
|
+
f"mintchip.{self.kind} has no graphic to save as .svg.",
|
|
317
|
+
fix_hint="Save as .html, .txt or .json.",
|
|
318
|
+
)
|
|
319
|
+
elif suffix in (".html", ".htm"):
|
|
320
|
+
opts = {"label": True, "compact": False, **render_options}
|
|
321
|
+
content = _html.page(self.html(**opts), title=self.alt)
|
|
322
|
+
elif suffix == ".txt":
|
|
323
|
+
content = self.text(**render_options) + "\n"
|
|
324
|
+
elif suffix == ".json":
|
|
325
|
+
content = json.dumps(self.to_dict(), ensure_ascii=False, **render_options) + "\n"
|
|
326
|
+
else:
|
|
327
|
+
raise ChipError(
|
|
328
|
+
f"mintchip.{self.kind}.save: unsupported extension {suffix!r}.",
|
|
329
|
+
fix_hint="Save as .svg, .html, .txt or .json.",
|
|
330
|
+
)
|
|
331
|
+
except TypeError as e:
|
|
332
|
+
raise ChipError(
|
|
333
|
+
f"mintchip.{self.kind}.save: {e}.",
|
|
334
|
+
fix_hint="Pass only the options of the matching render method.",
|
|
335
|
+
) from None
|
|
336
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
337
|
+
dest.write_text(content, encoding="utf-8")
|
|
338
|
+
return {**self.summary(), "path": str(dest)}
|
|
339
|
+
|
|
340
|
+
def __str__(self) -> str:
|
|
341
|
+
return self.text()
|
|
342
|
+
|
|
343
|
+
def __repr__(self) -> str:
|
|
344
|
+
t = self.text()
|
|
345
|
+
return f"<Chip {self.kind}: {t if len(t) <= 80 else t[:79] + '…'}>"
|
|
346
|
+
|
|
347
|
+
def _repr_html_(self) -> str:
|
|
348
|
+
return f"<style>{_html.css()}</style>{self.html()}"
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
# --- registration ---------------------------------------------------------------------------
|
|
352
|
+
def chip(
|
|
353
|
+
name: str,
|
|
354
|
+
*,
|
|
355
|
+
question: str,
|
|
356
|
+
have: str,
|
|
357
|
+
params: tuple[Param, ...],
|
|
358
|
+
example: Mapping[str, Any],
|
|
359
|
+
size: str = "m",
|
|
360
|
+
) -> Callable[[Callable[..., Built]], Callable[..., Chip]]:
|
|
361
|
+
"""Register a chip constructor. The body receives normalised arguments and returns
|
|
362
|
+
``Built(stats=..., facts=..., alt=..., warnings=..., domain=...)``."""
|
|
363
|
+
|
|
364
|
+
def register(fn: Callable[..., Built]) -> Callable[..., Chip]:
|
|
365
|
+
sig = inspect.signature(fn)
|
|
366
|
+
_check_params(name, fn, sig, params, size)
|
|
367
|
+
|
|
368
|
+
@functools.wraps(fn)
|
|
369
|
+
def build(*a: Any, **kw: Any) -> Chip:
|
|
370
|
+
try:
|
|
371
|
+
bound = sig.bind(*a, **kw)
|
|
372
|
+
except TypeError as e:
|
|
373
|
+
raise _call_error(name, params, kw, e) from None
|
|
374
|
+
bound.apply_defaults()
|
|
375
|
+
values = {p.name: _coerce(name, p, bound.arguments[p.name]) for p in params}
|
|
376
|
+
try:
|
|
377
|
+
out = fn(**values)
|
|
378
|
+
except ChipError as e:
|
|
379
|
+
if e.message.startswith("mintchip."):
|
|
380
|
+
raise
|
|
381
|
+
raise ChipError(f"mintchip.{name}: {e.message}", fix_hint=e.fix_hint) from None
|
|
382
|
+
args = {}
|
|
383
|
+
for p in params:
|
|
384
|
+
v = _jsonable(values[p.name])
|
|
385
|
+
if v != _jsonable(p.default):
|
|
386
|
+
args[p.name] = v
|
|
387
|
+
return Chip(
|
|
388
|
+
kind=name,
|
|
389
|
+
args=args,
|
|
390
|
+
stats=dict(out.stats),
|
|
391
|
+
facts=tuple(out.facts),
|
|
392
|
+
warnings=tuple(out.warnings),
|
|
393
|
+
alt=out.alt,
|
|
394
|
+
label=values.get("label"),
|
|
395
|
+
unit=values.get("unit"),
|
|
396
|
+
domain=None if out.domain is None else (float(out.domain[0]), float(out.domain[1])),
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
prior = REGISTRY.get(name)
|
|
400
|
+
if prior is not None and prior.fn.__module__ != fn.__module__:
|
|
401
|
+
raise ValueError(f"chip kind {name!r} is already registered by {prior.fn.__module__}")
|
|
402
|
+
REGISTRY[name] = Kind(name, build, question, have, tuple(params), dict(example), size)
|
|
403
|
+
return build
|
|
404
|
+
|
|
405
|
+
return register
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def own_scale(name: str) -> None:
|
|
409
|
+
"""Declare that this kind's natural scale is each chip's own total (call after ``@chip``).
|
|
410
|
+
|
|
411
|
+
Siblings of such a kind share a scale only when their scales already agree: 38/40 beside
|
|
412
|
+
1,840/1,850 are two shares, and drawing both against 1,850 would empty the first bar.
|
|
413
|
+
"""
|
|
414
|
+
REGISTRY[name] = replace(_registered(name), own_scale=True)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def sibling_domain(kind: str, domains: Iterable[Any]) -> tuple[float, float] | None:
|
|
418
|
+
"""One scale for sibling chips of one kind (a table column, a group in a sentence), or
|
|
419
|
+
None when each should keep its own."""
|
|
420
|
+
ds = [(float(d[0]), float(d[1])) for d in domains if d is not None]
|
|
421
|
+
if not ds:
|
|
422
|
+
return None
|
|
423
|
+
if _registered(kind).own_scale and len(set(ds)) > 1:
|
|
424
|
+
return None
|
|
425
|
+
return min(d[0] for d in ds), max(d[1] for d in ds)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def text_renderer(name: str) -> Callable[[Callable[[Chip, TextOptions], TextOut]], Any]:
|
|
429
|
+
"""Register ``render(chip, o: TextOptions) -> TextOut`` for a kind (after ``@chip``)."""
|
|
430
|
+
|
|
431
|
+
def register(fn: Callable[[Chip, TextOptions], TextOut]) -> Callable[..., TextOut]:
|
|
432
|
+
REGISTRY[name] = replace(_registered(name), text=fn)
|
|
433
|
+
return fn
|
|
434
|
+
|
|
435
|
+
return register
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def svg_renderer(name: str) -> Callable[[Callable[[Chip, Canvas], None]], Any]:
|
|
439
|
+
"""Register ``render(chip, c: Canvas) -> None`` for a kind (after ``@chip``)."""
|
|
440
|
+
|
|
441
|
+
def register(fn: Callable[[Chip, Canvas], None]) -> Callable[..., None]:
|
|
442
|
+
REGISTRY[name] = replace(_registered(name), svg=fn)
|
|
443
|
+
return fn
|
|
444
|
+
|
|
445
|
+
return register
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def domain_warnings(
|
|
449
|
+
name: str,
|
|
450
|
+
) -> Callable[[Callable[[Chip, tuple[float, float], bool], list[str]]], Any]:
|
|
451
|
+
"""Register ``cuts(chip, domain, own) -> [warning, ...]`` for a kind (after ``@chip``): the
|
|
452
|
+
warnings that depend on the scale, for a resolved ``domain``; ``own`` is True when that is
|
|
453
|
+
the chip's natural scale. The constructor must produce the same lines for its own scale, so
|
|
454
|
+
``Chip.warnings_for`` can swap them for those of an imposed one."""
|
|
455
|
+
|
|
456
|
+
def register(fn: Callable[[Chip, tuple[float, float], bool], list[str]]) -> Any:
|
|
457
|
+
REGISTRY[name] = replace(_registered(name), cuts=fn)
|
|
458
|
+
return fn
|
|
459
|
+
|
|
460
|
+
return register
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def from_dict(d: Mapping[str, Any]) -> Chip:
|
|
464
|
+
"""Rebuild a chip from ``chip.to_dict()`` (or any ``{"chip": kind, **args}`` spec)."""
|
|
465
|
+
if not isinstance(d, Mapping) or "chip" not in d:
|
|
466
|
+
raise ChipError(
|
|
467
|
+
"mintchip.from_dict needs a dict with a 'chip' key.",
|
|
468
|
+
fix_hint='Pass e.g. {"chip": "spark", "values": [1, 2, 3]}.',
|
|
469
|
+
)
|
|
470
|
+
kind = d["chip"]
|
|
471
|
+
if kind not in REGISTRY:
|
|
472
|
+
raise ChipError(f"mintchip.from_dict: unknown chip {kind!r}.", fix_hint=_kinds_hint(kind))
|
|
473
|
+
return REGISTRY[kind].fn(**{k: v for k, v in d.items() if k != "chip"})
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def catalog() -> tuple[dict[str, str], ...]:
|
|
477
|
+
"""Registered kinds in catalog order: name, question, have."""
|
|
478
|
+
order = {k: i for i, k in enumerate(CATALOG_ORDER)}
|
|
479
|
+
kinds = sorted(REGISTRY.values(), key=lambda k: (order.get(k.name, len(order)), k.name))
|
|
480
|
+
return tuple({"name": k.name, "question": k.question, "have": k.have} for k in kinds)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
# --- internals ------------------------------------------------------------------------------
|
|
484
|
+
def _registered(name: str) -> Kind:
|
|
485
|
+
if name not in REGISTRY:
|
|
486
|
+
raise ValueError(f"register the constructor with @chip({name!r}) before its renderers")
|
|
487
|
+
return REGISTRY[name]
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _kinds_hint(near: Any = None) -> str:
|
|
491
|
+
names = sorted(REGISTRY)
|
|
492
|
+
if isinstance(near, str):
|
|
493
|
+
import difflib
|
|
494
|
+
|
|
495
|
+
close = difflib.get_close_matches(near, names, n=1)
|
|
496
|
+
if close:
|
|
497
|
+
return f"Did you mean {close[0]!r}? Kinds: {', '.join(names)}."
|
|
498
|
+
return f"Use one of: {', '.join(names)}."
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def _check_params(
|
|
502
|
+
name: str, fn: Callable[..., Any], sig: inspect.Signature, params: tuple[Param, ...], size: str
|
|
503
|
+
) -> None:
|
|
504
|
+
where = f"@chip({name!r}) on {fn.__module__}.{fn.__name__}"
|
|
505
|
+
if size not in SIZES:
|
|
506
|
+
raise TypeError(f"{where}: size must be one of {', '.join(SIZES)}")
|
|
507
|
+
fn_names = list(sig.parameters)
|
|
508
|
+
p_names = [p.name for p in params]
|
|
509
|
+
if fn_names != p_names:
|
|
510
|
+
raise TypeError(f"{where}: signature {fn_names} does not match params {p_names}")
|
|
511
|
+
for p, sp in zip(params, sig.parameters.values(), strict=True):
|
|
512
|
+
if p.type not in PARAM_TYPES:
|
|
513
|
+
raise TypeError(f"{where}: param {p.name!r} has unknown type {p.type!r}")
|
|
514
|
+
if p.positional != (sp.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD):
|
|
515
|
+
raise TypeError(f"{where}: {p.name!r} positional={p.positional} disagrees with def")
|
|
516
|
+
if sp.kind not in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY):
|
|
517
|
+
raise TypeError(f"{where}: {p.name!r} must be a plain or keyword-only argument")
|
|
518
|
+
has_default = sp.default is not inspect.Parameter.empty
|
|
519
|
+
if p.required == has_default:
|
|
520
|
+
raise TypeError(f"{where}: {p.name!r} required={p.required} disagrees with def")
|
|
521
|
+
if has_default and sp.default != p.default:
|
|
522
|
+
raise TypeError(f"{where}: {p.name!r} default {sp.default!r} != {p.default!r}")
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _call_error(name: str, params: tuple[Param, ...], kw: Mapping[str, Any], e: TypeError):
|
|
526
|
+
names = [p.name for p in params]
|
|
527
|
+
unknown = [k for k in kw if k not in names]
|
|
528
|
+
if unknown:
|
|
529
|
+
import difflib
|
|
530
|
+
|
|
531
|
+
close = difflib.get_close_matches(unknown[0], names, n=1)
|
|
532
|
+
hint = f"Did you mean {close[0]}=?" if close else f"Accepted: {', '.join(names)}."
|
|
533
|
+
return ChipError(f"mintchip.{name}: unknown argument {unknown[0]!r}.", fix_hint=hint)
|
|
534
|
+
usage = ", ".join(p.name for p in params if p.required)
|
|
535
|
+
return ChipError(f"mintchip.{name}: {e}.", fix_hint=f"Call mintchip.{name}({usage}, ...).")
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
_HINTS = {
|
|
539
|
+
"number": "a finite number, e.g. 0.82",
|
|
540
|
+
"int": "a whole number, e.g. 10",
|
|
541
|
+
"string": "a string",
|
|
542
|
+
"bool": "True or False",
|
|
543
|
+
"numbers": "a list of numbers (None for gaps), e.g. [0.9, 0.6, 0.4]",
|
|
544
|
+
"range": "a (lo, hi) pair with lo <= hi, e.g. (0.05, 0.11)",
|
|
545
|
+
"strings": 'a list of strings, e.g. ["a", "b"]',
|
|
546
|
+
"values": 'a list of booleans, strings, numbers or None, e.g. [True, "warn", False]',
|
|
547
|
+
"mapping": 'a dict or list of (name, number) pairs, e.g. {"fetch": 1.2, "solve": 4.8}',
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _fail(kind: str, p: Param | str, value: Any, why: str = "") -> ChipError:
|
|
552
|
+
name, ptype = (p.name, p.type) if isinstance(p, Param) else (p, "range")
|
|
553
|
+
got = repr(value)
|
|
554
|
+
got = got if len(got) <= 40 else got[:37] + "..."
|
|
555
|
+
msg = f"mintchip.{kind}: {name} must be {_HINTS[ptype].split(', e.g.')[0]}"
|
|
556
|
+
msg += f"; {why}." if why else f"; got {got} ({type(value).__name__})."
|
|
557
|
+
return ChipError(msg, fix_hint=f"Pass {name}= {_HINTS[ptype]}.")
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _number(kind: str, p: Param | str, v: Any, *, gaps: bool = False) -> float | None:
|
|
561
|
+
if v is None and gaps:
|
|
562
|
+
return None
|
|
563
|
+
if isinstance(v, (bool, str, bytes)) or v is None:
|
|
564
|
+
raise _fail(kind, p, v)
|
|
565
|
+
try:
|
|
566
|
+
f = float(v)
|
|
567
|
+
except (TypeError, ValueError):
|
|
568
|
+
raise _fail(kind, p, v) from None
|
|
569
|
+
if math.isnan(f) and gaps:
|
|
570
|
+
return None
|
|
571
|
+
if not math.isfinite(f):
|
|
572
|
+
raise _fail(kind, p, v, f"got {v!r}")
|
|
573
|
+
return f
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _items(kind: str, p: Param | str, v: Any) -> list[Any]:
|
|
577
|
+
if isinstance(v, (str, bytes, Mapping)) or not isinstance(v, Iterable):
|
|
578
|
+
raise _fail(kind, p, v)
|
|
579
|
+
return list(v)
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def _range(kind: str, p: Param | str, v: Any) -> tuple[float, float]:
|
|
583
|
+
items = _items(kind, p, v)
|
|
584
|
+
if len(items) != 2:
|
|
585
|
+
raise _fail(kind, p, v, f"got {len(items)} values")
|
|
586
|
+
lo, hi = (_number(kind, p, x) for x in items)
|
|
587
|
+
if lo > hi: # type: ignore[operator]
|
|
588
|
+
raise _fail(kind, p, v, f"got lo {lo} > hi {hi}")
|
|
589
|
+
return lo, hi # type: ignore[return-value]
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _coerce(kind: str, p: Param, v: Any) -> Any:
|
|
593
|
+
"""Type-check and normalise one argument (None passes through as "not given")."""
|
|
594
|
+
if v is None:
|
|
595
|
+
if p.required:
|
|
596
|
+
raise _fail(kind, p, v, "it is required")
|
|
597
|
+
return None
|
|
598
|
+
t = p.type
|
|
599
|
+
if t == "number":
|
|
600
|
+
return _number(kind, p, v)
|
|
601
|
+
if t == "int":
|
|
602
|
+
if isinstance(v, bool):
|
|
603
|
+
raise _fail(kind, p, v)
|
|
604
|
+
f = _number(kind, p, v)
|
|
605
|
+
if not float(f).is_integer(): # type: ignore[arg-type]
|
|
606
|
+
raise _fail(kind, p, v)
|
|
607
|
+
return int(f) # type: ignore[arg-type]
|
|
608
|
+
if t == "string":
|
|
609
|
+
if not isinstance(v, str):
|
|
610
|
+
raise _fail(kind, p, v)
|
|
611
|
+
if p.choices and v not in p.choices:
|
|
612
|
+
raise _fail(kind, p, v, f"got {v!r}; choose one of {', '.join(p.choices)}")
|
|
613
|
+
return v
|
|
614
|
+
if t == "bool":
|
|
615
|
+
if not (isinstance(v, bool) or type(v).__name__ == "bool_"):
|
|
616
|
+
raise _fail(kind, p, v)
|
|
617
|
+
return bool(v)
|
|
618
|
+
if t == "numbers":
|
|
619
|
+
return [_number(kind, p, x, gaps=True) for x in _items(kind, p, v)]
|
|
620
|
+
if t == "range":
|
|
621
|
+
lo, hi = _range(kind, p, v)
|
|
622
|
+
if p.name == "domain" and not lo < hi:
|
|
623
|
+
raise _fail(kind, p, v, f"got an empty domain ({lo}, {hi})")
|
|
624
|
+
return lo, hi
|
|
625
|
+
if t == "strings":
|
|
626
|
+
items = _items(kind, p, v)
|
|
627
|
+
if not all(isinstance(x, str) for x in items):
|
|
628
|
+
raise _fail(kind, p, v)
|
|
629
|
+
return items
|
|
630
|
+
if t == "values":
|
|
631
|
+
out: list[Any] = []
|
|
632
|
+
for x in _items(kind, p, v):
|
|
633
|
+
if x is None or isinstance(x, (bool, str)):
|
|
634
|
+
out.append(x)
|
|
635
|
+
else:
|
|
636
|
+
out.append(_number(kind, p, x, gaps=True))
|
|
637
|
+
return out
|
|
638
|
+
if t == "mapping":
|
|
639
|
+
pairs = list(v.items()) if isinstance(v, Mapping) else _items(kind, p, v)
|
|
640
|
+
result: dict[str, Any] = {}
|
|
641
|
+
for pair in pairs:
|
|
642
|
+
if isinstance(pair, (str, bytes)) or not isinstance(pair, Iterable):
|
|
643
|
+
raise _fail(kind, p, v)
|
|
644
|
+
kv = list(pair)
|
|
645
|
+
if len(kv) != 2 or not isinstance(kv[0], str) or kv[0] in result:
|
|
646
|
+
raise _fail(kind, p, v, f"bad or repeated entry {pair!r}")
|
|
647
|
+
val = kv[1]
|
|
648
|
+
is_pair = isinstance(val, Iterable) and not isinstance(val, (str, bytes))
|
|
649
|
+
result[kv[0]] = _range(kind, p, val) if is_pair else _number(kind, p, val)
|
|
650
|
+
return result
|
|
651
|
+
raise TypeError(f"unknown param type {t!r}")
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def _jsonable(v: Any) -> Any:
|
|
655
|
+
if isinstance(v, (tuple, list)):
|
|
656
|
+
return [_jsonable(x) for x in v]
|
|
657
|
+
if isinstance(v, dict):
|
|
658
|
+
return {k: _jsonable(x) for k, x in v.items()}
|
|
659
|
+
return v
|