mintfig 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.
Files changed (47) hide show
  1. mintfig/__init__.py +162 -0
  2. mintfig/_explain/__init__.py +1 -0
  3. mintfig/_explain/change.py +392 -0
  4. mintfig/_explain/compare.py +1308 -0
  5. mintfig/_explain/compare_grouped.py +472 -0
  6. mintfig/_explain/core.py +2005 -0
  7. mintfig/_explain/distribution.py +1268 -0
  8. mintfig/_explain/flow.py +508 -0
  9. mintfig/_explain/layout.py +2012 -0
  10. mintfig/_explain/matrix.py +623 -0
  11. mintfig/_explain/relate.py +1318 -0
  12. mintfig/_explain/timeline.py +595 -0
  13. mintfig/_explain/trend.py +2557 -0
  14. mintfig/_explain/waterfall.py +459 -0
  15. mintfig/_table.py +691 -0
  16. mintfig/_tabular.py +738 -0
  17. mintfig/annotations.py +1165 -0
  18. mintfig/assets/AGENTS_SNIPPET.md +11 -0
  19. mintfig/assets/SKILL.md +143 -0
  20. mintfig/assets/__init__.py +1 -0
  21. mintfig/assets/references/publication.md +79 -0
  22. mintfig/assets/references/scientific_and_recipes.md +213 -0
  23. mintfig/audit.py +179 -0
  24. mintfig/brief.py +518 -0
  25. mintfig/bundle.py +333 -0
  26. mintfig/cli.py +1300 -0
  27. mintfig/edit.py +347 -0
  28. mintfig/epistemic.py +1083 -0
  29. mintfig/explainer.py +194 -0
  30. mintfig/export.py +247 -0
  31. mintfig/inspect_data.py +583 -0
  32. mintfig/interactive.py +1028 -0
  33. mintfig/palettes.py +233 -0
  34. mintfig/plate.py +784 -0
  35. mintfig/preflight.py +2398 -0
  36. mintfig/proof.py +627 -0
  37. mintfig/runner.py +403 -0
  38. mintfig/skill.py +167 -0
  39. mintfig/specs.py +291 -0
  40. mintfig/style.py +151 -0
  41. mintfig/terminal.py +785 -0
  42. mintfig/themes.py +660 -0
  43. mintfig-0.2.0.dist-info/METADATA +239 -0
  44. mintfig-0.2.0.dist-info/RECORD +47 -0
  45. mintfig-0.2.0.dist-info/WHEEL +4 -0
  46. mintfig-0.2.0.dist-info/entry_points.txt +2 -0
  47. mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
mintfig/terminal.py ADDED
@@ -0,0 +1,785 @@
1
+ """Terminal-adaptive rendering and inline graphics protocol support for mintfig.
2
+
3
+ Supports:
4
+ * Graphics protocol detection (Kitty / Ghostty APC, iTerm2 / WezTerm OSC 1337,
5
+ or rich Unicode fallback).
6
+ * Standard Kitty APC and iTerm2 OSC 1337 PNG encoders.
7
+ * High-legibility Unicode and ASCII terminal renderings for every ``mint.explain``
8
+ panel form (horizontal bars, box-drawn tables, sparklines, structured facts).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import io
15
+ import json
16
+ import math
17
+ import os
18
+ import textwrap
19
+ from collections.abc import Mapping, Sequence
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from matplotlib.colors import to_rgb
24
+
25
+ from ._explain.core import Panel, _GlyphCapture
26
+ from ._explain.layout import Explanation, explain_from_spec, read_png_text
27
+
28
+ __all__ = [
29
+ "detect_graphics_protocol",
30
+ "encode_iterm2_png",
31
+ "encode_kitty_png",
32
+ "render_terminal",
33
+ "show_in_terminal",
34
+ ]
35
+
36
+ _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
37
+ _KITTY_CHUNK_SIZE = 4096
38
+
39
+ _UNICODE_BAR_BLOCKS = (" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█")
40
+ _UNICODE_SPARK = "▁▂▃▄▅▆▇█"
41
+ _ASCII_SPARK = "._-=+*#@"
42
+
43
+ _ASCII_TRANSLATE = str.maketrans(
44
+ {
45
+ "\N{RIGHTWARDS ARROW}": "->",
46
+ "\N{LEFTWARDS ARROW}": "<-",
47
+ "\N{MINUS SIGN}": "-",
48
+ "\N{EN DASH}": "-",
49
+ "\N{EM DASH}": "--",
50
+ "\N{MULTIPLICATION SIGN}": "x",
51
+ "\N{HORIZONTAL ELLIPSIS}": "...",
52
+ "\N{PLUS-MINUS SIGN}": "+/-",
53
+ "\N{GREEK SMALL LETTER MU}": "u",
54
+ "\N{MICRO SIGN}": "u",
55
+ "\N{DEGREE SIGN}": " deg",
56
+ "\N{BULLET}": "*",
57
+ "\N{MIDDLE DOT}": "*",
58
+ "\N{NO-BREAK SPACE}": " ",
59
+ }
60
+ )
61
+
62
+
63
+ def _to_ascii(text: str) -> str:
64
+ """Transliterate typographic Unicode to clean printable ASCII."""
65
+ mapped = text.translate(_ASCII_TRANSLATE)
66
+ return mapped.encode("ascii", errors="replace").decode("ascii")
67
+
68
+
69
+ def _ensure_explanation(exp_or_spec: Explanation | Mapping[str, Any]) -> Explanation:
70
+ if isinstance(exp_or_spec, Explanation):
71
+ return exp_or_spec
72
+ if isinstance(exp_or_spec, Mapping):
73
+ return explain_from_spec(exp_or_spec)
74
+ raise TypeError(
75
+ "Expected an Explanation or a spec mapping, "
76
+ f"got {type(exp_or_spec).__name__}."
77
+ )
78
+
79
+
80
+ def _is_num(val: Any) -> bool:
81
+ if isinstance(val, bool) or val is None:
82
+ return False
83
+ if isinstance(val, (int, float)):
84
+ return math.isfinite(float(val))
85
+ return False
86
+
87
+
88
+ def _fmt_num(val: Any, *, ascii_only: bool = False) -> str:
89
+ if val is None:
90
+ return "-" if ascii_only else "—"
91
+ if isinstance(val, bool):
92
+ return "true" if val else "false"
93
+ if isinstance(val, float):
94
+ if not math.isfinite(val):
95
+ return "-" if ascii_only else "—"
96
+ if abs(val - round(val)) < 1e-9 and abs(val) < 1e12:
97
+ text = f"{round(val):,}"
98
+ else:
99
+ text = f"{val:,.3g}" if abs(val) < 1e6 else f"{val:.3g}"
100
+ return text if ascii_only else text.replace("-", "\N{MINUS SIGN}")
101
+ if isinstance(val, int):
102
+ text = f"{val:,}"
103
+ return text if ascii_only else text.replace("-", "\N{MINUS SIGN}")
104
+ text = str(val)
105
+ return _to_ascii(text) if ascii_only else text
106
+
107
+
108
+ def _ansi_rgb(hex_color: str, *, bold: bool = False) -> str:
109
+ r, g, b = (round(c * 255) for c in to_rgb(hex_color))
110
+ prefix = "1;" if bold else ""
111
+ return f"\x1b[{prefix}38;2;{r};{g};{b}m"
112
+
113
+
114
+ class _Style:
115
+ """Minimal ANSI styler that becomes a no-op when ``color=False``."""
116
+
117
+ def __init__(self, enabled: bool, *, accent: str = "#CD4324", primary: str = "#1F5A9D") -> None:
118
+ self.enabled = enabled
119
+ self._accent = _ansi_rgb(accent, bold=True) if enabled else ""
120
+ self._primary = _ansi_rgb(primary) if enabled else ""
121
+ self._reset = "\x1b[0m" if enabled else ""
122
+
123
+ def bold(self, text: str) -> str:
124
+ return f"\x1b[1m{text}{self._reset}" if self.enabled else text
125
+
126
+ def dim(self, text: str) -> str:
127
+ return f"\x1b[2m{text}{self._reset}" if self.enabled else text
128
+
129
+ def accent(self, text: str) -> str:
130
+ return f"{self._accent}{text}{self._reset}" if self.enabled else text
131
+
132
+ def primary(self, text: str) -> str:
133
+ return f"{self._primary}{text}{self._reset}" if self.enabled else text
134
+
135
+
136
+ def detect_graphics_protocol(env: Mapping[str, str] | None = None) -> str:
137
+ """Detect inline terminal graphics support from environment variables.
138
+
139
+ Returns ``"kitty"`` (Kitty / Ghostty), ``"iterm2"`` (iTerm2 / WezTerm), or
140
+ ``"unicode"`` (plain text fallback).
141
+ """
142
+ source = os.environ if env is None else env
143
+ if source.get("KITTY_WINDOW_ID"):
144
+ return "kitty"
145
+ term = str(source.get("TERM", "")).lower()
146
+ term_program = str(source.get("TERM_PROGRAM", "")).lower()
147
+ if "kitty" in term or "ghostty" in term or term_program in {"kitty", "ghostty"}:
148
+ return "kitty"
149
+ lc_terminal = str(source.get("LC_TERMINAL", "")).lower()
150
+ if term_program in {"iterm.app", "wezterm"} or lc_terminal == "iterm2":
151
+ return "iterm2"
152
+ return "unicode"
153
+
154
+
155
+ def encode_kitty_png(png_bytes: bytes) -> str:
156
+ """Encode PNG bytes as a Kitty Graphics Protocol APC escape sequence."""
157
+ if not png_bytes:
158
+ raise ValueError("png_bytes must not be empty.")
159
+ b64 = base64.b64encode(png_bytes).decode("ascii")
160
+ chunks = [b64[i : i + _KITTY_CHUNK_SIZE] for i in range(0, len(b64), _KITTY_CHUNK_SIZE)]
161
+ parts: list[str] = []
162
+ last_idx = len(chunks) - 1
163
+ for idx, chunk in enumerate(chunks):
164
+ more = 1 if idx < last_idx else 0
165
+ if idx == 0:
166
+ parts.append(f"\x1b_Ga=T,f=100,m={more};{chunk}\x1b\\")
167
+ else:
168
+ parts.append(f"\x1b_Gm={more};{chunk}\x1b\\")
169
+ return "".join(parts)
170
+
171
+
172
+ def encode_iterm2_png(png_bytes: bytes) -> str:
173
+ """Encode PNG bytes as an iTerm2 OSC 1337 inline image escape sequence."""
174
+ if not png_bytes:
175
+ raise ValueError("png_bytes must not be empty.")
176
+ b64 = base64.b64encode(png_bytes).decode("ascii")
177
+ return f"\x1b]1337;File=inline=1;size={len(png_bytes)}:{b64}\x07"
178
+
179
+
180
+ def _bar_str(fraction: float, max_chars: int, *, ascii_only: bool) -> str:
181
+ frac = max(0.0, min(1.0, fraction))
182
+ if max_chars <= 0:
183
+ return ""
184
+ if ascii_only:
185
+ count = max(1, round(frac * max_chars)) if frac > 0 else 0
186
+ return "#" * count
187
+ eighths = round(frac * max_chars * 8)
188
+ if frac > 0 and eighths == 0:
189
+ eighths = 1
190
+ full = eighths // 8
191
+ rem = eighths % 8
192
+ return "█" * full + (_UNICODE_BAR_BLOCKS[rem] if rem else "")
193
+
194
+
195
+ def _sparkline(values: Sequence[float | None], *, ascii_only: bool) -> str:
196
+ glyphs = _ASCII_SPARK if ascii_only else _UNICODE_SPARK
197
+ finite = [float(v) for v in values if _is_num(v)]
198
+ if not finite:
199
+ return ""
200
+ lo, hi = min(finite), max(finite)
201
+ span = hi - lo
202
+ out: list[str] = []
203
+ for v in values:
204
+ if not _is_num(v):
205
+ out.append(" ")
206
+ continue
207
+ if span <= 0:
208
+ idx = len(glyphs) // 2
209
+ else:
210
+ idx = round((float(v) - lo) / span * (len(glyphs) - 1))
211
+ idx = max(0, min(len(glyphs) - 1, idx))
212
+ out.append(glyphs[idx])
213
+ return "".join(out)
214
+
215
+
216
+ def _render_bars_panel(
217
+ panel: Panel,
218
+ *,
219
+ width: int,
220
+ style: _Style,
221
+ ascii_only: bool,
222
+ ) -> list[str]:
223
+ spec = panel.spec
224
+ is_share = panel.kind == "share"
225
+ raw_map = spec.get("parts") if is_share else spec.get("values")
226
+ if not isinstance(raw_map, Mapping) or not raw_map:
227
+ return [f" {fact}" for fact in panel.facts]
228
+
229
+ first_val = next(iter(raw_map.values()))
230
+ if isinstance(first_val, Mapping):
231
+ # Grouped compare: render as a crisp table of item x series
232
+ series_names: list[str] = []
233
+ for sub in raw_map.values():
234
+ if isinstance(sub, Mapping):
235
+ for sk in sub:
236
+ if str(sk) not in series_names:
237
+ series_names.append(str(sk))
238
+ headers = ["Item", *series_names]
239
+ rows = [
240
+ [
241
+ str(item),
242
+ *[_fmt_num(sub.get(s) if isinstance(sub, Mapping) else None, ascii_only=ascii_only) for s in series_names],
243
+ ]
244
+ for item, sub in raw_map.items()
245
+ ]
246
+ return _render_box_table(
247
+ headers,
248
+ rows,
249
+ aligns=["left", *(["right"] * len(series_names))],
250
+ width=width,
251
+ style=style,
252
+ ascii_only=ascii_only,
253
+ )
254
+
255
+ items = [(str(k), float(v)) for k, v in raw_map.items() if _is_num(v)]
256
+ if not items:
257
+ return []
258
+ if is_share or spec.get("sort", True):
259
+ items.sort(key=lambda kv: kv[1], reverse=True)
260
+
261
+ hl_raw = spec.get("highlight") or []
262
+ hl_set = {str(h) for h in ([hl_raw] if isinstance(hl_raw, str) else hl_raw)}
263
+ total = sum(v for _, v in items) if is_share else 0.0
264
+ max_abs = max((abs(v) for _, v in items), default=1.0) or 1.0
265
+ unit = f" {panel.unit}" if panel.unit and not is_share else ""
266
+
267
+ formatted_vals: list[str] = []
268
+ for _, v in items:
269
+ if is_share and total > 0:
270
+ formatted_vals.append(f"{v / total * 100.0:.1f}% ({_fmt_num(v, ascii_only=ascii_only)})")
271
+ else:
272
+ formatted_vals.append(f"{_fmt_num(v, ascii_only=ascii_only)}{unit}")
273
+
274
+ max_lbl = min(max(len(k) for k, _ in items), max(12, width // 3))
275
+ max_val_w = max(len(s) for s in formatted_vals)
276
+ # 2 indent + 2 marker + lbl + 2 gap + bar + 1 space + val
277
+ bar_w = max(8, width - (4 + max_lbl + 2 + 1 + max_val_w))
278
+
279
+ lines: list[str] = []
280
+ marker_on = ">" if ascii_only else "▸"
281
+ for (name, val), val_str in zip(items, formatted_vals, strict=True):
282
+ is_hl = name in hl_set
283
+ disp_name = name if len(name) <= max_lbl else name[: max_lbl - 1] + ("." if ascii_only else "…")
284
+ padded_lbl = disp_name.rjust(max_lbl)
285
+ bar = _bar_str(abs(val) / max_abs, bar_w, ascii_only=ascii_only)
286
+ marker = marker_on if is_hl else " "
287
+ if is_hl:
288
+ line = f" {style.accent(marker)} {style.bold(padded_lbl)} {style.accent(bar)} {style.bold(val_str)}"
289
+ else:
290
+ line = f" {marker} {padded_lbl} {style.primary(bar)} {val_str}"
291
+ lines.append(line)
292
+ return lines
293
+
294
+
295
+ def _render_box_table(
296
+ headers: list[str],
297
+ rows: list[list[str]],
298
+ *,
299
+ aligns: list[str],
300
+ width: int,
301
+ style: _Style,
302
+ ascii_only: bool,
303
+ highlight_rows: set[str] | None = None,
304
+ ) -> list[str]:
305
+ if not headers:
306
+ return []
307
+ n_cols = len(headers)
308
+ col_w = [
309
+ max(len(headers[c]), *(len(r[c]) for r in rows if c < len(r)), 1)
310
+ for c in range(n_cols)
311
+ ]
312
+ # Fit within width if needed
313
+ overhead = 3 * n_cols + 1
314
+ avail = max(n_cols * 4, width - overhead)
315
+ if sum(col_w) > avail:
316
+ scale = avail / sum(col_w)
317
+ col_w = [max(4, int(w * scale)) for w in col_w]
318
+
319
+ def _clip(text: str, w: int) -> str:
320
+ if len(text) <= w:
321
+ return text
322
+ return text[: max(1, w - 1)] + ("." if ascii_only else "…")
323
+
324
+ def _pad(text: str, w: int, al: str) -> str:
325
+ clipped = _clip(text, w)
326
+ if al == "right":
327
+ return clipped.rjust(w)
328
+ if al == "center":
329
+ return clipped.center(w)
330
+ return clipped.ljust(w)
331
+
332
+ if ascii_only:
333
+ tl, tm, tr, h, v = "+", "+", "+", "-", "|"
334
+ ml, mm, mr = "+", "+", "+"
335
+ bl, bm, br = "+", "+", "+"
336
+ else:
337
+ tl, tm, tr, h, v = "┌", "┬", "┐", "─", "│"
338
+ ml, mm, mr = "├", "┼", "┤"
339
+ bl, bm, br = "└", "┴", "┘"
340
+
341
+ top = tl + tm.join(h * (w + 2) for w in col_w) + tr
342
+ mid = ml + mm.join(h * (w + 2) for w in col_w) + mr
343
+ bot = bl + bm.join(h * (w + 2) for w in col_w) + br
344
+
345
+ hdr_cells = [style.bold(_pad(headers[c], col_w[c], aligns[c])) for c in range(n_cols)]
346
+ lines = [top, f"{v} " + f" {v} ".join(hdr_cells) + f" {v}", mid]
347
+ hl = highlight_rows or set()
348
+ for row in rows:
349
+ row_key = row[0] if row else ""
350
+ is_hl = row_key in hl
351
+ cells = []
352
+ for c in range(n_cols):
353
+ val = row[c] if c < len(row) else ""
354
+ padded = _pad(val, col_w[c], aligns[c])
355
+ cells.append(style.accent(padded) if is_hl and c == 0 else padded)
356
+ lines.append(f"{v} " + f" {v} ".join(cells) + f" {v}")
357
+ lines.append(bot)
358
+ return lines
359
+
360
+
361
+ def _render_table_panel(
362
+ panel: Panel,
363
+ *,
364
+ width: int,
365
+ style: _Style,
366
+ ascii_only: bool,
367
+ ) -> list[str]:
368
+ spec = panel.spec
369
+ headers = [str(c) for c in (spec.get("columns") or [])]
370
+ raw_rows = spec.get("rows") or []
371
+ if not headers or not isinstance(raw_rows, Sequence):
372
+ return [f" {fact}" for fact in panel.facts]
373
+
374
+ align_map = spec.get("align") if isinstance(spec.get("align"), Mapping) else {}
375
+ aligns: list[str] = []
376
+ for c_idx, col_name in enumerate(headers):
377
+ if col_name in align_map:
378
+ aligns.append(str(align_map[col_name]))
379
+ else:
380
+ col_vals = [r[c_idx] for r in raw_rows if isinstance(r, Sequence) and c_idx < len(r)]
381
+ is_num_col = bool(col_vals) and all(_is_num(v) or v is None for v in col_vals)
382
+ aligns.append("right" if is_num_col else "left")
383
+
384
+ str_rows = [
385
+ [_fmt_num(r[c], ascii_only=ascii_only) if c < len(r) else "" for c in range(len(headers))]
386
+ for r in raw_rows
387
+ if isinstance(r, Sequence)
388
+ ]
389
+ hl_raw = spec.get("highlight") or []
390
+ hl_set = {str(h) for h in ([hl_raw] if isinstance(hl_raw, str) else hl_raw)}
391
+ return _render_box_table(
392
+ headers,
393
+ str_rows,
394
+ aligns=aligns,
395
+ width=width,
396
+ style=style,
397
+ ascii_only=ascii_only,
398
+ highlight_rows=hl_set,
399
+ )
400
+
401
+
402
+ def _render_trend_panel(
403
+ panel: Panel,
404
+ *,
405
+ width: int,
406
+ style: _Style,
407
+ ascii_only: bool,
408
+ ) -> list[str]:
409
+ spec = panel.spec
410
+ series_raw = spec.get("series")
411
+ x_vals = spec.get("x") or []
412
+ unit = f" {panel.unit}" if panel.unit else ""
413
+ arrow = "->" if ascii_only else "→"
414
+
415
+ series_map: dict[str, list[float | None]] = {}
416
+ if isinstance(series_raw, Mapping):
417
+ for name, vals in series_raw.items():
418
+ if isinstance(vals, Sequence):
419
+ series_map[str(name)] = [float(v) if _is_num(v) else None for v in vals]
420
+ elif isinstance(series_raw, Sequence) and not isinstance(series_raw, (str, bytes)):
421
+ series_map[panel.label or "series"] = [float(v) if _is_num(v) else None for v in series_raw]
422
+ elif isinstance(spec.get("points"), Mapping):
423
+ for name, buckets in spec["points"].items():
424
+ if isinstance(buckets, Sequence):
425
+ disp_name = str(name) or panel.label or "series"
426
+ means: list[float | None] = []
427
+ for bucket in buckets:
428
+ if isinstance(bucket, Sequence) and not isinstance(bucket, (str, bytes)):
429
+ nums = [float(v) for v in bucket if _is_num(v)]
430
+ means.append(sum(nums) / len(nums) if nums else None)
431
+ elif _is_num(bucket):
432
+ means.append(float(bucket))
433
+ else:
434
+ means.append(None)
435
+ series_map[disp_name] = means
436
+
437
+ if not series_map:
438
+ return [f" {fact}" for fact in panel.facts]
439
+
440
+ hl_raw = spec.get("highlight") or []
441
+ hl_set = {str(h) for h in ([hl_raw] if isinstance(hl_raw, str) else hl_raw)}
442
+ max_lbl = min(max(len(k) for k in series_map), max(12, width // 4))
443
+ lines: list[str] = []
444
+ marker_on = ">" if ascii_only else "▸"
445
+
446
+ for name, vals in series_map.items():
447
+ spark = _sparkline(vals, ascii_only=ascii_only)
448
+ finite = [v for v in vals if v is not None]
449
+ if finite:
450
+ first, last = finite[0], finite[-1]
451
+ if first != 0:
452
+ pct = (last - first) / abs(first) * 100.0
453
+ sign = "+" if pct > 0 else ""
454
+ delta_str = f" ({sign}{pct:.0f}%)"
455
+ else:
456
+ delta_str = ""
457
+ summary = f"{_fmt_num(first, ascii_only=ascii_only)}{unit} {arrow} {_fmt_num(last, ascii_only=ascii_only)}{unit}{delta_str}"
458
+ else:
459
+ summary = "no finite values"
460
+ disp = name if len(name) <= max_lbl else name[: max_lbl - 1] + ("." if ascii_only else "…")
461
+ padded = disp.rjust(max_lbl)
462
+ is_hl = name in hl_set
463
+ if is_hl:
464
+ lines.append(
465
+ f" {style.accent(marker_on)} {style.bold(padded)} {style.accent(spark)} {style.bold(summary)}"
466
+ )
467
+ else:
468
+ lines.append(f" {padded} {style.primary(spark)} {summary}")
469
+
470
+ meta_bits: list[str] = []
471
+ if len(x_vals) >= 2:
472
+ x_lbl = spec.get("x_label") or "x"
473
+ meta_bits.append(f"{x_lbl}: {x_vals[0]} {arrow} {x_vals[-1]}")
474
+ events = spec.get("events")
475
+ if isinstance(events, Mapping) and events:
476
+ ev_str = ", ".join(f"{k}: {v}" for k, v in events.items())
477
+ meta_bits.append(f"Events: {ev_str}")
478
+ if meta_bits:
479
+ lines.append(" " + style.dim(" | ".join(meta_bits)))
480
+ return lines
481
+
482
+
483
+ def _render_facts_panel(
484
+ panel: Panel,
485
+ *,
486
+ width: int,
487
+ style: _Style,
488
+ ascii_only: bool,
489
+ ) -> list[str]:
490
+ bullet = "-" if ascii_only else "•"
491
+ lines: list[str] = []
492
+ if panel.kind == "matrix":
493
+ spec = panel.spec
494
+ rows_lbl = [str(r) for r in (spec.get("rows") or [])]
495
+ cols_lbl = [str(c) for c in (spec.get("cols") or [])]
496
+ vals = spec.get("values") or []
497
+ if cols_lbl and isinstance(vals, Sequence) and len(cols_lbl) <= 6 and len(vals) <= 8:
498
+ str_rows = []
499
+ for r_idx, rv in enumerate(vals):
500
+ rl = rows_lbl[r_idx] if r_idx < len(rows_lbl) else f"r{r_idx + 1}"
501
+ if isinstance(rv, Sequence):
502
+ str_rows.append([rl, *[_fmt_num(v, ascii_only=ascii_only) for v in rv]])
503
+ lines.extend(
504
+ _render_box_table(
505
+ ["", *cols_lbl],
506
+ str_rows,
507
+ aligns=["left", *(["right"] * len(cols_lbl))],
508
+ width=width,
509
+ style=style,
510
+ ascii_only=ascii_only,
511
+ )
512
+ )
513
+ elif panel.kind == "change":
514
+ spec = panel.spec
515
+ before = spec.get("before") or {}
516
+ after = spec.get("after") or {}
517
+ unit = f" {panel.unit}" if panel.unit else ""
518
+ arrow = "->" if ascii_only else "→"
519
+ if isinstance(before, Mapping) and isinstance(after, Mapping) and before:
520
+ max_lbl = min(max(len(str(k)) for k in before), max(12, width // 3))
521
+ for item, bv in before.items():
522
+ av = after.get(item)
523
+ if _is_num(bv) and _is_num(av):
524
+ delta = float(av) - float(bv)
525
+ sign = "+" if delta > 0 else ""
526
+ lines.append(
527
+ f" {str(item).rjust(max_lbl)} "
528
+ f"{_fmt_num(bv, ascii_only=ascii_only)}{unit} {arrow} "
529
+ f"{_fmt_num(av, ascii_only=ascii_only)}{unit} "
530
+ f"({sign}{_fmt_num(delta, ascii_only=ascii_only)}{unit})"
531
+ )
532
+ elif panel.kind == "waterfall":
533
+ spec = panel.spec
534
+ steps = spec.get("steps") or {}
535
+ unit = f" {panel.unit}" if panel.unit else ""
536
+ if isinstance(steps, Mapping) and steps:
537
+ rows_wf: list[list[str]] = []
538
+ running = 0.0
539
+ st = spec.get("start")
540
+ if isinstance(st, Sequence) and not isinstance(st, (str, bytes)) and len(st) == 2:
541
+ running = float(st[1])
542
+ rows_wf.append([str(st[0]), "-", f"{_fmt_num(running, ascii_only=ascii_only)}{unit}"])
543
+ for nm, dv in steps.items():
544
+ val = float(dv)
545
+ running += val
546
+ sign = "+" if val > 0 else ""
547
+ rows_wf.append(
548
+ [
549
+ str(nm),
550
+ f"{sign}{_fmt_num(val, ascii_only=ascii_only)}{unit}",
551
+ f"{_fmt_num(running, ascii_only=ascii_only)}{unit}",
552
+ ]
553
+ )
554
+ if spec.get("show_total", True):
555
+ rows_wf.append(
556
+ [
557
+ str(spec.get("total_label") or "Total"),
558
+ "-",
559
+ f"{_fmt_num(running, ascii_only=ascii_only)}{unit}",
560
+ ]
561
+ )
562
+ lines.extend(
563
+ _render_box_table(
564
+ ["Step", "Delta", "Cumulative"],
565
+ rows_wf,
566
+ aligns=["left", "right", "right"],
567
+ width=width,
568
+ style=style,
569
+ ascii_only=ascii_only,
570
+ )
571
+ )
572
+ elif panel.kind == "timeline":
573
+ spans = panel.spec.get("spans") or []
574
+ unit = f" {panel.unit}" if panel.unit else ""
575
+ if isinstance(spans, Sequence) and spans:
576
+ valid = [s for s in spans if isinstance(s, Sequence) and len(s) >= 3]
577
+ if valid:
578
+ t0 = min(float(s[1]) for s in valid)
579
+ t1 = max(float(s[2]) for s in valid)
580
+ wall = (t1 - t0) or 1.0
581
+ max_lbl = min(max(len(str(s[0])) for s in valid), max(12, width // 3))
582
+ bar_w = max(12, width - max_lbl - 18)
583
+ fill_ch = "#" if ascii_only else "█"
584
+ empty_ch = "." if ascii_only else "·"
585
+ for sp in valid:
586
+ nm = str(sp[0])[:max_lbl].rjust(max_lbl)
587
+ s_v, e_v = float(sp[1]), float(sp[2])
588
+ c0 = max(0, min(bar_w - 1, round((s_v - t0) / wall * bar_w)))
589
+ c1 = max(c0 + 1, min(bar_w, round((e_v - t0) / wall * bar_w)))
590
+ bar = empty_ch * c0 + fill_ch * (c1 - c0) + empty_ch * (bar_w - c1)
591
+ dur_s = _fmt_num(e_v - s_v, ascii_only=ascii_only)
592
+ lines.append(f" {nm} {style.primary(bar)} {dur_s}{unit}")
593
+ elif panel.kind == "flow":
594
+ stages = panel.spec.get("stages") or []
595
+ unit = f" {panel.unit}" if panel.unit else ""
596
+ if isinstance(stages, Sequence) and stages:
597
+ valid = [s for s in stages if isinstance(s, Sequence) and len(s) >= 2]
598
+ if valid:
599
+ max_v = max(float(s[1]) for s in valid) or 1.0
600
+ start_v = float(valid[0][1]) or 1.0
601
+ max_lbl = min(max(len(str(s[0])) for s in valid), max(12, width // 3))
602
+ bar_w = max(10, width - max_lbl - 24)
603
+ fill_ch = "#" if ascii_only else "█"
604
+ arrow = "v" if ascii_only else "↓"
605
+ prev_v: float | None = None
606
+ for idx_f, st in enumerate(valid):
607
+ nm = str(st[0])[:max_lbl].rjust(max_lbl)
608
+ val = float(st[1])
609
+ if prev_v is not None:
610
+ delta = val - prev_v
611
+ sp = (100.0 * delta / prev_v) if prev_v > 0 else 0.0
612
+ rsn = f" · {st[2]}" if len(st) >= 3 and st[2] else ""
613
+ lines.append(
614
+ f" {' ' * max_lbl} {arrow} {_fmt_num(delta, ascii_only=ascii_only)}{unit} ({sp:+.0f}%){rsn}"
615
+ )
616
+ filled = max(1 if val > 0 else 0, round(val / max_v * bar_w))
617
+ pct = 100.0 * val / start_v
618
+ lines.append(
619
+ f" {nm} {style.primary(fill_ch * filled)} {_fmt_num(val, ascii_only=ascii_only)}{unit} ({pct:.0f}%)"
620
+ )
621
+ prev_v = val
622
+
623
+ if panel.facts:
624
+ for fact in panel.facts:
625
+ wrapped = textwrap.wrap(fact, width=max(30, width - 4))
626
+ for idx, wline in enumerate(wrapped):
627
+ prefix = f" {bullet} " if idx == 0 else " "
628
+ lines.append(prefix + wline)
629
+ elif not lines and panel.describe:
630
+ lines.append(f" {bullet} {panel.describe}")
631
+ return lines
632
+
633
+
634
+ def render_terminal(
635
+ exp_or_spec: Explanation | Mapping[str, Any],
636
+ *,
637
+ width: int = 78,
638
+ color: bool = True,
639
+ ascii_only: bool = False,
640
+ ) -> str:
641
+ """Render an ``Explanation`` or spec dict as crisp Unicode or ASCII terminal output."""
642
+ exp = _ensure_explanation(exp_or_spec)
643
+ w = max(40, int(width))
644
+ accent = exp.theme.accent_colors[0] if exp.theme.accent_colors else "#CD4324"
645
+ primary = exp.theme.series_colors[0] if exp.theme.series_colors else "#1F5A9D"
646
+ style = _Style(enabled=color, accent=accent, primary=primary)
647
+ rule = ("-" if ascii_only else "─") * w
648
+
649
+ out: list[str] = []
650
+ for line in textwrap.wrap(exp.takeaway, width=w):
651
+ out.append(style.bold(line))
652
+ if exp.subtitle:
653
+ for line in textwrap.wrap(exp.subtitle, width=w):
654
+ out.append(style.dim(line))
655
+ out.append(style.dim(rule))
656
+
657
+ multi = len(exp.panels) > 1
658
+ bullet = "-" if ascii_only else "•"
659
+ for p_idx, (key, panel) in enumerate(exp.panels.items()):
660
+ if p_idx > 0:
661
+ out.append("")
662
+ title_part = panel.title or panel.label or panel.kind
663
+ meta_part = ""
664
+ if panel.label and panel.unit:
665
+ meta_part = f" [{panel.label}, {panel.unit}]"
666
+ elif panel.unit:
667
+ meta_part = f" [{panel.unit}]"
668
+ elif panel.label and panel.label != title_part:
669
+ meta_part = f" [{panel.label}]"
670
+ prefix = f"[{key}] " if multi else ""
671
+ out.append(style.bold(f"{prefix}{title_part}") + style.dim(meta_part))
672
+
673
+ if panel.kind in {"compare", "share"}:
674
+ out.extend(_render_bars_panel(panel, width=w, style=style, ascii_only=ascii_only))
675
+ if panel.facts:
676
+ out.append(style.dim(f" {bullet} {panel.facts[0]}"))
677
+ elif panel.kind == "table":
678
+ out.extend(_render_table_panel(panel, width=w, style=style, ascii_only=ascii_only))
679
+ if panel.facts:
680
+ out.append(style.dim(f" {bullet} {panel.facts[0]}"))
681
+ elif panel.kind == "trend":
682
+ out.extend(_render_trend_panel(panel, width=w, style=style, ascii_only=ascii_only))
683
+ if panel.facts:
684
+ out.append(style.dim(f" {bullet} {panel.facts[0]}"))
685
+ else:
686
+ out.extend(_render_facts_panel(panel, width=w, style=style, ascii_only=ascii_only))
687
+
688
+ footer_lines: list[str] = []
689
+ if exp.note:
690
+ footer_lines.extend(textwrap.wrap(f"Note: {exp.note}", width=w))
691
+ if exp.source:
692
+ footer_lines.extend(textwrap.wrap(f"Source: {exp.source}", width=w))
693
+ if footer_lines:
694
+ out.append(style.dim(rule))
695
+ for fl in footer_lines:
696
+ out.append(style.dim(fl))
697
+
698
+ rendered = "\n".join(out)
699
+ return _to_ascii(rendered) if ascii_only else rendered
700
+
701
+
702
+ def _explanation_to_png_bytes(exp: Explanation) -> bytes:
703
+ buf = io.BytesIO()
704
+ dpi = round(exp.display_width_px * 2.0 / float(exp.fig.get_figwidth()))
705
+ with exp.theme.rc_context(exp.spec), _GlyphCapture():
706
+ exp.fig.savefig(
707
+ buf,
708
+ format="png",
709
+ dpi=dpi,
710
+ facecolor=exp.theme.background,
711
+ edgecolor=exp.theme.background,
712
+ )
713
+ return buf.getvalue()
714
+
715
+
716
+ def show_in_terminal(
717
+ path_or_spec: str | Path | Explanation | Mapping[str, Any],
718
+ *,
719
+ mode: str = "auto",
720
+ width: int = 78,
721
+ color: bool = True,
722
+ env: Mapping[str, str] | None = None,
723
+ ) -> str:
724
+ """Return a terminal-ready string (inline graphics escape sequence or rich text).
725
+
726
+ ``path_or_spec`` may be a PNG path, a JSON spec path, an ``Explanation``, or
727
+ a spec dict. ``mode`` may be ``"auto"``, ``"kitty"``, ``"iterm2"``,
728
+ ``"unicode"``, or ``"ascii"``.
729
+ """
730
+ valid_modes = {"auto", "kitty", "iterm2", "unicode", "ascii"}
731
+ if mode not in valid_modes:
732
+ raise ValueError(
733
+ f"Unknown terminal mode {mode!r}. Choose one of: {', '.join(sorted(valid_modes))}."
734
+ )
735
+
736
+ resolved = detect_graphics_protocol(env) if mode == "auto" else mode
737
+ png_bytes: bytes | None = None
738
+ exp_or_spec: Explanation | Mapping[str, Any] | None = None
739
+ raw_png_path: Path | None = None
740
+
741
+ if isinstance(path_or_spec, (Explanation, Mapping)):
742
+ exp_or_spec = path_or_spec
743
+ elif isinstance(path_or_spec, (str, Path)):
744
+ path = Path(path_or_spec)
745
+ raw = path.read_bytes()
746
+ if raw.startswith(_PNG_SIGNATURE):
747
+ png_bytes = raw
748
+ raw_png_path = path
749
+ embedded = read_png_text(path)
750
+ if "mintfig:spec" in embedded:
751
+ exp_or_spec = json.loads(embedded["mintfig:spec"])
752
+ else:
753
+ spec = json.loads(raw.decode("utf-8"))
754
+ if not isinstance(spec, Mapping):
755
+ raise ValueError("JSON spec must be an object.")
756
+ exp_or_spec = spec
757
+ else:
758
+ raise TypeError(
759
+ "path_or_spec must be a Path, str, Explanation, or spec mapping, "
760
+ f"got {type(path_or_spec).__name__}."
761
+ )
762
+
763
+ if resolved in {"kitty", "iterm2"}:
764
+ if png_bytes is None:
765
+ assert exp_or_spec is not None
766
+ exp = _ensure_explanation(exp_or_spec)
767
+ png_bytes = _explanation_to_png_bytes(exp)
768
+ return encode_kitty_png(png_bytes) if resolved == "kitty" else encode_iterm2_png(png_bytes)
769
+
770
+ ascii_only = resolved == "ascii"
771
+ if exp_or_spec is not None:
772
+ return render_terminal(exp_or_spec, width=width, color=color, ascii_only=ascii_only)
773
+
774
+ # Plain PNG with no embedded mintfig spec in text-only mode: return clean summary
775
+ from PIL import Image
776
+
777
+ assert png_bytes is not None
778
+ with Image.open(io.BytesIO(png_bytes)) as img:
779
+ img_w, img_h = img.size
780
+ name = raw_png_path.name if raw_png_path else "image.png"
781
+ msg = (
782
+ f"{name} ({img_w}x{img_h} px PNG, no embedded mintfig spec for text rendering; "
783
+ "use --mode kitty or --mode iterm2 for inline image display)"
784
+ )
785
+ return _to_ascii(msg) if ascii_only else msg