Logo Svg Primitives

Svg Primitives

Cộng đồng
neuromechanist
svg-primitives

Use when the user asks to build a programmatic SVG schematic in Python: flowcharts, boxes and arrows, auto-fit SVG text, mm-precise diagrams, edge-snapped arrows, tangent-correct curve arrowheads, orthogonal or Manhattan routing, deterministic z-order layers, labeled groups, bracket groupings, leader-line annotations, or strict Canvas.save validation for text overflow. Use figure-qa instead for after-the-fact validation of arbitrary hand-authored or exported SVGs. Built on drawsvg, svgpathtools, and fontTools; output SVGs can be composed by scientific-figure.

Tổng quan

Nhà phát hànhneuromechanist
Kho mãresearch-skills
Tên kỹ năngsvg-primitives
Sao
51
Bản fork
9
Tệp đi kèm
19
Giấy phépBSD-3-Clause
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 19 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được neuromechanist công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Svg Primitives trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/neuromechanist/research-skills/tree/main/plugins/figures/skills/svg-primitives
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/neuromechanist/research-skills.git /tmp/research-skills
mkdir -p .claude/skills
cp -r /tmp/research-skills/plugins/figures/skills/svg-primitives .claude/skills/svg-primitives
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Svg Primitives trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Svg Primitives ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Svg Primitives với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

SVG Primitives

Build mm-precise SVG schematics in Python with three mechanical guarantees:

  1. Text never overflows its container — labeled shapes auto-size to fit measured text bbox + padding.
  2. Arrowheads stay tangent-correct — arrows emit <marker orient="auto"> so the renderer rotates the head along the path's terminal tangent; works on straight lines and cubic Beziers.
  3. Paint order is deterministic — layers paint in registration order; connectors visibly pass under boxes without manual reordering.

The skill ships an end-to-end pytest suite (50+ tests) that renders SVGs and asserts these invariants on the rendered output, so the guarantees are enforced by construction rather than by hand-checking each figure.

When to use this skill

Reach for svg-primitives when:

  • The figure is a schematic (boxes, arrows, labels) and you're driving it from Python — e.g. nodes come from a YAML config, or the layout depends on data.
  • You need the boxes to auto-fit their labels (no hand-tuning widths).
  • The figure has curved arrows that must point cleanly at their targets.
  • You want deterministic z-order so connectors sit under shapes without manual element reordering.
  • The output will be composed into a multi-panel figure as a panel SVG that scientific-figure/compose.py loads.

Reach for a different tool when:

  • The figure is plotted from numbers (matplotlib/seaborn/plotnine) → use figures:plot-styling.
  • The figure is a photographic / pictorial substrate (a brain scene, microscope setup) → use figures:ai-full-figure for the substrate and overlay labels via Arrow/LabeledBox here.
  • The figure is hand-authored SVG or the patterns are reference material for hand-authoring → use figures:svg-figure (this skill's library-agnostic counterpart).

Quick start

python
from svg_primitives import Canvas, LabeledBox, Arrow

c = Canvas(width_mm=183, height_mm=80)
boxes = c.layer("boxes")
arrows = c.layer("connectors")

raw = boxes.add(LabeledBox(x=10, y=20, text="Raw EEG", font_size=7))
band = boxes.add(LabeledBox.next_to(raw, side="E", gap=10, text="Bandpass\nfilter", font_size=7))
ica = boxes.add(LabeledBox.next_to(band, side="E", gap=10, text="Independent component\nanalysis", font_size=7))

arrows.add(Arrow.connect(raw, band))                          # straight, snapped to edges
arrows.add(Arrow.connect(band, ica))                          # straight
arrows.add(Arrow.connect(ica, raw, curve="cubic", bow=14,     # feedback arc
                          stroke="#C45146"))                  # red — gets its own red marker

c.save("eeg.svg", output_png=True)

examples/eeg_pipeline.py is the canonical reference; run it to see the full output:

bash
uv run --with drawsvg --with svgpathtools --with Pillow --with fonttools --with cairosvg \
  python plugins/figures/skills/svg-primitives/examples/eeg_pipeline.py

Primitive reference

Canvas(width_mm, height_mm, background=None)

The root drawing surface. User units equal mm; the viewBox is set so coordinates inside the SVG are in mm and font-size is emitted in mm regardless of the input pt size.

  • .layer(name) -> Layer — gets or creates a named layer. Subsequent .layer("boxes") calls return the same layer.
  • .add_layer(Layer) -> Canvas — explicit insertion when registration order matters.
  • .save(path, output_png=False, png_width=1800) — writes the SVG; with output_png=True, also writes a sibling PNG via cairosvg.

Layer paint order is the order layers were first registered. Typical convention: background → connectors → boxes → labels.

Layer(name)

An ordered bucket of elements. .add(element) appends and returns the element so calls chain.

LabeledBox(x, y, text, font_size=7, padding=2, ...)

Auto-sized rounded rectangle with centered text. The width and height are computed from the measured text bbox (via fontTools) plus padding on every side, clamped by min_width / min_height. Multi-line text (newline-separated) stacks with line_spacing em between baselines.

  • anchor="top-left" (default) — x, y is the top-left corner.
  • anchor="center" — x, y is the centroid.
  • .anchor_point("N"|"S"|"E"|"W") -> complex — exposed for Arrow.connect.
  • .outline_path() -> svgpathtools.Path — used internally for arrow edge snapping.
  • .next_to(other, side, gap, **kwargs) (classmethod) — build a sibling positioned relative to an existing box.

font_size is in pt for ergonomics (font_size=7 matches "7 pt Helvetica" in typographic terms). The emitted SVG font-size attribute is in mm (pt × 25.4 / 72).

Pill(...) and Diamond(...)

Variants of LabeledBox:

  • Pill — corner radius equals height/2 after auto-sizing → flat-sided capsule. Good for terminal nodes.
  • Diamond — rhombus. Width and height are doubled after the text + padding measurement so the inscribed text rectangle fits. Outline is a 4-edge polygon.

Arrow.connect(src, dst, curve=..., bow=0, src_side="auto", dst_side="auto", via=None, corner_radius=0, stroke, stroke_width)

Connector between two shapes (any Shape — LabeledBox, Pill, Diamond, Group). Returns an Arrow object that the Canvas renders as an SVG <path> with marker-end referencing a per-color marker.

  • curve="straight" (default) — direct line; endpoints snapped to box outlines.
  • curve="cubic" — Bezier with control points perpendicular to the chord at bow mm of bulge. Positive bow = upward (negative SVG y), negative = downward.
  • curve="orthogonal-h" — three-segment right-angle path: out horizontally from src, vertical traverse at the x-midpoint, in horizontally to dst. Auto-sides become E/W.
  • curve="orthogonal-v" — same idea, vertical-first: out vertically, horizontal at the y-midpoint, in vertically. Auto-sides become N/S.
  • via=[(x, y), ...] — multi-waypoint path (straight curve only). The polyline passes through each waypoint in order between src and dst.
  • corner_radius — when > 0, each interior corner of a polyline (via mode) is replaced with a quadratic Bezier of that radius, clamped to half the shorter adjoining segment.
  • src_side / dst_side — "auto" picks the appropriate side; override to force "N", "S", "E", "W".

Arrowhead orientation is delivered by <marker orient="auto">, so the head is always rotated to match the path tangent at the terminal point — including on cubic splines and orthogonal turns.

Bracket(start, end, depth, label=None, label_offset=2, ...)

Square-style bracket ("rake") for grouping elements. The spine sits depth mm perpendicular to the start-end line; the optional label sits at the spine apex label_offset mm further out on the closed side of the bracket. Renders as one <path> plus an optional <text>. Useful for electrode-group labels, time-window annotations, or condition spans in EEG/EMG figures.

Annotation(x, y, text, leader_to=None, ...)

Text label at (x, y) with an optional leader line drawn from the text bounding box edge to a target coordinate. When leader_to is None, just text. The leader is computed against the measured text bbox so the line starts at the visual edge of the text (not its centroid), with a configurable leader_gap.

Group(*shapes)

Virtual container — not a renderable. Exposes the union-bbox geometry of its member shapes (cx, cy, left/right/top/bottom, anchor_point, outline_path) so Arrow.connect(group, other_box) works the same as connecting two boxes, but the arrow snaps to the rectangle that bounds all members. Useful when an arrow should target a cluster of boxes as one visual unit (e.g. "all frontal channels feed the regressor").

The Shape Protocol formalizes the minimal geometry contract — anything with cx, cy, anchor_point, and outline_path is accepted by Arrow.connect. LabeledBox, Pill, Diamond, and Group all satisfy it.

Anchor system

Every shape exposes four cardinal anchor points: N (top center), S (bottom center), E (right center), W (left center). When Arrow.connect is given src_side="auto", it picks the side of src facing dst and likewise for dst. Override either side explicitly to draw a feedback loop:

python
Arrow.connect(rejection, ica, curve="cubic", src_side="N", dst_side="N", bow=14)

Layering rules

SVG has no z-index — paint order is document order. The Canvas flushes layers in the order they were first registered, so c.layer("background").add(...) will sit behind c.layer("boxes").add(...) even if it's added later, as long as the background layer was registered first. Add a layer once at the top of the build function to lock its z-position:

python
c.layer("background")    # locks z=0
c.layer("connectors")    # locks z=1
c.layer("boxes")         # locks z=2
# ... add elements to any layer in any order from here

Validation

Canvas.save(path, validate=...) accepts three modes:

ModeBehavior
"warn" (default)Run all validators on the rendered SVG. Log each finding at WARNING. Return the list. Caller can ignore.
"strict"Run all validators. Raise ValidationError if any findings; the exception's .findings attribute carries the full list.
"off"Skip validation entirely. Return [].

Canvas.validate() runs the same checks against an in-memory render without writing to disk and returns the findings — useful for assertion-style gates.

The validators that run:

  • text-overflow — every <text> bbox must sit inside at least one rect or diamond in the same layer (0.5 mm tolerance). The same-layer scope is intentional: text labels belong to their box's layer.
  • arrow-tip-distance — every arrow tip must be within 0.6 mm of some target shape's edge anywhere on the canvas (any layer). The cross-layer scope is intentional: arrows commonly span layers (e.g. a connector layer pointing into a boxes layer).
  • marker-orient — every <marker> must use orient="auto".
  • sibling-overlap — no two rects in the same non-background layer should overlap (use validate_sibling_overlap(ignore_layers=...) to whitelist additional layers).

Each Finding carries category, message, element_id, and location (mm). See examples/validation_demo.py for a runnable demonstration.

svg-primitives validation is complementary to the figures:figure-qa agent: figure-qa validates any SVG (including hand-authored ones); this validates SVGs produced by this skill, in-process, before they hit disk.

Composition into a panel

Once authored, the SVG is a panel source for figures:scientific-figure:

python
from compose import Figure

Figure(width_mm=183, height_mm=60, journal="nature") \
    .add_panel("schematic.svg", x_mm=0, y_mm=0, scale=1.0, label="A") \
    .add_panel("plot.svg", x_mm=92, y_mm=0, scale=0.5, label="B") \
    .save("figure.svg")

Schematics are typically sized at the final panel dimensions and composed at scale=1.0 so labels stay at their authored size.

Running the examples

bash
uv run --with drawsvg --with svgpathtools --with Pillow --with fonttools --with cairosvg \
  python plugins/figures/skills/svg-primitives/examples/eeg_pipeline.py
uv run --with drawsvg --with svgpathtools --with Pillow --with fonttools --with cairosvg \
  python plugins/figures/skills/svg-primitives/examples/stress_test.py

Each writes <file>.svg and <file>.png into examples/out/ (gitignored).

Running the tests

The skill ships an E2E pytest suite that asserts text containment, arrow tip distance to target edges, marker orientation, layer paint order, per-color marker generation, font-size unit correctness, and Diamond text containment — all on real rendered SVGs parsed from disk. No mocks.

bash
uv run --with pytest --with lxml --with svgelements --with svgpathtools \
    --with drawsvg --with Pillow --with fonttools --with cairosvg --with shapely \
    pytest plugins/figures/skills/svg-primitives/tests/ -v

Expected: all tests pass (50+ tests covering text containment, arrow geometry, layer order, validation errors, and Phase 2 primitives).

Quality assurance

After authoring, run figures:figure-qa for the standard pre-export font / palette / geometry checks:

bash
uv run --with lxml --with svgelements --with svgpathtools --with shapely \
    python plugins/figures/agents/figure-qa-scripts/check_svg.py \
    schematic.svg --journal nature --palette okabe-ito

The geometry section (bbox-overlap, arrow-tip-to-target, text-overflow) landed via issue #47; the primitive-layer tests in this skill cover the same invariants for SVGs built from svg_primitives.

Handoff to Illustrator or Affinity Designer

Canvas output is already close to the editor-safe dialect (named <g id="layer-..."> groups, origin-0 mm viewBox, single positioning, no data URIs). Two constructs are intentionally kept editor-unfriendly in the master because validation depends on them: <marker orient="auto"> arrowheads and middle-anchored labels (LabeledBox/Pill/Diamond/Bracket always center; Annotation defaults to middle but is configurable). When a figure goes to a human editor, derive the handoff copy with the editor-prep pass in the figures:svg-figure skill's scripts/editor_prep.py, which bakes markers into rotated geometry and resolves anchors to measured left edges. The editor-handoff reference in figures:svg-figure explains why.

Additional resources

  • examples/eeg_pipeline.py — canonical EEG preprocessing flowchart.
  • examples/stress_test.py — edge cases (min-size, long labels, multi-line, crossing arrows, 6 pt vs 12 pt).
  • references/api.md — full API reference.
  • references/design.md — design rationale, library choices, convention notes.
  • references/font-metrics.md — how fontTools advance widths feed the auto-fit logic, font search path, fallbacks.

Cross-references

Invoke each installed skill by its fully qualified figures:<skill> name through the host's skill-invocation mechanism. Keep host-specific command or tool syntax in the host adapter, not in shared skill instructions.

  • figures:svg-figure — hand-authored SVG patterns; reference material for writing SVG by hand or generating it ad-hoc.
  • figures:scientific-figure — multi-panel composer that loads SVGs produced here.
  • figures:plot-styling — data plots (matplotlib / seaborn / plotnine / plotly / PyVista).
  • figures:ai-full-figure — AI-generated pictorial substrate; overlay labels with LabeledBox / Arrow here.
  • figures:transparent-icons — flat scientific icons; place them inside a LabeledBox neighborhood with Arrow.connect.
  • figures:figure-qa — QA agent that validates the rendered SVG.

Running in CI

measure_text_mm reads real font tables (fontTools/Pillow). A vanilla Linux CI container has no system fonts — install one before running the tests:

bash
apt-get install -y fonts-liberation     # or fonts-dejavu-core

Without a system font, measure_text_mm falls back to a 0.55-em-per-character heuristic and logs a WARNING. Pass strict_metrics=True to LabeledBox to raise MetricsFallbackError instead — recommended for journal-submission workflows.

Tệp đi kèm

Khi kỹ năng đã được tải, mô hình có thể đọc các tệp này nếu cần. Các tệp này chỉ dùng để đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Svg Primitives làm được gì?

Use when the user asks to build a programmatic SVG schematic in Python: flowcharts, boxes and arrows, auto-fit SVG text, mm-precise diagrams, edge-snapped arrows, tangent-correct curve arrowheads, orthogonal or Manhattan routing, deterministic z-order layers, labeled groups, bracket groupings, leader-line annotations, or strict Canvas.save validation for text overflow. Use figure-qa instead for after-the-fact validation of arbitrary hand-authored or exported SVGs. Built on drawsvg, svgpathtools, and fontTools; output SVGs can be composed by scientific-figure.

Vì sao nên dùng Svg Primitives trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Svg Primitives là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Svg Primitives trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/neuromechanist/research-skills/tree/main/plugins/figures/skills/svg-primitives. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm rồi cài đặt cả gói dưới dạng một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Svg Primitives?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Svg Primitives với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Svg Primitives với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Svg Primitives có miễn phí không?

Có. Kỹ năng này được neuromechanist phát hành trên GitHub theo giấy phép BSD-3-Clause. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇