@dsh-ft/dsh-fft-plot 0.1.0 → 0.2.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.
@@ -38,7 +38,8 @@ def rows_of(spec):
38
38
 
39
39
  ref = spec.get('data')
40
40
  if ref is None:
41
- raise SpecError('spec needs either "rows" (inline array) or "data" (file path)')
41
+ # 示意图(chain)这类图型不消费数据行;是否需要数据由 charts.render 判断。
42
+ return []
42
43
  path = ref if os.path.isabs(ref) else os.path.join(spec.get('_dir', '.'), ref)
43
44
  if not os.path.exists(path):
44
45
  raise SpecError(f'data file not found: {path}')
@@ -12,28 +12,46 @@
12
12
  _REQUIRED = (
13
13
  'bg', 'card', 'ink', 'mute', 'line',
14
14
  'up', 'down', 'neutral', 'accent', 'band',
15
- 'title_font',
15
+ 'series', 'title_font',
16
16
  )
17
17
 
18
+ #: 分类序列色。多序列图没给 color 时按顺序取,避免各条线默认挤成同一个颜色。
19
+ SERIES_FALLBACK = ('#1F5FA8', '#C98A00', '#2F7F73', '#7B5EA7', '#B5563F', '#5F6B73')
20
+
18
21
  THEMES = {
19
22
  # 米白纸底 + 朱红/墨蓝:默认。像财经杂志内页,截图与打印都清楚。
20
23
  'paper': dict(
21
24
  bg='#FBF9F4', card='#FFFFFF', ink='#1B1B1F', mute='#6F6B66', line='#E2DCD0',
22
25
  up='#D93A3A', down='#1F5FA8', neutral='#A9A39A', accent='#C98A00', band='#1F5FA8',
26
+ series=('#1F5FA8', '#C98A00', '#2F7F73', '#7B5EA7', '#B5563F', '#5F6B73'),
27
+ ),
28
+ # 米白底 + A 股惯例:红涨绿跌。K 线类图(或给国内读者看的涨跌排名)用这套。
29
+ 'ashare': dict(
30
+ bg='#FBF9F4', card='#FFFFFF', ink='#1B1B1F', mute='#6F6B66', line='#E2DCD0',
31
+ up='#D93A3A', down='#14805E', neutral='#A9A39A', accent='#C98A00', band='#1F5FA8',
32
+ series=('#D93A3A', '#14805E', '#C98A00', '#1F5FA8', '#7B5EA7', '#5F6B73'),
23
33
  ),
24
34
  # 纯白 + 单一亮橙:极简,字更大,适合只看结论的场合。
25
35
  'poster': dict(
26
36
  bg='#FFFFFF', card='#F7F7F7', ink='#111111', mute='#7A7A7A', line='#E6E6E6',
27
37
  up='#FF5A1F', down='#111111', neutral='#C8C8C8', accent='#FF5A1F', band='#FF5A1F',
38
+ series=('#FF5A1F', '#111111', '#2F7F73', '#7B5EA7', '#C9A227', '#5F6B73'),
28
39
  ),
29
40
  # 冷灰底 + 青红:数据密度高的图更耐看。
30
41
  'slate': dict(
31
42
  bg='#F7F8FA', card='#FFFFFF', ink='#16181D', mute='#6B7280', line='#E1E4EA',
32
43
  up='#E5484D', down='#0A7EA4', neutral='#9AA1AE', accent='#B7791F', band='#0A7EA4',
44
+ series=('#2563EB', '#0D9488', '#D97706', '#7C3AED', '#E11D48', '#4F46E5'),
33
45
  ),
34
46
  }
35
47
 
36
48
 
49
+ def series_color(theme, index):
50
+ """取第 index 个分类色,循环使用;主题没配时退回内置分类色。"""
51
+ palette = theme.get('series') or SERIES_FALLBACK
52
+ return palette[index % len(palette)]
53
+
54
+
37
55
  def load(name='paper'):
38
56
  """取一套主题;未知名字报错并列出可选值,缺键立刻失败。"""
39
57
  if name not in THEMES:
@@ -4,19 +4,22 @@
4
4
  用法:
5
5
  python3 plot.py --spec spec.json --out /abs/path/chart.svg
6
6
  python3 plot.py --spec spec.json --out chart.svg --theme poster --width 1000
7
+ python3 plot.py --tokens [--theme paper] # 打印当前主题的色板/字号/几何
7
8
 
8
9
  产物是自包含 SVG(无外链、无脚本、浅色底),可直接写进 Markdown 图片语法内联显示。
9
10
  只依赖 Python 标准库。
10
11
 
11
- **布局原则**:头部(chip/标题/副标题)与底部(说明/结论/页脚)都走同一个游标顺序排布,
12
- 任何元素都不自己算 y 坐标。上一版让 `legend` 自己贴绘图区底边,结果和第一条结论撞在
13
- 一起;游标是唯一能防止这类重叠的写法。
14
-
15
- 这些头部元素全是可选的——图在聊天流中间时,前后已有文字说明,不传就不会占位,
16
- 绘图区自动上移占满。
12
+ **布局原则**:头部(chip/标题/副标题)、底部(说明/结论/页脚)与横轴高度都参与
13
+ "先量后排":文本先按画布宽度折行、算出真实高度,再倒推绘图区。上一版把
14
+ `legend`/`notes` 当固定行数、把"哪些图型有横轴"写死成图型名单,结果长文本跑出
15
+ 画布、新图型的横轴标签压到说明行上;现在两者都由 `charts.py` 的图型元数据和
16
+ 文本折行决定。
17
17
  """
18
18
  import argparse
19
+ import hashlib
20
+ import json
19
21
  import os
22
+ import re
20
23
  import sys
21
24
 
22
25
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
@@ -25,33 +28,148 @@ from ftplot import charts, spec as specmod, theme as thememod # noqa: E402
25
28
  from ftplot.canvas import Svg, text_width, wrap # noqa: E402
26
29
 
27
30
  MARGIN = 60
28
- NOTE_STEP = 27 # 结论行行距
29
- LEGEND_STEP = 26 # 图内说明行高
30
31
  HEADER_GAP = 26 # 头部与绘图区的间距
31
32
  BOTTOM_GAP = 20 # 绘图区与底部说明的间距
32
- FOOTER_H = 54 # 页脚高度(分隔线 + 两行小字)
33
- #: x 轴标签占用的高度:标签画在绘图区底边之下 21px,字高约 13px,再加 12px 呼吸。
34
- #: 绘图区高度必须先扣掉它,否则底部的说明行会紧贴横轴标签——只有 9px 间距时,
35
- #: 12.5px 的字高就已经和标签糊在一起了。
36
- XAXIS_H = 46
33
+ XAXIS_H = 46 # 横轴标签默认占用的高度(图型可声明更小)
37
34
  MIN_CHART_H = 170 # 绘图区最小高度,低于此值直接失败而不是画出糊掉的图
35
+ MIN_WIDTH = 360 # 两侧留白之外至少要放得下一列标签
36
+ FOOTER_LINE_H = 18 # 页脚每行高度
37
+
38
+ #: 结论行前缀 → (字号, 颜色键, 字重, 行高)
39
+ _NOTE_STYLES = {
40
+ '**': (16, 'ink', 'bold', 26),
41
+ '!': (16, 'up', 'bold', 26),
42
+ '*': (13, 'mute', 'normal', 20),
43
+ '': (14.5, 'mute', 'normal', 23),
44
+ }
45
+
46
+
47
+ def _wrapped(text, size, width):
48
+ """折行;空文本返回空列表。"""
49
+ if text is None or str(text) == '':
50
+ return []
51
+ return wrap(str(text), size, width)
52
+
53
+
54
+ def _bottom_blocks(spec, theme, width):
55
+ """底部说明块:每块含折行后的行、字号、颜色、字重、行高。"""
56
+ blocks = []
57
+
58
+ def add(text, style):
59
+ lines = _wrapped(text, style[0], width)
60
+ if lines:
61
+ blocks.append({'lines': lines, 'size': style[0], 'fill': theme[style[1]],
62
+ 'weight': style[2], 'step': style[3]})
38
63
 
64
+ legend = spec.get('legend')
65
+ if legend:
66
+ add(legend, (12.5, 'mute', 'normal', 20))
67
+ for raw in (spec.get('notes') or []):
68
+ add(_note_text(raw), _note_style(raw))
69
+ return blocks
70
+
71
+
72
+ def _note_style(raw):
73
+ raw = str(raw)
74
+ for prefix in ('**', '!', '*'):
75
+ if raw.startswith(prefix):
76
+ return _NOTE_STYLES[prefix]
77
+ return _NOTE_STYLES['']
39
78
 
40
- def main():
41
- ap = argparse.ArgumentParser(description='render a JSON chart spec into standalone SVG')
42
- ap.add_argument('--spec', required=True, help='spec JSON path')
43
- ap.add_argument('--out', required=True, help='output SVG path')
44
- ap.add_argument('--theme', default=None, help='override spec theme (paper/poster/slate)')
45
- ap.add_argument('--width', type=int, default=None)
46
- ap.add_argument('--height', type=int, default=None)
47
- args = ap.parse_args()
79
+
80
+ def _note_text(raw):
81
+ raw = str(raw)
82
+ for prefix in ('**', '!', '*'):
83
+ if raw.startswith(prefix):
84
+ return raw[len(prefix):].strip('*')
85
+ return raw
86
+
87
+
88
+ def _footer_lines(spec, width):
89
+ """页脚文本行(数据来源与样本口径),先折行再定页脚高度。"""
90
+ lines = []
91
+ sources = spec.get('sources') or []
92
+ if sources:
93
+ text = '数据来源 FTShare 接口:' + ' / '.join(map(str, sources))
94
+ lines.extend(_wrapped(text, 11.5, width))
95
+ sample = spec.get('sample')
96
+ if sample:
97
+ lines.extend(_wrapped(sample, 11.5, width))
98
+ return lines
99
+
100
+
101
+ def _tokens(args):
102
+ """打印当前主题的配色、字号与几何常量,供模型手绘 SVG 时引用真值。"""
103
+ theme = thememod.load(args.theme or 'paper')
104
+ width = int(args.width or 1200)
105
+ height = int(args.height or 700)
106
+ payload = {
107
+ 'theme': theme['name'],
108
+ 'themes': sorted(thememod.THEMES),
109
+ 'charts': sorted(charts.CHARTS),
110
+ 'canvas': {'width': width, 'height': height, 'margin': MARGIN,
111
+ 'header_gap': HEADER_GAP, 'bottom_gap': BOTTOM_GAP,
112
+ 'xaxis_h': XAXIS_H, 'min_chart_h': MIN_CHART_H,
113
+ 'content_width': width - 2 * MARGIN},
114
+ 'colors': {key: theme[key] for key in
115
+ ('bg', 'card', 'ink', 'mute', 'line', 'up', 'down', 'neutral', 'accent', 'band')},
116
+ 'series': list(theme['series']),
117
+ 'fonts': {'family': theme['body_font'], 'title_family': theme['title_font']},
118
+ 'type_scale': {'title': 26, 'subtitle': 14.5, 'body': 13.5, 'small': 12.5,
119
+ 'tick': 12.5, 'note_bold': 16, 'note_small': 13},
120
+ 'chart_types': {kind: {'x_axis': charts.needs_x_axis(kind)} for kind in sorted(charts.CHARTS)},
121
+ }
122
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
123
+
124
+
125
+ def main(argv=None):
126
+ parser = argparse.ArgumentParser(description='render a JSON chart spec into standalone SVG')
127
+ parser.add_argument('--spec', help='spec JSON path')
128
+ parser.add_argument('--out', help='output SVG path')
129
+ parser.add_argument('--out-dir',
130
+ help='write <dir>/<slug>-<hash8>.svg instead of --out; hash covers '
131
+ 'spec/rows/theme/size so the same chart keeps the same file')
132
+ parser.add_argument('--slug', default='chart',
133
+ help='file name prefix for --out-dir (default: chart)')
134
+ parser.add_argument('--theme', default=None, help='override spec theme (paper/ashare/poster/slate)')
135
+ parser.add_argument('--width', type=int, default=None)
136
+ parser.add_argument('--height', type=int, default=None)
137
+ parser.add_argument('--tokens', action='store_true',
138
+ help='print theme colors, type scale and layout constants as JSON')
139
+ args = parser.parse_args(argv)
140
+
141
+ if args.tokens:
142
+ _tokens(args)
143
+ return 0
144
+ if not args.spec or (not args.out and not args.out_dir):
145
+ parser.error('--spec and one of --out/--out-dir are required unless --tokens is used')
146
+ if args.out and args.out_dir:
147
+ parser.error('pass either --out or --out-dir, not both')
48
148
 
49
149
  spec = specmod.load(args.spec)
50
150
  rows = specmod.rows_of(spec)
51
151
  theme = thememod.load(args.theme or spec.get('theme', 'paper'))
52
- width = args.width or int(spec.get('width', 1200))
53
- height = args.height or int(spec.get('height', 700))
54
-
152
+ width = int(args.width or spec.get('width', 1200))
153
+ height = int(args.height or spec.get('height', 700))
154
+ if width < MIN_WIDTH:
155
+ raise SystemExit(f'canvas width {width}px is too small: at least {MIN_WIDTH}px '
156
+ '(raise --width / spec width, or drop the chart)')
157
+ if height < 320:
158
+ raise SystemExit(f'canvas height {height}px is too small: at least 320px '
159
+ '(raise --height / spec height)')
160
+
161
+ if args.out_dir:
162
+ # 固定产物目录(如 <workspace>/.dsh/plots)时由内容决定文件名:
163
+ # 同一张图重复生成不会改名,旧消息的引用也不会被后一次渲染覆盖。
164
+ fingerprint = json.dumps(
165
+ {'spec': {k: v for k, v in spec.items() if k != '_dir'},
166
+ 'rows': rows, 'theme': theme['name'], 'width': width, 'height': height},
167
+ sort_keys=True, ensure_ascii=False, default=str).encode('utf-8')
168
+ digest = hashlib.sha256(fingerprint).hexdigest()[:8]
169
+ slug = re.sub(r'[^\w\-]+', '-', str(args.slug)).strip('-') or 'chart'
170
+ args.out = os.path.join(os.path.expanduser(args.out_dir), f'{slug}-{digest}.svg')
171
+
172
+ chart_cfg = spec['chart']
55
173
  svg = Svg(width, height, theme)
56
174
  cursor = MARGIN
57
175
 
@@ -68,81 +186,62 @@ def main():
68
186
 
69
187
  title = spec.get('title')
70
188
  if title:
71
- lines = wrap(str(title), 26, width - 2 * MARGIN)
189
+ lines = _wrapped(title, 26, width - 2 * MARGIN)
72
190
  cursor = svg.text_block(MARGIN, cursor + 24, lines, size=26, fill=theme['ink'],
73
191
  weight='bold', line_height=37)
74
192
 
75
193
  subtitle = spec.get('subtitle')
76
194
  if subtitle:
77
- sub_lines = wrap(str(subtitle), 14.5, width - 2 * MARGIN)
78
- cursor = svg.text_block(MARGIN, cursor + 22, sub_lines, size=14.5,
195
+ lines = _wrapped(subtitle, 14.5, width - 2 * MARGIN)
196
+ cursor = svg.text_block(MARGIN, cursor + 22, lines, size=14.5,
79
197
  fill=theme['mute'], line_height=22)
80
198
 
81
199
  has_header = bool(chip or title or subtitle)
82
200
  chart_top = cursor + (HEADER_GAP if has_header else 8)
83
201
 
84
- # ---------------- 底部:先精确算高,再倒推绘图区高度
85
- legend = spec.get('legend')
86
- notes = [str(n) for n in (spec.get('notes') or [])]
87
- legend_h = LEGEND_STEP if legend else 0
88
- notes_h = len(notes) * NOTE_STEP
89
- notes_gap = 12 if (legend and notes) else 0
90
-
91
- footer_top = height - FOOTER_H
92
- bottom_top = footer_top - (legend_h + notes_gap + notes_h)
93
- if legend or notes:
94
- bottom_top -= BOTTOM_GAP
95
- # 绘图区高度要扣掉 x 轴标签的地盘,否则底边就是标签基线,标签会压到说明行上。
96
- # 横条图与表格没有 x 轴标签,不扣这 46px,把空间还给图形本身。
97
- axis_h = XAXIS_H if spec['chart'].get('type') in ('line', 'bar') else 0
98
- chart_h = bottom_top - chart_top - axis_h
202
+ # ---------------- 底部:先量后排列,再倒推绘图区
203
+ blocks = _bottom_blocks(spec, theme, width - 2 * MARGIN)
204
+ blocks_h = sum(len(block['lines']) * block['step'] for block in blocks)
205
+ blocks_h += 4 * max(0, len(blocks) - 1)
206
+ footer_lines = _footer_lines(spec, width - 2 * MARGIN)
207
+ footer_h = (14 + FOOTER_LINE_H * len(footer_lines)) if footer_lines else 0
208
+ footer_top = height - footer_h
209
+ bottom_gap = BOTTOM_GAP if blocks else 8
210
+ chart_bottom = footer_top - bottom_gap - blocks_h
211
+ axis_h = charts.x_axis_height(chart_cfg.get('type'), XAXIS_H)
212
+ chart_h = chart_bottom - chart_top - axis_h
99
213
 
214
+ if chart_h <= 0:
215
+ raise SystemExit(
216
+ f'chart area is negative ({chart_h:.0f}px): canvas {width}x{height} is too short '
217
+ 'for this header/notes/footer; raise --height or drop title/subtitle/notes')
100
218
  if chart_h < MIN_CHART_H:
101
219
  raise SystemExit(
102
220
  f'chart area too short ({chart_h:.0f}px < {MIN_CHART_H}px): '
103
- f'drop the title/subtitle/notes for an inline chart, or pass a taller --height')
104
- if chart_h <= 0:
105
- raise SystemExit(f'chart area is negative ({chart_h:.0f}px): lower the header or notes')
221
+ 'drop the title/subtitle/notes for an inline chart, or pass a taller --height')
106
222
 
107
- charts.render(svg, (MARGIN, chart_top, width - 2 * MARGIN, chart_h), spec['chart'], rows)
223
+ charts.render(svg, (MARGIN, chart_top, width - 2 * MARGIN, chart_h), chart_cfg, rows)
108
224
 
109
- # ---------------- 底部内容:一个游标顺序排,绝不重叠
110
- y = bottom_top + BOTTOM_GAP
111
- if legend:
112
- svg.text(MARGIN, y + 10, str(legend), size=12.5, fill=theme['mute'])
113
- y += LEGEND_STEP
114
- if legend and notes:
115
- y += notes_gap
116
- for raw in notes:
117
- text, size, fill, weight = _note_style(raw, theme)
118
- svg.text(MARGIN, y + size, text, size=size, fill=fill, weight=weight)
119
- y += NOTE_STEP
120
-
121
- # ---------------- 页脚(固定贴底)
122
- svg.line(MARGIN, footer_top, width - MARGIN, footer_top, theme['line'], 1)
123
- sources = spec.get('sources') or []
124
- if sources:
125
- svg.text(MARGIN, footer_top + 20,
126
- '数据来源 FTShare 接口:' + ' / '.join(map(str, sources)),
127
- size=11.5, fill=theme['mute'])
128
- if spec.get('sample'):
129
- svg.text(MARGIN, footer_top + 38, str(spec['sample']), size=11.5, fill=theme['mute'])
225
+ # ---------------- 底部内容:单个游标顺序排,绝不重叠
226
+ y = chart_bottom + bottom_gap
227
+ for block in blocks:
228
+ for index, line in enumerate(block['lines']):
229
+ svg.text(MARGIN, y + block['size'] + index * block['step'], line,
230
+ size=block['size'], fill=block['fill'], weight=block['weight'])
231
+ y += len(block['lines']) * block['step'] + 4
232
+
233
+ # ---------------- 页脚(贴底、按折行后的真实高度)
234
+ if footer_lines:
235
+ svg.line(MARGIN, footer_top, width - MARGIN, footer_top, theme['line'], 1)
236
+ for index, line in enumerate(footer_lines):
237
+ svg.text(MARGIN, footer_top + 18 + index * FOOTER_LINE_H, line,
238
+ size=11.5, fill=theme['mute'])
130
239
 
131
240
  size = svg.save(args.out)
132
241
  print(f'{args.out} ({size} bytes, {width}x{height}, {len(rows)} rows, '
133
242
  f'theme={theme["name"]}, chart_h={chart_h:.0f})')
134
-
135
-
136
- def _note_style(raw, theme):
137
- """结论行前缀:`**` 加粗主结论、`!` 强调色、`*` 小字注释,其余为普通灰字。"""
138
- if raw.startswith('**'):
139
- return raw.strip('*'), 16, theme['ink'], 'bold'
140
- if raw.startswith('!'):
141
- return raw[1:], 16, theme['up'], 'bold'
142
- if raw.startswith('*'):
143
- return raw[1:], 13, theme['mute'], 'normal'
144
- return raw, 14.5, theme['mute'], 'normal'
243
+ return 0
145
244
 
146
245
 
147
246
  if __name__ == '__main__':
148
- main()
247
+ sys.exit(main())
package/src/index.js CHANGED
@@ -46,8 +46,9 @@ const PACKAGED_SKILL_RANK = 600
46
46
  * `description` frontmatter in SKILL.md.
47
47
  */
48
48
  const DESCRIPTION = '把 FTShare 接口返回的数据渲染成图,图直接显示在聊天流里(内联 SVG,无需点开侧栏)。'
49
- + '用于热榜、板块、资金流、估值、财报、宏观、指数等结果的趋势、排名、分布、对比。'
50
- + '当用户说画图/出图/可视化/来张图,或在分析金融数据后需要更直观呈现时使用。'
49
+ + '用于热榜、板块、资金流、估值、财报、宏观、指数等结果的趋势、排名、分布、对比,'
50
+ + '也支持热力图、构成图、瀑布图、事件时间轴与产业链示意图。'
51
+ + '用户要画图/出图/可视化时默认用本技能,直接在对话里出图。'
51
52
 
52
53
  const CANDIDATE = {
53
54
  name: SKILL_NAME,
@@ -76,12 +77,13 @@ function installedRuntime() {
76
77
  '脚本只用 Python 标准库,**不需要 uv、不需要 venv、不需要 pip 安装**。优先用 `python3`:',
77
78
  '',
78
79
  '```bash',
79
- `python3 ${directory}/scripts/plot.py --spec /绝对路径/spec.json --out /绝对路径/chart.svg`,
80
+ `python3 ${directory}/scripts/plot.py --spec /绝对路径/spec.json --out-dir "$(pwd)/.dsh/plots" --slug 图名`,
80
81
  '```',
81
82
  '',
82
83
  '若 `python3` 不可用,用 `load_workspace_dependencies` 返回的 `python` 绝对路径替代。',
83
84
  '',
84
- '**产物路径必须写成绝对路径**,并在回复里用 Markdown 图片语法引用,图才会内联显示。',
85
+ '**产物路径以 stdout 打印的绝对路径为准**(`--out-dir` 会按内容哈希命名,重复生成同名覆盖),'
86
+ + '并在回复里用 Markdown 图片语法引用,图才会内联显示。需要色值/字号时先跑 `--tokens`。',
85
87
  '',
86
88
  ].join('\n')
87
89
  }