572 lines
27 KiB
Python
Executable File
572 lines
27 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Draw a chart in the ai-agent conversation (the Charts plugin's card).
|
||
|
||
chart line --csv cost.csv --x date --y opus,sonnet --title "Daily spend" --format usd
|
||
chart bar --csv - --x model --y cost # CSV on stdin
|
||
chart hbar --csv runs.csv --x project --y cost --top 12
|
||
chart line --csv long.csv --x date --y cost --group model # long format: one series per model
|
||
chart --json spec.json # a spec file (the ```chart block's format)
|
||
chart <<'EOF' # a spec on stdin
|
||
{"type": "donut", "title": "Tokens by model", "slices": [{"label": "Opus", "value": 812}, …]}
|
||
EOF
|
||
chart --example kpi # a sample spec to adapt (nothing drawn)
|
||
|
||
Types: line · area · bar · hbar · scatter · donut · kpi. It checks the data,
|
||
keeps big series small enough for the conversation (shape kept, said in a
|
||
note), and prints one `CHART {…}` line the conversation draws as a card —
|
||
tooltips, legend, a Data table. Nothing leaves this machine. Stdlib only.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import csv
|
||
import io
|
||
import json
|
||
import math
|
||
import re
|
||
import sys
|
||
|
||
sys.dont_write_bytecode = True
|
||
|
||
TYPES = ("line", "area", "bar", "hbar", "scatter", "donut", "kpi")
|
||
ALIASES = {"column": "bar", "columns": "bar", "barh": "hbar", "horizontal": "hbar", "pie": "donut",
|
||
"doughnut": "donut", "stats": "kpi", "tiles": "kpi", "points": "scatter",
|
||
"stacked-bar": "bar", "stacked-area": "area"}
|
||
FORMATS = ("number", "compact", "usd", "eur", "gbp", "chf", "jpy", "percent", "ratio", "bytes",
|
||
"duration", "seconds", "ms")
|
||
MAX_SERIES = 8 # categorical colour slots: never a 9th hue
|
||
MAX_SLICES = 6 # a donut past 6 parts folds the rest into "Other"
|
||
MAX_BARS = 60 # categories on a bar chart (hbar: --top, default 25)
|
||
BUDGET = 7000 # chars of the CHART line: the hub keeps a call's output whole up to 8,000
|
||
NOTES_ROOM = 500 # of which the notes added after the data is fitted
|
||
|
||
EXAMPLES = {
|
||
"line": {"type": "line", "title": "Daily spend", "format": "usd",
|
||
"x": ["2026-11-20", "2026-11-21", "2026-11-22", "2026-11-23"],
|
||
"series": [{"name": "Opus", "data": [42.1, 51.3, 38.9, 61.0]},
|
||
{"name": "Sonnet", "data": [12.0, 15.2, 11.8, 18.4]}]},
|
||
"area": {"type": "area", "title": "Context per turn", "format": "compact", "xLabel": "turn",
|
||
"x": [1, 2, 3, 4, 5], "series": [{"name": "tokens", "data": [18000, 26000, 34000, 41000, 52000]}]},
|
||
"bar": {"type": "bar", "title": "Tool calls", "stacked": True, "x": ["Mon", "Tue", "Wed"],
|
||
"series": [{"name": "shell", "data": [120, 80, 140]}, {"name": "edit", "data": [40, 20, 60]}]},
|
||
"hbar": {"type": "hbar", "title": "Spend by project", "format": "usd",
|
||
"x": ["ai-agent", "infra", "blog"], "series": [{"name": "spend", "data": [412.5, 233.1, 41.7]}]},
|
||
"scatter": {"type": "scatter", "title": "Cost vs duration", "xLabel": "minutes", "yLabel": "cost", "format": "usd",
|
||
"series": [{"name": "Opus", "data": [[3, 0.8], [12, 2.4], [41, 9.8]]}]},
|
||
"donut": {"type": "donut", "title": "Where the money went", "format": "usd",
|
||
"slices": [{"label": "Messages", "value": 48.2}, {"label": "Shell", "value": 31.5}, {"label": "Reads", "value": 18.9}]},
|
||
"kpi": {"type": "kpi", "title": "This week", "stats": [
|
||
{"label": "Spend", "value": 412.5, "format": "usd", "delta": 12.4, "deltaFormat": "percent",
|
||
"deltaLabel": "vs last week", "good": "down", "trend": [40, 52, 48, 61, 55, 70, 72]},
|
||
{"label": "Conversations", "value": 263, "delta": 18, "deltaLabel": "vs last week"}]},
|
||
}
|
||
|
||
|
||
class ChartError(Exception):
|
||
pass
|
||
|
||
|
||
# ── values ─────────────────────────────────────────────────────────────────
|
||
_NUM_RE = re.compile(r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$")
|
||
|
||
|
||
def num(v):
|
||
"""A cell as a number, or None (empty / not a number)."""
|
||
if v is None or isinstance(v, bool):
|
||
return None if v is None else float(v)
|
||
if isinstance(v, (int, float)):
|
||
return v if math.isfinite(v) else None
|
||
s = str(v).strip().replace(" ", "").replace("\xa0", "").replace(" ", "").replace("_", "")
|
||
if not s or s.lower() in ("null", "none", "nan", "-", "–", "n/a"):
|
||
return None
|
||
s = re.sub(r"^[$€£]|[$€£%]$", "", s)
|
||
if re.fullmatch(r"[-+]?\d{1,3}(,\d{3})+(\.\d+)?", s):
|
||
s = s.replace(",", "")
|
||
if not _NUM_RE.match(s):
|
||
return None
|
||
f = float(s)
|
||
return f if math.isfinite(f) else None
|
||
|
||
|
||
def short(v: float | None):
|
||
"""6 significant digits (integers kept whole): smaller CHART lines, cents kept."""
|
||
if v is None:
|
||
return None
|
||
if float(v).is_integer() and abs(v) < 1e15:
|
||
return int(v)
|
||
r = float(f"{v:.6g}")
|
||
return int(r) if r.is_integer() and abs(r) < 1e15 else r
|
||
|
||
|
||
def text(v, n: int = 80) -> str:
|
||
return "" if v is None else str(v)[:n]
|
||
|
||
|
||
# ── input ──────────────────────────────────────────────────────────────────
|
||
def read_source(path: str) -> str:
|
||
if path == "-":
|
||
return sys.stdin.read()
|
||
try:
|
||
with open(path, encoding="utf-8-sig") as f:
|
||
return f.read()
|
||
except OSError as e:
|
||
raise ChartError(f"can't read {path}: {e.strerror}") from None
|
||
|
||
|
||
def read_stdin(wait: float = 5.0) -> str | None:
|
||
"""What was piped in (a heredoc, `… | chart bar`) — never a wait on a
|
||
terminal or on a pipe nobody writes to."""
|
||
if sys.stdin is None or sys.stdin.closed or sys.stdin.isatty():
|
||
return None
|
||
try:
|
||
import select
|
||
ready, _, _ = select.select([sys.stdin], [], [], wait)
|
||
if not ready:
|
||
return None
|
||
except (ImportError, OSError, ValueError):
|
||
pass
|
||
return sys.stdin.read()
|
||
|
||
|
||
def parse_csv(raw: str) -> list[dict]:
|
||
raw = raw.strip("\n\r ")
|
||
if not raw:
|
||
raise ChartError("the CSV is empty")
|
||
first = raw.split("\n", 1)[0]
|
||
delim = max(("\t", ",", ";", "|"), key=first.count)
|
||
if first.count(delim) == 0:
|
||
delim = ","
|
||
rows = list(csv.DictReader(io.StringIO(raw), delimiter=delim))
|
||
if not rows:
|
||
raise ChartError("the CSV has a header but no rows")
|
||
return [{(k or "").strip(): v for k, v in r.items() if k is not None} for r in rows]
|
||
|
||
|
||
def rows_to_spec(rows: list[dict], a, ctype: str) -> dict:
|
||
"""Table rows (CSV or a JSON array of objects) → a spec, by --x / --y / --group."""
|
||
cols = list(rows[0].keys())
|
||
xk = a.x or cols[0]
|
||
if xk not in cols:
|
||
raise ChartError(f"--x {xk!r} is not a column ({', '.join(cols)})")
|
||
group = a.group
|
||
if group and group not in cols:
|
||
raise ChartError(f"--group {group!r} is not a column ({', '.join(cols)})")
|
||
if a.y:
|
||
yks = [c.strip() for c in a.y.split(",") if c.strip()]
|
||
bad = [c for c in yks if c not in cols]
|
||
if bad:
|
||
raise ChartError(f"--y {', '.join(bad)}: not a column ({', '.join(cols)})")
|
||
else:
|
||
yks = [c for c in cols if c not in (xk, group) and any(num(r.get(c)) is not None for r in rows)]
|
||
if not yks:
|
||
raise ChartError(f"no numeric column besides {xk!r} — name one with --y")
|
||
bad_cells = [(i + 2, c, r.get(c)) for i, r in enumerate(rows) for c in yks
|
||
if r.get(c) not in (None, "") and num(r.get(c)) is None]
|
||
if bad_cells:
|
||
ex = "; ".join(f"row {n} {c}={v!r}" for n, c, v in bad_cells[:3])
|
||
raise ChartError(f"{len(bad_cells)} value(s) are not numbers ({ex})")
|
||
|
||
if ctype == "scatter":
|
||
if len(yks) != 1:
|
||
raise ChartError("scatter takes one --y (the vertical value); --x is the horizontal one, --group splits series")
|
||
by: dict[str, list] = {}
|
||
for r in rows:
|
||
g = text(r.get(group), 60) if group else yks[0]
|
||
xv, yv = r.get(xk), num(r.get(yks[0]))
|
||
if yv is None or xv in (None, ""):
|
||
continue
|
||
xn = num(xv)
|
||
by.setdefault(g, []).append([xn if xn is not None else text(xv, 40), yv])
|
||
return {"type": "scatter", "xLabel": xk, "yLabel": yks[0],
|
||
"series": [{"name": g, "data": pts} for g, pts in by.items()]}
|
||
|
||
if group:
|
||
if len(yks) != 1:
|
||
raise ChartError("--group takes one --y (the value to split by group)")
|
||
xs: list = []
|
||
xi: dict[str, int] = {}
|
||
gs: dict[str, dict[int, float]] = {}
|
||
for r in rows:
|
||
xv = text(r.get(xk))
|
||
if xv not in xi:
|
||
xi[xv] = len(xs)
|
||
xs.append(xv)
|
||
v = num(r.get(yks[0]))
|
||
if v is not None:
|
||
cell = gs.setdefault(text(r.get(group), 60), {})
|
||
cell[xi[xv]] = cell.get(xi[xv], 0) + v
|
||
series = [{"name": g, "data": [d.get(i) for i in range(len(xs))]} for g, d in gs.items()]
|
||
return {"type": ctype, "x": xs, "series": series, "xLabel": xk}
|
||
|
||
xs = [r.get(xk) for r in rows]
|
||
# A line over numbers (turn 1, 2, 3…) keeps them numbers; dates and names stay text.
|
||
if ctype in ("line", "area") and all(num(v) is not None for v in xs):
|
||
xs = [num(v) for v in xs]
|
||
else:
|
||
xs = [text(v) for v in xs]
|
||
return {"type": ctype, "x": xs, "xLabel": xk if ctype not in ("donut",) else "",
|
||
"series": [{"name": k, "data": [num(r.get(k)) for r in rows]} for k in yks]}
|
||
|
||
|
||
def load_spec(a) -> dict:
|
||
"""The spec from --json / --csv / stdin, with the flags laid over it."""
|
||
ctype = ALIASES.get(a.type or "", a.type)
|
||
raw = None
|
||
if a.json:
|
||
raw = read_source(a.json)
|
||
elif a.csv:
|
||
raw = read_source(a.csv)
|
||
else:
|
||
raw = read_stdin()
|
||
if raw is None or not raw.strip():
|
||
raise ChartError("no data: give --csv FILE, --json FILE, or a spec / CSV on stdin (chart --help)")
|
||
data = None
|
||
if not a.csv:
|
||
try:
|
||
data = json.loads(raw)
|
||
except json.JSONDecodeError as e:
|
||
if a.json:
|
||
raise ChartError(f"--json: not valid JSON ({e.msg} at line {e.lineno})") from None
|
||
if data is None:
|
||
if not ctype:
|
||
raise ChartError("CSV data needs a type first: chart line|area|bar|hbar|scatter|donut --csv …")
|
||
spec = rows_to_spec(parse_csv(raw), a, ctype)
|
||
elif isinstance(data, list):
|
||
if not ctype:
|
||
raise ChartError("a JSON array of rows needs a type first: chart bar --json rows.json --x … --y …")
|
||
if not data or not all(isinstance(r, dict) for r in data):
|
||
raise ChartError("a JSON array must hold row objects ({column: value})")
|
||
spec = rows_to_spec(data, a, ctype)
|
||
elif isinstance(data, dict):
|
||
spec = data
|
||
if isinstance(spec.get("rows"), list) and spec["rows"] and isinstance(spec["rows"][0], dict):
|
||
a.x = a.x or (spec.get("x") if isinstance(spec.get("x"), str) else None)
|
||
a.y = a.y or (",".join(spec["y"]) if isinstance(spec.get("y"), list) else spec.get("y"))
|
||
a.group = a.group or spec.get("group")
|
||
t = ALIASES.get(str(spec.get("type") or ctype or "line"), spec.get("type") or ctype or "line")
|
||
spec = {**{k: v for k, v in spec.items() if k not in ("rows", "x", "y", "group")},
|
||
**rows_to_spec(spec["rows"], a, t)}
|
||
else:
|
||
raise ChartError("a spec is a JSON object (chart --example line)")
|
||
if ctype:
|
||
spec["type"] = ctype
|
||
for key, val in (("title", a.title), ("subtitle", a.subtitle), ("format", a.format), ("unit", a.unit),
|
||
("xLabel", a.x_label), ("yLabel", a.y_label), ("source", a.source),
|
||
("highlight", a.highlight)):
|
||
if val:
|
||
spec[key] = val
|
||
if a.stacked:
|
||
spec["stacked"] = True
|
||
if a.no_sort:
|
||
spec["sort"] = False
|
||
return spec
|
||
|
||
|
||
# ── checks + normalization (what ui/chart.html draws) ──────────────────────
|
||
def normalize(spec: dict, top: int | None = None) -> tuple[dict, list[str]]:
|
||
notes: list[str] = []
|
||
t0 = str(spec.get("type") or ("kpi" if spec.get("stats") else "line")).lower()
|
||
ctype = ALIASES.get(t0, t0)
|
||
if ctype not in TYPES:
|
||
raise ChartError(f"unknown type {t0!r} — one of {', '.join(TYPES)}")
|
||
out: dict = {"v": 1, "type": ctype}
|
||
for k, n in (("title", 140), ("subtitle", 200), ("unit", 16), ("xLabel", 60), ("yLabel", 60),
|
||
("source", 200), ("highlight", 60), ("note", 200)):
|
||
if spec.get(k) not in (None, ""):
|
||
out[k] = text(spec[k], n)
|
||
fmt = str(spec.get("format") or "").lower()
|
||
if fmt:
|
||
if fmt not in FORMATS and not re.fullmatch(r"currency:[a-z]{3}", fmt):
|
||
raise ChartError(f"unknown format {fmt!r} — one of {', '.join(FORMATS)}, currency:XXX")
|
||
out["format"] = fmt
|
||
if spec.get("stacked") is True or t0.startswith("stacked-"):
|
||
out["stacked"] = True
|
||
if spec.get("sort") is False:
|
||
out["sort"] = False
|
||
|
||
if ctype == "kpi":
|
||
stats = spec.get("stats") or spec.get("kpis") or spec.get("tiles")
|
||
if not isinstance(stats, list) or not stats:
|
||
raise ChartError('a kpi chart needs "stats": [{"label", "value", "delta"?, "trend"?}]')
|
||
out["stats"] = []
|
||
for i, s in enumerate(stats[:8]):
|
||
if not isinstance(s, dict) or s.get("label") in (None, ""):
|
||
raise ChartError(f"stats[{i}] needs a label and a value")
|
||
st = {"label": text(s["label"], 60), "value": short(num(s.get("value")))}
|
||
if st["value"] is None:
|
||
st["value"] = text(s.get("value"), 40)
|
||
for k in ("format", "deltaFormat", "deltaLabel", "unit", "good"):
|
||
if s.get(k):
|
||
st[k] = text(s[k], 40)
|
||
if num(s.get("delta")) is not None:
|
||
st["delta"] = short(num(s["delta"]))
|
||
if isinstance(s.get("trend"), list):
|
||
tr = [short(num(v)) for v in s["trend"][-60:]]
|
||
if sum(v is not None for v in tr) > 1:
|
||
st["trend"] = tr
|
||
out["stats"].append(st)
|
||
if len(stats) > 8:
|
||
notes.append(f"first 8 of {len(stats)} stats")
|
||
return out, notes
|
||
|
||
if ctype == "donut" and isinstance(spec.get("slices"), list):
|
||
spec = {**spec, "x": [s.get("label", s.get("name")) if isinstance(s, dict) else s for s in spec["slices"]],
|
||
"series": [{"name": out.get("title", "total"),
|
||
"data": [s.get("value") if isinstance(s, dict) else None for s in spec["slices"]]}]}
|
||
series = spec.get("series")
|
||
if series is None:
|
||
vals = spec.get("y", spec.get("data", spec.get("values")))
|
||
if vals is not None:
|
||
series = [{"name": spec.get("name") or out.get("yLabel") or out.get("title") or "value", "data": vals}]
|
||
if isinstance(series, dict):
|
||
series = [{"name": k, "data": v} for k, v in series.items()]
|
||
if not isinstance(series, list) or not series:
|
||
raise ChartError('no series: give "series": [{"name", "data": [...]}] (chart --example ' + ctype + ")")
|
||
sers = []
|
||
for i, s in enumerate(series):
|
||
if isinstance(s, list):
|
||
s = {"data": s}
|
||
if not isinstance(s, dict):
|
||
raise ChartError(f"series[{i}] is a {{name, data}} object")
|
||
data = s.get("data", s.get("values", s.get("points", s.get("y"))))
|
||
if not isinstance(data, list):
|
||
raise ChartError(f"series[{i}] has no data list")
|
||
sers.append({"name": text(s.get("name") if s.get("name") is not None else f"series {i + 1}", 60), "data": data})
|
||
|
||
if ctype == "scatter":
|
||
res = []
|
||
total = 0
|
||
for s in sers:
|
||
pts = []
|
||
for p in s["data"]:
|
||
if isinstance(p, dict):
|
||
p = [p.get("x"), p.get("y"), p.get("label")]
|
||
if not isinstance(p, list) or len(p) < 2:
|
||
continue
|
||
yv = num(p[1])
|
||
xv = num(p[0]) if not (isinstance(p[0], str) and re.match(r"^\d{4}-\d{2}", p[0])) else p[0]
|
||
if yv is None or xv is None:
|
||
continue
|
||
pt = [short(xv) if not isinstance(xv, str) else xv, short(yv)]
|
||
if len(p) > 2 and p[2] not in (None, ""):
|
||
pt.append(text(p[2], 40))
|
||
pts.append(pt)
|
||
total += len(pts)
|
||
res.append({"name": s["name"], "data": pts})
|
||
if not total:
|
||
raise ChartError("scatter: no [x, y] points with numbers")
|
||
if len(res) > MAX_SERIES:
|
||
notes.append(f"first {MAX_SERIES} of {len(res)} series")
|
||
res = res[:MAX_SERIES]
|
||
elif len(res) > 3:
|
||
notes.append("more than 3 series on a scatter are hard to tell apart — consider --group less")
|
||
out["series"] = res
|
||
return out, notes
|
||
|
||
x = spec.get("x", spec.get("labels", spec.get("categories")))
|
||
n = max(len(s["data"]) for s in sers)
|
||
if not isinstance(x, list):
|
||
x = list(range(1, n + 1))
|
||
if not x:
|
||
raise ChartError("x is empty")
|
||
for s in sers:
|
||
bad = [v for v in s["data"] if v not in (None, "") and num(v) is None]
|
||
if bad:
|
||
raise ChartError(f"series {s['name']!r}: {len(bad)} value(s) are not numbers (e.g. {bad[0]!r})")
|
||
if len(s["data"]) != len(x):
|
||
notes.append(f"series {s['name']!r} has {len(s['data'])} values for {len(x)} x — padded / cut")
|
||
s["data"] = [short(num(v)) for v in (s["data"] + [None] * len(x))[: len(x)]]
|
||
if all(v is None for s in sers for v in s["data"]):
|
||
raise ChartError("every value is empty")
|
||
x = [v if isinstance(v, (int, float)) and not isinstance(v, bool) else text(v) for v in x]
|
||
|
||
if len(sers) > MAX_SERIES:
|
||
if ctype in ("bar", "area") and out.get("stacked"):
|
||
keep = sorted(sers, key=lambda s: -sum(abs(v or 0) for v in s["data"]))
|
||
rest = keep[MAX_SERIES - 1:]
|
||
sers = keep[: MAX_SERIES - 1] + [{"name": "Other", "data": [
|
||
short(sum(s["data"][j] or 0 for s in rest)) for j in range(len(x))]}]
|
||
notes.append(f"{len(rest)} smallest series folded into Other")
|
||
else:
|
||
keep = sorted(sers, key=lambda s: -sum(abs(v or 0) for v in s["data"]))[:MAX_SERIES]
|
||
notes.append(f"the {MAX_SERIES} biggest of {len(sers)} series")
|
||
sers = [s for s in sers if s in keep]
|
||
|
||
if ctype == "donut":
|
||
vals = sers[0]["data"]
|
||
parts = sorted([(text(l, 60), v) for l, v in zip(x, vals) if v is not None and v > 0], key=lambda p: -p[1])
|
||
if not parts:
|
||
raise ChartError("donut: no positive value")
|
||
if any(v is not None and v < 0 for v in vals):
|
||
notes.append("negative values left out of the donut")
|
||
if len(parts) > MAX_SLICES + 1:
|
||
rest = parts[MAX_SLICES:]
|
||
parts = parts[:MAX_SLICES] + [("Other", short(sum(v for _, v in rest)))]
|
||
notes.append(f"{len(rest)} smallest parts folded into Other")
|
||
x = [p[0] for p in parts]
|
||
sers = [{"name": sers[0]["name"], "data": [p[1] for p in parts]}]
|
||
|
||
if ctype in ("bar", "hbar"):
|
||
limit = top or (25 if ctype == "hbar" else MAX_BARS)
|
||
if len(x) > limit:
|
||
if not top and ctype == "bar":
|
||
raise ChartError(f"{len(x)} bars is too many to read — draw a line, or keep the biggest with --top N")
|
||
order = sorted(range(len(x)), key=lambda j: -sum(abs(s["data"][j] or 0) for s in sers))
|
||
keep = sorted(order[: limit - 1]) if ctype == "bar" else order[: limit - 1]
|
||
rest = [j for j in order[limit - 1:]]
|
||
x = [x[j] for j in keep] + ["Other"]
|
||
for s in sers:
|
||
s["data"] = [s["data"][j] for j in keep] + [short(sum(s["data"][j] or 0 for j in rest))]
|
||
notes.append(f"top {limit - 1} of {len(order)}, the other {len(rest)} summed into Other")
|
||
if ctype == "hbar" and len(sers) == 1 and out.get("sort") is not False:
|
||
order = sorted(range(len(x)), key=lambda j: -(sers[0]["data"][j] if sers[0]["data"][j] is not None else -math.inf))
|
||
x = [x[j] for j in order]
|
||
sers[0]["data"] = [sers[0]["data"][j] for j in order]
|
||
out["x"] = x
|
||
out["series"] = sers
|
||
return out, notes
|
||
|
||
|
||
# ── the size budget ─────────────────────────────────────────────────────────
|
||
def lttb(ys: list[float | None], keep: int) -> list[int]:
|
||
"""Largest-Triangle-Three-Buckets over the index axis: the `keep` indices
|
||
that best keep the curve's shape (first and last always kept)."""
|
||
n = len(ys)
|
||
if keep >= n or keep < 3:
|
||
return list(range(n)) if keep >= n else [0, n - 1]
|
||
y = [v if v is not None else 0.0 for v in ys]
|
||
out = [0]
|
||
every = (n - 2) / (keep - 2)
|
||
a = 0
|
||
for i in range(keep - 2):
|
||
lo = int(math.floor((i + 1) * every)) + 1
|
||
hi = min(int(math.floor((i + 2) * every)) + 1, n)
|
||
nxt_lo, nxt_hi = hi, min(int(math.floor((i + 3) * every)) + 1, n)
|
||
if nxt_lo >= nxt_hi:
|
||
nxt_lo, nxt_hi = n - 1, n
|
||
avg_x = (nxt_lo + nxt_hi - 1) / 2
|
||
avg_y = sum(y[nxt_lo:nxt_hi]) / max(1, nxt_hi - nxt_lo)
|
||
best, best_area = lo, -1.0
|
||
for j in range(lo, hi):
|
||
area = abs((a - avg_x) * (y[j] - y[a]) - (a - j) * (avg_y - y[a]))
|
||
if area > best_area:
|
||
best, best_area = j, area
|
||
out.append(best)
|
||
a = best
|
||
out.append(n - 1)
|
||
return out
|
||
|
||
|
||
def dumps(c: dict) -> str:
|
||
return json.dumps(c, separators=(",", ":"), ensure_ascii=False)
|
||
|
||
|
||
def fit_budget(c: dict, notes: list[str], budget: int = BUDGET - NOTES_ROOM) -> dict:
|
||
if len(dumps(c)) <= budget or c["type"] == "kpi":
|
||
return c
|
||
if c["type"] in ("line", "area"):
|
||
n = len(c["x"])
|
||
# The shape of the sum of the series (one curve when there is one).
|
||
total = [sum(s["data"][j] or 0 for s in c["series"]) for j in range(n)]
|
||
lo, hi, best = 3, n, None
|
||
while lo <= hi:
|
||
mid = (lo + hi) // 2
|
||
idx = lttb(total, mid)
|
||
cand = {**c, "x": [c["x"][j] for j in idx],
|
||
"series": [{**s, "data": [s["data"][j] for j in idx]} for s in c["series"]]}
|
||
if len(dumps(cand)) <= budget:
|
||
best, lo = cand, mid + 1
|
||
else:
|
||
hi = mid - 1
|
||
if best:
|
||
notes.append(f"{len(best['x']):,} of {n:,} points shown, the curve's shape kept")
|
||
return best
|
||
elif c["type"] == "scatter":
|
||
pts = sum(len(s["data"]) for s in c["series"])
|
||
for keep in (0.5, 0.33, 0.25, 0.15, 0.1, 0.05, 0.02):
|
||
cand = {**c, "series": [{**s, "data": s["data"][:: max(1, round(1 / keep))]} for s in c["series"]]}
|
||
if len(dumps(cand)) <= budget:
|
||
shown = sum(len(s["data"]) for s in cand["series"])
|
||
notes.append(f"{shown:,} of {pts:,} points shown (evenly sampled)")
|
||
return cand
|
||
elif c["type"] in ("bar", "hbar", "donut"):
|
||
cand = {**c, "x": [text(v, 24) if isinstance(v, str) else v for v in c["x"]]}
|
||
if len(dumps(cand)) <= budget:
|
||
notes.append("long labels cut to 24 characters")
|
||
return cand
|
||
raise ChartError(f"the chart is too big for the conversation ({len(dumps(c)):,} chars) — "
|
||
"fewer series, --top N, or aggregate the data first")
|
||
|
||
|
||
# ── CLI ────────────────────────────────────────────────────────────────────
|
||
def describe(c: dict) -> str:
|
||
title = f' "{c["title"]}"' if c.get("title") else ""
|
||
if c["type"] == "kpi":
|
||
size = f"{len(c['stats'])} tiles"
|
||
elif c["type"] == "scatter":
|
||
size = f"{len(c['series'])} series, {sum(len(s['data']) for s in c['series']):,} points"
|
||
elif c["type"] == "donut":
|
||
size = f"{len(c['x'])} parts"
|
||
else:
|
||
size = f"{len(c['series'])} series × {len(c['x']):,} {'bars' if c['type'] in ('bar', 'hbar') else 'points'}"
|
||
return f"chart: {c['type']}{title} · {size} — drawn in the conversation as a card"
|
||
|
||
|
||
def main(argv: list[str] | None = None) -> int:
|
||
ap = argparse.ArgumentParser(prog="chart", description=__doc__.split("\n\n")[0],
|
||
formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__.split("\n\n", 1)[1])
|
||
ap.add_argument("type", nargs="?", help=" · ".join(TYPES) + " (else the spec's type)")
|
||
src = ap.add_argument_group("data (one of)")
|
||
src.add_argument("--csv", metavar="FILE", help="a CSV/TSV with a header row (- = stdin)")
|
||
src.add_argument("--json", metavar="FILE", help="a spec object, or an array of row objects (- = stdin)")
|
||
cols = ap.add_argument_group("columns (CSV / rows)")
|
||
cols.add_argument("--x", help="the x / category column (default: the first)")
|
||
cols.add_argument("--y", help="value column(s), comma-separated (default: every numeric one)")
|
||
cols.add_argument("--group", help="long format: one series per value of this column")
|
||
look = ap.add_argument_group("look")
|
||
look.add_argument("--title")
|
||
look.add_argument("--subtitle")
|
||
look.add_argument("--format", help=", ".join(FORMATS) + ", currency:XXX")
|
||
look.add_argument("--unit", help='a suffix: "ms", "req/s"…')
|
||
look.add_argument("--x-label", dest="x_label")
|
||
look.add_argument("--y-label", dest="y_label")
|
||
look.add_argument("--source", help="where the data comes from (shown under the chart)")
|
||
look.add_argument("--highlight", metavar="SERIES", help="this series in colour, the others grey")
|
||
look.add_argument("--stacked", action="store_true", help="bar / area: stack the series")
|
||
look.add_argument("--top", type=int, help="bar / hbar: keep the N biggest, sum the rest into Other")
|
||
look.add_argument("--no-sort", dest="no_sort", action="store_true", help="hbar: keep the given order")
|
||
ap.add_argument("--example", metavar="TYPE", help="print a sample spec of TYPE and exit (nothing drawn)")
|
||
a = ap.parse_args(argv)
|
||
if a.example:
|
||
t = ALIASES.get(a.example, a.example)
|
||
if t not in EXAMPLES:
|
||
print(f"error: no example for {a.example!r} — {', '.join(TYPES)}", file=sys.stderr)
|
||
return 2
|
||
print(json.dumps(EXAMPLES[t], indent=2))
|
||
return 0
|
||
if a.type and ALIASES.get(a.type, a.type) not in TYPES:
|
||
print(f"error: unknown type {a.type!r} — {', '.join(TYPES)}", file=sys.stderr)
|
||
return 2
|
||
if a.top is not None and a.top < 2:
|
||
print("error: --top needs 2 or more", file=sys.stderr)
|
||
return 2
|
||
try:
|
||
spec = load_spec(a)
|
||
chart, notes = normalize(spec, a.top)
|
||
chart = fit_budget(chart, notes)
|
||
except ChartError as e:
|
||
print(f"error: {e}", file=sys.stderr)
|
||
return 2
|
||
if notes:
|
||
chart["notes"] = [n[:110] for n in notes[:4]]
|
||
print(describe(chart))
|
||
for n in notes:
|
||
print(f"note: {n}")
|
||
print("CHART " + dumps(chart))
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|