@dsh-ft/dsh-fft-plot 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,454 @@
1
+ """图型注册表。**这是唯一的扩展点。**
2
+
3
+ 新增一种图,只做两件事:
4
+
5
+ 1. 在下面写一个函数并加 `@chart('名字')` 装饰器;
6
+ 2. 在 SKILL.md 的图型表里加一行(给模型看的字段说明)。
7
+
8
+ 函数签名固定为 `(c, rect, cfg, rows)`:
9
+
10
+ - `c` —— `canvas.Svg`,画布;`c.t[...]` 取主题色
11
+ - `rect` —— `(x, y, w, h)` 绘图区像素矩形,已避开标题与页脚
12
+ - `cfg` —— spec 里 `chart:` 的内容,字段由本图型自己定义
13
+ - `rows` —— 数据行 `list[dict]`
14
+
15
+ 约定:**列名缺失或类型不符必须报错**,绝不静默丢行——金融图上少一根线而不报错,
16
+ 比直接失败更危险。颜色用 `resolve_color()`,既接受主题键也接受 `#RRGGBB`。
17
+ """
18
+ import math
19
+
20
+ from .canvas import (Axes, fmt_compact, fmt_date_label, fmt_num, fmt_pct, has_multiple_years,
21
+ nice_ticks, text_width)
22
+
23
+ #: 图型注册表。键是 `chart.type` 的取值。
24
+ CHARTS = {}
25
+
26
+
27
+ def chart(name):
28
+ """把一个函数登记成 `chart.type = name` 的渲染器。"""
29
+ def deco(fn):
30
+ CHARTS[name] = fn
31
+ return fn
32
+ return deco
33
+
34
+
35
+ def render(c, rect, cfg, rows):
36
+ """按 `cfg['type']` 分派。未知类型列出全部可用值,便于直接改正。"""
37
+ kind = cfg.get('type')
38
+ if kind is None:
39
+ raise ValueError("chart.type is required; available: " + ", ".join(sorted(CHARTS)))
40
+ if kind not in CHARTS:
41
+ raise KeyError(f"unknown chart.type {kind!r}; available: " + ", ".join(sorted(CHARTS)))
42
+ if not rows:
43
+ raise ValueError(f'chart type {kind!r} needs rows, but the data is empty')
44
+ return CHARTS[kind](c, rect, cfg, rows)
45
+
46
+
47
+ # ---------------------------------------------------------------- 取值
48
+
49
+ def column(rows, name):
50
+ """取一列原始值;任一行缺这个键就报错(含行号)。"""
51
+ out = []
52
+ for i, row in enumerate(rows):
53
+ if name not in row:
54
+ raise KeyError(f'column {name!r} missing at row {i}; available: '
55
+ + ', '.join(sorted(row)))
56
+ out.append(row[name])
57
+ return out
58
+
59
+
60
+ def numbers(rows, name):
61
+ """取数值列。数值字符串按数值处理,无法转换则报错。"""
62
+ out = []
63
+ for i, value in enumerate(column(rows, name)):
64
+ if isinstance(value, bool) or value is None:
65
+ raise TypeError(f'column {name!r} is not numeric at row {i}: {value!r}')
66
+ try:
67
+ out.append(float(value))
68
+ except (TypeError, ValueError):
69
+ raise TypeError(f'column {name!r} is not numeric at row {i}: {value!r}') from None
70
+ return out
71
+
72
+
73
+ def labels(rows, name):
74
+ """取标签列,统一转成字符串。"""
75
+ return [str(v) for v in column(rows, name)]
76
+
77
+
78
+ def resolve_color(theme, token, default='down'):
79
+ """`#RRGGBB` 原样返回;否则按主题键取,取不到时用 fallback,绝不画成黑色。"""
80
+ if token is None:
81
+ return theme.get(default, theme['ink'])
82
+ if isinstance(token, str) and token.startswith('#'):
83
+ return token
84
+ return theme.get(token, theme.get(default, theme['ink']))
85
+
86
+
87
+ def padded_domain(*groups, include_zero=True, pad=0.10):
88
+ """由若干组数值算 y 轴范围,留出上下留白。"""
89
+ values = [v for group in groups for v in group if v is not None and math.isfinite(v)]
90
+ if not values:
91
+ return (0.0, 1.0)
92
+ lo, hi = min(values), max(values)
93
+ if include_zero:
94
+ lo, hi = min(lo, 0.0), max(hi, 0.0)
95
+ if hi == lo:
96
+ hi = lo + (abs(lo) * 0.1 or 1.0)
97
+ span = hi - lo
98
+ return (lo - span * pad, hi + span * pad)
99
+
100
+
101
+ class XAxis:
102
+ """x 轴。
103
+
104
+ 三种定位方式,由 `kind` 选择:
105
+
106
+ - `auto`(默认):能被 `float()` 解析的按真实数值定位(天数、年份、比率),
107
+ 其余按行序等距。
108
+ - `category`:一律按行序等距——**日期必须用这个**。`20260810` 是可解析的整数,
109
+ 若按数值定位,`0810→0811` 的差值(1)与 `0814→0817`(3,跨周末)不相等,
110
+ 横轴就会按日历日拉开,交易日之间的间距看着忽宽忽窄。
111
+ - `value`:强制按数值定位,非数值直接报错。
112
+ """
113
+
114
+ def __init__(self, values, kind='auto'):
115
+ self.raw = [str(v) for v in values]
116
+ self.numeric = None
117
+ if kind == 'category':
118
+ return
119
+ try:
120
+ self.numeric = [float(v) for v in values]
121
+ except (TypeError, ValueError):
122
+ if kind == 'value':
123
+ raise TypeError(
124
+ 'chart.x_kind is "value" but the x column has non-numeric entries: '
125
+ + ', '.join(repr(v) for v in self.raw[:5])) from None
126
+ self.numeric = None
127
+
128
+ def __len__(self):
129
+ return len(self.raw)
130
+
131
+ def position(self, index):
132
+ """第 index 行在 x 轴上的数据坐标。"""
133
+ if self.numeric is not None:
134
+ return self.numeric[index]
135
+ return float(index)
136
+
137
+ def domain(self):
138
+ """x 轴数据范围(两端各留一点,避免首尾贴着边框)。"""
139
+ if self.numeric is not None:
140
+ lo, hi = min(self.numeric), max(self.numeric)
141
+ if hi == lo:
142
+ hi = lo + 1
143
+ span = hi - lo
144
+ return (lo - span * 0.02, hi + span * 0.02)
145
+ return (-0.5, len(self.raw) - 0.5)
146
+
147
+ def ticks(self, max_ticks=8, min_gap_px=None, width_px=None, label_size=12.5):
148
+ """挑出要显示标签的下标。**按像素等距分配,始终含首尾。**
149
+
150
+ 早先的写法是"固定步长抽样 + 末尾强行补最后一根",两个毛病:抽出来的点可能
151
+ 彼此挨着(`09-01` 后面紧跟 `09-23`,只隔 76px),末尾那根还可能撞上倒数第二个。
152
+ 这里改成:先按可用宽度算出最多能放几个,再在 `[0, n-1]` 上等距取值——
153
+ 间距天然均匀,首尾天然在内。
154
+ """
155
+ n = len(self.raw)
156
+ if n == 0:
157
+ return []
158
+ if n == 1:
159
+ return [0]
160
+
161
+ if width_px and min_gap_px is None:
162
+ min_gap_px = text_width('0' * 8, label_size)
163
+
164
+ # 按宽度决定能容纳几个标签;放不下就宁可少放,也不让字叠在一起。
165
+ capacity = n
166
+ if width_px and min_gap_px:
167
+ capacity = max(2, int(width_px // min_gap_px) + 1)
168
+ count = min(max_ticks, capacity, n)
169
+
170
+ if count >= n:
171
+ return list(range(n))
172
+ if count == 2:
173
+ return [0, n - 1]
174
+ step = (n - 1) / (count - 1)
175
+ picked = sorted({round(i * step) for i in range(count)})
176
+ picked[-1] = n - 1 # 浮点舍入后确保末位在内
177
+ return picked
178
+
179
+
180
+ # ---------------------------------------------------------------- line
181
+
182
+ @chart('line')
183
+ def line(c, rect, cfg, rows):
184
+ """时序折线。
185
+
186
+ 字段:`x`(x 列名)、`series`(必填,`[{col,label,color,dash}]`)、
187
+ `band`(可选 `{lo,hi,label,color}`)、`refs`(可选 `[{y,label,color}]`)、
188
+ `marks`(可选,要打点的 x 值列表)、`annotate`(可选 `[{x,text,color,dy}]`)、
189
+ `y_fmt`(`num`/`pct`)、`y_dec`(小数位)。
190
+ """
191
+ x_col = cfg.get('x')
192
+ if x_col is None:
193
+ raise ValueError('line chart needs "x" (the column holding the x axis values)')
194
+ series_cfg = cfg.get('series') or []
195
+ if not series_cfg:
196
+ raise ValueError('line chart needs at least one entry in "series"')
197
+
198
+ xaxis = XAxis(column(rows, x_col), kind=cfg.get('x_kind', 'auto'))
199
+ n = len(xaxis)
200
+ series = [{'label': s.get('label', s['col']), 'col': s['col'],
201
+ 'values': numbers(rows, s['col']),
202
+ 'color': resolve_color(c.t, s.get('color'), 'down'),
203
+ 'dash': s.get('dash')} for s in series_cfg]
204
+ for s in series:
205
+ if len(s['values']) != n:
206
+ raise ValueError(f"series {s['col']!r} has {len(s['values'])} values but x has {n}")
207
+
208
+ band = cfg.get('band')
209
+ band_lo = band_hi = None
210
+ if band:
211
+ band_lo, band_hi = numbers(rows, band['lo']), numbers(rows, band['hi'])
212
+
213
+ refs = cfg.get('refs') or []
214
+ dom_values = [v for s in series for v in s['values']]
215
+ if band_lo:
216
+ dom_values += band_lo + band_hi
217
+ dom_values += [float(r['y']) for r in refs if r.get('y') is not None]
218
+ y_domain = padded_domain(dom_values, include_zero=cfg.get('include_zero', True))
219
+
220
+ ax = Axes(c, rect, xaxis.domain(), y_domain)
221
+ y_fmt = cfg.get('y_fmt', 'num')
222
+ y_dec = cfg.get('y_dec', 0)
223
+ formatter = (lambda v: fmt_pct(v, y_dec)) if y_fmt == 'pct' else (lambda v: fmt_num(v, y_dec))
224
+ ticks = nice_ticks(y_domain[0], y_domain[1], cfg.get('y_ticks', 5))
225
+ ax.grid_y(ticks, [formatter(t) for t in ticks], c.t['line'])
226
+
227
+ # 分布带:上下边界围出的多边形
228
+ if band:
229
+ color = resolve_color(c.t, band.get('color'), 'band')
230
+ upper = [(ax.px(xaxis.position(i)), ax.py(v)) for i, v in enumerate(band_hi)]
231
+ lower = [(ax.px(xaxis.position(i)), ax.py(v)) for i, v in enumerate(reversed(band_lo))]
232
+ c.polygon(upper + lower, color, opacity=band.get('opacity', 0.13))
233
+ if band.get('label'):
234
+ c.text(upper[0][0] + 6, upper[0][1] - 6, band['label'], size=12,
235
+ fill=c.t['mute'])
236
+
237
+ # 参考线
238
+ for ref in refs:
239
+ if ref.get('y') is None:
240
+ continue
241
+ color = resolve_color(c.t, ref.get('color'), 'accent')
242
+ y = ax.py(float(ref['y']))
243
+ c.line(rect[0], y, rect[0] + rect[2], y, color, ref.get('width', 1.6),
244
+ dash=ref.get('dash', '6 4'))
245
+ if ref.get('label'):
246
+ c.text(rect[0] + 6, y - 7, ref['label'], size=12.5, fill=color)
247
+
248
+ # 折线
249
+ for s in series:
250
+ pts = [(ax.px(xaxis.position(i)), ax.py(v)) for i, v in enumerate(s['values'])]
251
+ if cfg.get('area') and len(series) == 1:
252
+ baseline = ax.py(max(y_domain[0], 0.0))
253
+ c.polygon(pts + [(pts[-1][0], baseline), (pts[0][0], baseline)],
254
+ s['color'], opacity=0.16)
255
+ c.polyline(pts, s['color'], width=s.get('width', 2.6), dash=s['dash'])
256
+ # 线尾标系列名
257
+ if len(series) > 1 and s.get('label'):
258
+ lx, ly = pts[-1]
259
+ c.text(lx + 8, ly, s['label'], size=12.5, fill=s['color'], weight='bold',
260
+ baseline='middle')
261
+
262
+ # 标记点 + 数值
263
+ if cfg.get('marks'):
264
+ primary = series[0]
265
+ for mark in cfg['marks']:
266
+ idx = _index_of_mark(xaxis, mark)
267
+ if idx is None:
268
+ continue
269
+ px, py = ax.px(xaxis.position(idx)), ax.py(primary['values'][idx])
270
+ c.circle(px, py, 4.6, c.t['card'], stroke=primary['color'], stroke_width=2.4)
271
+ c.text(px, py - 13, formatter(primary['values'][idx]), size=13,
272
+ fill=primary['color'], weight='bold', anchor='middle')
273
+
274
+ # 文字标注
275
+ for note in cfg.get('annotate') or []:
276
+ idx = _index_of_mark(xaxis, note.get('x'))
277
+ if idx is None:
278
+ continue
279
+ px, py = ax.px(xaxis.position(idx)), ax.py(series[0]['values'][idx])
280
+ c.text(px + note.get('dx', 8), py + note.get('dy', 0), note.get('text', ''),
281
+ size=note.get('size', 13), fill=resolve_color(c.t, note.get('color'), 'up'),
282
+ weight='bold', anchor=note.get('anchor', 'start'))
283
+
284
+ # x 标签:先按像素宽度挑出不重叠的位置,再把日期收敛成短标签。
285
+ # 日期识别统一交给 `fmt_date_label`——它对认不出的值原样返回,所以「第5天」
286
+ # 「2024Q3」这类非日期标签不会被误改。特意不另设开关:多一个 `date_axis`
287
+ # 布尔就会和 `x_kind` 职责重叠,两者给出矛盾设置时无人能判断该听谁的。
288
+ label_size = 12.5
289
+ picked = xaxis.ticks(cfg.get('x_ticks', 8), width_px=ax.w, label_size=label_size)
290
+ compact_dates = not has_multiple_years(xaxis.raw)
291
+ for i in picked:
292
+ label = fmt_date_label(xaxis.raw[i], compact=compact_dates)
293
+ c.text(ax.px(xaxis.position(i)), rect[1] + rect[3] + 21, label,
294
+ size=label_size, fill=c.t['mute'], anchor='middle')
295
+
296
+
297
+ def _index_of_mark(xaxis, mark):
298
+ """把 marks/annotate 里写的 x 值换算成行下标;数值与字符串都试。"""
299
+ if mark is None:
300
+ return None
301
+ text = str(mark)
302
+ if text in xaxis.raw:
303
+ return xaxis.raw.index(text)
304
+ try:
305
+ wanted = float(mark)
306
+ except (TypeError, ValueError):
307
+ return None
308
+ if xaxis.numeric is not None:
309
+ for i, value in enumerate(xaxis.numeric):
310
+ if abs(value - wanted) < 1e-9:
311
+ return i
312
+ return None
313
+
314
+
315
+ # ---------------------------------------------------------------- barh
316
+
317
+ @chart('barh')
318
+ def barh(c, rect, cfg, rows):
319
+ """横向条形,用于横截面排名(热榜、板块涨幅、个股贡献)。
320
+
321
+ 字段:`label`(标签列)、`value`(数值列)、`sign`(可选,带正负的列,
322
+ 决定红/蓝)、`rank`(可选,名次列,画在标签前)、`top`(默认 10)、
323
+ `fmt`(`compact`/`num`/`pct`)、`dec`(小数位)。
324
+ 说明文字用 spec 顶层的 `legend`,不在这里——图内元素与页脚说明要由
325
+ 同一个游标排布,图型自己贴底边写说明会和结论行撞在一起。
326
+ """
327
+ label_col = cfg.get('label')
328
+ value_col = cfg.get('value')
329
+ if label_col is None or value_col is None:
330
+ raise ValueError('barh chart needs "label" and "value" column names')
331
+
332
+ pairs = list(zip(labels(rows, label_col), numbers(rows, value_col),
333
+ numbers(rows, cfg['sign']) if cfg.get('sign') else [None] * len(rows),
334
+ labels(rows, cfg['rank']) if cfg.get('rank') else [None] * len(rows)))
335
+ if cfg.get('sort', True):
336
+ pairs.sort(key=lambda p: p[1], reverse=not cfg.get('ascending', False))
337
+ pairs = pairs[:int(cfg.get('top', 10))]
338
+ if not pairs:
339
+ raise ValueError('barh chart has no rows to draw')
340
+
341
+ fmt_kind, dec = cfg.get('fmt', 'num'), cfg.get('dec', 0)
342
+ if fmt_kind == 'pct':
343
+ formatter = lambda v: fmt_pct(v, dec, signed=bool(cfg.get('sign'))) # noqa: E731
344
+ elif fmt_kind == 'compact':
345
+ formatter = lambda v: fmt_compact(v, dec or 1) # noqa: E731
346
+ else:
347
+ formatter = lambda v: fmt_num(v, dec) # noqa: E731
348
+
349
+ label_pad = cfg.get('label_width', 168)
350
+ value_pad = cfg.get('value_width', 104)
351
+ plot_x = rect[0] + label_pad
352
+ plot_w = max(rect[2] - label_pad - value_pad, 40)
353
+ max_value = max(abs(p[1]) for p in pairs) or 1.0
354
+ rows_n = len(pairs)
355
+ slot = rect[3] / rows_n
356
+ bar_h = min(slot * 0.62, cfg.get('bar_max', 34))
357
+
358
+ for i, (label, value, sign, rank) in enumerate(pairs):
359
+ cy = rect[1] + slot * (i + 0.5)
360
+ # 金融惯例:涨红跌蓝;无 sign 列时整组同色。
361
+ if sign is None:
362
+ tone = resolve_color(c.t, cfg.get('color'), 'down')
363
+ elif sign > 0:
364
+ tone = c.t['up']
365
+ elif sign < 0:
366
+ tone = c.t['down']
367
+ else:
368
+ tone = c.t['neutral']
369
+
370
+ width = abs(value) / max_value * plot_w
371
+ c.rect(plot_x, cy - bar_h / 2, max(width, 1.5), bar_h, tone,
372
+ rx=min(3, bar_h / 2), opacity=cfg.get('bar_opacity', 0.92))
373
+
374
+ head = f'#{rank} {label}' if rank else label
375
+ c.text(rect[0], cy, _ellipsis(head, 13.5, label_pad - 14), size=13.5,
376
+ fill=c.t['ink'], anchor='start', baseline='middle')
377
+ c.text(plot_x + width + 8, cy, formatter(value), size=13, fill=tone,
378
+ weight='bold', anchor='start', baseline='middle')
379
+
380
+
381
+ def _ellipsis(text, size, max_width):
382
+ """按估算宽度截断并加省略号,避免长标签压到条形上。"""
383
+ if text_width(text, size) <= max_width:
384
+ return text
385
+ cut = text
386
+ while cut and text_width(cut + '…', size) > max_width:
387
+ cut = cut[:-1]
388
+ return cut + '…'
389
+
390
+
391
+ # ---------------------------------------------------------------- table
392
+
393
+ @chart('table')
394
+ def table(c, rect, cfg, rows):
395
+ """表格,用于名录类数据(基金列表、成分股、接口字段)。
396
+
397
+ 字段:`columns`(必填,`[{col,label,align,dec}]`)、`top`(默认 12)、
398
+ `row_height`(默认 30)、`font_size`(默认 13)。
399
+ """
400
+ columns = cfg.get('columns') or []
401
+ if not columns:
402
+ raise ValueError('table chart needs "columns": [{col, label}]')
403
+ limit = int(cfg.get('top', 12))
404
+ shown = rows[:limit]
405
+ size = cfg.get('font_size', 13)
406
+ row_h = cfg.get('row_height', 30)
407
+
408
+ weights = [col.get('weight', 1) for col in columns]
409
+ total = sum(weights) or 1
410
+ widths = [rect[2] * w / total for w in weights]
411
+ offsets, acc = [], rect[0]
412
+ for w in widths:
413
+ offsets.append(acc)
414
+ acc += w
415
+
416
+ # 表头
417
+ y = rect[1] + size
418
+ for col, x, w in zip(columns, offsets, widths):
419
+ align = col.get('align', 'left')
420
+ tx = x if align == 'left' else x + w - 6
421
+ c.text(tx, y, col.get('label', col['col']), size=size, fill=c.t['mute'],
422
+ weight='bold', anchor='start' if align == 'left' else 'end')
423
+ y += row_h * 0.55
424
+ c.line(rect[0], y, rect[0] + rect[2], y, c.t['line'], 1)
425
+
426
+ # 数据行
427
+ for r, row in enumerate(shown):
428
+ y += row_h
429
+ if r % 2 == 1:
430
+ c.rect(rect[0], y - size - 6, rect[2], row_h - 4, c.t['card'], opacity=0.7)
431
+ for col, x, w in zip(columns, offsets, widths):
432
+ raw = row.get(col['col'])
433
+ text = _cell_text(raw, col)
434
+ align = col.get('align', 'left')
435
+ tx = x if align == 'left' else x + w - 6
436
+ c.text(tx, y, _ellipsis(text, size, w - 12), size=size, fill=c.t['ink'],
437
+ anchor='start' if align == 'left' else 'end')
438
+
439
+ if len(rows) > limit:
440
+ c.text(rect[0], y + row_h * 0.9, f'(共 {len(rows)} 条,此处显示前 {limit} 条)',
441
+ size=12, fill=c.t['mute'])
442
+
443
+
444
+ def _cell_text(raw, col):
445
+ """单元格取值:按 `dec` 格式化数值,缺失写 `—`(不写 None)。"""
446
+ if raw is None:
447
+ return '—'
448
+ dec = col.get('dec')
449
+ if dec is not None:
450
+ try:
451
+ return fmt_num(float(raw), int(dec))
452
+ except (TypeError, ValueError):
453
+ return str(raw)
454
+ return str(raw)
@@ -0,0 +1,62 @@
1
+ """spec 与数据加载。
2
+
3
+ spec 是 **JSON**(不是 YAML):只依赖标准库,机器上无需 PyYAML。
4
+ 数据可以在 spec 里直接给(`"rows": [...]`),也可以给一个文件路径
5
+ (`"data": "rows.json"`,相对 spec 文件所在目录解析)——行数多时用后者,
6
+ spec 保持可读。
7
+ """
8
+ import json
9
+ import os
10
+
11
+
12
+ class SpecError(ValueError):
13
+ """spec 内容不合规。消息里写清哪个字段、期望什么,便于直接改正。"""
14
+
15
+
16
+ def load(path):
17
+ """读 spec 文件,返回 dict。"""
18
+ with open(path, encoding='utf-8') as handle:
19
+ try:
20
+ spec = json.load(handle)
21
+ except json.JSONDecodeError as exc:
22
+ raise SpecError(f'{path} is not valid JSON: {exc}') from None
23
+ if not isinstance(spec, dict):
24
+ raise SpecError(f'{path} must contain a JSON object at the top level')
25
+ spec.setdefault('_dir', os.path.dirname(os.path.abspath(path)))
26
+ if 'chart' not in spec:
27
+ raise SpecError('spec needs a "chart" object')
28
+ return spec
29
+
30
+
31
+ def rows_of(spec):
32
+ """取数据行:支持内联 `rows` 或引用 `data` 文件。"""
33
+ inline = spec.get('rows')
34
+ if inline is not None:
35
+ if not isinstance(inline, list):
36
+ raise SpecError('"rows" must be a JSON array of objects')
37
+ return [_as_row(r, i) for i, r in enumerate(inline)]
38
+
39
+ ref = spec.get('data')
40
+ if ref is None:
41
+ raise SpecError('spec needs either "rows" (inline array) or "data" (file path)')
42
+ path = ref if os.path.isabs(ref) else os.path.join(spec.get('_dir', '.'), ref)
43
+ if not os.path.exists(path):
44
+ raise SpecError(f'data file not found: {path}')
45
+ with open(path, encoding='utf-8') as handle:
46
+ payload = json.load(handle)
47
+
48
+ # 允许 {"rows": [...]} 或直接是数组
49
+ if isinstance(payload, dict):
50
+ for key in ('rows', 'data', 'items', 'records', 'list', 'result'):
51
+ if isinstance(payload.get(key), list):
52
+ return [_as_row(r, i) for i, r in enumerate(payload[key])]
53
+ raise SpecError(f'{path}: object has no array under rows/data/items/records/list/result')
54
+ if isinstance(payload, list):
55
+ return [_as_row(r, i) for i, r in enumerate(payload)]
56
+ raise SpecError(f'{path}: expected an array or an object holding one')
57
+
58
+
59
+ def _as_row(row, index):
60
+ if not isinstance(row, dict):
61
+ raise SpecError(f'row {index} is {type(row).__name__}, expected an object')
62
+ return row
@@ -0,0 +1,60 @@
1
+ """配色主题。每套主题是一个 dict,键名固定。
2
+
3
+ **加主题**:复制一个 dict、改颜色即可,不需要改任何渲染代码。
4
+ **加颜色语义**:在 `_REQUIRED` 里加键名,所有主题同步补上——漏一个会在加载时立刻报错,
5
+ 而不是在图上画出一块黑色。
6
+
7
+ 所有主题都是浅色底(`bg` 不透明填充),这是刻意的:SVG 以 `<img>` 内联进聊天时读不到
8
+ 宿主的 `body[data-ds-dark-theme]`,深色模式下它就是一张浅色图表卡片,永不会黑底黑字。
9
+ """
10
+
11
+ #: 模板与图型只认这些键名。
12
+ _REQUIRED = (
13
+ 'bg', 'card', 'ink', 'mute', 'line',
14
+ 'up', 'down', 'neutral', 'accent', 'band',
15
+ 'title_font',
16
+ )
17
+
18
+ THEMES = {
19
+ # 米白纸底 + 朱红/墨蓝:默认。像财经杂志内页,截图与打印都清楚。
20
+ 'paper': dict(
21
+ bg='#FBF9F4', card='#FFFFFF', ink='#1B1B1F', mute='#6F6B66', line='#E2DCD0',
22
+ up='#D93A3A', down='#1F5FA8', neutral='#A9A39A', accent='#C98A00', band='#1F5FA8',
23
+ ),
24
+ # 纯白 + 单一亮橙:极简,字更大,适合只看结论的场合。
25
+ 'poster': dict(
26
+ bg='#FFFFFF', card='#F7F7F7', ink='#111111', mute='#7A7A7A', line='#E6E6E6',
27
+ up='#FF5A1F', down='#111111', neutral='#C8C8C8', accent='#FF5A1F', band='#FF5A1F',
28
+ ),
29
+ # 冷灰底 + 青红:数据密度高的图更耐看。
30
+ 'slate': dict(
31
+ bg='#F7F8FA', card='#FFFFFF', ink='#16181D', mute='#6B7280', line='#E1E4EA',
32
+ up='#E5484D', down='#0A7EA4', neutral='#9AA1AE', accent='#B7791F', band='#0A7EA4',
33
+ ),
34
+ }
35
+
36
+
37
+ def load(name='paper'):
38
+ """取一套主题;未知名字报错并列出可选值,缺键立刻失败。"""
39
+ if name not in THEMES:
40
+ raise KeyError(f'unknown theme {name!r}; available: {", ".join(sorted(THEMES))}')
41
+ theme = dict(THEMES[name])
42
+ theme['name'] = name
43
+ missing = [k for k in _REQUIRED if k not in theme]
44
+ if missing:
45
+ raise KeyError(f'theme {name!r} is missing keys: {", ".join(missing)}')
46
+ theme.setdefault('title_font', theme.get('body_font', _FONT_STACK))
47
+ return theme
48
+
49
+
50
+ #: 中文字体回退链。SVG 作为独立文档渲染,字体必须由自身声明,不能继承宿主。
51
+ _FONT_STACK = (
52
+ 'PingFang SC, Hiragino Sans GB, Microsoft YaHei, Noto Sans CJK SC, '
53
+ 'Source Han Sans SC, sans-serif'
54
+ )
55
+
56
+ for _t in THEMES.values():
57
+ _t.setdefault('body_font', _FONT_STACK)
58
+ _t.setdefault('title_font', _t['body_font'])
59
+
60
+ FONT_STACK = _FONT_STACK