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/cli.py
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
"""Command line, generated from the chip registry.
|
|
2
|
+
|
|
3
|
+
``mintchip <kind> …`` for every registered kind, plus ``render`` (prose with ``{{…}}``
|
|
4
|
+
directives), ``table``, ``guide``, ``schema`` and ``catalog``. stdout carries only the result;
|
|
5
|
+
warnings go to stderr as ``mintchip: warning: …`` (exit 1 under ``--strict``), and errors as
|
|
6
|
+
``mintchip: error: …`` with a ``fix:`` line (exit 2).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import csv
|
|
13
|
+
import difflib
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from collections.abc import Iterable, Sequence
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import mintchip as mc
|
|
22
|
+
|
|
23
|
+
from .directives import (
|
|
24
|
+
SYNTAX,
|
|
25
|
+
DirectiveError,
|
|
26
|
+
call_text,
|
|
27
|
+
example_call,
|
|
28
|
+
metavar,
|
|
29
|
+
parse_tokens,
|
|
30
|
+
)
|
|
31
|
+
from .spec import REGISTRY, Chip, ChipError, Param
|
|
32
|
+
|
|
33
|
+
FORMATS = ("text", "ansi", "md", "svg", "html", "json")
|
|
34
|
+
OUTPUT = (
|
|
35
|
+
Param(
|
|
36
|
+
"format",
|
|
37
|
+
"string",
|
|
38
|
+
"Choose the output: text (default), ansi (colour), md (code span), svg, html or json.",
|
|
39
|
+
default="text",
|
|
40
|
+
choices=FORMATS,
|
|
41
|
+
),
|
|
42
|
+
Param("ascii", "bool", "Print pure ASCII.", default=False),
|
|
43
|
+
Param("compact", "bool", "Shorten the value for use mid-sentence.", default=False),
|
|
44
|
+
Param("strict", "bool", "Exit 1 if the chip has warnings.", default=False),
|
|
45
|
+
)
|
|
46
|
+
COMMANDS = ("render", "table", "from", "diff", "guide", "skill", "doctor", "schema", "catalog")
|
|
47
|
+
TABLE_EXAMPLE = "mintchip table results.json --col model --col acc:bar --col lift:ci --sort acc"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# --- output helpers -------------------------------------------------------------------------
|
|
51
|
+
def _out(text: str) -> None:
|
|
52
|
+
"""Write to stdout, newline-terminated, without newline translation where possible."""
|
|
53
|
+
if not text.endswith("\n"):
|
|
54
|
+
text += "\n"
|
|
55
|
+
_write_raw(text)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _write_raw(text: str) -> None:
|
|
59
|
+
buf = getattr(sys.stdout, "buffer", None)
|
|
60
|
+
if buf is None:
|
|
61
|
+
sys.stdout.write(text)
|
|
62
|
+
return
|
|
63
|
+
sys.stdout.flush()
|
|
64
|
+
buf.write(text.encode("utf-8", "surrogateescape"))
|
|
65
|
+
buf.flush()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _err(line: str) -> None:
|
|
69
|
+
print(line, file=sys.stderr)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _error(e: ChipError, example: str | None = None) -> int:
|
|
73
|
+
errors = e.errors if isinstance(e, DirectiveError) else [(None, e)]
|
|
74
|
+
for where, err in errors:
|
|
75
|
+
msg = err.message
|
|
76
|
+
msg = re.sub(r"^mintchip(: |\.| )", "", msg)
|
|
77
|
+
_err(f"mintchip: error: {where}: {msg}" if where else f"mintchip: error: {msg}")
|
|
78
|
+
if err.fix_hint:
|
|
79
|
+
_err(f" fix: {err.fix_hint}")
|
|
80
|
+
hint = errors[-1][1].fix_hint or ""
|
|
81
|
+
if example and "mintchip " not in hint:
|
|
82
|
+
_err(f" example: {example}")
|
|
83
|
+
return 2
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _warn(warnings: Iterable[str], strict: bool) -> int:
|
|
87
|
+
warnings = list(warnings)
|
|
88
|
+
for w in warnings:
|
|
89
|
+
_err(f"mintchip: warning: {w}")
|
|
90
|
+
return 1 if strict and warnings else 0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _code_span(s: str) -> str:
|
|
94
|
+
return f"`` {s} ``" if "`" in s else f"`{s}`"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _read(path: str) -> str:
|
|
98
|
+
"""Read a file or stdin (``-``) as text, keeping line endings and undecodable bytes."""
|
|
99
|
+
try:
|
|
100
|
+
if path == "-":
|
|
101
|
+
buf = getattr(sys.stdin, "buffer", None)
|
|
102
|
+
data = buf.read() if buf is not None else sys.stdin.read().encode()
|
|
103
|
+
else:
|
|
104
|
+
data = Path(path).read_bytes()
|
|
105
|
+
except OSError as e:
|
|
106
|
+
raise ChipError(
|
|
107
|
+
f"mintchip: cannot read {path!r}: {e.strerror}.",
|
|
108
|
+
fix_hint="Pass an existing file, or - to read stdin.",
|
|
109
|
+
) from None
|
|
110
|
+
return data.decode("utf-8", "surrogateescape")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# --- kind commands --------------------------------------------------------------------------
|
|
114
|
+
def chip_output(c: Chip, *, format: str = "text", ascii: bool = False, compact: bool = False):
|
|
115
|
+
"""The text a kind command prints for ``c`` in ``format``."""
|
|
116
|
+
if format == "text":
|
|
117
|
+
return c.text(ascii=ascii, compact=compact)
|
|
118
|
+
if format == "ansi":
|
|
119
|
+
return c.text(ascii=ascii, compact=compact, color=True)
|
|
120
|
+
if format == "md":
|
|
121
|
+
return _code_span(c.text(ascii=ascii, compact=compact))
|
|
122
|
+
if format == "svg":
|
|
123
|
+
svg = c.svg(standalone=True)
|
|
124
|
+
if not svg:
|
|
125
|
+
raise ChipError(
|
|
126
|
+
f"mintchip.{c.kind} has no graphic.", fix_hint="Use --format text, md or html."
|
|
127
|
+
)
|
|
128
|
+
return svg
|
|
129
|
+
if format == "html":
|
|
130
|
+
return c.html()
|
|
131
|
+
if format == "json":
|
|
132
|
+
return json.dumps({**c.summary(), "spec": c.to_dict()}, indent=2, ensure_ascii=ascii)
|
|
133
|
+
raise _bad_format(format, FORMATS)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _bad_format(fmt: str, allowed: Sequence[str]) -> ChipError:
|
|
137
|
+
close = difflib.get_close_matches(fmt, allowed, n=1, cutoff=0.5)
|
|
138
|
+
alias = "md" if fmt in ("markdown", "gfm") and "md" in allowed else None
|
|
139
|
+
best = alias or (close[0] if close else None)
|
|
140
|
+
hint = f"Use --format {best}." if best else f"Use one of: {', '.join(allowed)}."
|
|
141
|
+
return ChipError(f"mintchip: unknown format {fmt!r}.", fix_hint=hint)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _cmd_kind(kind: str, tokens: Sequence[str]) -> int:
|
|
145
|
+
example = example_call(kind)
|
|
146
|
+
try:
|
|
147
|
+
kw = parse_tokens(kind, tokens, extra=OUTPUT, style="cli")
|
|
148
|
+
opts = {p.name: kw.pop(p.name, p.default) for p in OUTPUT}
|
|
149
|
+
if opts["format"] not in FORMATS:
|
|
150
|
+
raise _bad_format(opts["format"], FORMATS)
|
|
151
|
+
c = REGISTRY[kind].fn(**kw)
|
|
152
|
+
text = chip_output(c, format=opts["format"], ascii=opts["ascii"], compact=opts["compact"])
|
|
153
|
+
except ChipError as e:
|
|
154
|
+
return _error(e, example)
|
|
155
|
+
_out(text)
|
|
156
|
+
return _warn(c.warnings, opts["strict"])
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# --- render ---------------------------------------------------------------------------------
|
|
160
|
+
def _cmd_render(args: argparse.Namespace) -> int:
|
|
161
|
+
from . import directives
|
|
162
|
+
|
|
163
|
+
text = _read(args.file)
|
|
164
|
+
title = args.title or (Path(args.file).stem if args.file != "-" else "mintchip")
|
|
165
|
+
try:
|
|
166
|
+
out, found = directives.render(
|
|
167
|
+
text,
|
|
168
|
+
format=args.format,
|
|
169
|
+
ascii=args.ascii,
|
|
170
|
+
compact=args.compact,
|
|
171
|
+
title=title,
|
|
172
|
+
fragment=args.fragment,
|
|
173
|
+
)
|
|
174
|
+
except ChipError as e:
|
|
175
|
+
return _error(e)
|
|
176
|
+
if args.format == "html":
|
|
177
|
+
_out(out)
|
|
178
|
+
else:
|
|
179
|
+
_write_raw(out)
|
|
180
|
+
warnings = [
|
|
181
|
+
f"{d.where}: {w}" for d in found for w in (d.chip.warnings_for(d.domain) if d.chip else ())
|
|
182
|
+
]
|
|
183
|
+
code = _warn(warnings, args.strict)
|
|
184
|
+
if args.check:
|
|
185
|
+
notes = _lint(text, found)
|
|
186
|
+
for n in notes:
|
|
187
|
+
_err(f"mintchip: check: {n}")
|
|
188
|
+
if notes and args.strict:
|
|
189
|
+
code = 1
|
|
190
|
+
return code
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _lint(text: str, found: list[Any]) -> list[str]:
|
|
194
|
+
"""Density checks from ``mintchip.lint``, with each directive standing in as a
|
|
195
|
+
placeholder; chips' own warnings are left out (they were already printed). A crowded
|
|
196
|
+
sentence is quoted as written, its directives' locations after the quote."""
|
|
197
|
+
chips: dict[str, Chip] = {}
|
|
198
|
+
shown: dict[str, str] = {}
|
|
199
|
+
written: dict[str, tuple[str, str]] = {}
|
|
200
|
+
parts, pos = [], 0
|
|
201
|
+
for n, d in enumerate(found):
|
|
202
|
+
name = f"d{n}"
|
|
203
|
+
chips[name] = d.chip
|
|
204
|
+
shown["{" + name + "}"] = f"{{{{{d.chip.kind}}}}} at {d.line}:{d.col}"
|
|
205
|
+
written[name] = (d.source, f"{d.line}:{d.col}")
|
|
206
|
+
parts += [text[pos : d.start], "{" + name + "}"]
|
|
207
|
+
pos = d.end
|
|
208
|
+
parts.append(text[pos:])
|
|
209
|
+
notes = []
|
|
210
|
+
for m in mc.lint("".join(parts), chips, written=written):
|
|
211
|
+
if any(m.startswith(f"{slot}: ") for slot in shown):
|
|
212
|
+
continue
|
|
213
|
+
for slot, label in shown.items():
|
|
214
|
+
m = m.replace(slot, label)
|
|
215
|
+
notes.append(m)
|
|
216
|
+
return notes
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# --- table ----------------------------------------------------------------------------------
|
|
220
|
+
def table_columns(cols: Sequence[str], sets: Sequence[str]) -> dict[str, Any] | None:
|
|
221
|
+
"""Columns for ``mintchip.table`` from ``--col key[:kind[:header]]`` and
|
|
222
|
+
``--set key.option=value`` arguments."""
|
|
223
|
+
if not cols:
|
|
224
|
+
if sets:
|
|
225
|
+
raise ChipError(
|
|
226
|
+
"mintchip table: --set needs the column listed with --col.",
|
|
227
|
+
fix_hint=f"e.g. {TABLE_EXAMPLE} --set acc.target=0.9",
|
|
228
|
+
)
|
|
229
|
+
return None
|
|
230
|
+
columns: dict[str, dict[str, Any]] = {}
|
|
231
|
+
for spec in cols:
|
|
232
|
+
key, _, rest = spec.partition(":")
|
|
233
|
+
kind, _, header = rest.partition(":")
|
|
234
|
+
kind = kind.strip()
|
|
235
|
+
if not key:
|
|
236
|
+
raise ChipError(
|
|
237
|
+
f"mintchip table: --col {spec!r} has no key.", fix_hint="Write --col KEY:KIND."
|
|
238
|
+
)
|
|
239
|
+
if kind and kind != "text" and kind not in REGISTRY:
|
|
240
|
+
names = ["text", *REGISTRY]
|
|
241
|
+
close = difflib.get_close_matches(kind, names, n=1)
|
|
242
|
+
hint = f"Did you mean --col {key}:{close[0]}? " if close else ""
|
|
243
|
+
raise ChipError(
|
|
244
|
+
f"mintchip table: unknown column kind {kind!r} in --col {spec!r}.",
|
|
245
|
+
fix_hint=f"{hint}Kinds: {', '.join(names)}.",
|
|
246
|
+
)
|
|
247
|
+
columns[key] = {
|
|
248
|
+
**({"chip": kind} if kind else {}),
|
|
249
|
+
**({"header": header} if header else {}),
|
|
250
|
+
}
|
|
251
|
+
for s in sets:
|
|
252
|
+
lhs, eq, value = s.partition("=")
|
|
253
|
+
key, dot, opt = lhs.rpartition(".")
|
|
254
|
+
if not (eq and dot and key and opt):
|
|
255
|
+
raise ChipError(
|
|
256
|
+
f"mintchip table: --set {s!r} must be KEY.OPTION=VALUE.",
|
|
257
|
+
fix_hint="e.g. --set acc.target=0.9",
|
|
258
|
+
)
|
|
259
|
+
if key not in columns:
|
|
260
|
+
raise ChipError(
|
|
261
|
+
f"mintchip table: --set {s!r} names column {key!r}, which has no --col.",
|
|
262
|
+
fix_hint=f"Add --col {key}:KIND first. Columns: {', '.join(columns)}.",
|
|
263
|
+
)
|
|
264
|
+
kind = columns[key].get("chip")
|
|
265
|
+
if opt == "header":
|
|
266
|
+
columns[key]["header"] = value
|
|
267
|
+
elif opt == "share":
|
|
268
|
+
columns[key]["share"] = value.lower() not in ("false", "no", "0")
|
|
269
|
+
elif kind in (None, "text"):
|
|
270
|
+
raise ChipError(
|
|
271
|
+
f"mintchip table: column {key!r} has no chip kind, so only header can be set.",
|
|
272
|
+
fix_hint=f"Give it a kind, e.g. --col {key}:bar.",
|
|
273
|
+
)
|
|
274
|
+
else:
|
|
275
|
+
names = [p.name for p in REGISTRY[kind].params]
|
|
276
|
+
if opt.replace("-", "_") not in names:
|
|
277
|
+
close = difflib.get_close_matches(opt, names, n=1)
|
|
278
|
+
hint = f"Did you mean --set {key}.{close[0]}=…? " if close else ""
|
|
279
|
+
raise ChipError(
|
|
280
|
+
f"mintchip table: {kind} has no option {opt!r} (in --set {s!r}).",
|
|
281
|
+
fix_hint=f"{hint}Options: {', '.join([*names, 'header', 'share'])}.",
|
|
282
|
+
)
|
|
283
|
+
columns[key].update(parse_tokens(kind, [f"{opt}={value}"], partial=True))
|
|
284
|
+
return {k: (v["chip"] if list(v) == ["chip"] else v) for k, v in columns.items()}
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _table_rows(path: str) -> Any:
|
|
288
|
+
"""A path ``mintchip.table`` can read, or rows parsed from stdin (JSON, JSONL, CSV or TSV)."""
|
|
289
|
+
if path != "-":
|
|
290
|
+
if not Path(path).is_file():
|
|
291
|
+
raise ChipError(
|
|
292
|
+
f"mintchip table: no such file {path!r}.",
|
|
293
|
+
fix_hint="Pass a .json, .jsonl, .csv or .tsv file, or - for stdin.",
|
|
294
|
+
)
|
|
295
|
+
return path
|
|
296
|
+
text = _read("-")
|
|
297
|
+
stripped = text.lstrip()
|
|
298
|
+
if stripped[:1] in ("[", "{"):
|
|
299
|
+
try:
|
|
300
|
+
return json.loads(text)
|
|
301
|
+
except json.JSONDecodeError as e:
|
|
302
|
+
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
|
|
303
|
+
if stripped[:1] == "{" and len(lines) > 1:
|
|
304
|
+
try:
|
|
305
|
+
return [json.loads(ln) for ln in lines]
|
|
306
|
+
except json.JSONDecodeError:
|
|
307
|
+
pass
|
|
308
|
+
raise ChipError(
|
|
309
|
+
f"mintchip table: stdin is not valid JSON (line {e.lineno}, column {e.colno}: "
|
|
310
|
+
f"{e.msg}).",
|
|
311
|
+
fix_hint='Pass a list of objects, e.g. [{"model": "a", "acc": 0.82}].',
|
|
312
|
+
) from None
|
|
313
|
+
lines = text.splitlines()
|
|
314
|
+
if lines and "\t" in lines[0] and "," not in lines[0]:
|
|
315
|
+
return list(csv.DictReader(lines, delimiter="\t"))
|
|
316
|
+
return list(csv.DictReader(lines))
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _cmd_table(args: argparse.Namespace) -> int:
|
|
320
|
+
try:
|
|
321
|
+
columns = table_columns(args.col, args.set)
|
|
322
|
+
t = mc.table(
|
|
323
|
+
_table_rows(args.file),
|
|
324
|
+
columns,
|
|
325
|
+
sort=args.sort,
|
|
326
|
+
descending=False if args.asc else True if args.desc else None,
|
|
327
|
+
limit=args.limit,
|
|
328
|
+
title=args.title,
|
|
329
|
+
highlight=args.highlight or None,
|
|
330
|
+
baseline=args.baseline,
|
|
331
|
+
)
|
|
332
|
+
if args.format == "json":
|
|
333
|
+
text = json.dumps(t.to_dict(), indent=2, ensure_ascii=args.ascii)
|
|
334
|
+
elif args.format == "md":
|
|
335
|
+
text = t.markdown()
|
|
336
|
+
elif args.format == "html":
|
|
337
|
+
text = t.html()
|
|
338
|
+
else:
|
|
339
|
+
text = t.text(ascii=args.ascii, color=args.format == "ansi", width=args.width)
|
|
340
|
+
except ChipError as e:
|
|
341
|
+
return _error(e, TABLE_EXAMPLE)
|
|
342
|
+
_out(text)
|
|
343
|
+
return _warn(t.warnings, args.strict)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# --- schema ---------------------------------------------------------------------------------
|
|
347
|
+
_SCHEMA_TYPES: dict[str, dict[str, Any]] = {
|
|
348
|
+
"number": {"type": "number"},
|
|
349
|
+
"int": {"type": "integer"},
|
|
350
|
+
"string": {"type": "string"},
|
|
351
|
+
"bool": {"type": "boolean"},
|
|
352
|
+
"numbers": {"type": "array", "items": {"type": ["number", "null"]}},
|
|
353
|
+
"range": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2},
|
|
354
|
+
"strings": {"type": "array", "items": {"type": "string"}},
|
|
355
|
+
"values": {"type": "array", "items": {"type": ["boolean", "string", "number", "null"]}},
|
|
356
|
+
}
|
|
357
|
+
_PAIR = {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}
|
|
358
|
+
_SCHEMA_TYPES["mapping"] = {
|
|
359
|
+
"type": "object",
|
|
360
|
+
"additionalProperties": {"anyOf": [{"type": "number"}, _PAIR]},
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
DRAFT = "https://json-schema.org/draft/2020-12/schema"
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def kind_schema(kind: str) -> dict[str, Any]:
|
|
367
|
+
"""JSON Schema for one kind's spec, ``{"chip": kind, **args}``."""
|
|
368
|
+
k = REGISTRY[kind]
|
|
369
|
+
props: dict[str, Any] = {"chip": {"const": kind}}
|
|
370
|
+
for p in k.params:
|
|
371
|
+
s = json.loads(json.dumps(_SCHEMA_TYPES[p.type]))
|
|
372
|
+
if p.choices:
|
|
373
|
+
s["enum"] = list(p.choices)
|
|
374
|
+
if p.default is not None:
|
|
375
|
+
s["default"] = p.default
|
|
376
|
+
if not p.required: # null overrides the default, e.g. no reference line
|
|
377
|
+
t = s["type"]
|
|
378
|
+
s["type"] = [t, "null"] if isinstance(t, str) else [*t, "null"]
|
|
379
|
+
props[p.name] = {"description": p.help, **s}
|
|
380
|
+
return {
|
|
381
|
+
"title": f"mintchip {kind}",
|
|
382
|
+
"description": f"{k.question} Use for: {k.have[0].lower()}{k.have[1:]}.",
|
|
383
|
+
"type": "object",
|
|
384
|
+
"properties": props,
|
|
385
|
+
"required": ["chip", *(p.name for p in k.params if p.required)],
|
|
386
|
+
"additionalProperties": False,
|
|
387
|
+
"examples": [k.example_chip().to_dict()],
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def schema(kind: str | None = None) -> dict[str, Any]:
|
|
392
|
+
"""Draft 2020-12 JSON Schema for one kind, or a ``oneOf`` over all kinds on ``"chip"``."""
|
|
393
|
+
if kind is not None:
|
|
394
|
+
if kind not in REGISTRY:
|
|
395
|
+
close = difflib.get_close_matches(kind, sorted(REGISTRY), n=1)
|
|
396
|
+
hint = f"Did you mean {close[0]!r}? " if close else ""
|
|
397
|
+
raise ChipError(
|
|
398
|
+
f"mintchip schema: unknown chip {kind!r}.",
|
|
399
|
+
fix_hint=f"{hint}Chips: {', '.join(e['name'] for e in mc.CATALOG)}.",
|
|
400
|
+
)
|
|
401
|
+
return {"$schema": DRAFT, "$id": f"mintchip:{kind}", **kind_schema(kind)}
|
|
402
|
+
names = [e["name"] for e in mc.CATALOG]
|
|
403
|
+
return {
|
|
404
|
+
"$schema": DRAFT,
|
|
405
|
+
"$id": "mintchip:chip",
|
|
406
|
+
"title": "mintchip chip spec",
|
|
407
|
+
"description": 'One chip as {"chip": kind, ...arguments}; "chip" picks the kind.',
|
|
408
|
+
"type": "object",
|
|
409
|
+
"required": ["chip"],
|
|
410
|
+
"properties": {"chip": {"enum": names}},
|
|
411
|
+
"oneOf": [{"$ref": f"#/$defs/{n}"} for n in names],
|
|
412
|
+
"$defs": {n: kind_schema(n) for n in names},
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _cmd_schema(args: argparse.Namespace) -> int:
|
|
417
|
+
try:
|
|
418
|
+
_out(json.dumps(schema(args.kind), indent=2, ensure_ascii=False))
|
|
419
|
+
except ChipError as e:
|
|
420
|
+
return _error(e)
|
|
421
|
+
return 0
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
# --- catalog and guide ----------------------------------------------------------------------
|
|
425
|
+
def _cmd_catalog(args: argparse.Namespace) -> int:
|
|
426
|
+
rows = []
|
|
427
|
+
for entry in mc.CATALOG:
|
|
428
|
+
example = mc.REGISTRY[entry["name"]].example_chip()
|
|
429
|
+
rows.append({**entry, "spec": example.to_dict(), "text": example.text(ascii=args.ascii)})
|
|
430
|
+
if args.json:
|
|
431
|
+
_out(json.dumps(rows, indent=2, ensure_ascii=args.ascii))
|
|
432
|
+
return 0
|
|
433
|
+
width = max(len(r["name"]) for r in rows)
|
|
434
|
+
lines = [f"mintchip {mc.__version__}: {len(rows)} chips", ""]
|
|
435
|
+
for r in rows:
|
|
436
|
+
lines.append(f" {r['name']:<{width}} {r['text']}")
|
|
437
|
+
lines.append(f" {'':<{width}} {r['have']}: {r['question']}")
|
|
438
|
+
_out("\n".join(lines))
|
|
439
|
+
return 0
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _cmd_guide(args: argparse.Namespace) -> int:
|
|
443
|
+
from . import guide
|
|
444
|
+
|
|
445
|
+
if args.write:
|
|
446
|
+
for path in guide.write(args.write):
|
|
447
|
+
_out(str(path))
|
|
448
|
+
return 0
|
|
449
|
+
_out(guide.agents_snippet() if args.agents else guide.guide_text())
|
|
450
|
+
return 0
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
# --- parser ---------------------------------------------------------------------------------
|
|
454
|
+
class _Help(argparse.RawDescriptionHelpFormatter):
|
|
455
|
+
def __init__(self, prog: str) -> None:
|
|
456
|
+
super().__init__(prog, max_help_position=26, width=100)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _pct(s: str) -> str:
|
|
460
|
+
return s.replace("%", "%%")
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _param_help(p: Param) -> str:
|
|
464
|
+
text = p.help
|
|
465
|
+
if p.type in ("numbers", "range", "mapping", "values", "strings"):
|
|
466
|
+
text += f" Syntax: {SYNTAX[p.type][1]}."
|
|
467
|
+
if p.default is not None and p.type != "bool":
|
|
468
|
+
default = int(p.default) if isinstance(p.default, float) and p.default.is_integer() else (
|
|
469
|
+
p.default) # fmt: skip
|
|
470
|
+
text += f" Default: {default}."
|
|
471
|
+
return _pct(text)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _kind_parser(sub: Any, kind: str) -> None:
|
|
475
|
+
k = REGISTRY[kind]
|
|
476
|
+
positional = [p for p in k.params if p.positional]
|
|
477
|
+
metas = [metavar(p) if p.required else f"[{metavar(p)}]" for p in positional]
|
|
478
|
+
c = k.example_chip()
|
|
479
|
+
epilog = (
|
|
480
|
+
f"example:\n $ {example_call(kind)}\n {c.text()}\n\n"
|
|
481
|
+
f"as a directive in `mintchip render`:\n {example_call(kind, 'directive')}"
|
|
482
|
+
)
|
|
483
|
+
p = sub.add_parser(
|
|
484
|
+
kind,
|
|
485
|
+
help=_pct(k.question),
|
|
486
|
+
usage=_pct(f"mintchip {kind} {' '.join(metas)} [--option value …]"),
|
|
487
|
+
description=f"{k.question}\nUse it for: {k.have[0].lower()}{k.have[1:]}.",
|
|
488
|
+
epilog=epilog,
|
|
489
|
+
formatter_class=_Help,
|
|
490
|
+
)
|
|
491
|
+
for param in positional:
|
|
492
|
+
p.add_argument(param.name, metavar=metavar(param), nargs="?", help=_param_help(param))
|
|
493
|
+
for param in k.params:
|
|
494
|
+
if param.positional:
|
|
495
|
+
continue
|
|
496
|
+
flag = "--" + param.name.replace("_", "-")
|
|
497
|
+
if param.type == "bool":
|
|
498
|
+
p.add_argument(flag, action=argparse.BooleanOptionalAction, help=_param_help(param))
|
|
499
|
+
else:
|
|
500
|
+
p.add_argument(flag, metavar=SYNTAX[param.type][0], help=_param_help(param))
|
|
501
|
+
out = p.add_argument_group("output")
|
|
502
|
+
for param in OUTPUT:
|
|
503
|
+
flag = "--" + param.name
|
|
504
|
+
if param.type == "bool":
|
|
505
|
+
out.add_argument(flag, action="store_true", help=_pct(param.help))
|
|
506
|
+
else:
|
|
507
|
+
out.add_argument(flag, choices=param.choices, help=_pct(param.help))
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
511
|
+
parser = argparse.ArgumentParser(
|
|
512
|
+
prog="mintchip",
|
|
513
|
+
description="Word-sized graphics for numbers: one chip, a sentence, or a table.",
|
|
514
|
+
epilog="Start with: mintchip guide",
|
|
515
|
+
formatter_class=_Help,
|
|
516
|
+
)
|
|
517
|
+
sub = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
|
|
518
|
+
|
|
519
|
+
p = sub.add_parser(
|
|
520
|
+
"render",
|
|
521
|
+
help="Replace {{kind …}} directives in prose with chips.",
|
|
522
|
+
description=(
|
|
523
|
+
"Read prose from FILE (or stdin) and replace each {{kind tokens…}} directive with\n"
|
|
524
|
+
"its chip. Directives use the same tokens as the kind commands, with options as\n"
|
|
525
|
+
"name=value: {{spark 1.84 1.32 0.96 band=0.38:0.48}} is\n"
|
|
526
|
+
"`mintchip spark 1.84 1.32 0.96 --band 0.38:0.48`. A directive may also be a JSON\n"
|
|
527
|
+
'spec: {{ {"chip": "ci", "estimate": 0.08, "interval": [0.05, 0.11]} }}.\n'
|
|
528
|
+
"Text outside directives is copied unchanged; write \\{{ for a literal {{."
|
|
529
|
+
),
|
|
530
|
+
formatter_class=_Help,
|
|
531
|
+
)
|
|
532
|
+
p.add_argument("file", nargs="?", default="-", metavar="FILE", help="Prose file; - is stdin.")
|
|
533
|
+
p.add_argument("--format", choices=("text", "ansi", "md", "html"), default="text",
|
|
534
|
+
help="text (default), ansi, md (chips in code spans) or html (a full page).") # fmt: skip
|
|
535
|
+
p.add_argument("--ascii", action="store_true", help="Pure ASCII chips.")
|
|
536
|
+
p.add_argument("--compact", action="store_true", help="Shorter chip values.")
|
|
537
|
+
p.add_argument("--strict", action="store_true", help="Exit 1 on any warning.")
|
|
538
|
+
p.add_argument("--check", action="store_true", help="Also lint density to stderr.")
|
|
539
|
+
p.add_argument("--title", help="Page title for --format html.")
|
|
540
|
+
p.add_argument("--fragment", action="store_true",
|
|
541
|
+
help="Emit embeddable HTML without the page shell (for --format html).") # fmt: skip
|
|
542
|
+
p.set_defaults(func=_cmd_render, _parser=p)
|
|
543
|
+
|
|
544
|
+
p = sub.add_parser(
|
|
545
|
+
"table",
|
|
546
|
+
help="Render rows from a JSON, JSONL, CSV or TSV file as a table with shared scales.",
|
|
547
|
+
description=(
|
|
548
|
+
"Rows come from a .json (list of objects), .jsonl, .csv or .tsv file, or stdin (-).\n"
|
|
549
|
+
"Each --col KEY[:KIND[:HEADER]] adds a column in order; KIND is a chip kind or\n"
|
|
550
|
+
"text, inferred from the values if left out. A cell is a number, a list for the\n"
|
|
551
|
+
"kind's values (ci takes [estimate, low, high]) or an object of arguments. Every\n"
|
|
552
|
+
"chip column shares one scale. --set KEY.OPTION=VALUE applies an option to every\n"
|
|
553
|
+
"cell in a column."
|
|
554
|
+
),
|
|
555
|
+
epilog=f"example:\n $ {TABLE_EXAMPLE} --set acc.target=0.9",
|
|
556
|
+
formatter_class=_Help,
|
|
557
|
+
)
|
|
558
|
+
p.add_argument("file", metavar="FILE", help="A .json, .jsonl, .csv or .tsv file; - is stdin.")
|
|
559
|
+
p.add_argument("--col", action="append", default=[], metavar="KEY[:KIND[:HEADER]]",
|
|
560
|
+
help="Add a column; repeat in display order. No --col: every key.") # fmt: skip
|
|
561
|
+
p.add_argument("--set", action="append", default=[], metavar="KEY.OPTION=VALUE",
|
|
562
|
+
help="Apply a chip option to a whole column, e.g. acc.target=0.9.") # fmt: skip
|
|
563
|
+
p.add_argument(
|
|
564
|
+
"--sort", metavar="KEY", help="Sort by this column (largest first; text A to Z)."
|
|
565
|
+
)
|
|
566
|
+
order = p.add_mutually_exclusive_group()
|
|
567
|
+
order.add_argument("--asc", action="store_true", help="Sort smallest first (A to Z for text).")
|
|
568
|
+
order.add_argument("--desc", action="store_true", help="Sort largest first (Z to A for text).")
|
|
569
|
+
p.add_argument("--limit", type=int, metavar="N", help="Keep the first N rows after sorting.")
|
|
570
|
+
p.add_argument("--title", help="A title above the table.")
|
|
571
|
+
p.add_argument("--highlight", action="append", default=[], metavar="ROW",
|
|
572
|
+
help="Emphasise a row matching ROW in the first text column (repeatable).") # fmt: skip
|
|
573
|
+
p.add_argument("--baseline", metavar="ROW",
|
|
574
|
+
help="Mark a row matching ROW as the baseline.") # fmt: skip
|
|
575
|
+
p.add_argument("--width", type=int, default=80, metavar="N",
|
|
576
|
+
help="Target width for text output (default: 80).") # fmt: skip
|
|
577
|
+
p.add_argument("--format", choices=("text", "ansi", "md", "html", "json"), default="text",
|
|
578
|
+
help="text (default), ansi, md, html or json.") # fmt: skip
|
|
579
|
+
p.add_argument("--ascii", action="store_true", help="Pure ASCII.")
|
|
580
|
+
p.add_argument("--strict", action="store_true", help="Exit 1 on any warning.")
|
|
581
|
+
p.set_defaults(func=_cmd_table, _parser=p)
|
|
582
|
+
|
|
583
|
+
p = sub.add_parser("guide", help="Print the agent guide (start here).", formatter_class=_Help)
|
|
584
|
+
p.add_argument("--agents", action="store_true",
|
|
585
|
+
help="Print a short snippet to paste into AGENTS.md or CLAUDE.md.") # fmt: skip
|
|
586
|
+
p.add_argument("--write", metavar="DIR",
|
|
587
|
+
help="Write DIR/skills/mintchip/SKILL.md and DIR/llms.txt.") # fmt: skip
|
|
588
|
+
p.set_defaults(func=_cmd_guide, _parser=p)
|
|
589
|
+
|
|
590
|
+
p = sub.add_parser("schema", help="Print JSON Schema for chip specs.", formatter_class=_Help)
|
|
591
|
+
p.add_argument("kind", nargs="?", metavar="KIND", help="One kind; default: all, as oneOf.")
|
|
592
|
+
p.set_defaults(func=_cmd_schema, _parser=p)
|
|
593
|
+
|
|
594
|
+
p = sub.add_parser("catalog", help="List every chip with its example rendered as text.")
|
|
595
|
+
p.add_argument("--ascii", action="store_true", help="Print pure ASCII.")
|
|
596
|
+
p.add_argument("--json", action="store_true", help="Print the catalog as JSON.")
|
|
597
|
+
p.set_defaults(func=_cmd_catalog, _parser=p)
|
|
598
|
+
|
|
599
|
+
from . import diff as _diff
|
|
600
|
+
from . import doctor as _doctor
|
|
601
|
+
from . import ingest as _ingest
|
|
602
|
+
from . import skill as _skill
|
|
603
|
+
|
|
604
|
+
_ingest.add_from_parser(sub, _Help)
|
|
605
|
+
_diff.add_diff_parser(sub, _Help)
|
|
606
|
+
_skill.add_skill_parser(sub, _Help)
|
|
607
|
+
_doctor.add_doctor_parser(sub, _Help)
|
|
608
|
+
|
|
609
|
+
for entry in mc.CATALOG:
|
|
610
|
+
_kind_parser(sub, entry["name"])
|
|
611
|
+
return parser
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _wants_help(tokens: Sequence[str]) -> bool:
|
|
615
|
+
for t in tokens:
|
|
616
|
+
if t == "--":
|
|
617
|
+
return False
|
|
618
|
+
if t in ("-h", "--help"):
|
|
619
|
+
return True
|
|
620
|
+
return False
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def _unknown_option(parser: argparse.ArgumentParser, extra: Sequence[str]) -> ChipError:
|
|
624
|
+
options = sorted({s for a in parser._actions for s in a.option_strings if s.startswith("--")})
|
|
625
|
+
bad = next((t for t in extra if t.startswith("-")), extra[0])
|
|
626
|
+
close = difflib.get_close_matches(bad.split("=")[0], options, n=1)
|
|
627
|
+
hint = f"Did you mean {close[0]}? " if close else ""
|
|
628
|
+
if not bad.startswith("-"):
|
|
629
|
+
return ChipError(
|
|
630
|
+
f"mintchip: unexpected argument {bad!r}.", fix_hint=f"See {parser.prog} -h."
|
|
631
|
+
)
|
|
632
|
+
return ChipError(
|
|
633
|
+
f"mintchip: unknown option {bad!r} for {parser.prog}.",
|
|
634
|
+
fix_hint=f"{hint}Options: {', '.join(options)}.",
|
|
635
|
+
)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _main(argv: list[str]) -> int:
|
|
639
|
+
if argv and argv[0] in REGISTRY and not _wants_help(argv[1:]):
|
|
640
|
+
return _cmd_kind(argv[0], argv[1:])
|
|
641
|
+
if argv and not argv[0].startswith("-") and argv[0] not in (*COMMANDS, *REGISTRY):
|
|
642
|
+
names = [*COMMANDS, *(e["name"] for e in mc.CATALOG)]
|
|
643
|
+
close = difflib.get_close_matches(argv[0], names, n=1)
|
|
644
|
+
hint = f"Did you mean {close[0]!r}? " if close else ""
|
|
645
|
+
return _error(
|
|
646
|
+
ChipError(
|
|
647
|
+
f"mintchip: unknown command {argv[0]!r}.",
|
|
648
|
+
fix_hint=f"{hint}Commands: {', '.join(names)}. Start with: mintchip guide",
|
|
649
|
+
)
|
|
650
|
+
)
|
|
651
|
+
parser = build_parser()
|
|
652
|
+
args, extra = parser.parse_known_args(argv)
|
|
653
|
+
if extra:
|
|
654
|
+
return _error(_unknown_option(args._parser, extra))
|
|
655
|
+
return int(args.func(args))
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
659
|
+
"""Run the command line; returns the exit status (0 ok, 1 warnings under --strict,
|
|
660
|
+
2 errors)."""
|
|
661
|
+
try:
|
|
662
|
+
return _main(list(sys.argv[1:] if argv is None else argv))
|
|
663
|
+
except ChipError as e:
|
|
664
|
+
return _error(e)
|
|
665
|
+
except SystemExit as e: # argparse --help and usage errors
|
|
666
|
+
return e.code if isinstance(e.code, int) else (0 if e.code is None else 2)
|
|
667
|
+
except BrokenPipeError:
|
|
668
|
+
return 0
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def run(argv: Sequence[str], stdin: str | None = None) -> tuple[int, str, str]:
|
|
672
|
+
"""Run ``mintchip argv`` in-process with ``stdin`` text; returns (status, stdout, stderr).
|
|
673
|
+
Used by the guide so its examples show real output."""
|
|
674
|
+
import contextlib
|
|
675
|
+
import io
|
|
676
|
+
|
|
677
|
+
out, err = io.StringIO(), io.StringIO()
|
|
678
|
+
old_in = sys.stdin
|
|
679
|
+
sys.stdin = io.StringIO(stdin or "")
|
|
680
|
+
try:
|
|
681
|
+
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
|
682
|
+
code = main(argv)
|
|
683
|
+
finally:
|
|
684
|
+
sys.stdin = old_in
|
|
685
|
+
return code, out.getvalue(), err.getvalue()
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
__all__ = ["build_parser", "call_text", "chip_output", "kind_schema", "main", "run", "schema"]
|
|
689
|
+
|
|
690
|
+
if __name__ == "__main__":
|
|
691
|
+
sys.exit(main())
|