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/brief.py ADDED
@@ -0,0 +1,518 @@
1
+ """Stateful multi-turn visual memory (``mint.Session``) and multi-figure briefings (``mint.brief``).
2
+
3
+ Solves two multi-turn agent communication gaps:
4
+ 1. ``Session`` maintains a persistent entity-colour ledger across figures with
5
+ smart base-entity prefix matching (so ``"Alpha-3 (int4)"`` inherits
6
+ ``"Alpha-3"``'s hue automatically instead of drifting to a random colour).
7
+ 2. ``Brief`` composes 1–12 figures into a single cohesive self-contained HTML
8
+ briefing or PR-/Artifact-ready Markdown bundle with consistent theme,
9
+ executive takeaway index, L2/L3 narrative bullets, and exact Markdown tables.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import html
15
+ import json
16
+ import re
17
+ from collections.abc import Mapping, Sequence
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from ._explain.core import ExplainError, Panel
22
+ from ._explain.layout import Explanation, explain, explain_from_spec, load
23
+ from .edit import edit as _edit_figure
24
+ from .epistemic import build_narrative
25
+ from .interactive import render_html_fragment
26
+ from .themes import Theme, get_theme, relative_luminance
27
+
28
+ __all__ = ["Brief", "Session", "brief"]
29
+
30
+ _MAX_BRIEF_FIGURES = 12
31
+ _TOKEN_BOUNDARY = re.compile(r"[\s(\[\-/:,_]")
32
+
33
+
34
+ def _match_pinned_slot(item: str, ledger: Mapping[str, str]) -> str | None:
35
+ """Find an exact or longest token-boundary prefix match in ``ledger``."""
36
+ low = item.strip().lower()
37
+ if not low:
38
+ return None
39
+ norm_ledger = {k.strip().lower(): slot for k, slot in ledger.items() if k.strip()}
40
+ if low in norm_ledger:
41
+ return norm_ledger[low]
42
+ # Longest token-boundary prefix match ("alpha-3" -> "alpha-3 (int4)", "us-west" -> "us-west after")
43
+ best_len = 0
44
+ best_slot: str | None = None
45
+ for base_k, slot in norm_ledger.items():
46
+ if len(base_k) < 3 or len(base_k) <= best_len:
47
+ continue
48
+ if low.startswith(base_k) and len(low) > len(base_k):
49
+ nxt = low[len(base_k)]
50
+ if _TOKEN_BOUNDARY.match(nxt):
51
+ best_len = len(base_k)
52
+ best_slot = slot
53
+ return best_slot
54
+
55
+
56
+ def _resolve_figure(item: Explanation | str | Path | Mapping[str, Any]) -> Explanation:
57
+ if isinstance(item, Explanation):
58
+ return item
59
+ if isinstance(item, Mapping):
60
+ return explain_from_spec(item)
61
+ if isinstance(item, (str, Path)):
62
+ return load(item)
63
+ raise ExplainError(
64
+ f"brief() items must be Explanation objects, PNG/JSON paths, or spec dicts; got {type(item).__name__}.",
65
+ fix_hint='Pass figures from mint.explain(...) or saved paths like "fig1.png".',
66
+ )
67
+
68
+
69
+ class Session:
70
+ """Multi-turn visual memory keeping style, palette, and entity colours aligned across figures."""
71
+
72
+ def __init__(
73
+ self,
74
+ *,
75
+ style: str | Theme = "mintfig",
76
+ palette: str | None = None,
77
+ accent: str | None = None,
78
+ width: str | float = "chat",
79
+ colors: Mapping[str, str] | None = None,
80
+ state_path: str | Path | None = None,
81
+ ) -> None:
82
+ self.style = style
83
+ self.palette = palette
84
+ self.accent = accent
85
+ self.width = width
86
+ self.state_path = Path(state_path) if state_path is not None else None
87
+ self.colors: dict[str, str] = {}
88
+ self.figures: list[Explanation] = []
89
+
90
+ if self.state_path is not None and self.state_path.exists():
91
+ try:
92
+ saved = json.loads(self.state_path.read_text(encoding="utf-8"))
93
+ if isinstance(saved, Mapping):
94
+ for k, v in (saved.get("colors") or {}).items():
95
+ self.colors[str(k)] = str(v)
96
+ if style == "mintfig" and isinstance(saved.get("style"), str):
97
+ self.style = saved["style"]
98
+ if palette is None and isinstance(saved.get("palette"), str):
99
+ self.palette = saved["palette"]
100
+ if accent is None and isinstance(saved.get("accent"), str):
101
+ self.accent = saved["accent"]
102
+ except (OSError, json.JSONDecodeError):
103
+ pass
104
+
105
+ if colors:
106
+ for k, v in colors.items():
107
+ self.colors[str(k)] = str(v)
108
+
109
+ def _save_state(self) -> None:
110
+ if self.state_path is None:
111
+ return
112
+ self.state_path.parent.mkdir(parents=True, exist_ok=True)
113
+ payload = {
114
+ "style": self.style.name if isinstance(self.style, Theme) else self.style,
115
+ "palette": self.palette,
116
+ "accent": self.accent,
117
+ "colors": dict(self.colors),
118
+ }
119
+ self.state_path.write_text(
120
+ json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
121
+ encoding="utf-8",
122
+ )
123
+
124
+ def _merged_colors(
125
+ self,
126
+ panels: Sequence[Panel | Mapping[str, Any]],
127
+ explicit: Mapping[str, str] | None,
128
+ ) -> dict[str, str] | None:
129
+ merged: dict[str, str] = {}
130
+ # Collect candidate entity names appearing in this figure's panels
131
+ candidates: list[str] = []
132
+ for p in panels:
133
+ if isinstance(p, Panel):
134
+ candidates.extend(p.color_items)
135
+ candidates.extend(p.color_focus)
136
+ # First honor explicit caller pins
137
+ if explicit:
138
+ for k, v in explicit.items():
139
+ merged[str(k)] = str(v)
140
+ # Then match session ledger (exact + prefix inheritance, up to 4 pins)
141
+ for cand in dict.fromkeys(candidates):
142
+ if cand in merged or len(merged) >= 4:
143
+ continue
144
+ slot = _match_pinned_slot(cand, self.colors)
145
+ if slot is not None:
146
+ merged[cand] = slot
147
+ # If no candidates matched directly (e.g. spec dicts), carry over up to 4 session pins
148
+ if not merged and self.colors:
149
+ for k, v in list(self.colors.items())[:4]:
150
+ merged[k] = v
151
+ return merged or None
152
+
153
+ def explain(
154
+ self,
155
+ takeaway: str,
156
+ *panels: Panel | Mapping[str, Any],
157
+ colors: Mapping[str, str] | None = None,
158
+ **kwargs: Any,
159
+ ) -> Explanation:
160
+ """Render an :class:`Explanation` inheriting session theme and entity colours."""
161
+ kwargs.setdefault("style", self.style)
162
+ if self.palette is not None:
163
+ kwargs.setdefault("palette", self.palette)
164
+ if self.accent is not None:
165
+ kwargs.setdefault("accent", self.accent)
166
+ kwargs.setdefault("width", self.width)
167
+ merged = self._merged_colors(panels, colors)
168
+ result = explain(takeaway, *panels, colors=merged, **kwargs)
169
+ self._harvest(result, explicit=colors)
170
+ self.figures.append(result)
171
+ return result
172
+
173
+ def edit(self, figure: Explanation | str | Path | Mapping[str, Any], **kwargs: Any) -> Explanation:
174
+ """Edit an existing figure and record updated entity colours in this session."""
175
+ result = _edit_figure(figure, **kwargs)
176
+ self._harvest(result)
177
+ self.figures.append(result)
178
+ return result
179
+
180
+ def _harvest(
181
+ self,
182
+ result: Explanation,
183
+ *,
184
+ explicit: Mapping[str, str] | None = None,
185
+ ) -> None:
186
+ if explicit:
187
+ for k, v in explicit.items():
188
+ self.colors[str(k)] = str(v)
189
+ for k, slot in result.entity_colors.items():
190
+ # Preserve earlier canonical names; add newly seen names cleanly
191
+ self.colors.setdefault(str(k), str(slot))
192
+ self._save_state()
193
+
194
+ def brief(
195
+ self,
196
+ title: str,
197
+ *,
198
+ subtitle: str | None = None,
199
+ summary: Sequence[str] | str | None = None,
200
+ source: str | None = None,
201
+ ) -> Brief:
202
+ """Compose all figures created in this session into a cohesive :class:`Brief`."""
203
+ if not self.figures:
204
+ raise ExplainError(
205
+ "Session has no figures yet.",
206
+ fix_hint="Call session.explain(...) at least once before session.brief(...).",
207
+ )
208
+ return brief(
209
+ title,
210
+ *self.figures,
211
+ subtitle=subtitle,
212
+ summary=summary,
213
+ source=source,
214
+ style=self.style if isinstance(self.style, str) else self.style.name,
215
+ )
216
+
217
+
218
+ class Brief:
219
+ """A cohesive multi-figure investigation briefing exportable to HTML or Markdown."""
220
+
221
+ def __init__(
222
+ self,
223
+ title: str,
224
+ figures: Sequence[Explanation],
225
+ *,
226
+ subtitle: str | None = None,
227
+ summary: Sequence[str] | str | None = None,
228
+ source: str | None = None,
229
+ style: str | Theme | None = None,
230
+ ) -> None:
231
+ self.title = title
232
+ self.figures = list(figures)
233
+ self.subtitle = subtitle
234
+ if isinstance(summary, str):
235
+ self.summary_points = [summary]
236
+ elif summary is not None:
237
+ self.summary_points = [str(s) for s in summary if str(s).strip()]
238
+ else:
239
+ self.summary_points = []
240
+ self.source = source
241
+ self.theme = get_theme(style) if style is not None else self.figures[0].theme
242
+
243
+ @property
244
+ def ship_all(self) -> bool:
245
+ return all(fig.ship for fig in self.figures)
246
+
247
+ def to_html(self) -> str:
248
+ """Render a self-contained zero-CDN interactive HTML briefing with jump navigation."""
249
+ theme = self.theme
250
+ is_dark = relative_luminance(theme.background) < 0.25
251
+ page_bg = "#0C0F14" if is_dark else "#F4F5F7"
252
+ card_bg = theme.background
253
+ border = "rgba(255,255,255,0.12)" if is_dark else "rgba(26,29,33,0.12)"
254
+ accent = theme.accent_colors[0] if theme.accent_colors else theme.series_colors[0]
255
+ esc = html.escape
256
+
257
+ toc_items = "\n".join(
258
+ f'<li><a href="#fig-{i + 1}"><span class="fm-bnum">{i + 1}</span>'
259
+ f'<span>{esc(fig.takeaway)}</span></a></li>'
260
+ for i, fig in enumerate(self.figures)
261
+ )
262
+ summary_html = ""
263
+ if self.summary_points:
264
+ bullets = "".join(f"<li>{esc(pt)}</li>" for pt in self.summary_points)
265
+ summary_html = f'<section class="fm-bsum"><h2>Key findings</h2><ul>{bullets}</ul></section>'
266
+
267
+ sections: list[str] = []
268
+ for idx, fig in enumerate(self.figures, 1):
269
+ frag = render_html_fragment(fig, interactive=True)
270
+ sections.append(
271
+ f'<section id="fig-{idx}" class="fm-bsec">'
272
+ f'<div class="fm-bsec-label">Finding {idx} of {len(self.figures)}</div>'
273
+ f"{frag}"
274
+ f"</section>"
275
+ )
276
+
277
+ sub_html = f'<p class="fm-bsub">{esc(self.subtitle)}</p>' if self.subtitle else ""
278
+ src_html = f'<footer class="fm-bfoot">Source: {esc(self.source)}</footer>' if self.source else ""
279
+
280
+ return f"""<!DOCTYPE html>
281
+ <html lang="en">
282
+ <head>
283
+ <meta charset="utf-8">
284
+ <meta name="viewport" content="width=device-width, initial-scale=1">
285
+ <title>{esc(self.title)}</title>
286
+ <style>
287
+ :root {{
288
+ color-scheme: {"dark" if is_dark else "light"};
289
+ }}
290
+ * {{ box-sizing: border-box; }}
291
+ body {{
292
+ margin: 0;
293
+ padding: 32px 20px 64px;
294
+ background: {page_bg};
295
+ color: {theme.ink};
296
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
297
+ line-height: 1.5;
298
+ }}
299
+ .fm-brief {{
300
+ max-width: 1080px;
301
+ margin: 0 auto;
302
+ }}
303
+ .fm-bhead {{
304
+ background: {card_bg};
305
+ border: 1px solid {border};
306
+ border-top: 3px solid {accent};
307
+ border-radius: 10px;
308
+ padding: 24px 28px;
309
+ margin-bottom: 24px;
310
+ }}
311
+ .fm-bhead h1 {{
312
+ margin: 0 0 6px;
313
+ font-size: 1.65rem;
314
+ line-height: 1.2;
315
+ }}
316
+ .fm-bsub {{
317
+ margin: 0 0 16px;
318
+ color: {theme.muted};
319
+ font-size: 0.98rem;
320
+ }}
321
+ .fm-bsum {{
322
+ margin: 14px 0 16px;
323
+ padding: 12px 16px;
324
+ border-left: 3px solid {accent};
325
+ background: {"rgba(255,255,255,0.04)" if is_dark else "rgba(0,0,0,0.03)"};
326
+ border-radius: 0 6px 6px 0;
327
+ }}
328
+ .fm-bsum h2 {{
329
+ margin: 0 0 6px;
330
+ font-size: 0.85rem;
331
+ text-transform: uppercase;
332
+ letter-spacing: 0.05em;
333
+ color: {theme.muted};
334
+ }}
335
+ .fm-bsum ul {{ margin: 0; padding-left: 18px; }}
336
+ .fm-btoc {{
337
+ list-style: none;
338
+ margin: 12px 0 0;
339
+ padding: 0;
340
+ display: grid;
341
+ gap: 6px;
342
+ }}
343
+ .fm-btoc a {{
344
+ display: flex;
345
+ align-items: baseline;
346
+ gap: 10px;
347
+ text-decoration: none;
348
+ color: {theme.ink};
349
+ padding: 6px 8px;
350
+ border-radius: 6px;
351
+ }}
352
+ .fm-btoc a:hover {{
353
+ background: {"rgba(255,255,255,0.06)" if is_dark else "rgba(0,0,0,0.04)"};
354
+ }}
355
+ .fm-bnum {{
356
+ display: inline-flex;
357
+ align-items: center;
358
+ justify-content: center;
359
+ min-width: 22px;
360
+ height: 22px;
361
+ border-radius: 999px;
362
+ background: {accent};
363
+ color: #fff;
364
+ font-size: 0.78rem;
365
+ font-weight: 700;
366
+ }}
367
+ .fm-bsec {{
368
+ margin-bottom: 28px;
369
+ }}
370
+ .fm-bsec-label {{
371
+ font-size: 0.78rem;
372
+ font-weight: 700;
373
+ text-transform: uppercase;
374
+ letter-spacing: 0.06em;
375
+ color: {theme.muted};
376
+ margin: 0 0 8px 4px;
377
+ }}
378
+ .fm-bfoot {{
379
+ margin-top: 24px;
380
+ font-size: 0.85rem;
381
+ color: {theme.muted};
382
+ text-align: center;
383
+ }}
384
+ </style>
385
+ </head>
386
+ <body>
387
+ <main class="fm-brief">
388
+ <header class="fm-bhead">
389
+ <h1>{esc(self.title)}</h1>
390
+ {sub_html}
391
+ {summary_html}
392
+ <ol class="fm-btoc">{toc_items}</ol>
393
+ </header>
394
+ {"".join(sections)}
395
+ {src_html}
396
+ </main>
397
+ </body>
398
+ </html>
399
+ """
400
+
401
+ def to_markdown(
402
+ self,
403
+ *,
404
+ image_paths: Sequence[str] | None = None,
405
+ ) -> str:
406
+ """Render a PR- and Artifact-ready Markdown briefing with L2/L3 facts and tables."""
407
+ lines: list[str] = [f"# {self.title}"]
408
+ if self.subtitle:
409
+ lines.append(f"\n*{self.subtitle}*")
410
+ if self.summary_points:
411
+ lines.append("\n## Key findings\n")
412
+ for pt in self.summary_points:
413
+ lines.append(f"- {pt}")
414
+
415
+ for idx, fig in enumerate(self.figures, 1):
416
+ lines.append(f"\n---\n\n## {idx}. {fig.takeaway}")
417
+ if fig.subtitle:
418
+ lines.append(f"\n*{fig.subtitle}*")
419
+ img_ref = (
420
+ image_paths[idx - 1]
421
+ if image_paths is not None and idx - 1 < len(image_paths)
422
+ else (str(fig.saved_path) if fig.saved_path else None)
423
+ )
424
+ if img_ref:
425
+ lines.append(f"\n![{fig.takeaway}]({img_ref})")
426
+ narr = build_narrative(fig.takeaway, fig.panels, subtitle=fig.subtitle, source=fig.source)
427
+ key_bullets = [*narr["L2"][:3], *narr["L3"][:2]]
428
+ if key_bullets:
429
+ lines.append("")
430
+ for b in key_bullets:
431
+ lines.append(f"- {b}")
432
+ for panel in fig.panels.values():
433
+ if panel.kind == "table":
434
+ lines.append("")
435
+ lines.append(panel.to_markdown())
436
+ if fig.source:
437
+ lines.append(f"\n*Source: {fig.source}*")
438
+
439
+ if self.source:
440
+ lines.append(f"\n---\n\n*Briefing source: {self.source}*")
441
+ return "\n".join(lines) + "\n"
442
+
443
+ def save(self, path: str | Path, *, scale: float = 2.0) -> dict[str, Any]:
444
+ """Write the briefing as ``.html`` (self-contained) or ``.md`` (with saved figure PNGs)."""
445
+ out = Path(path)
446
+ out.parent.mkdir(parents=True, exist_ok=True)
447
+ suffix = out.suffix.lower()
448
+ assets: list[str] = []
449
+
450
+ if suffix in {".html", ".htm"}:
451
+ out.write_text(self.to_html(), encoding="utf-8")
452
+ fmt_name = "html"
453
+ elif suffix in {".md", ".markdown"}:
454
+ asset_dir = out.parent / f"{out.stem}_figures"
455
+ asset_dir.mkdir(parents=True, exist_ok=True)
456
+ rel_paths: list[str] = []
457
+ for idx, fig in enumerate(self.figures, 1):
458
+ png_name = f"fig_{idx:02d}.png"
459
+ png_path = asset_dir / png_name
460
+ fig.save(png_path, scale=scale)
461
+ assets.append(str(png_path.resolve()))
462
+ rel_paths.append(f"{asset_dir.name}/{png_name}")
463
+ out.write_text(self.to_markdown(image_paths=rel_paths), encoding="utf-8")
464
+ fmt_name = "markdown"
465
+ else:
466
+ raise ExplainError(
467
+ f"Brief.save() expects a .html or .md path, got {out.suffix!r}.",
468
+ fix_hint='Save to "brief.html" (self-contained) or "brief.md" (Markdown + PNGs).',
469
+ )
470
+
471
+ return {
472
+ "path": str(out.resolve()),
473
+ "format": fmt_name,
474
+ "title": self.title,
475
+ "figure_count": len(self.figures),
476
+ "ship_all": self.ship_all,
477
+ "figures": [
478
+ {"index": i + 1, "takeaway": f.takeaway, "ok": f.ok, "ship": f.ship}
479
+ for i, f in enumerate(self.figures)
480
+ ],
481
+ "assets": assets,
482
+ }
483
+
484
+
485
+ def brief(
486
+ title: str,
487
+ *figures: Explanation | str | Path | Mapping[str, Any],
488
+ subtitle: str | None = None,
489
+ summary: Sequence[str] | str | None = None,
490
+ source: str | None = None,
491
+ style: str | Theme | None = None,
492
+ ) -> Brief:
493
+ """Compose 1–12 figures into a single HTML or Markdown investigation briefing."""
494
+ if not isinstance(title, str) or not title.strip():
495
+ raise ExplainError(
496
+ "brief() needs a non-empty title.",
497
+ fix_hint='e.g. mint.brief("Q4 latency investigation", fig1, fig2).',
498
+ )
499
+ if not figures:
500
+ raise ExplainError(
501
+ "brief() needs at least one figure.",
502
+ fix_hint="Pass one or more Explanation objects or saved mintfig PNG/JSON paths.",
503
+ )
504
+ if len(figures) > _MAX_BRIEF_FIGURES:
505
+ raise ExplainError(
506
+ f"brief() got {len(figures)} figures; at most {_MAX_BRIEF_FIGURES} fit one cohesive briefing.",
507
+ fix_hint=f"Keep at most {_MAX_BRIEF_FIGURES} key figures in one brief.",
508
+ rule="too_many_items",
509
+ )
510
+ resolved = [_resolve_figure(item) for item in figures]
511
+ return Brief(
512
+ title.strip(),
513
+ resolved,
514
+ subtitle=subtitle,
515
+ summary=summary,
516
+ source=source,
517
+ style=style,
518
+ )