Print this guide
Table of Contents
- 1 Overview
- 2 Installation
- 3 API Reference
- 4 AI Rename
- How it works
- Quick start
- Configuring the model
- Artifacts
- API reference
- rename_lines(lines_path, output_path=None, *, client=None, config=None, work_dir=None, dpi=72, dry_run=False, **plan_kwargs) -> RenamePlan
- build_rename_plan(lines_path, client, *, config=None, work_dir=None, dpi=72, render_timeout=600.0, render_lines_png=None, describe=None, suggest=None, save_artifacts=True) -> RenamePlan
- apply_rename_plan(plan, output_path) -> int
- Data classes
- VLM helpers (vexy_lines_api.rename.vlm)
- Inspection helpers (vexy_lines_api.rename.inspection)
- File editing (vexy-lines-py)
- Installation
- Using it from the CLI and GUI
- See also
- 5 Style Engine
- 6 MCP Protocol
- 7 Examples
- Open a document and inspect it
- Walk the layer tree
- Change fill colours and re-export
- Create a document from scratch
- Build a multi-layer composition
- Style transfer: one style, many images
- Style transfer with error handling and progress
- Style interpolation for animation
- Export to multiple formats
- Get SVG as a string
- Error handling
- Low-level tool calls
- Video processing with per-frame style transfer
- Video with style interpolation
- Using the JobFolder for resumable batch export
- Export pipeline with callbacks
- Style creation and consolidation
- Integration with Claude Desktop
- 8 Changelog
- 9 Topics
Vexy Lines for Mac & Windows | Download | Buy | Batch GUI | CLI/MCP | API | .lines format
vexy-lines-apy¶
Python bindings to the Vexy Lines MCP API and style engine.
Connect to the Vexy Lines app over TCP, drive it programmatically, and transfer artistic styles between images, all from Python.
Three entry points¶
MCPClient: a context-managed TCP client that speaks JSON-RPC 2.0 to the Vexy Lines embedded server. Open documents, manipulate layers, change fill parameters, render, export. If the app isn't running, the client launches it.
Style engine: extract a fill style from a .lines file, apply it to any source image, or blend two styles at any mix ratio. No GUI interaction needed.
JobFolder: persistent intermediate storage for resumable export pipelines. Stores .lines, .svg, and frame artifacts alongside the final output instead of in temp directories.
Quick start: MCP client¶
from vexy_lines_api import MCPClient
with MCPClient() as vl:
vl.open_document("photo.lines")
info = vl.get_document_info()
print(f"{info.width_mm:.0f} x {info.height_mm:.0f} mm @ {info.resolution} dpi")
tree = vl.get_layer_tree() # LayerNode tree
vl.render() # render + wait for completion
vl.export_svg("output.svg")
Quick start: style transfer¶
from vexy_lines_api import MCPClient, extract_style, apply_style
style = extract_style("reference.lines")
with MCPClient() as vl:
svg = apply_style(vl, style, "photo.jpg", dpi=72)
with open("result.svg", "w") as f:
f.write(svg)
Quick start: style interpolation¶
from vexy_lines_api import extract_style, interpolate_style
a = extract_style("painterly.lines")
b = extract_style("technical.lines")
mid = interpolate_style(a, b, t=0.5) # halfway between both
Quick start: resumable batch export¶
from vexy_lines_api.export import JobFolder, ExportRequest, process_export
request = ExportRequest(
mode="images",
input_paths=["photo1.jpg", "photo2.jpg"],
style_path="artistic.lines",
end_style_path=None,
output_path="./output/",
format="SVG",
size="1x",
)
process_export(request, on_progress=lambda cur, total, msg: print(f"[{cur}/{total}] {msg}"))
Next steps¶
- Installation: install options, dependencies, and optional extras
- API Reference: every class, method, function, and constant
- AI Rename: describe each fill with a vision model and rename layers & fills
- Style Engine: how extraction, application, interpolation, and relative scaling work
- MCP Protocol: the 25 tools in 5 groups, wire format, parameter reference, bridge setup
- Examples: real-world usage patterns including batch processing, video, and error handling
Installation¶
Requirements¶
- Python 3.11 or newer
- The Vexy Lines desktop app (macOS or Windows) for all MCP operations
Install from PyPI¶
pip install vexy-lines-apy
Or with uv:
uv add vexy-lines-apy
Runtime dependencies¶
| Package | Version | Why |
|---|---|---|
vexy-lines-py |
>=0.1.0 |
.lines file parser and types (GroupInfo, LayerInfo, FillNode, FillParams, DocumentProps) |
loguru |
>=0.7.2 |
Structured debug logging |
typing-extensions |
>=4.0 |
Backported type hints for Python 3.11 |
Pillow |
>=10.0.0 |
Image manipulation (source image dimensions, frame extraction, resizing) |
resvg-py |
>=0.2.0 |
SVG rasterisation for video frame pipeline |
opencv-python-headless |
>=4.8.0 |
Video decoding/encoding and frame extraction |
av |
>=12.0.0 |
Additional video container support |
What works without the app¶
These functions work offline, with no Vexy Lines app required:
extract_style(): parse.linesfilesinterpolate_style(): blend two stylesstyles_compatible(): check style compatibilityprobe(): read video metadatasvg_to_pil(): rasterise SVG stringsextract_preview_from_lines(): extract embedded images
These require a running Vexy Lines app:
MCPClientand all its methodsapply_style(): style transfer via MCPcreate_styled_document(): document creation via MCPsave_and_consolidate(): save/reopen/render cycleprocess_video_with_style(): per-frame style transfer
Optional extras¶
SVG manipulation¶
pip install "vexy-lines-apy[svg]"
Adds the svglab package, which enables client.svg_parsed(). That method returns a full SVG DOM object you can traverse, edit, and render.
External tools (optional, not Python packages)¶
| Tool | Used by | Purpose |
|---|---|---|
ffprobe |
probe() |
Audio stream detection in video files |
ffmpeg |
process_video() |
Audio stream merging in output videos |
Both are optional. Without them, VideoInfo.has_audio defaults to False and video output has no audio track.
Verify the install¶
from vexy_lines_api import MCPClient, extract_style
print("vexy-lines-apy is ready")
To verify the MCP connection:
from vexy_lines_api import MCPClient
with MCPClient() as vl:
info = vl.get_document_info()
print(f"Connected: {info.width_mm:.0f} x {info.height_mm:.0f} mm")
The Vexy Lines app¶
The MCP client connects to a TCP server embedded in the Vexy Lines desktop app at localhost:47384. By default, MCPClient launches the app if it isn't running.
To disable auto-launch:
with MCPClient(auto_launch=False) as vl:
...
Auto-launch behaviour by platform:
| Platform | Mechanism |
|---|---|
| macOS | open -a "Vexy Lines" |
| Windows | Searches standard install paths for Vexy Lines.exe |
| Linux | Not supported (raises MCPError) |
After launching, the client polls the TCP port for up to 30 seconds with exponential back-off before giving up.
Development install¶
git clone https://github.com/vexyart/vexy-lines.git
cd vexy-lines/vexy-lines-apy
uv venv --python 3.12
uv pip install -e ".[dev]"
Run tests:
uvx hatch test
Run type checking:
uvx hatch run lint:typing
Run linting:
uvx hatch fmt
API Reference¶
MCPClient¶
Context-managed TCP client for the Vexy Lines MCP server. Speaks JSON-RPC 2.0 over newline-delimited TCP to the server embedded in the Vexy Lines desktop app.
from vexy_lines_api import MCPClient
with MCPClient(host="127.0.0.1", port=47384, timeout=30.0, auto_launch=True) as vl:
info = vl.get_document_info()
Constructor:
MCPClient(
host: str = "127.0.0.1",
port: int = 47384,
timeout: float = 30.0,
*,
auto_launch: bool = True,
)
| Parameter | Type | Default | Description |
|---|---|---|---|
host |
str |
"127.0.0.1" |
Server address |
port |
int |
47384 |
Server TCP port |
timeout |
float |
30.0 |
Socket timeout in seconds for all operations |
auto_launch |
bool |
True |
Launch the Vexy Lines app if connection fails |
Connection lifecycle¶
__enter__calls_connect()then_handshake()._connect()opens a TCP socket. On failure, ifauto_launch=True, launches the app and polls with exponential back-off (0.5 s initial, 1.2x growth, 2.0 s cap) for up to 30 seconds._handshake()sendsinitializewith protocol version"2024-11-05"and client info{"name": "vexy-lines-apy", "version": "1.0.0"}. Validates the server returns the same protocol version. Sendsnotifications/initializednotification.- Tool calls use
_send_request("tools/call", ...)which assigns an auto-incrementing integer request ID. __exit__shuts down and closes the socket.
Auto-launch behaviour¶
When auto_launch=True and the initial connection fails:
- macOS: runs
open -a "Vexy Lines"via subprocess. - Windows: searches
C:\Program Files\Vexy Lines\,C:\Program Files (x86)\Vexy Lines\, and%LOCALAPPDATA%\Programs\Vexy Lines\forVexy Lines.exe. RaisesMCPErrorif not found. - Other platforms: raises
MCPError(auto-launch unsupported).
After launching, polls the TCP port for up to 30 seconds before giving up.
Document methods¶
new_document(width, height, dpi, source_image) -> NewDocumentResult¶
Create a new document. Width and height are inferred from the source image when omitted.
def new_document(
self,
width: float | None = None,
height: float | None = None,
dpi: float = 300,
source_image: str | None = None,
) -> NewDocumentResult
| Parameter | Type | Default | Description |
|---|---|---|---|
width |
float \| None |
None |
Width in pixels (inferred from source image if omitted) |
height |
float \| None |
None |
Height in pixels (inferred from source image if omitted) |
dpi |
float |
300 |
Document resolution |
source_image |
str \| None |
None |
Path to source image file (resolved to absolute) |
Returns a NewDocumentResult with the created document's metadata.
open_document(path) -> str¶
Open a .lines file. The path is resolved to absolute before sending.
def open_document(self, path: str) -> str
Returns server status string.
save_document(path=None) -> str¶
Save the current document. Pass a path for Save As.
def save_document(self, path: str | None = None) -> str
export_document(path, dpi=None, format=None) -> str¶
Export to file. Format is one of "svg", "pdf", "png", "jpg", "eps".
def export_document(
self,
path: str,
dpi: int | None = None,
format: str | None = None,
) -> str
| Parameter | Type | Default | Description |
|---|---|---|---|
path |
str |
required | Output file path (resolved to absolute) |
dpi |
int \| None |
None |
Override document DPI for export |
format |
str \| None |
None |
"svg", "pdf", "png", "jpg", or "eps" |
get_document_info() -> DocumentInfo¶
Returns a DocumentInfo with dimensions, DPI, units, and unsaved changes flag.
def get_document_info(self) -> DocumentInfo
Structure methods¶
get_layer_tree() -> LayerNode¶
Returns the full document tree as a recursive LayerNode. The root node has type == "document".
def get_layer_tree(self) -> LayerNode
add_group(parent_id=None, caption=None, source_image_path=None) -> dict¶
Add a group to the document.
def add_group(
self,
parent_id: int | None = None,
caption: str | None = None,
source_image_path: str | None = None,
) -> dict[str, object]
| Parameter | Type | Default | Description |
|---|---|---|---|
parent_id |
int \| None |
None |
Parent object ID (defaults to document root) |
caption |
str \| None |
None |
Group display name |
source_image_path |
str \| None |
None |
Source image for the group |
Returns a dict containing "id" of the created group.
add_layer(group_id) -> dict¶
Add a layer to a group.
def add_layer(self, group_id: int) -> dict[str, object]
Returns a dict containing "id" of the created layer.
add_fill(layer_id, fill_type, color=None, params=None) -> dict¶
Add a fill to a layer.
def add_fill(
self,
layer_id: int,
fill_type: str,
color: str | None = None,
params: dict[str, object] | None = None,
) -> dict[str, object]
| Parameter | Type | Default | Description |
|---|---|---|---|
layer_id |
int |
required | Parent layer object ID |
fill_type |
str |
required | One of FILL_TYPES: "linear", "wave", "circular", "radial", "spiral", "scribble", "halftone", "handmade", "fractals", "trace" |
color |
str \| None |
None |
Hex colour string ("#RRGGBB" or "#RRGGBBAA") |
params |
dict \| None |
None |
Fill parameters dict (see FILL_TYPE_PARAMS) |
Returns a dict containing "id" of the created fill.
delete_object(object_id) -> str¶
Delete any object by ID (group, layer, or fill).
def delete_object(self, object_id: int) -> str
Note: the wire argument key is "id", not "object_id".
Fill parameter methods¶
get_fill_params(fill_id) -> dict¶
Get all parameters of a fill as a dict. The wire argument key is "id".
def get_fill_params(self, fill_id: int) -> dict[str, object]
Returns a dict of parameter names to current values.
set_fill_params(fill_id, **params) -> str¶
Set fill parameters by keyword. The wire format wraps kwargs inside a "params" dict alongside "id".
def set_fill_params(self, fill_id: int, **params: object) -> str
vl.set_fill_params(42, color="#ff0000", interval=3.0, angle=45)
All spatial values (interval, thickness, dispersion) are in pixels. The server converts internally to mm or points based on the document DPI. See FILL_TYPE_PARAMS for valid parameter names per fill type.
Visual methods¶
set_source_image(image_path, group_id=None) -> str¶
Set the source image for a group.
def set_source_image(self, image_path: str, group_id: int | None = None) -> str
set_caption(object_id, caption) -> str¶
Rename any object. Wire argument key is "id".
def set_caption(self, object_id: int, caption: str) -> str
set_visible(object_id, visible) -> str¶
Toggle visibility. The visible parameter is keyword-only.
def set_visible(self, object_id: int, *, visible: bool) -> str
set_layer_mask(layer_id, paths, mode="create") -> str¶
Set an SVG vector mask on a layer.
def set_layer_mask(
self,
layer_id: int,
paths: list[str],
mode: str = "create",
) -> str
| Parameter | Type | Default | Description |
|---|---|---|---|
layer_id |
int |
required | Target layer object ID |
paths |
list[str] |
required | SVG path data strings (e.g. ["M 0 0 L 100 100 Z"]) |
mode |
str |
"create" |
"create" (replace), "add" (union), "subtract" (difference) |
get_layer_mask(layer_id) -> dict¶
Get mask data for a layer.
def get_layer_mask(self, layer_id: int) -> dict[str, object]
transform_layer(layer_id, ...) -> str¶
Apply a 2D transform to a layer.
def transform_layer(
self,
layer_id: int,
translate_x: float = 0,
translate_y: float = 0,
rotate_deg: float = 0,
scale_x: float = 1,
scale_y: float = 1,
) -> str
All positional values are in pixels. Wire argument key for the layer is "id".
set_layer_warp(layer_id, top_left, top_right, bottom_right, bottom_left) -> str¶
Set perspective warp corners. Each corner is [x, y] in pixels. Wire argument key for the layer is "id".
def set_layer_warp(
self,
layer_id: int,
top_left: list[float],
top_right: list[float],
bottom_right: list[float],
bottom_left: list[float],
) -> str
Control methods¶
render(timeout=120.0) -> bool¶
Render all layers and wait for completion. Combines render_all() + wait_for_render().
def render(self, timeout: float = 120.0) -> bool
Returns True when rendering completed, False if timed out. The app continues rendering in the background on timeout.
render_all() -> str¶
Trigger a render without waiting.
def render_all(self) -> str
wait_for_render(timeout=120.0, poll_interval=0.5) -> bool¶
Poll until rendering finishes. Waits 0.5 s before the first check to let the render thread set its flag. Handles two scenarios:
- Render started and finished: detected by a
True -> Falsetransition inget_render_status. - Render already finished: detected by four consecutive
Falsereadings without ever seeingTrue.
Adds a 0.5 s settling delay after detecting completion.
def wait_for_render(self, timeout: float = 120.0, poll_interval: float = 0.5) -> bool
get_render_status() -> RenderStatus¶
Check whether the document is currently rendering.
def get_render_status(self) -> RenderStatus
undo() -> str / redo() -> str¶
Undo or redo the last action.
get_selection() -> dict | str¶
Get the currently selected objects.
def get_selection(self) -> dict[str, object] | str
select_object(object_id) -> str¶
Select an object by ID. Wire argument key is "id".
def select_object(self, object_id: int) -> str
Export shortcuts¶
Convenience methods that call export_document with the appropriate format and return the resolved absolute path. The dpi parameter is keyword-only.
def export_svg(self, path: str, *, dpi: int | None = None) -> Path
def export_pdf(self, path: str, *, dpi: int | None = None) -> Path
def export_png(self, path: str, *, dpi: int | None = None) -> Path
def export_jpeg(self, path: str, *, dpi: int | None = None) -> Path
def export_eps(self, path: str, *, dpi: int | None = None) -> Path
| Method | Format | Notes |
|---|---|---|
export_svg(path, *, dpi=None) |
"svg" |
Vector output |
export_pdf(path, *, dpi=None) |
"pdf" |
Vector output |
export_png(path, *, dpi=None) |
"png" |
Raster; lower DPI = faster export |
export_jpeg(path, *, dpi=None) |
"jpg" |
Raster; lower DPI = faster export |
export_eps(path, *, dpi=None) |
"eps" |
Encapsulated PostScript |
All return the resolved Path of the exported file.
svg() -> str¶
Export as SVG to a temporary file, read it, clean up, and return the SVG content as a string. Useful when you pipe SVG into other tools or return it from an API.
def svg(self) -> str
svg_parsed() -> svglab.Svg¶
Export as SVG and return a parsed svglab.Svg DOM object for traversal, editing, and rasterisation. Requires the [svg] extra (pip install vexy-lines-apy[svg]).
def svg_parsed(self) -> object # svglab.Svg at runtime
Raises ImportError if svglab is not installed.
Low-level method¶
call_tool(name, arguments=None) -> dict | str¶
Call any MCP tool by name. The server wraps results in content[0].text which may be JSON or plain text. This method attempts JSON parse first, then falls back to returning the raw string.
def call_tool(
self,
name: str,
arguments: dict[str, object] | None = None,
) -> dict[str, object] | str
Use this to call tools not yet wrapped as typed methods, or to pass through raw arguments:
# Direct tool call
result = vl.call_tool("get_document_info")
# With arguments
result = vl.call_tool("set_fill_params", {"id": 42, "params": {"color": "#ff0000"}})
MCPError¶
Raised when the MCP server returns an error, connection fails, or protocol validation fails.
class MCPError(Exception):
message: str # Human-readable error description
Common scenarios that raise MCPError:
| Cause | Example message |
|---|---|
| Connection refused | Cannot connect to Vexy Lines MCP server at 127.0.0.1:47384: ... |
| App not found (Windows) | Vexy Lines not found. Install it or pass auto_launch=False... |
| Unsupported platform | Auto-launch not supported on linux... |
| Server timeout | Vexy Lines launched but MCP server not ready after 30s... |
| Protocol mismatch | Protocol mismatch: client=2024-11-05, server=... |
| Server error | MCP error -32000: No document open |
| Connection closed | Connection closed by server |
| Invalid JSON | Invalid JSON from server: ... |
| Unexpected response | Unexpected response from new_document: ... |
from vexy_lines_api import MCPClient, MCPError
try:
with MCPClient(auto_launch=False) as vl:
vl.get_document_info()
except MCPError as e:
print(f"MCP failed: {e.message}")
Style functions¶
extract_style(path) -> Style¶
Parse a .lines file and return a Style containing the full group/layer/fill tree and document properties. Does not need the app: it works offline via the vexy-lines-py parser.
If Pillow is available, also extracts the pixel dimensions of the embedded source image into style.source_image_size.
def extract_style(path: str | Path) -> Style
apply_style(client, style, source_image, ...) -> str¶
Apply a style to a source image via MCP. Returns the SVG string.
def apply_style(
client: MCPClient,
style: Style,
source_image: str | Path,
*,
dpi: int = 72,
relative: bool = False,
render_timeout: float = 300.0,
style_mode: Literal["auto", "fast", "slow"] = "fast",
save_lines_to: str | Path | None = None,
) -> str
| Parameter | Type | Default | Description |
|---|---|---|---|
client |
MCPClient |
required | Connected MCP client |
style |
Style |
required | Style to apply |
source_image |
str \| Path |
required | Path to source image |
dpi |
int |
72 |
Document DPI (lower = faster; 72 good for video) |
relative |
bool |
False |
Scale spatial params to match target size |
render_timeout |
float |
300.0 |
Max seconds to wait for render (Fractals at high res may need 120-300 s) |
style_mode |
"auto" \| "fast" \| "slow" |
"fast" |
Transfer strategy (see below) |
save_lines_to |
str \| Path \| None |
None |
Save intermediate .lines to this path |
Style modes:
| Mode | Strategy |
|---|---|
"fast" |
XML source-image swap in the .lines file, then open in app. Preserves all fill params losslessly. If the source image has different dimensions, it is resized to match. Falls back to "slow" if the original .lines file is not available. |
"slow" |
Creates a new document via MCP, replicates the style tree by calling add_group / add_layer / add_fill / set_fill_params for every node. |
"auto" |
Uses "fast" if the target image pixel dimensions exactly match the embedded source image; otherwise "slow". |
create_styled_document(client, style, source_image, ...) -> None¶
Create a styled document in Vexy Lines without rendering or exporting. The document remains open in the app.
def create_styled_document(
client: MCPClient,
style: Style,
source_image: str | Path,
*,
dpi: int = 72,
relative: bool = False,
) -> None
save_and_consolidate(client, path, ...) -> None¶
Save, reopen, render, and save again. This improves .lines reliability after programmatic edits.
def save_and_consolidate(
client: MCPClient,
path: str | Path,
*,
render_timeout: float = 300.0,
) -> None
Sequence: save -> reopen -> render -> save.
interpolate_style(a, b, t) -> Style¶
Blend two compatible styles. t=0 returns style A, t=1 returns style B. Numeric fill parameters and hex colours interpolate linearly.
def interpolate_style(a: Style, b: Style, t: float) -> Style
The t value is clamped to [0.0, 1.0]. If styles are incompatible, logs a warning and returns a deep copy of style A.
styles_compatible(a, b) -> bool¶
Check whether two styles have matching tree structures. Required before interpolation.
def styles_compatible(a: Style, b: Style) -> bool
JobFolder¶
Persistent job folder for resumable export pipelines. Stores intermediate artifacts (.lines, .svg, frames) alongside the final output instead of using temporary directories that vanish on crash.
from vexy_lines_api.export import JobFolder
jf = JobFolder("output.mp4", force=False)
print(jf.path) # /absolute/path/to/output-vljob/
print(jf.output_stem) # "output"
print(jf.src_path) # /absolute/path/to/output-vljob/src/
Constructor:
JobFolder(output_path: str | Path, *, force: bool = False)
| Parameter | Type | Default | Description |
|---|---|---|---|
output_path |
str \| Path |
required | Final output destination (file or directory) |
force |
bool |
False |
Delete existing job folder and start fresh |
Path resolution:
| Output type | Example output path | Computed job folder |
|---|---|---|
File (.mp4, .png, .jpg, .jpeg, .svg, .lines) |
./out/video.mp4 |
./out/video-vljob/ |
| Directory | ./output/ |
./output-vljob/ |
Override with the VEXY_LINES_JOB_FOLDER environment variable.
Properties:
| Property | Type | Description |
|---|---|---|
path |
Path |
The job folder directory |
output_stem |
str |
Base name for naming intermediate files |
src_path |
Path |
{job_folder}/src/ directory for raw source frames |
Methods:
| Method | Signature | Returns | Description |
|---|---|---|---|
asset_path |
(name: str, ext: str) |
Path |
{job_folder}/{name}.{ext} |
frame_path |
(name: str, frame_num: int, ext: str, *, pad_width: int) |
Path |
{job_folder}/{name}--{NNN}.{ext} (zero-padded) |
frame_src_path |
(name: str, frame_num: int, ext: str, *, pad_width: int) |
Path |
{job_folder}/src/src--{name}--{NNN}.{ext} |
existing_frames |
(name: str, ext: str) |
set[int] |
Frame numbers already on disk |
existing_src_frames |
(name: str, ext: str) |
set[int] |
Source frame numbers already on disk |
copy_to_output |
(src_name: str, dest: str \| Path) |
Path |
Copy file from job folder to destination |
cleanup |
() |
None |
Delete the entire job folder |
Export pipeline¶
process_export(request, ...) -> None¶
Unified entry point for all export modes. Accepts either an ExportRequest dataclass or legacy positional arguments. Creates a JobFolder, dispatches to the appropriate processor, and optionally cleans up.
def process_export(
request: ExportRequest | str,
input_paths: list[str] | None = None,
style_path: str | None = None,
end_style_path: str | None = None,
output_path: str | None = None,
fmt: str | None = None,
size: str | None = None,
*,
audio: bool = True,
frame_range: tuple[int, int] | None = None,
relative_style: bool = False,
force: bool = False,
cleanup: bool = False,
abort_event: threading.Event | None = None,
on_progress: ProgressCallback | None = None,
on_complete: CompleteCallback | None = None,
on_error: ErrorCallback | None = None,
on_preview: PreviewCallback | None = None,
) -> None
ExportRequest¶
Canonical export request dataclass. Frozen (immutable after creation).
@dataclass(frozen=True)
class ExportRequest:
mode: ExportMode # "lines" | "images" | "video"
input_paths: list[str]
style_path: str | None
end_style_path: str | None
output_path: str
format: ExportFormat # "LINES" | "SVG" | "PNG" | "JPG" | "MP4"
size: str
audio: bool = True
frame_range: tuple[int, int] | None = None
relative_style: bool = False
style_mode: str = "fast"
force: bool = False # Force-clean job folder
cleanup: bool = False # Delete job folder after success
Callback types¶
ProgressCallback = Callable[[int, int, str], None] # (current, total, message)
CompleteCallback = Callable[[str], None] # (message)
ErrorCallback = Callable[[str], None] # (message)
PreviewCallback = Callable[[bytes], None] # (image_bytes)
Export errors¶
| Exception | When raised |
|---|---|
ExportAborted |
Abort event was set during processing |
ExportValidationError |
Missing required fields in legacy argument mode |
Video utilities¶
VideoInfo¶
Frozen dataclass with video metadata.
| Field | Type | Description |
|---|---|---|
width |
int |
Frame width in pixels |
height |
int |
Frame height in pixels |
fps |
float |
Frames per second |
total_frames |
int |
Total number of frames |
duration |
float |
Duration in seconds |
has_audio |
bool |
Whether the file contains an audio stream (requires ffprobe) |
probe(path) -> VideoInfo¶
Read video metadata using OpenCV. Audio detection requires ffprobe on PATH.
def probe(path: str) -> VideoInfo
svg_to_pil(svg_string, width, height) -> Image.Image¶
Rasterise an SVG string to a PIL Image via resvg_py. Patches mm dimensions to px before rasterising. Falls back to a blank white image if resvg_py is not installed.
def svg_to_pil(svg_string: str, width: int, height: int) -> Image.Image
process_video(input_path, output_path, ...) -> VideoInfo¶
Re-encode a video with optional trim and scale. No style transfer.
def process_video(
input_path: str,
output_path: str,
*,
start_frame: int = 0,
end_frame: int | None = None,
include_audio: bool = True,
size_multiplier: int = 1,
abort_event: Any = None,
on_frame_image: Any = None,
) -> VideoInfo
process_video_with_style(input_path, output_path, ...) -> VideoInfo¶
Per-frame style transfer. Each frame is: decoded -> saved as PNG -> styled via MCP -> rasterised via resvg_py -> encoded to output video. If end_style is provided, the style interpolates linearly across the frame range.
def process_video_with_style(
input_path: str,
output_path: str,
*,
style: Style | None = None,
end_style: Style | None = None,
start_frame: int = 0,
end_frame: int | None = None,
include_audio: bool = True,
size_multiplier: int = 1,
relative: bool = False,
style_mode: str = "auto",
abort_event: Any = None,
on_progress: Callable[[int, int], None] | None = None,
on_frame_image: Callable[[Image.Image], None] | None = None,
) -> VideoInfo
Media utilities¶
extract_preview_from_lines(filepath) -> bytes | None¶
Extract the embedded preview or source image from a .lines file. Returns PNG or JPEG bytes, or None on failure.
extract_frame(video_path, frame_number=1) -> Image.Image | None¶
Extract a single frame from a video file as a PIL Image. frame_number is 1-based.
fit_image_to_box(image, width, height) -> Image.Image¶
Scale a PIL Image to fit within width x height while preserving aspect ratio. Composites RGBA onto white, returns RGB.
truncate_start(text, max_chars=60) -> str¶
Truncate a string from the start, prepending "..." if truncated. For display in progress messages.
Dataclasses¶
Style¶
A transferable style extracted from a .lines document.
| Field | Type | Description |
|---|---|---|
groups |
list[GroupInfo \| LayerInfo] |
Top-level fill tree (from vexy_lines.types) |
props |
DocumentProps |
Document dimensions, DPI, and thickness/interval ranges |
source_path |
str \| None |
Path of the .lines file this style was extracted from |
source_image_size |
tuple[int, int] \| None |
(width, height) of the embedded source image in pixels |
StyleMode = Literal["auto", "fast", "slow"]: type alias for the style_mode parameter.
DocumentInfo¶
MCP response from get_document_info.
| Field | Type | Description |
|---|---|---|
width_mm |
float |
Document width in mm |
height_mm |
float |
Document height in mm |
resolution |
float |
DPI |
units |
str |
Measurement units (e.g. "mm") |
has_changes |
bool |
Unsaved changes flag |
LayerNode¶
Recursive tree node from get_layer_tree().
| Field | Type | Description |
|---|---|---|
id |
int |
Object ID for MCP calls |
type |
str |
"document", "group", "layer", or "fill" |
caption |
str |
Display name |
visible |
bool |
Visibility state |
fill_type |
str \| None |
Fill algorithm name (only when type == "fill") |
children |
list[LayerNode] |
Child nodes (empty for fills) |
Class method LayerNode.from_dict(d) constructs the tree from nested dicts returned by the server.
NewDocumentResult¶
MCP response from new_document.
| Field | Type | Description |
|---|---|---|
status |
str |
Status string (e.g. "ok") |
width |
float |
Width in pixels |
height |
float |
Height in pixels |
dpi |
float |
Resolution |
root_id |
int |
Root node object ID (use as parent_id for add_group) |
RenderStatus¶
MCP response from get_render_status.
| Field | Type | Description |
|---|---|---|
rendering |
bool |
Whether the document is currently rendering |
Constants¶
FILL_TYPES¶
FILL_TYPES: frozenset[str] = frozenset({
"linear", "wave", "circular", "radial", "spiral",
"scribble", "halftone", "handmade", "fractals", "trace",
})
All valid fill type names accepted by add_fill.
FILL_TYPE_PARAMS¶
FILL_TYPE_PARAMS: dict[str, tuple[str, ...]]
Maps each fill type to its valid parameter names for set_fill_params. Derived from the C++ paramsForType() in mcptools.cpp.
Base parameters (shared by all stroke-based fills except trace):
interval, angle, thickness, thickness_min, contrast, smoothness, break_up, break_down, dispersion, vdisp, color_mode, color_seg_len, color_seg_disp
Per-type additions:
| Fill type | Extra parameters |
|---|---|
linear |
(base only) |
wave |
wave_height, wave_length, wave_fade, phase, curviness |
circular |
x0, y0 |
radial |
x0, y0, r0, auto_distance, auto_randomize |
spiral |
x0, y0, direction_ccw |
scribble |
scribble_length, curviness, variety, complexity, rotation, scribble_pattern |
halftone |
cell_size, rotation, halftone_mode, rotation_mode, morphing, randomization |
handmade |
mode, parity_mode, is_filled, expand_lines, averaging |
fractals |
depth, kind |
trace |
smoothness, clearing_level, detailing, color_mode (no base params) |
Parameter name mapping (parser to MCP)¶
The .lines XML uses different attribute names from the MCP server. The style engine handles this translation internally via PARSER_TO_MCP_PARAMS:
| Parser field (XML) | MCP parameter | Notes |
|---|---|---|
interval |
interval |
Line spacing, stored in points |
angle |
angle |
Degrees |
multiplier |
thickness |
Stroke width multiplier, stored in mm |
thickness_min |
thickness_min |
Min stroke width, stored in mm |
smoothness |
contrast |
Tone-mapping curve |
uplimit |
break_up |
Upper brightness threshold |
downlimit |
break_down |
Lower brightness threshold |
dispersion |
dispersion |
Random offset, stored in points |
Note: XML thick_gap has no MCP equivalent and is not settable via the API.
Vexy Lines for Mac & Windows | Help & Docs | Batch GUI | CLI/MCP | API | .lines format
AI-assisted rename of layers & fills¶
Vexy Lines documents are built from layers and fills that often keep generic captions: Layer, Layer 2, Blended, Linear, or nothing at all. The vexy_lines_api.rename package looks at what each fill actually draws and renames it to something descriptive (e.g. car-on-road, top-sky-bridge, foreground-road-surface), then names each layer from the fills it contains.
It works by rendering each fill in isolation, asking a vision-language model (VLM) what it sees, and writing a renamed copy of the .lines file. Nothing about the original artwork changes, only the captions.
How it works¶
For a .lines file with N fills:
- Parse the structure with
vexy-lines-pyto enumerate every group, layer, and fill (with their object IDs). - Render the full artwork once (all fills, as authored). This is the "context" image.
- For each fill, render it in isolation: write a copy of the
.linesfile with only that fill (and its containing layer/groups) visible, open that file in Vexy Lines, render, and export. - Build an "inspection image" for the fill:
- find the bounding box of the visible (non-white) content in the single-fill render;
- composite the full artwork on top at 20% opacity for context;
- draw a 5px-thick red rectangle around the bounding box.
- Ask a VLM to describe, telegraphically in three words, where and what is inside the red rectangle.
- Slugify the description with
pathvalidate+python-slugifyinto a filesystem-safe caption. - Name each layer by asking the model for a short name from its fills' descriptions, then slugify it.
- Write the renamed
.linesby rewriting only thecaptionattributes. Every fill parameter, mask, mesh, and embedded image is preserved byte-for-byte.
Why visibility is baked into a file copy
Toggling visibility live over the MCP API (set_visible) does not change what the app exports: every per-fill render comes out identical. The renamer instead writes a copy of the .lines with visible="0" / visible="1" baked into the XML (via vexy_lines.set_visibility) and opens that file. The app honours the visible attribute on load, so each fill renders correctly in isolation.
Quick start¶
from vexy_lines_api import rename_lines
# Analyse, name, and write a renamed copy next to the input.
plan = rename_lines("road-12.lines") # -> road-12-renamed.lines
for fill in plan.fills:
print(f"fill {fill.object_id}: {fill.old_caption!r} -> {fill.new_caption!r} ({fill.description})")
for layer in plan.layers:
print(f"layer {layer.object_id}: {layer.old_caption!r} -> {layer.new_caption!r}")
Compute the plan without writing anything:
plan = rename_lines("road-12.lines", dry_run=True)
print(plan.to_dict()) # JSON-serialisable summary
Reuse an existing MCP connection and choose a work directory for artifacts:
from vexy_lines_api import MCPClient, rename_lines
with MCPClient() as vl:
plan = rename_lines("art.lines", "art-named.lines", client=vl, work_dir="./rename-work")
Configuring the model¶
The renamer talks to a single OpenAI-compatible /v1 endpoint and uses two models: a vision model to describe each fill and a text model to name each layer (they can be the same). Everything is configured from four environment variables, read by default_config():
| Setting | Environment variable | VLMConfig field |
|---|---|---|
| API base URL | VEXY_LINES_LLM_API_URL |
api_url |
| API key | VEXY_LINES_LLM_API_KEY |
api_key |
| Vision model | VEXY_LINES_LLM_MODEL_VISION |
model_vision |
| Text model | VEXY_LINES_VLM_MODEL |
model |
export VEXY_LINES_LLM_API_URL="http://127.0.0.1:1234/v1"
export VEXY_LINES_LLM_API_KEY="sk-..." # any value for local servers
export VEXY_LINES_LLM_MODEL_VISION="my-vision-model"
export VEXY_LINES_VLM_MODEL="my-text-model"
Any OpenAI-compatible server works: a locally-served model, a hosted gateway, or the OpenAI API itself. Override per call with a VLMConfig (or config_with_overrides, which the CLI flags and GUI settings both use):
from vexy_lines_api import rename_lines, VLMConfig
cfg = VLMConfig(
api_url="http://127.0.0.1:1234/v1",
api_key="not-needed",
model_vision="my-vision-model",
model="my-text-model",
)
plan = rename_lines("art.lines", config=cfg)
Artifacts¶
With save_artifacts=True (the default), the work directory (<stem>-rename/ beside the input, or work_dir) receives:
_full.png: the all-fills renderfill_<id>_single.png: each fill rendered in isolationfill_<id>_inspect.png: each inspection image (red box + faint context)rename-plan.json: the full plan
The per-fill .lines copies are intermediate and are always deleted after rendering.
API reference¶
rename_lines(lines_path, output_path=None, *, client=None, config=None, work_dir=None, dpi=72, dry_run=False, **plan_kwargs) -> RenamePlan¶
Analyse, name, and (unless dry_run) write a renamed .lines file. Creates and tears down an MCPClient when client is None. output_path defaults to <stem>-renamed.lines.
build_rename_plan(lines_path, client, *, config=None, work_dir=None, dpi=72, render_timeout=600.0, render_lines_png=None, describe=None, suggest=None, save_artifacts=True) -> RenamePlan¶
The core planner. The rendering, description, and layer-naming steps are injectable (render_lines_png(client, path), describe(png_bytes), suggest(list_of_phrases)) so the logic is testable without the app or a network.
apply_rename_plan(plan, output_path) -> int¶
Write a renamed copy of the plan's source file; returns the number of objects renamed. Equivalent to vexy_lines.rename_objects(plan.lines_path, output_path, plan.as_renames()).
Data classes¶
RenamePlan:lines_path,fills: list[FillRename],layers: list[LayerRename],full_image: bytes | None. Helpers:as_renames() -> dict[int, str],to_dict().FillRename:object_id,old_caption,fill_type,layer_id,description,new_caption.LayerRename:object_id,old_caption,fill_ids,description,new_caption.
VLM helpers (vexy_lines_api.rename.vlm)¶
VLMConfig/default_config(): connection settings (see above).describe_region(image_bytes, *, config=None, prompt=...) -> str: three-word description of the red-boxed region.suggest_layer_name(fill_descriptions, *, config=None) -> str: short layer name from its fills.to_slug(text) -> str:slugify(sanitize_filename(text)), with a built-in fallback when the optional packages are absent.
Inspection helpers (vexy_lines_api.rename.inspection)¶
content_bbox(image, *, bg=(255,255,255), threshold=16): bounding box of non-background content.make_inspection_image(single_fill, full_filled, *, overlay_opacity=0.2, rect_color=(255,0,0), rect_width=5) -> bytes: the composited inspection PNG.
File editing (vexy-lines-py)¶
vexy_lines.set_visibility(lines_path, output_path, {object_id: bool}): bakevisible=into a copy.vexy_lines.rename_objects(lines_path, output_path, {object_id: caption}): rewrite captions.
Installation¶
The AI extra pulls the LLM client and slug libraries:
pip install "vexy-lines-apy[ai]" # openai + pathvalidate + python-slugify
Using it from the CLI and GUI¶
- CLI:
vexy-lines-cli ai-rename road-12.lines. See the CLI docs. - GUI: Lines ▸ AI Rename Layers & Fills… in Vexy Lines Run.
See also¶
- Official Vexy Lines help: Document Structure · Fill Properties · Layers Panel · Export
- .lines parser reference in
vexy-lines-py - MCP Protocol: the tools the renamer drives
Style Engine¶
The style engine extracts, applies, and interpolates fill structures from .lines files. It bridges the parser (vexy-lines-py) and the MCP client into a high-level workflow: take a style from one file, apply it to a different image.
Concepts¶
A Style is a snapshot of the group/layer/fill tree and document properties from a .lines file. It contains everything needed to replicate the artistic look: which fill algorithms, in what order, with what parameters.
Extraction reads a .lines file and captures the tree. This works offline, with no app needed.
Application creates a new document in Vexy Lines via MCP, rebuilds the fill tree with matching parameters, renders, and exports SVG.
Interpolation blends two compatible styles at any ratio. Numeric parameters and hex colours interpolate linearly.
Extract a style¶
from vexy_lines_api import extract_style
style = extract_style("reference.lines")
# Inspect what's inside
for node in style.groups:
print(node)
print(f"Source: {style.source_path}")
print(f"Canvas: {style.props.width_mm} x {style.props.height_mm} mm")
print(f"DPI: {style.props.dpi}")
print(f"Source image size: {style.source_image_size}") # (width, height) or None
The returned Style is a deep copy, so modifying it does not affect the parsed document.
What's inside a Style¶
| Field | Type | Source |
|---|---|---|
groups |
list[GroupInfo \| LayerInfo] |
Deep copy of the document's fill tree |
props |
DocumentProps |
Canvas dimensions (mm), DPI, thickness/interval ranges |
source_path |
str \| None |
Path of the .lines file |
source_image_size |
tuple[int, int] \| None |
Pixel dimensions of the embedded source image (requires Pillow) |
DocumentProps fields:
| Field | Type | Description |
|---|---|---|
width_mm |
float |
Canvas width in millimetres |
height_mm |
float |
Canvas height in millimetres |
dpi |
int |
Document resolution (default 300) |
thickness_min |
float |
Minimum allowed stroke thickness (mm) |
thickness_max |
float |
Maximum allowed stroke thickness (mm) |
interval_min |
float |
Minimum allowed line spacing (mm) |
interval_max |
float |
Maximum allowed line spacing (mm) |
Edge case: no embedded source image¶
If the .lines file has no embedded source image (doc.source_image_data is None), source_image_size will be None. This affects:
style_mode="auto": falls back to"slow"mode since dimension comparison is impossible.style_mode="fast": falls back to"slow"if the original.linesfile is not available on disk.- Relative scaling: still works because it uses
DocumentPropsdimensions, not the source image size.
Apply a style to an image¶
from vexy_lines_api import MCPClient, extract_style, apply_style
style = extract_style("reference.lines")
with MCPClient() as vl:
svg = apply_style(vl, style, "photo.jpg", dpi=72)
with open("result.svg", "w") as f:
f.write(svg)
Style transfer modes¶
The style_mode parameter controls how the style is transferred:
| Mode | Strategy | Speed | Fidelity |
|---|---|---|---|
"fast" |
Copy the original .lines file, swap the source image at the XML level, open in app |
Fastest | Lossless -- all fills preserved exactly |
"slow" |
Create a new document via MCP, replicate the tree with add_group/add_layer/add_fill/set_fill_params |
Slower | Good -- but some params (like thick_gap) have no MCP equivalent |
"auto" |
Use "fast" if source and target images have identical pixel dimensions; otherwise "slow" |
Varies | Best available |
Fast mode internals:
- Copies the original
.linesfile to a temp location. - Calls
vexy_lines.editor.replace_source_image()to swap the embedded source image at the XML level. - If the target image has different dimensions, resizes it to match the original (downscale if larger, pad with white if smaller).
- Opens the modified
.linesin the app viaopen_document. - Renders and exports SVG.
Slow mode internals:
- Creates a new document with
new_document(source_image=..., dpi=...). - Walks the style tree and calls
add_group,add_layer,add_fillfor each node. - For each fill, converts parser parameters to MCP parameters (name mapping + unit conversion), then calls
set_fill_params. - Renders with
render(timeout=render_timeout). - Exports SVG with
svg().
Fallback behaviour:
- Fast mode falls back to slow if
style.source_pathisNoneor the file no longer exists on disk. - Auto mode falls back to slow if
style.source_image_sizeisNoneor image dimensions don't match.
Unit conversion in slow mode¶
The .lines XML stores fill parameters in physical units (mm, points). The MCP server expects pixels and converts internally. The style engine handles this translation:
| Parser field | MCP name | XML unit | Conversion to pixels |
|---|---|---|---|
interval |
interval |
points | value * (source_dpi / 72.0) |
multiplier |
thickness |
mm | value * (source_dpi / 25.4) |
thickness_min |
thickness_min |
mm | value * (source_dpi / 25.4) |
dispersion |
dispersion |
points | value * (source_dpi / 72.0) |
angle |
angle |
degrees | No conversion |
smoothness |
contrast |
unitless | No conversion |
uplimit |
break_up |
0--255 | No conversion |
downlimit |
break_down |
0--255 | No conversion |
The source_dpi is taken from style.props.dpi (defaulting to 72 if zero).
Render timeout¶
The render_timeout parameter (default 300 seconds) controls how long apply_style waits for rendering. Complex fills at high resolution may need the full 300 s:
| Fill type | Typical render time (1920x1080 @ 72 dpi) |
|---|---|
linear, wave |
< 2 s |
circular, radial, spiral |
2--5 s |
scribble, halftone |
5--15 s |
handmade |
5--30 s |
fractals (high depth) |
30--300 s |
trace |
10--60 s |
For batch processing, 72 dpi is the recommended target: it renders faster than 150 or 300 dpi with minimal visual difference in SVG output.
Relative mode¶
By default, apply_style uses absolute mode: fill parameters are applied as-is from the source style. If the target image is much larger or smaller than the original, the style may look different (e.g. line spacing appears tighter on a larger image).
Relative mode scales spatial parameters to match the target document size:
svg = apply_style(vl, style, "large_photo.jpg", dpi=72, relative=True)
Scale factor calculation¶
The scale factor is the geometric mean of the width and height ratios between source and target pixel dimensions:
source_w_px = style.props.width_mm * source_dpi / 25.4
source_h_px = style.props.height_mm * source_dpi / 25.4
scale_x = target_width / source_w_px
scale_y = target_height / source_h_px
scale = sqrt(scale_x * scale_y)
The geometric mean preserves the style's visual density regardless of aspect ratio changes. A scale of 1.0 means the dimensions match and no scaling occurs.
Which parameters are spatial¶
These parameters are multiplied by the scale factor in relative mode:
| Parser field | MCP name | Why it's spatial |
|---|---|---|
interval |
interval |
Line spacing -- mm |
multiplier |
thickness |
Stroke width multiplier -- mm |
thickness_min |
thickness_min |
Minimum stroke width -- mm |
dispersion |
dispersion |
Random perpendicular offset -- mm |
These parameters are not scaled (they are ratios, angles, or thresholds):
| Parser field | MCP name | Why it's not spatial |
|---|---|---|
angle |
angle |
Degrees -- scale-independent |
smoothness |
contrast |
Unitless curve parameter |
uplimit |
break_up |
Brightness threshold (0--255) |
downlimit |
break_down |
Brightness threshold (0--255) |
shear |
-- | Angle in degrees |
Edge case: very different aspect ratios¶
When the target image has a very different aspect ratio from the source (e.g. portrait source applied to landscape target), the geometric mean balances the scaling. However, angle-dependent fills like linear at angle=0 may appear visually different because the stroke direction interacts with the image composition differently. This is inherent to the geometry, and no scaling can fix it.
Edge case: zero source dimensions¶
If style.props.width_mm or height_mm is zero (corrupt file or missing metadata), relative scaling is disabled and a warning is logged. Same if the target document has zero dimensions. The function returns scale = 1.0 in both cases.
Interpolate two styles¶
Blend two styles to create smooth transitions. Both styles must be compatible: same tree structure, same fill types at each position.
from vexy_lines_api import extract_style, interpolate_style, styles_compatible
a = extract_style("painterly.lines")
b = extract_style("technical.lines")
# Check compatibility first
if styles_compatible(a, b):
mid = interpolate_style(a, b, t=0.5) # halfway blend
The t parameter controls the mix:
t value |
Result |
|---|---|
0.0 |
Identical to style A |
0.25 |
75% A, 25% B |
0.5 |
Halfway between A and B |
1.0 |
Identical to style B |
The value is clamped to [0.0, 1.0].
What interpolates¶
- Numeric fill params (
NUMERIC_PARAMS):interval,angle,thick_gap,smoothness,uplimit,downlimit,multiplier,base_width,dispersion,vert_disp,shear: all linearly interpolated - Colours: hex RGB (and RGBA) channels interpolated independently, clamped to
[0, 255] - Document props:
width_mm,height_mm,thickness_min,thickness_max,interval_min,interval_max: linearly interpolated
What doesn't interpolate¶
- DPI: kept from style A (integer device setting)
- Fill types: must match (no blending between algorithms)
- Tree structure: must match exactly
- Captions, visibility, masks, grid edges: taken from style A
source_path: set toNoneon interpolated styles
Compatibility check¶
Two styles are compatible when they share the exact same structure:
- Same number of top-level nodes
- Same node types at each position (group vs layer)
- Within each group, same number and types of children (recursive)
- Within each layer, same number of fills with matching fill types
from vexy_lines_api import styles_compatible
if not styles_compatible(a, b):
print("Styles have different structures -- can't interpolate")
If you pass incompatible styles to interpolate_style, it logs a warning and returns a deep copy of style A unchanged.
Animation workflow¶
Interpolation across a sequence of images creates smooth style transitions:
from vexy_lines_api import MCPClient, extract_style, interpolate_style, apply_style
start = extract_style("start.lines")
end = extract_style("end.lines")
images = ["frame_001.jpg", "frame_002.jpg", "frame_003.jpg"]
with MCPClient() as vl:
for i, img in enumerate(images):
t = i / max(len(images) - 1, 1)
style = interpolate_style(start, end, t)
svg = apply_style(vl, style, img, dpi=72)
with open(f"output_{i:03d}.svg", "w") as f:
f.write(svg)
The CLI command vexy-lines-cli style-transfer --style start.lines --end-style end.lines does this automatically.
Preserving intermediates¶
save_lines_to parameter¶
When save_lines_to is provided, the intermediate .lines file is saved during style transfer:
svg = apply_style(client, style, "photo.jpg", save_lines_to="styled.lines")
# styled.lines is now a valid .lines file with the style applied to photo.jpg
The path this takes depends on the style mode:
| Mode | Save mechanism | When it happens |
|---|---|---|
"fast" |
shutil.copy2() of the modified temp .lines file |
Before opening in the app |
"slow" |
client.save_document(path) after building the tree |
After render, before SVG export |
The fast path is a file copy (no MCP roundtrip), so it is faster and produces a .lines file that exactly matches what the app sees. The slow path calls save_document, which triggers the app's serialiser.
Job folder integration¶
The JobFolder system uses save_lines_to automatically. Every export saves the full artifact chain: .lines -> .svg -> final format (.png/.jpg/.mp4). This enables resume after a crash, because the pipeline skips frames whose artifacts already exist on disk.
create_styled_document and save_and_consolidate¶
For workflows where you need more control than apply_style provides:
from vexy_lines_api import MCPClient, extract_style
from vexy_lines_api.style import create_styled_document, save_and_consolidate
style = extract_style("reference.lines")
with MCPClient() as vl:
# Create the document but don't render or export
create_styled_document(vl, style, "photo.jpg", dpi=150)
# Make additional manual adjustments
vl.set_fill_params(42, angle=90)
vl.set_visible(43, visible=False)
# Save with consolidation (save -> reopen -> render -> save)
save_and_consolidate(vl, "final.lines", render_timeout=300)
The consolidation sequence improves .lines reliability by forcing the app to re-parse and re-render the file before the final write.
MCP Protocol¶
The Vexy Lines macOS/Windows app embeds an MCP server: a JSON-RPC 2.0 endpoint on localhost:47384 over raw TCP with newline-delimited messages. This document covers the wire protocol, all 25 tools, and the bridge binary for Claude Desktop/Cursor.
Connection¶
The server listens on 127.0.0.1:47384 by default. Connect with a TCP socket and perform the MCP handshake before calling tools.
MCPClient handles all of this automatically:
from vexy_lines_api import MCPClient
with MCPClient() as vl:
# handshake done, ready to call tools
info = vl.get_document_info()
Handshake protocol¶
The MCP handshake follows the Model Context Protocol specification:
Step 1. Client sends initialize:
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "vexy-lines-apy", "version": "1.0.0"}
}
}
Step 2. Server responds with capabilities:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}},
"serverInfo": {"name": "vexy-lines", "version": "..."}
}
}
The client validates that the server's protocolVersion matches "2024-11-05". A mismatch raises MCPError.
Step 3. Client sends notifications/initialized:
{"jsonrpc": "2.0", "method": "notifications/initialized"}
This is a notification (no id, no response expected). The connection is now ready for tool calls.
Wire format¶
Each message is a single line of JSON followed by \n:
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_document_info"}}
Responses follow the same format:
{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"{\"width_mm\":210,...}"}]}}
Tool results are wrapped in content[0].text which contains either a JSON string or plain text. The MCPClient.call_tool() method attempts JSON parse first, falling back to the raw string.
Calling a tool¶
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "set_fill_params",
"arguments": {
"id": 42,
"params": {"color": "#ff0000", "interval": 20}
}
}
}
The id field is an auto-incrementing integer assigned by the client. The name field selects the tool. arguments contains tool-specific parameters.
Listing available tools¶
After handshake, you can call tools/list to get the full tool catalog:
{"jsonrpc":"2.0","id":2,"method":"tools/list"}
The response contains a tools array with name, description, and JSON Schema for each tool's parameters. MCPClient does not call this automatically: it uses hardcoded method wrappers instead.
Coordinates¶
All spatial coordinates are in pixels at the document's DPI. Origin is top-left corner. The server converts to internal units automatically:
| Internal unit | Conversion | Applies to |
|---|---|---|
| Millimetres | px * 25.4 / dpi |
thickness, thickness_min |
| Points | px * 72 / dpi |
interval, dispersion |
| Degrees | No conversion | angle, rotate_deg |
| Unitless | No conversion | contrast, break_up, break_down, ratios |
The 25 tools¶
Document tools (5)¶
new_document¶
Create a new document with optional source image.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
width |
float |
no | inferred | Document width in pixels |
height |
float |
no | inferred | Document height in pixels |
dpi |
int |
no | 300 |
Document resolution |
source_image |
string |
no | -- | Absolute path to source image file |
When source_image is provided without width/height, the document dimensions are inferred from the image. The source image is embedded in the document.
Response (JSON): {"status": "ok", "width": 1920, "height": 1080, "dpi": 300, "root_id": 1}
open_document¶
Open a .lines file from disk.
| Parameter | Type | Required | Description |
|---|---|---|---|
path |
string |
yes | Absolute path to .lines file |
Response (text): status string.
save_document¶
Save the current document. Omit path to save in-place.
| Parameter | Type | Required | Description |
|---|---|---|---|
path |
string |
no | Absolute path for Save As |
Response (text): status string.
export_document¶
Export the document to a file.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
path |
string |
yes | -- | Absolute output path |
format |
string |
no | inferred from extension | "svg", "pdf", "png", "jpg", or "eps" |
dpi |
int |
no | document DPI | Override resolution for export |
Response (text): status string.
get_document_info¶
Get metadata about the current document. No parameters.
Response (JSON):
{
"width_mm": 210.0,
"height_mm": 297.0,
"resolution": 300.0,
"units": "mm",
"has_changes": false
}
Structure tools (5)¶
get_layer_tree¶
Get the full document tree. No parameters.
Response (JSON): recursive tree structure:
{
"id": 1,
"type": "document",
"caption": "My Document",
"visible": true,
"children": [
{
"id": 2,
"type": "group",
"caption": "Group 1",
"visible": true,
"children": [
{
"id": 3,
"type": "layer",
"caption": "Layer 1",
"visible": true,
"children": [
{
"id": 4,
"type": "fill",
"caption": "Linear Fill",
"visible": true,
"fill_type": "linear",
"children": []
}
]
}
]
}
]
}
Node types: "document" (root, one per document), "group", "layer", "fill" (leaf). Only "fill" nodes have fill_type set.
add_group¶
Add a new group to the document tree.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
parent_id |
int |
no | document root | Parent object ID |
caption |
string |
no | auto-generated | Group display name |
source_image_path |
string |
no | -- | Source image for the group |
Response (JSON): {"id": 5}: object ID of the created group.
add_layer¶
Add a new layer to a group.
| Parameter | Type | Required | Description |
|---|---|---|---|
group_id |
int |
yes | Parent group object ID |
Response (JSON): {"id": 6}: object ID of the created layer.
add_fill¶
Add a fill algorithm to a layer.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
layer_id |
int |
yes | -- | Parent layer object ID |
fill_type |
string |
yes | -- | Algorithm name (see table below) |
color |
string |
no | -- | Hex colour "#RRGGBB" or "#RRGGBBAA" |
params |
object |
no | -- | Initial fill parameters dict |
Valid fill_type values:
| Value | Algorithm | Description |
|---|---|---|
"linear" |
Linear strokes | Parallel straight lines at a given angle |
"wave" |
Sigmoid/wave strokes | Sinusoidal parallel lines |
"circular" |
Circular strokes | Concentric circles from a centre point |
"radial" |
Radial strokes | Lines radiating outward from a centre |
"spiral" |
Spiral strokes | Spiralling outward from a centre |
"scribble" |
Scribble strokes | Random hand-drawn-looking paths |
"halftone" |
Halftone dots | Dot/circle grid simulating halftone printing |
"handmade" |
Free-curve strokes | User-drawn or pattern-based curves |
"fractals" |
Peano/fractal curves | Space-filling fractal curves (slow to render at high depth) |
"trace" |
Traced area | Edge-tracing vectorisation of the source image |
Response (JSON): {"id": 7}: object ID of the created fill.
delete_object¶
Delete any object (group, layer, or fill) from the document tree.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
int |
yes | Object ID to delete |
Response (text): status string.
Fill parameter tools (2)¶
get_fill_params¶
Get all current parameters of a fill.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
int |
yes | Fill object ID |
Response (JSON): dict of parameter names to current values. The keys depend on the fill type (see parameter reference below).
set_fill_params¶
Set one or more parameters on a fill.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
int |
yes | Fill object ID |
params |
object |
yes | Dict of parameter names to new values |
All spatial values must be in pixels. The server converts internally. Example wire message:
{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "set_fill_params",
"arguments": {
"id": 42,
"params": {
"color": "#ff0000",
"interval": 20,
"angle": 45,
"thickness": 3.5,
"contrast": 0.8
}
}
}
}
Response (text): status string.
Visual tools (7)¶
set_source_image¶
Set the source image for a group.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
image_path |
string |
yes | -- | Absolute path to image file |
group_id |
int |
no | current group | Target group |
set_caption¶
Rename an object.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
int |
yes | Object ID |
caption |
string |
yes | New display name |
set_visible¶
Toggle object visibility.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
int |
yes | Object ID |
visible |
boolean |
yes | true to show, false to hide |
set_layer_mask¶
Set an SVG vector mask on a layer.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
layer_id |
int |
yes | -- | Target layer |
paths |
array[string] |
yes | -- | SVG path data strings |
mode |
string |
no | "create" |
"create" (replace), "add" (union), "subtract" (difference) |
SVG path data uses standard syntax: "M 0 0 L 100 0 L 100 100 L 0 100 Z". Coordinates are in pixels at document DPI, origin top-left.
get_layer_mask¶
Get the current mask data for a layer.
| Parameter | Type | Required | Description |
|---|---|---|---|
layer_id |
int |
yes | Target layer |
Response (JSON): mask data dict.
transform_layer¶
Apply a 2D affine transform to a layer.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
id |
int |
yes | -- | Target layer |
translate_x |
float |
no | 0 |
Horizontal translation in pixels |
translate_y |
float |
no | 0 |
Vertical translation in pixels |
rotate_deg |
float |
no | 0 |
Rotation angle in degrees |
scale_x |
float |
no | 1 |
Horizontal scale factor |
scale_y |
float |
no | 1 |
Vertical scale factor |
set_layer_warp¶
Set perspective warp on a layer by specifying four corner positions.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
int |
yes | Target layer |
top_left |
[float, float] |
yes | [x, y] coordinates in pixels |
top_right |
[float, float] |
yes | [x, y] coordinates in pixels |
bottom_right |
[float, float] |
yes | [x, y] coordinates in pixels |
bottom_left |
[float, float] |
yes | [x, y] coordinates in pixels |
Example: warp a 1000x1000 layer into a trapezoid:
vl.set_layer_warp(
layer_id=3,
top_left=[100, 0],
top_right=[900, 0],
bottom_right=[1000, 1000],
bottom_left=[0, 1000],
)
Control tools (6)¶
render_all¶
Trigger rendering of all layers. No parameters. Returns immediately. Use get_render_status to poll for completion.
Response (text): status string.
get_render_status¶
Check whether the document is currently rendering. No parameters.
Response (JSON): {"rendering": true} or {"rendering": false}.
Note: the rendering flag may not flip to true immediately after render_all. The Python client's wait_for_render() handles this by waiting 0.5 s before polling and detecting completion via consecutive false readings.
undo¶
Undo the last action. No parameters.
redo¶
Redo the last undone action. No parameters.
get_selection¶
Get the currently selected objects. No parameters.
Response (JSON): selection data dict or status string.
select_object¶
Select an object by ID.
| Parameter | Type | Required | Description |
|---|---|---|---|
id |
int |
yes | Object to select |
Fill parameter reference¶
Base parameters (all stroke fills except trace)¶
| Parameter | Type | Unit | Description |
|---|---|---|---|
interval |
float |
px (stored as pt) | Line spacing |
angle |
float |
degrees | Stroke angle |
thickness |
float |
px (stored as mm) | Stroke width multiplier |
thickness_min |
float |
px (stored as mm) | Minimum stroke width |
contrast |
float |
unitless | Tone-mapping curve steepness |
smoothness |
float |
unitless | Curve smoothness |
break_up |
float |
0--255 | Upper brightness threshold |
break_down |
float |
0--255 | Lower brightness threshold |
dispersion |
float |
px (stored as pt) | Random perpendicular offset |
vdisp |
float |
px | Random vertical displacement |
color_mode |
int |
enum | Colour mode (0=source, 2=static) |
color_seg_len |
float |
px | Colour segment length |
color_seg_disp |
float |
px | Colour segment dispersion |
color |
string |
hex | Fill colour ("#RRGGBB" or "#RRGGBBAA") |
Wave extras¶
| Parameter | Type | Description |
|---|---|---|
wave_height |
float |
Wave amplitude in pixels |
wave_length |
float |
Wavelength in pixels |
wave_fade |
float |
Fade factor |
phase |
float |
Phase offset |
curviness |
float |
Curve smoothness of wave |
Circular extras¶
| Parameter | Type | Description |
|---|---|---|
x0 |
float |
Centre X in pixels |
y0 |
float |
Centre Y in pixels |
Radial extras¶
| Parameter | Type | Description |
|---|---|---|
x0 |
float |
Centre X in pixels |
y0 |
float |
Centre Y in pixels |
r0 |
float |
Starting radius in pixels |
auto_distance |
bool |
Auto-calculate line distance |
auto_randomize |
bool |
Randomise ray distribution |
Spiral extras¶
| Parameter | Type | Description |
|---|---|---|
x0 |
float |
Centre X in pixels |
y0 |
float |
Centre Y in pixels |
direction_ccw |
bool |
Counter-clockwise direction |
Scribble extras¶
| Parameter | Type | Description |
|---|---|---|
scribble_length |
float |
Scribble path length |
curviness |
float |
Path curvature |
variety |
float |
Path variety |
complexity |
float |
Path complexity |
rotation |
float |
Pattern rotation in degrees |
scribble_pattern |
int |
Pattern preset index |
Halftone extras¶
| Parameter | Type | Description |
|---|---|---|
cell_size |
float |
Cell size in pixels |
rotation |
float |
Grid rotation in degrees |
halftone_mode |
int |
Dot shape mode |
rotation_mode |
int |
Rotation algorithm |
morphing |
float |
Shape morphing factor |
randomization |
float |
Random offset factor |
Handmade extras¶
| Parameter | Type | Description |
|---|---|---|
mode |
int |
Drawing mode preset |
parity_mode |
int |
Parity handling |
is_filled |
bool |
Fill closed paths |
expand_lines |
bool |
Expand line widths |
averaging |
float |
Smoothing factor |
Fractals extras¶
| Parameter | Type | Description |
|---|---|---|
depth |
int |
Recursion depth (higher = slower render) |
kind |
int |
Fractal type preset |
Trace parameters (standalone, no base params)¶
| Parameter | Type | Description |
|---|---|---|
smoothness |
float |
Edge smoothness |
clearing_level |
float |
Detail clearing threshold |
detailing |
float |
Detail level |
color_mode |
int |
Colour mode |
Error handling¶
Server errors are returned as JSON-RPC error objects:
{"jsonrpc": "2.0", "id": 3, "error": {"code": -32000, "message": "No document open"}}
MCPClient raises MCPError with the error code and message. Common error codes:
| Code | Meaning |
|---|---|
-32000 |
Application error (e.g. no document open, invalid object ID) |
-32600 |
Invalid request |
-32601 |
Method not found |
-32602 |
Invalid params |
-32603 |
Internal error |
Bridge binary¶
For Claude Desktop and Cursor integration, the vexy-lines-mcp bridge binary converts between stdio and TCP. It reads JSON-RPC from stdin, forwards to the TCP server at localhost:47384, and writes responses to stdout.
Claude Desktop setup¶
Add to your claude_desktop_config.json:
{
"mcpServers": {
"vexy-lines": {
"command": "/path/to/vexy-lines-mcp"
}
}
}
The bridge binary is bundled with the Vexy Lines app. Typical locations:
- macOS:
/Applications/Vexy Lines.app/Contents/Resources/vexy-lines-mcp - Windows:
C:\Program Files\Vexy Lines\vexy-lines-mcp.exe
Cursor setup¶
Add to .cursor/mcp.json in your project:
{
"mcpServers": {
"vexy-lines": {
"command": "/path/to/vexy-lines-mcp"
}
}
}
The bridge handles the MCP handshake transparently. All 25 tools are exposed with their JSON Schema parameter definitions via tools/list.
See the CLI docs for additional setup instructions and the vexy-lines-cli mcp-serve command, or run the installed vexy-lines-mcp script directly.
Examples¶
Open a document and inspect it¶
from vexy_lines_api import MCPClient
with MCPClient() as vl:
vl.open_document("artwork.lines")
info = vl.get_document_info()
print(f"{info.width_mm:.0f} x {info.height_mm:.0f} mm")
print(f"Resolution: {info.resolution} dpi")
print(f"Unsaved changes: {info.has_changes}")
Walk the layer tree¶
from vexy_lines_api import MCPClient
with MCPClient() as vl:
vl.open_document("artwork.lines")
root = vl.get_layer_tree()
def print_tree(node, depth=0):
indent = " " * depth
label = f"{node.type}: {node.caption}"
if node.fill_type:
label += f" [{node.fill_type}]"
if not node.visible:
label += " [hidden]"
print(f"{indent}{label} (id={node.id})")
for child in node.children:
print_tree(child, depth + 1)
print_tree(root)
Change fill colours and re-export¶
from vexy_lines_api import MCPClient
with MCPClient() as vl:
vl.open_document("artwork.lines")
root = vl.get_layer_tree()
# Find all fill nodes and set them to blue
def set_all_fills_blue(node):
if node.type == "fill":
vl.set_fill_params(node.id, color="#2563eb")
for child in node.children:
set_all_fills_blue(child)
set_all_fills_blue(root)
vl.render()
vl.export_png("blue_version.png", dpi=150)
Create a document from scratch¶
Build a complete document programmatically. No .lines template needed.
from vexy_lines_api import MCPClient
with MCPClient() as vl:
doc = vl.new_document(source_image="photo.jpg", dpi=150)
# Add a group, layer, and fill
group = vl.add_group(parent_id=doc.root_id, caption="My Group")
layer = vl.add_layer(group_id=group["id"])
fill = vl.add_fill(
layer_id=layer["id"],
fill_type="linear",
color="#333333",
params={"interval": 2.0, "angle": 45},
)
vl.render()
vl.export_svg("from_scratch.svg")
Build a multi-layer composition¶
Combine multiple fill algorithms on separate layers with different colours.
from vexy_lines_api import MCPClient
with MCPClient() as vl:
doc = vl.new_document(source_image="portrait.jpg", dpi=150)
group = vl.add_group(parent_id=doc.root_id, caption="Composition")
# Layer 1: coarse linear fill for shadows
layer1 = vl.add_layer(group_id=group["id"])
vl.add_fill(
layer_id=layer1["id"],
fill_type="linear",
color="#1a1a2e",
params={"interval": 8.0, "angle": 45, "thickness": 2.0, "contrast": 0.9},
)
# Layer 2: fine circular fill for midtones
layer2 = vl.add_layer(group_id=group["id"])
vl.add_fill(
layer_id=layer2["id"],
fill_type="circular",
color="#16213e",
params={"interval": 3.0, "thickness": 0.8, "x0": 500, "y0": 400},
)
# Layer 3: halftone overlay for highlights
layer3 = vl.add_layer(group_id=group["id"])
vl.add_fill(
layer_id=layer3["id"],
fill_type="halftone",
color="#e94560",
params={"cell_size": 12.0, "rotation": 15, "break_down": 180},
)
vl.render(timeout=60)
vl.export_svg("composition.svg")
vl.export_png("composition.png", dpi=300)
Style transfer: one style, many images¶
from pathlib import Path
from vexy_lines_api import MCPClient, extract_style, apply_style
style = extract_style("artistic.lines")
photos = sorted(Path("./photos").glob("*.jpg"))
output = Path("./output")
output.mkdir(exist_ok=True)
with MCPClient() as vl:
for photo in photos:
svg = apply_style(vl, style, photo, dpi=72)
(output / f"{photo.stem}.svg").write_text(svg)
print(f"Done: {photo.name}")
Style transfer with error handling and progress¶
from pathlib import Path
from vexy_lines_api import MCPClient, MCPError, extract_style, apply_style
style = extract_style("artistic.lines")
photos = sorted(Path("./photos").glob("*.jpg"))
output = Path("./output")
output.mkdir(exist_ok=True)
failed: list[tuple[str, str]] = []
with MCPClient(timeout=60.0) as vl:
for i, photo in enumerate(photos, 1):
print(f"[{i}/{len(photos)}] Processing {photo.name}...")
try:
svg = apply_style(
vl,
style,
photo,
dpi=72,
relative=True,
render_timeout=120.0,
save_lines_to=output / f"{photo.stem}.lines",
)
(output / f"{photo.stem}.svg").write_text(svg)
except MCPError as e:
print(f" FAILED: {e.message}")
failed.append((photo.name, e.message))
except Exception as e:
print(f" FAILED: {e}")
failed.append((photo.name, str(e)))
if failed:
print(f"\n{len(failed)} failures:")
for name, reason in failed:
print(f" {name}: {reason}")
else:
print(f"\nAll {len(photos)} images processed successfully.")
Style interpolation for animation¶
from vexy_lines_api import MCPClient, extract_style, interpolate_style, apply_style
start = extract_style("soft.lines")
end = extract_style("bold.lines")
frames = [f"frame_{i:04d}.jpg" for i in range(60)]
with MCPClient() as vl:
for i, frame in enumerate(frames):
t = i / max(len(frames) - 1, 1)
blended = interpolate_style(start, end, t)
svg = apply_style(vl, blended, frame, dpi=72)
with open(f"output/frame_{i:04d}.svg", "w") as f:
f.write(svg)
Export to multiple formats¶
from vexy_lines_api import MCPClient
with MCPClient() as vl:
vl.open_document("artwork.lines")
vl.render()
vl.export_svg("output.svg")
vl.export_pdf("output.pdf")
vl.export_png("output.png", dpi=300)
vl.export_jpeg("output.jpg", dpi=150)
vl.export_eps("output.eps")
Get SVG as a string¶
from vexy_lines_api import MCPClient
with MCPClient() as vl:
vl.open_document("artwork.lines")
vl.render()
svg_text = vl.svg()
print(f"SVG length: {len(svg_text)} chars")
# Parse with svglab (requires: pip install vexy-lines-apy[svg])
svg_obj = vl.svg_parsed()
Error handling¶
from vexy_lines_api import MCPClient, MCPError
try:
with MCPClient(auto_launch=False, timeout=5.0) as vl:
vl.get_document_info()
except MCPError as e:
print(f"Could not connect: {e.message}")
Low-level tool calls¶
Use call_tool to access any MCP tool directly, including tools not yet wrapped as typed methods.
from vexy_lines_api import MCPClient
with MCPClient() as vl:
vl.open_document("artwork.lines")
# Direct tool call -- returns parsed JSON dict or raw string
info = vl.call_tool("get_document_info")
print(info) # {'width_mm': 210.0, 'height_mm': 297.0, ...}
# Tool call with arguments
result = vl.call_tool("set_fill_params", {
"id": 42,
"params": {"color": "#ff0000", "interval": 20},
})
# List all available tools from the server
tools = vl.call_tool("tools/list")
Video processing with per-frame style transfer¶
from vexy_lines_api import extract_style, process_video_with_style
style = extract_style("engraving.lines")
info = process_video_with_style(
"input.mp4",
"output.mp4",
style=style,
start_frame=0,
end_frame=120, # first 4 seconds at 30fps
include_audio=True,
relative=True,
on_progress=lambda current, total: print(f"Frame {current}/{total}"),
)
print(f"Output: {info.width}x{info.height} @ {info.fps}fps, {info.total_frames} frames")
Video with style interpolation¶
Transition between two styles across the video duration.
from vexy_lines_api import extract_style, process_video_with_style
start_style = extract_style("watercolor.lines")
end_style = extract_style("woodcut.lines")
info = process_video_with_style(
"clip.mp4",
"transition.mp4",
style=start_style,
end_style=end_style,
include_audio=True,
relative=True,
style_mode="auto",
)
Using the JobFolder for resumable batch export¶
from pathlib import Path
from vexy_lines_api import MCPClient, extract_style, apply_style
from vexy_lines_api.export import JobFolder
style = extract_style("reference.lines")
photos = sorted(Path("./photos").glob("*.jpg"))
output_dir = Path("./output")
jf = JobFolder(output_dir)
with MCPClient() as vl:
existing = jf.existing_frames("styled", "svg")
for i, photo in enumerate(photos):
if i in existing:
print(f"Skipping frame {i} (already exists)")
continue
svg_path = jf.frame_path("styled", i, "svg", pad_width=4)
lines_path = jf.frame_path("styled", i, "lines", pad_width=4)
svg = apply_style(vl, style, photo, dpi=72, save_lines_to=lines_path)
svg_path.write_text(svg)
print(f"Frame {i}: {svg_path.name}")
# When done, optionally clean up intermediates
# jf.cleanup()
Export pipeline with callbacks¶
Use process_export for GUI/CLI integration with progress reporting.
import threading
from vexy_lines_api.export import ExportRequest, process_export
request = ExportRequest(
mode="images",
input_paths=["photo1.jpg", "photo2.jpg", "photo3.jpg"],
style_path="artistic.lines",
end_style_path=None,
output_path="./output/",
format="SVG",
size="1x",
relative_style=True,
style_mode="fast",
force=False,
cleanup=False,
)
abort = threading.Event()
process_export(
request,
abort_event=abort,
on_progress=lambda cur, total, msg: print(f"[{cur}/{total}] {msg}"),
on_complete=lambda msg: print(f"Done: {msg}"),
on_error=lambda msg: print(f"Error: {msg}"),
)
Style creation and consolidation¶
Create a styled document, make manual adjustments, then save with the consolidation pattern.
from vexy_lines_api import MCPClient, extract_style
from vexy_lines_api.style import create_styled_document, save_and_consolidate
style = extract_style("base.lines")
with MCPClient() as vl:
create_styled_document(vl, style, "photo.jpg", dpi=150, relative=True)
# Tweak individual fills after the style is applied
tree = vl.get_layer_tree()
for child in tree.children:
for layer in child.children:
for fill in layer.children:
if fill.fill_type == "linear":
vl.set_fill_params(fill.id, angle=90)
# Save -> reopen -> render -> save (ensures file integrity)
save_and_consolidate(vl, "custom.lines", render_timeout=120)
Integration with Claude Desktop¶
If you configure Vexy Lines as an MCP server in Claude Desktop via the vexy-lines-mcp bridge, Claude can call the tools directly. The Python client and the bridge share the same underlying TCP connection to the app.
To use both simultaneously, ensure only one connection is active at a time:
from vexy_lines_api import MCPClient
# Close any Claude Desktop MCP connection first (or use a separate document)
with MCPClient() as vl:
vl.open_document("artwork.lines")
# ... work with the document ...
vl.save_document()
# Connection released -- Claude Desktop can reconnect
The bridge binary location depends on your platform. See MCP Protocol for setup instructions.
Changelog¶
2026-04-01 — Job Folder System (Issue #617)¶
- feat: New
JobFolderclass inexport/job.py— persistent intermediate file storage alongside output, replacing temp directories. Supports resume, force-clean, and cleanup modes. - feat:
ExportRequestgainsforceandcleanupfields for controlling job folder lifecycle. - feat:
apply_style()gainssave_lines_toparameter — saves the styled.linesdocument to a specified path during style transfer. - feat: All export processors (lines, images, video) now save the complete artifact chain to the job folder:
.lines→.svg→ final format (.png/.jpg/.mp4). - feat: Video export now extracts all requested source frames into the job folder before styling or assembly, then reuses those cached raw frames for resume.
- feat: Source video frames now live under
src/with thesrc--prefix (src/src--{stem}--{NNN}.png), and job-folder frame artifacts use zero-padded numbering derived from the video's total frame count. - feat:
VEXY_LINES_JOB_FOLDERenvironment variable overrides computed job folder path. - test: 24 new tests for
JobFolder— path resolution, frame naming, resume detection, force/cleanup, copy-to-output.
Previous releases¶
See GitHub releases for earlier versions.
Topics¶
Find related pages by topic.
