discord-bot / vb_draw.py
jay0826's picture
更新 5 個檔(discordbot.py、vb_draw.py、2026112206.json、2026112206.json…)
a488e90 verified
Raw History Blame Contribute Delete
23.5 kB
# -*- coding: utf-8 -*-
"""聊天裡畫圖(2026-11-22 主人:「資料圖跟流程圖都要」→「A 為主、有圖用 B」)。
主模型覺得需要就呼叫 draw_chart/draw_diagram 工具:這裡把模型給的文字解析成資料、用 matplotlib 畫成 PNG;
discordbot 那邊把圖包成卡片(Components V2,跟指令卡片同一套)貼出去。
★配色、背景、字型跟 /sb 的圖同一套(vb_sb_style)——主人 2026-09-26 講過「兩張圖沒有統一」。
★流程圖不裝 Graphviz、不送外部網站:自己排(分層),映像不變大、不多一個外部服務。複雜的大圖會比較陽春。
純函式:沒有 Discord、沒有網路。
"""
import json
import re
from typing import Dict, List, Optional, Sequence, Tuple
import vb_sb_style as S
SERIES_COLORS = ["#60a5fa", "#f59e0b", "#c084fc", "#2dd4bf", "#f472b6", "#a3e635"] # 固定順序,不循環
MAX_SERIES = 6
MAX_POINTS = 60
MAX_NODES = 30
MAX_EDGES = 50
KINDS = ("line", "bar", "hbar", "pie")
NODE_FILL = "#161b22"
NODE_EDGE = "#60a5fa" # 一般步驟
START_EDGE = "#22c55e" # 起點(沒有箭頭進來)
END_EDGE = "#8b949e" # 終點(沒有箭頭出去)
DECIDE_EDGE = "#f59e0b" # 判斷(問號結尾、{ } 包起來)
_NUM_RE = re.compile(r"[-+]?\d[\d,]*\.?\d*(?:[eE][-+]?\d+)?|[-+]?\.\d+")
# ── 資料圖 ─────────────────────────────────────────────────────────────
def _num(tok: str) -> Optional[float]:
t = (tok or "").strip().replace(",", ",")
if not t or t in ("-", "—", "null", "None", "NaN"):
return None
m = _NUM_RE.search(t)
if not m:
return None
try:
v = float(m.group(0).replace(",", ""))
except ValueError:
return None
if "萬" in t[m.end():m.end() + 2]:
v *= 1e4
elif "億" in t[m.end():m.end() + 2]:
v *= 1e8
elif t[m.end():m.end() + 1] == "%":
pass
return v
def _split_items(s: str) -> List[str]:
return [x.strip() for x in re.split(r"[,,、;;|\t]+", s or "") if x.strip()]
def parse_chart(labels: str, series: str) -> Tuple[List[str], List[Tuple[str, List[Optional[float]]]]]:
"""模型給的文字 → (X 軸標籤, [(數列名, 數值…)])。
labels:「一月, 二月, 三月」;series 一行一條:「營收: 10, 12, 15」。也收 JSON({"名稱":[...]}、[{"name","values"}])。
數值可以帶單位(12%、3.5萬);缺的填 None(畫成斷線)。長度跟標籤對齊(多的截掉、少的補 None)。
"""
labs = _split_items(labels)
out: List[Tuple[str, List[Optional[float]]]] = []
raw = (series or "").strip()
parsed = None
if raw[:1] in "[{":
try:
parsed = json.loads(raw)
except ValueError:
parsed = None
if isinstance(parsed, dict):
for k, v in parsed.items():
if isinstance(v, list):
out.append((str(k), [_num(str(x)) for x in v]))
elif isinstance(parsed, list):
for i, s in enumerate(parsed):
if isinstance(s, dict) and isinstance(s.get("values"), list):
out.append((str(s.get("name") or f"數列{i + 1}"), [_num(str(x)) for x in s["values"]]))
else:
for i, ln in enumerate(l for l in raw.split("\n") if l.strip()):
m = re.match(r"^\s*(?:[-*•]\s*)?([^::=]{1,40}?)\s*[::=]\s*(.+)$", ln)
name, vals = (m.group(1).strip(), m.group(2)) if m else (f"數列{i + 1}", ln)
nums = [_num(x) for x in _split_items(vals)]
if any(v is not None for v in nums):
out.append((name, nums))
if not out:
raise ValueError("沒有看得懂的數字(series 一行一條:「名稱: 1, 2, 3」)")
n = max(len(v) for _n, v in out)
if not labs:
labs = [str(i + 1) for i in range(n)]
labs = labs[:MAX_POINTS]
out = [(nm, (vs + [None] * len(labs))[:len(labs)]) for nm, vs in out]
if len(out) > MAX_SERIES:
raise ValueError(f"數列太多({len(out)} 條):最多 {MAX_SERIES} 條,其餘請合併成「其他」或分成兩張圖")
return labs, out
# ★2026-11-22 主人截圖(烏伯林根空難「照真實軌跡」):香草搜到的只有摘要(36,000 呎巡航、34,890 呎相撞),
# 中間的 35,880、35,500、36,200 全是自己補的,還說「根據 BFU 官方調查報告的真實飛行資料」,
# DHL 那條甚至畫成先爬升(跟自己文字講的「往下飛」相反)。提示裡早就寫「不可以編」,模型照樣編 → 改成程式檢查。
_EST_RE = re.compile(r"示意|推估|估計|估算|假設|模擬|概念")
def is_estimate(*texts: str) -> bool:
"""標題或 note 寫明是示意/推估的圖。"""
return any(_EST_RE.search(t or "") for t in texts)
def _num_forms(v: float) -> List[str]:
"""一個數字在文章裡常見的寫法:36000 → 36000、36,000、3.6萬、FL360;12.5 → 12.5、12.50。"""
a = abs(v)
out = set()
if float(a).is_integer():
i = int(a)
out.update((str(i), f"{i:,}"))
if i >= 1000 and i % 100 == 0:
out.add("FL%d" % (i // 100)) # 飛行高度層
else:
for d in (1, 2, 3):
t = f"{a:.{d}f}"
out.update((t, t.rstrip("0").rstrip(".")))
if a >= 1e4:
out.add(f"{a / 1e4:g}萬")
if a >= 1e8:
out.add(f"{a / 1e8:g}億")
return [x for x in out if x]
def _norm_src(src: str) -> str:
import unicodedata
s = unicodedata.normalize("NFKC", src or "")
return re.sub(r"(?<=\d)[ \u00a0\u202f](?=\d{3}(?!\d))", "", s) # 36 000 → 36000
def unsourced(labels: str, series: str, src: str) -> Tuple[List[str], int]:
"""圖上的數字哪些在 src(這次查到的資料)裡找不到。回 (找不到的數字(顯示用), 不重複的數字總數)。"""
_labs, data = parse_chart(labels, series)
vals: List[float] = []
for _nm, vs in data:
for v in vs:
if v is not None and v not in vals:
vals.append(v)
s = _norm_src(src)
miss = []
for v in vals:
if not any(re.search(r"(?<![\d.,])" + re.escape(f) + r"(?![\d]|[.,]\d)", s, re.I) for f in _num_forms(v)):
miss.append(_fmt(v))
return miss, len(vals)
def _fmt(v: float) -> str:
a = abs(v)
if a >= 1e8:
return f"{v / 1e8:.3g}億"
if a >= 1e6: # ★2026-11-22 台股 38,500 顯示成「3.85萬」很難讀 → 百萬以上才用萬
return f"{v / 1e4:,.0f}萬"
if a >= 100 or float(v).is_integer():
return f"{v:,.0f}"
return f"{v:.3g}"
def render_chart(kind: str, title: str, labels: str, series: str, unit: str = "", note: str = "",
font: Optional[str] = None) -> bytes:
"""畫資料圖 → PNG bytes。kind:line 折線/bar 長條/hbar 橫條/pie 圓餅(只畫第一條數列)。"""
kind = (kind or "bar").strip().lower()
if kind not in KINDS:
raise ValueError(f"圖的種類只能是 {'/'.join(KINDS)}")
labs, ser = parse_chart(labels, series)
S.setup(font)
from matplotlib.figure import Figure
from matplotlib.ticker import FuncFormatter
n = len(labs)
tall = kind == "hbar" and n > 8
fig = Figure(figsize=(9, max(5.4, 1.9 + 0.38 * n) if tall else 5.4), dpi=S.DPI, facecolor=S.BG)
h = fig.get_figheight()
top = 1 - 1.15 / h
bottom = 0.9 / h + (0.25 if kind in ("line", "bar") and (n > 8 or max(len(x) for x in labs) > 4) else 0) / h * 2
sub = (unit and f"單位:{unit}") or ""
if kind == "pie":
ax = fig.add_axes([0.05, bottom, 0.9, top - bottom])
ax.set_facecolor(S.BG)
name, vals = ser[0]
pairs = [(l, v) for l, v in zip(labs, vals) if v is not None and v > 0]
if not pairs:
raise ValueError("圓餅圖要正數")
pairs.sort(key=lambda p: -p[1])
if len(pairs) > MAX_SERIES:
pairs = pairs[:MAX_SERIES - 1] + [("其他", sum(v for _l, v in pairs[MAX_SERIES - 1:]))]
tot = sum(v for _l, v in pairs)
wedges, _t = ax.pie([v for _l, v in pairs], colors=SERIES_COLORS[:len(pairs)], startangle=90, counterclock=False,
wedgeprops={"width": 0.42, "edgecolor": S.BG, "linewidth": 2})
ax.set_aspect("equal")
ax.legend(wedges, [f"{l} {v / tot:.0%}({_fmt(v)})" for l, v in pairs], loc="center left",
bbox_to_anchor=(0.78, 0.5), frameon=False, labelcolor=S.INK, fontsize=12)
ax.set_position([0.02, bottom, 0.62, top - bottom])
sub = sub or name
else:
ax = fig.add_axes([0.1, bottom, 0.86, top - bottom])
S.style_axes(ax, money=False)
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _p: _fmt(v)))
idx = list(range(n))
k = len(ser)
if kind == "line":
for i, (nm, vs) in enumerate(ser):
xs = [x for x, v in zip(idx, vs) if v is not None]
ys = [v for v in vs if v is not None]
ax.plot(xs, ys, color=SERIES_COLORS[i], lw=2, marker="o" if n <= 24 else None, ms=5, label=nm)
if ys: # 只標最後一點(不在每點標數字)
ax.annotate(_fmt(ys[-1]), (xs[-1], ys[-1]), xytext=(6, 0), textcoords="offset points",
color=S.INK, fontsize=11, va="center")
ax.set_xticks(idx)
ax.set_xticklabels(labs)
elif kind == "bar":
w = 0.8 / k
for i, (nm, vs) in enumerate(ser):
xs = [x - 0.4 + w * (i + 0.5) for x in idx]
ys = [v if v is not None else 0 for v in vs]
bars = ax.bar(xs, ys, width=w * 0.92, color=SERIES_COLORS[i], label=nm, zorder=3)
if n * k <= 16:
for b, v in zip(bars, vs):
if v is not None:
ax.annotate(_fmt(v), (b.get_x() + b.get_width() / 2, v), xytext=(0, 3),
textcoords="offset points", ha="center", va="bottom", color=S.INK, fontsize=10.5)
ax.set_xticks(idx)
ax.set_xticklabels(labs)
if all(v is None or v >= 0 for _n, vs in ser for v in vs):
ax.set_ylim(bottom=0)
else: # hbar
w = 0.8 / k
for i, (nm, vs) in enumerate(ser):
ys = [y - 0.4 + w * (i + 0.5) for y in idx]
xv = [v if v is not None else 0 for v in vs]
bars = ax.barh(ys, xv, height=w * 0.92, color=SERIES_COLORS[i], label=nm, zorder=3)
if n * k <= 24:
for b, v in zip(bars, vs):
if v is not None:
ax.annotate(_fmt(v), (v, b.get_y() + b.get_height() / 2), xytext=(4, 0),
textcoords="offset points", va="center", color=S.INK, fontsize=10.5)
ax.set_yticks(idx)
ax.set_yticklabels(labs)
ax.invert_yaxis()
ax.xaxis.set_major_formatter(FuncFormatter(lambda v, _p: _fmt(v)))
ax.set_position([0.22, bottom, 0.72, top - bottom])
if kind in ("line", "bar") and (n > 8 or max(len(x) for x in labs) > 4):
for t in ax.get_xticklabels():
t.set_rotation(35)
t.set_ha("right")
if k >= 2:
ax.legend(loc="upper left", frameon=False, labelcolor=S.INK, fontsize=11, ncol=min(k, 3))
ax.margins(x=0.03)
S.header(fig, (title or "圖表")[:40], sub[:60], sub_color=S.MUT)
if note:
S.footer(fig, note[:90])
return S.save(fig)
# ── 流程圖 ─────────────────────────────────────────────────────────────
_ARROW_RE = re.compile(r"\s*(?:-{2}\s+([^->|]+?)\s+-{2,}>|-+>\s*\|([^|]*)\||-+\|([^|]*)\|-*>?|-+\(([^)]*)\)-*>|-{1,3}>|=+>|→|⟶)\s*")
def _node_key(raw: str) -> Tuple[str, str, bool]:
"""「A{要不要?}」「[開始]」「下雨了嗎?」→ (key, 顯示文字, 是不是判斷)。"""
t = (raw or "").strip().strip("\"'「」")
m = re.match(r"^([A-Za-z_][\w]*)\s*([\[\(\{<])(.+)[\]\)\}>]\s*$", t) # mermaid:id[文字]、id{判斷}
if m:
txt = m.group(3).strip().strip("[](){}\"'")
return m.group(1), txt, m.group(2) == "{" or txt.endswith(("?", "?"))
decide = t.startswith("{") and t.endswith("}")
txt = t.strip("[](){}").strip()
return txt, txt, decide or txt.endswith(("?", "?"))
def parse_diagram(edges: str) -> Tuple[Dict[str, Tuple[str, bool]], List[Tuple[str, str, str]]]:
"""一行一條連線(可以連鎖):「開始 -> 下雨了嗎? -> 帶傘」「下雨了嗎? -> 出門 : 沒下」「A -->|是| B」。
回 ({key: (顯示文字, 判斷?)}, [(from, to, 標籤)])。只有一個節點的行=單獨的節點。"""
nodes: Dict[str, Tuple[str, bool]] = {}
out: List[Tuple[str, str, str]] = []
def add(raw: str) -> str:
k, txt, dec = _node_key(raw)
if k not in nodes or (txt != k and nodes[k][0] == k):
nodes[k] = (txt or k, dec or (nodes.get(k, ("", False))[1]))
return k
for ln in (edges or "").replace(";", "\n").split("\n"):
ln = ln.strip().strip("-*•").strip() if not re.match(r"^\s*-+[>|(]", ln) else ln.strip()
if not ln or ln.lower().startswith(("graph ", "flowchart ")):
continue
tail = ""
m = re.search(r"\s[::]\s*([^::>]+)$", ln) # 「A -> B : 標籤」
if m and _ARROW_RE.search(ln[:m.start()]):
tail, ln = m.group(1).strip(), ln[:m.start()]
parts, labels, pos = [], [], 0
for am in _ARROW_RE.finditer(ln):
parts.append(ln[pos:am.start()])
labels.append(next((g for g in am.groups() if g), "").strip())
pos = am.end()
parts.append(ln[pos:])
parts = [p for p in parts]
if len(parts) == 1:
if parts[0].strip():
add(parts[0])
continue
keys = [add(p) for p in parts if p.strip()]
if len(keys) != len(parts):
continue
for i in range(len(keys) - 1):
lab = labels[i] or (tail if i == len(keys) - 2 else "")
out.append((keys[i], keys[i + 1], lab[:16]))
if len(nodes) > MAX_NODES or len(out) > MAX_EDGES:
raise ValueError(f"流程圖太大:最多 {MAX_NODES} 個方塊、{MAX_EDGES} 條箭頭,請拆成兩張")
if not out and len(nodes) < 2:
raise ValueError("沒有看得懂的連線(一行一條:「開始 -> 檢查 -> 結束」,標籤寫在最後「: 是」)")
return nodes, out
def layout(nodes: Sequence[str], edges: Sequence[Tuple[str, str, str]]):
"""分層排版(Sugiyama 簡化版):DFS 找出回頭的箭頭(環)→ 其餘照最長路徑分層 →
跨好幾層的箭頭在中間每一層放一個看不見的「轉折點」(佔一個位置,箭頭才不會穿過別的方塊)→
層內照上一層的平均位置排兩輪。
回 (第幾層, 層內第幾個, 回頭箭頭的 index 集合, {箭頭 index: [轉折點…]});轉折點的 key 以 "\x00" 開頭。"""
order = list(nodes)
adj: Dict[str, List[Tuple[int, str]]] = {k: [] for k in order}
for i, (a, b, _l) in enumerate(edges):
adj[a].append((i, b))
back, state = set(), {}
def dfs(u: str):
state[u] = 1
for i, v in adj[u]:
if state.get(v) == 1:
back.add(i)
elif v not in state:
dfs(v)
state[u] = 2
indeg = {k: 0 for k in order}
for a, b, _l in edges:
indeg[b] += 1
for k in [k for k in order if indeg[k] == 0] + order:
if k not in state:
dfs(k)
layer = {k: 0 for k in order}
fwd = [(i, a, b) for i, (a, b, _l) in enumerate(edges) if i not in back and a != b]
for _ in range(len(order)):
changed = False
for _i, a, b in fwd:
if layer[b] < layer[a] + 1:
layer[b] = layer[a] + 1
changed = True
if not changed:
break
chains: Dict[int, List[str]] = {}
links: List[Tuple[str, str]] = []
for i, a, b in fwd:
prev = a
for L in range(layer[a] + 1, layer[b]):
d = "\x00%d_%d" % (i, L)
layer[d] = L
chains.setdefault(i, []).append(d)
links.append((prev, d))
prev = d
links.append((prev, b))
rows: Dict[int, List[str]] = {}
for k in layer:
rows.setdefault(layer[k], []).append(k)
pos = {k: i for r in rows.values() for i, k in enumerate(r)}
preds: Dict[str, List[str]] = {k: [] for k in layer}
for a, b in links:
preds[b].append(a)
for _ in range(3):
for L in sorted(rows)[1:]:
def bary(k):
ps = preds[k]
return sum(pos[p] for p in ps) / len(ps) if ps else pos[k]
rows[L].sort(key=bary)
for i, k in enumerate(rows[L]):
pos[k] = i
return layer, pos, back, chains
def _wrap(txt: str, width: int = 9) -> str:
"""方塊裡的字換行:中文約 width 字一行、英文單字不拆。"""
out, cur, w = [], "", 0.0
for tok in re.findall(r"[A-Za-z0-9_.\-/+%]+|\s+|.", txt):
tw = len(tok) * (0.55 if tok.isascii() else 1.0)
if tok.isspace():
if cur:
cur += " "
w += 0.5
continue
if w + tw > width and cur:
out.append(cur.rstrip())
cur, w = "", 0.0
cur += tok
w += tw
if cur.strip():
out.append(cur.rstrip())
return "\n".join(out[:4]) + ("…" if len(out) > 4 else "")
def render_diagram(title: str, edges: str, direction: str = "TD", note: str = "",
font: Optional[str] = None) -> bytes:
"""畫流程圖 → PNG bytes。direction:TD 由上往下/LR 由左往右。"""
nodes, es = parse_diagram(edges)
keys = list(nodes)
layer, pos, back, chains = layout(keys, es)
lr = (direction or "TD").strip().upper() in ("LR", "RL", "左右", "橫")
S.setup(font)
from matplotlib.figure import Figure
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch, Polygon
nl = max(layer.values()) + 1
width = {L: sum(1 for k in layer if layer[k] == L) for L in range(nl)}
nw = max(width.values())
BW, BH = 2.5, 1.0 # 方塊大小(資料座標)
DX, DY = (3.1, 1.75) if not lr else (3.4, 1.55)
def xy(k: str) -> Tuple[float, float]:
L, i = layer[k], pos[k]
off = (nw - width[L]) / 2.0
if lr:
return L * DX, -(i + off) * DY
return (i + off) * DX, -L * DY
cols, rws = (nl, nw) if lr else (nw, nl)
fw = min(16.0, max(6.5, cols * (DX if lr else DX) * 0.95 + 0.8))
fh = min(20.0, max(4.2, rws * DY * 0.95 + 1.6))
fig = Figure(figsize=(fw, fh), dpi=130, facecolor=S.BG)
ax = fig.add_axes([0.02, 0.02, 0.96, 1 - 1.1 / fh - 0.02])
ax.set_facecolor(S.BG)
ax.axis("off")
xs = [xy(k)[0] for k in layer]
ys = [xy(k)[1] for k in layer]
ax.set_xlim(min(xs) - BW * 0.7, max(xs) + BW * 0.7)
ax.set_ylim(min(ys) - BH * 0.9, max(ys) + BH * 0.9)
ax.set_aspect("equal", adjustable="datalim")
indeg = {k: 0 for k in keys}
outdeg = {k: 0 for k in keys}
for a, b, _l in es:
outdeg[a] += 1
indeg[b] += 1
patches = {}
fs = 12 if len(keys) <= 12 else 10.5
for k in keys:
x, y = xy(k)
txt, dec = nodes[k]
col = DECIDE_EDGE if dec else START_EDGE if indeg[k] == 0 else END_EDGE if outdeg[k] == 0 else NODE_EDGE
if dec:
p = Polygon([(x, y + BH * 0.62), (x + BW * 0.58, y), (x, y - BH * 0.62), (x - BW * 0.58, y)],
closed=True, fc=NODE_FILL, ec=col, lw=1.8, zorder=3)
else:
p = FancyBboxPatch((x - BW / 2, y - BH / 2), BW, BH, boxstyle="round,pad=0.02,rounding_size=0.18",
fc=NODE_FILL, ec=col, lw=1.8, zorder=3)
ax.add_patch(p)
patches[k] = p
ax.text(x, y, _wrap(txt, 7 if dec else 9), ha="center", va="center", color=S.INK, fontsize=fs, zorder=4,
linespacing=1.15)
from matplotlib.lines import Line2D
for i, (a, b, lab) in enumerate(es):
if a == b:
continue
col = S.MUT if i in back else "#c9d1d9"
pts = [xy(a)] + [xy(d) for d in chains.get(i, [])] + [xy(b)]
if len(pts) > 2: # 跨層:經過轉折點(中間幾段是直線,最後一段才有箭頭)
lx = [p[0] for p in pts[1:-1]]
ly = [p[1] for p in pts[1:-1]]
first = FancyArrowPatch(pts[0], pts[1], patchA=patches[a], arrowstyle="-", color=col, lw=1.5,
zorder=2, shrinkA=2, shrinkB=0)
ax.add_patch(first)
ax.add_line(Line2D(lx, ly, color=col, lw=1.5, zorder=2))
arr = FancyArrowPatch(pts[-2], pts[-1], patchB=patches[b], arrowstyle="-|>", mutation_scale=15,
color=col, lw=1.5, zorder=2, shrinkA=0, shrinkB=2)
ax.add_patch(arr)
rad = 0.0
else:
same = (pts[0][0] == pts[1][0]) if lr else (pts[0][1] == pts[1][1])
rad = 0.35 if i in back else (0.25 if same else 0.0)
arr = FancyArrowPatch(pts[0], pts[1], patchA=patches[a], patchB=patches[b], arrowstyle="-|>",
mutation_scale=15, color=col, lw=1.5, connectionstyle=f"arc3,rad={rad}",
zorder=2, shrinkA=2, shrinkB=2)
ax.add_patch(arr)
if lab: # 標籤放在第一段、靠起點那一側(不蓋到別的方塊)
(x0, y0), (x1, y1) = pts[0], pts[1]
t = 0.5 if len(pts) == 2 else 0.6
mx, my = x0 + (x1 - x0) * t, y0 + (y1 - y0) * t
if rad:
dx, dy = x1 - x0, y1 - y0
mx, my = mx + dy * rad * 0.5, my - dx * rad * 0.5
ax.text(mx, my, lab, ha="center", va="center", color=DECIDE_EDGE, fontsize=fs - 1, zorder=5,
bbox={"boxstyle": "round,pad=0.2", "fc": S.BG, "ec": "none"})
S.header(fig, (title or "流程圖")[:40], "", sub_color=S.MUT)
if note:
S.footer(fig, note[:90])
return S.save(fig)