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

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,148 @@
1
+ #!/usr/bin/env python3
2
+ """ft-plot 入口:spec(JSON) → 独立 SVG。
3
+
4
+ 用法:
5
+ python3 plot.py --spec spec.json --out /abs/path/chart.svg
6
+ python3 plot.py --spec spec.json --out chart.svg --theme poster --width 1000
7
+
8
+ 产物是自包含 SVG(无外链、无脚本、浅色底),可直接写进 Markdown 图片语法内联显示。
9
+ 只依赖 Python 标准库。
10
+
11
+ **布局原则**:头部(chip/标题/副标题)与底部(说明/结论/页脚)都走同一个游标顺序排布,
12
+ 任何元素都不自己算 y 坐标。上一版让 `legend` 自己贴绘图区底边,结果和第一条结论撞在
13
+ 一起;游标是唯一能防止这类重叠的写法。
14
+
15
+ 这些头部元素全是可选的——图在聊天流中间时,前后已有文字说明,不传就不会占位,
16
+ 绘图区自动上移占满。
17
+ """
18
+ import argparse
19
+ import os
20
+ import sys
21
+
22
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
+
24
+ from ftplot import charts, spec as specmod, theme as thememod # noqa: E402
25
+ from ftplot.canvas import Svg, text_width, wrap # noqa: E402
26
+
27
+ MARGIN = 60
28
+ NOTE_STEP = 27 # 结论行行距
29
+ LEGEND_STEP = 26 # 图内说明行高
30
+ HEADER_GAP = 26 # 头部与绘图区的间距
31
+ BOTTOM_GAP = 20 # 绘图区与底部说明的间距
32
+ FOOTER_H = 54 # 页脚高度(分隔线 + 两行小字)
33
+ #: x 轴标签占用的高度:标签画在绘图区底边之下 21px,字高约 13px,再加 12px 呼吸。
34
+ #: 绘图区高度必须先扣掉它,否则底部的说明行会紧贴横轴标签——只有 9px 间距时,
35
+ #: 12.5px 的字高就已经和标签糊在一起了。
36
+ XAXIS_H = 46
37
+ MIN_CHART_H = 170 # 绘图区最小高度,低于此值直接失败而不是画出糊掉的图
38
+
39
+
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()
48
+
49
+ spec = specmod.load(args.spec)
50
+ rows = specmod.rows_of(spec)
51
+ 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
+
55
+ svg = Svg(width, height, theme)
56
+ cursor = MARGIN
57
+
58
+ # ---------------- 头部(全部可选)
59
+ chip = spec.get('chip')
60
+ if chip:
61
+ tone = charts.resolve_color(theme, spec.get('chip_tone'), 'down')
62
+ label = str(chip)
63
+ chip_w = text_width(label, 13) + 30
64
+ svg.rect(MARGIN, cursor, chip_w, 30, tone, rx=15, opacity=0.12)
65
+ svg.text(MARGIN + chip_w / 2, cursor + 15, label, size=13, fill=tone,
66
+ weight='bold', anchor='middle', baseline='middle')
67
+ cursor += 46
68
+
69
+ title = spec.get('title')
70
+ if title:
71
+ lines = wrap(str(title), 26, width - 2 * MARGIN)
72
+ cursor = svg.text_block(MARGIN, cursor + 24, lines, size=26, fill=theme['ink'],
73
+ weight='bold', line_height=37)
74
+
75
+ subtitle = spec.get('subtitle')
76
+ 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,
79
+ fill=theme['mute'], line_height=22)
80
+
81
+ has_header = bool(chip or title or subtitle)
82
+ chart_top = cursor + (HEADER_GAP if has_header else 8)
83
+
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
99
+
100
+ if chart_h < MIN_CHART_H:
101
+ raise SystemExit(
102
+ 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')
106
+
107
+ charts.render(svg, (MARGIN, chart_top, width - 2 * MARGIN, chart_h), spec['chart'], rows)
108
+
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'])
130
+
131
+ size = svg.save(args.out)
132
+ print(f'{args.out} ({size} bytes, {width}x{height}, {len(rows)} rows, '
133
+ 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'
145
+
146
+
147
+ if __name__ == '__main__':
148
+ main()
package/src/index.js ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Bundled `ft-plot` skill provider for DeepSeek Harness.
3
+ *
4
+ * Registers the packaged plotting skill on the `ctx.skills` registry so every
5
+ * session sees it in the model-facing catalog and the `/` menu, without anyone
6
+ * copying files into `$DSH_HOME/skills`.
7
+ *
8
+ * The host half deliberately owns no runtime state and imports no
9
+ * `@deepseek-ai/*` package: the plotting scripts are standard-library Python, so
10
+ * the plugin installs with no build step and cannot split a Cordis module
11
+ * instance when a profile links it from a source directory.
12
+ *
13
+ * @module @dsh-ft/dsh-fft-plot
14
+ */
15
+
16
+ import { readFile } from 'node:fs/promises'
17
+ import { resolve } from 'node:path'
18
+ import { fileURLToPath } from 'node:url'
19
+
20
+ /** Provider name in the `ctx.skills` registry. */
21
+ export const PROVIDER_NAME = 'dsh-fft-plot'
22
+
23
+ /** Skill name the model loads and the `/` menu lists. */
24
+ export const SKILL_NAME = 'dsh-fft-plot'
25
+
26
+ const SKILL_DIR_URL = new URL('../skills/dsh-fft-plot/', import.meta.url)
27
+
28
+ /**
29
+ * Relative paths inside SKILL.md resolve against the bundled skill directory.
30
+ * `fileURLToPath` keeps a trailing separator for directory URLs, which would
31
+ * double up in the paths this provider renders, so normalize it away.
32
+ */
33
+ const RESOURCE_BASE = { kind: 'directory', path: resolve(fileURLToPath(SKILL_DIR_URL)) }
34
+
35
+ /**
36
+ * Precedence rank for a packaged skill provider. Matches `BUNDLED_SKILL_RANK`
37
+ * from `@deepseek-ai/dsh-skill`; the literal keeps this package dependency-free.
38
+ */
39
+ const PACKAGED_SKILL_RANK = 600
40
+
41
+ /**
42
+ * Description rendered in the model-facing skill catalog (truncated at 500
43
+ * characters by `@deepseek-ai/dsh-skill`). It has to carry every trigger
44
+ * phrase the model might match against, because the skill body is loaded only
45
+ * after the model decides to call `skill`. Keep it in sync with the
46
+ * `description` frontmatter in SKILL.md.
47
+ */
48
+ const DESCRIPTION = '把 FTShare 接口返回的数据渲染成图,图直接显示在聊天流里(内联 SVG,无需点开侧栏)。'
49
+ + '用于热榜、板块、资金流、估值、财报、宏观、指数等结果的趋势、排名、分布、对比。'
50
+ + '当用户说画图/出图/可视化/来张图,或在分析金融数据后需要更直观呈现时使用。'
51
+
52
+ const CANDIDATE = {
53
+ name: SKILL_NAME,
54
+ description: DESCRIPTION,
55
+ invocation: { modelInvocable: true, userInvocable: true },
56
+ provider: PROVIDER_NAME,
57
+ source: 'bundled',
58
+ resourceBase: RESOURCE_BASE,
59
+ rank: PACKAGED_SKILL_RANK,
60
+ locator: new URL('SKILL.md', SKILL_DIR_URL),
61
+ }
62
+
63
+ /**
64
+ * Skill content, with the facts a model cannot derive appended as an
65
+ * installed-runtime note: the absolute skill directory, the output directory
66
+ * convention, and how to reach a Python interpreter.
67
+ */
68
+ function installedRuntime() {
69
+ const directory = RESOURCE_BASE.path
70
+ return [
71
+ '',
72
+ '## Installed runtime',
73
+ '',
74
+ `本 Skill 的绝对目录是 \`${directory}\`。脚本一律用这个目录拼绝对路径调用,不要依赖当前工作目录。`,
75
+ '',
76
+ '脚本只用 Python 标准库,**不需要 uv、不需要 venv、不需要 pip 安装**。优先用 `python3`:',
77
+ '',
78
+ '```bash',
79
+ `python3 ${directory}/scripts/plot.py --spec /绝对路径/spec.json --out /绝对路径/chart.svg`,
80
+ '```',
81
+ '',
82
+ '若 `python3` 不可用,用 `load_workspace_dependencies` 返回的 `python` 绝对路径替代。',
83
+ '',
84
+ '**产物路径必须写成绝对路径**,并在回复里用 Markdown 图片语法引用,图才会内联显示。',
85
+ '',
86
+ ].join('\n')
87
+ }
88
+
89
+ const provider = {
90
+ name: PROVIDER_NAME,
91
+ list() {
92
+ return Promise.resolve([CANDIDATE])
93
+ },
94
+ async get(candidate) {
95
+ const body = await readFile(candidate.locator, 'utf8')
96
+ return {
97
+ name: CANDIDATE.name,
98
+ description: CANDIDATE.description,
99
+ invocation: CANDIDATE.invocation,
100
+ provider: CANDIDATE.provider,
101
+ source: CANDIDATE.source,
102
+ resourceBase: RESOURCE_BASE,
103
+ content: stripFrontmatter(body) + installedRuntime(),
104
+ }
105
+ },
106
+ }
107
+
108
+ /**
109
+ * The skill registry renders the body, so the YAML frontmatter belongs to the
110
+ * on-disk copy only; leaving it in would show up verbatim in the model's
111
+ * `<skill_content>` block.
112
+ */
113
+ function stripFrontmatter(text) {
114
+ const normalized = text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')
115
+ if (!normalized.startsWith('---\n')) return normalized
116
+ const end = normalized.indexOf('\n---', 3)
117
+ if (end === -1) return normalized
118
+ const afterFence = normalized.indexOf('\n', end + 1)
119
+ return afterFence === -1 ? '' : normalized.slice(afterFence + 1).replace(/^\n+/, '')
120
+ }
121
+
122
+ /** Cordis plugin name. */
123
+ export const name = '@dsh-ft/dsh-fft-plot'
124
+
125
+ /** The bundled provider is only useful next to the skill registry. */
126
+ export const inject = ['skills']
127
+
128
+ /** Register the bundled plotting skill provider on `ctx.skills`. */
129
+ export function apply(ctx) {
130
+ if (typeof ctx.skills?.registerProvider !== 'function') {
131
+ throw new Error(
132
+ '@dsh-ft/dsh-fft-plot requires the skill registry (@deepseek-ai/dsh-skill, service `skills`) in this composition',
133
+ )
134
+ }
135
+ ctx.skills.registerProvider(() => provider)
136
+ }
137
+
138
+ export { provider, CANDIDATE, RESOURCE_BASE, installedRuntime, stripFrontmatter }