Table of Contents
Vexy Lines for Mac & Windows | Download | Buy | Batch GUI | CLI/MCP | API | .lines format
vexy-lines-py¶
Parse Vexy Lines .lines vector art files in pure Python.
What it does¶
A .lines file holds everything Vexy Lines needs to reproduce a piece of vector artwork: the layer tree (groups, layers, fills with algorithm parameters), document properties, and optionally the original source image and a rendered preview, all packed into XML.
This package reads that XML and gives you typed Python dataclasses. It can also replace the embedded source image to reuse a fill style with different content.
Quick start¶
from vexy_lines import parse, GroupInfo, LayerInfo
doc = parse("artwork.lines")
print(doc.caption, doc.dpi) # "My Art" 300
print(doc.props.width_mm, "x", doc.props.height_mm, "mm")
# Walk the layer tree
for node in doc.groups:
if isinstance(node, GroupInfo):
for child in node.children:
if isinstance(child, LayerInfo):
for fill in child.fills:
p = fill.params
print(p.fill_type, p.color, f"interval={p.interval}")
Extract embedded images¶
Every .lines file can contain a JPEG source image (the original photo) and a PNG preview (the rendered result). You can pull them out without opening the app:
from vexy_lines import extract_source_image, extract_preview_image
extract_source_image("artwork.lines", "source.jpg")
extract_preview_image("artwork.lines", "preview.png")
Replace the source image¶
Swap the source photo in an existing .lines file to reuse its fill style with new content:
from vexy_lines import replace_source_image
replace_source_image("template.lines", "new_photo.jpg", "output.lines")
Rename objects and toggle visibility¶
Edit a .lines file by object_id (from GroupInfo/LayerInfo/FillNode) while preserving everything else byte-for-byte. Both write to output_path (use the same path to edit in place) and return the count changed:
from vexy_lines import rename_objects, set_visibility
# Rewrite captions of groups, layers, and/or fills.
rename_objects("artwork.lines", "artwork.lines", {1: "Background", 10: "Sky lines"})
# Bake per-object visibility into a copy: only fill 10 stays visible.
set_visibility("artwork.lines", "fill_10_only.lines", {10: True, 11: False, 12: False})
set_visibility writes the visible="0"/"1" attribute (absent = visible). Toggling it live over the app's MCP API does not change what the app exports, but re-opening a baked copy does. This is how the AI-rename feature renders one fill in isolation.
Parse from a string¶
When you already have the XML in memory:
from vexy_lines import parse_string
doc = parse_string(xml_content)
Why this package exists¶
Vexy Lines is a macOS/Windows app that transforms raster images into vector artwork using 14 fill algorithms. The .lines file format stores everything, but the XML is undocumented.
This package decodes that format so you can:
- Inspect artwork metadata without the app
- Extract embedded images for thumbnailing or cataloguing
- Feed fill parameters into automation pipelines
- Replace source images to reuse fill styles with different content
- Rename objects by ID and bake per-object visibility into a copy (powers the AI-rename feature)
- Build tools on top of the parsed data (style transfer, interpolation, batch processing)
Next steps¶
- Installation: install options and requirements
- API Reference: every class, function, and constant
- File Format: how
.linesXML is structured - Examples: real-world usage patterns
Installation¶
Requirements¶
- Python 3.11 or newer
- No C extensions, no system libraries, no app required
Install from PyPI¶
pip install vexy-lines-py
Or with uv:
uv add vexy-lines-py
Runtime dependencies¶
| Package | Why |
|---|---|
loguru |
Structured debug logging (silent by default) |
pillow |
Image handling for replace_source_image() |
Two dependencies. Both are pure Python or ship pre-built wheels for all major platforms.
Verify the install¶
from vexy_lines import parse
print("vexy-lines-py is ready")
Development install¶
Clone the repo and install in editable mode:
git clone https://github.com/vexyart/vexy-lines.git
cd vexy-lines/vexy-lines-py
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 run lint:style
Format code:
uvx hatch fmt
Platform support¶
Works everywhere Python runs. The parser is pure Python using only xml.etree.ElementTree, base64, zlib, and struct from the standard library. The pillow dependency is needed only for replace_source_image().
Tested on macOS, Linux, and Windows. CPython and PyPy.
API Reference¶
Functions¶
parse(path) -> LinesDocument¶
Parse a .lines file and return a fully populated LinesDocument.
from vexy_lines import parse
doc = parse("artwork.lines")
print(doc.caption, doc.dpi)
Args:
| Parameter | Type | Description |
|---|---|---|
path |
str \| Path |
Path to the .lines file |
Returns: LinesDocument with the full layer tree, document properties, and decoded images.
Raises:
FileNotFoundError: path does not existxml.etree.ElementTree.ParseError: file is not valid XML
Type hint:
def parse(path: str | Path) -> LinesDocument: ...
parse_string(xml) -> LinesDocument¶
Parse a .lines XML string and return a LinesDocument. Use it when you already have the XML content in memory (from a network response, database, or test fixture) rather than a file path.
from vexy_lines import parse_string
xml = open("artwork.lines").read()
doc = parse_string(xml)
print(doc.caption, doc.dpi)
Args:
| Parameter | Type | Description |
|---|---|---|
xml |
str |
Raw XML string from a .lines file |
Returns: LinesDocument with the full layer tree, document properties, and decoded images.
Raises:
xml.etree.ElementTree.ParseError: string is not valid XML
Type hint:
def parse_string(xml: str) -> LinesDocument: ...
extract_source_image(path, output) -> Path¶
Parse a .lines file and save the embedded JPEG source image.
from vexy_lines import extract_source_image
extract_source_image("artwork.lines", "source.jpg")
Args:
| Parameter | Type | Description |
|---|---|---|
path |
str \| Path |
Path to the .lines file |
output |
str \| Path |
Destination path for the JPEG |
Returns: Resolved output Path.
Raises:
FileNotFoundError:.linesfile does not existValueError: no source image embedded in the file
extract_preview_image(path, output) -> Path¶
Parse a .lines file and save the embedded PNG preview image.
from vexy_lines import extract_preview_image
extract_preview_image("artwork.lines", "preview.png")
Args:
| Parameter | Type | Description |
|---|---|---|
path |
str \| Path |
Path to the .lines file |
output |
str \| Path |
Destination path for the PNG |
Returns: Resolved output Path.
Raises:
FileNotFoundError:.linesfile does not existValueError: no preview image embedded in the file
replace_source_image(lines_path, new_image_path, output_path, *, target_size) -> Path¶
Replace the embedded source image in a .lines file, writing the result to a new file. All fill parameters, layers, groups, masks, and document settings are preserved. The new image is converted to JPEG if needed (the .lines format requires JPEG for source images).
Requires the pillow package (installed as a dependency).
from vexy_lines import replace_source_image
replace_source_image(
"template.lines",
"new_photo.png",
"output.lines",
target_size=(1025, 1025),
)
Args:
| Parameter | Type | Description |
|---|---|---|
lines_path |
str \| Path |
Path to the source .lines file (template) |
new_image_path |
str \| Path |
Path to the replacement image (JPEG, PNG, etc.) |
output_path |
str \| Path |
Where to write the modified .lines file |
target_size |
tuple[int, int] \| None |
Optional (width, height) to resize the new image to fit |
When target_size is provided and the new image dimensions differ, the image is scaled to fit within the target dimensions (maintaining aspect ratio) and centred on a white canvas. White padding is correct for Vexy Lines: fill algorithms treat white as "no strokes".
Returns: Resolved output Path.
Raises:
FileNotFoundError: either input file does not existValueError: the.linesfile has no<SourcePict>element
Type hint:
def replace_source_image(
lines_path: str | Path,
new_image_path: str | Path,
output_path: str | Path,
*,
target_size: tuple[int, int] | None = None,
) -> Path: ...
rename_objects(lines_path, output_path, renames) -> int¶
Rename groups, layers, and/or fills in a .lines file by object ID. For every element carrying an object_id attribute whose value is a key in renames, sets its caption attribute to the new name. Everything else (fill parameters, masks, image data, document settings) is preserved byte-for-byte (the file is copied first, then only the matched caption attributes are rewritten).
Object IDs come from the parsed tree: GroupInfo.object_id, LayerInfo.object_id, and FillNode.object_id. href reference elements never carry an object_id of their own, so only the canonical definition of each object is touched. See the official Layers Panel help for how captions appear in the app.
from vexy_lines import rename_objects
# Rename layer 1 and fill 10 in place; returns the count actually changed.
n = rename_objects("artwork.lines", "artwork.lines", {1: "Background", 10: "Sky lines"})
print(f"Renamed {n} object(s)")
Args:
| Parameter | Type | Description |
|---|---|---|
lines_path |
str \| Path |
Path to the source .lines file |
output_path |
str \| Path |
Where to write the renamed file; may equal lines_path to edit in place |
renames |
Mapping[int, str] |
Mapping of object_id to the new caption string |
Returns: The number of elements actually renamed. A caption already equal to its target is not counted. An empty renames mapping copies the file unchanged and returns 0.
Raises:
FileNotFoundError:lines_pathdoes not exist
Type hint:
def rename_objects(
lines_path: str | Path,
output_path: str | Path,
renames: Mapping[int, str],
) -> int: ...
set_visibility(lines_path, output_path, visible) -> int¶
Set the visible attribute on objects in a .lines file by object ID. For every element whose object_id is a key in visible, sets the visible attribute to "1" (True) or "0" (False). Everything else is preserved byte-for-byte, with the same preservation, in-place, empty-mapping, and FileNotFoundError semantics as rename_objects.
Vexy Lines stores per-object visibility as a visible="0" / visible="1" XML attribute (absent means visible). Toggling visibility live over the app's MCP API does not change what the app exports; baking the attribute into a copy of the file and re-opening it does. This is how the AI-rename feature renders one fill in isolation: write a copy with every other fill set to visible="0", open that file, and export. See Document Structure for how groups, layers, and fills nest.
from vexy_lines import set_visibility
# Write a copy with only fill 10 visible (everything else hidden).
n = set_visibility("artwork.lines", "fill_10_only.lines", {10: True, 11: False, 12: False})
print(f"Changed visibility on {n} object(s)")
Args:
| Parameter | Type | Description |
|---|---|---|
lines_path |
str \| Path |
Path to the source .lines file |
output_path |
str \| Path |
Where to write the modified file; may equal lines_path to edit in place |
visible |
Mapping[int, bool] |
Mapping of object_id to desired visibility |
Returns: The number of elements whose visible attribute was changed.
Raises:
FileNotFoundError:lines_pathdoes not exist
Type hint:
def set_visibility(
lines_path: str | Path,
output_path: str | Path,
visible: Mapping[int, bool],
) -> int: ...
Dataclasses¶
LinesDocument¶
Everything parsed from a .lines file.
| Field | Type | Description |
|---|---|---|
caption |
str |
Project name from the root <Project> element |
version |
str |
Vexy Lines app version that created the file |
dpi |
int |
Document resolution (default 300) |
props |
DocumentProps |
Canvas dimensions and stroke limits |
groups |
list[GroupInfo \| LayerInfo] |
Top-level layer tree |
source_image_data |
bytes \| None |
Decoded JPEG bytes of the source image |
preview_image_data |
bytes \| None |
Decoded PNG bytes of the preview |
All fields have defaults, so LinesDocument() creates a valid empty document.
DocumentProps¶
Canvas dimensions and stroke range limits from the <Document> element.
| Field | Type | Default | Description |
|---|---|---|---|
width_mm |
float |
0.0 |
Canvas width in millimetres |
height_mm |
float |
0.0 |
Canvas height in millimetres |
dpi |
int |
300 |
Document resolution |
thickness_min |
float |
0.0 |
Minimum stroke thickness (mm) |
thickness_max |
float |
0.0 |
Maximum stroke thickness (mm) |
interval_min |
float |
0.0 |
Minimum line spacing (mm) |
interval_max |
float |
0.0 |
Maximum line spacing (mm) |
Maps from XML attributes: thicknessMin -> thickness_min, thicknessMax -> thickness_max, intervalMin -> interval_min, intervalMax -> interval_max.
GroupInfo¶
A group (<LrSection> element) containing layers and sub-groups.
| Field | Type | Default | Description |
|---|---|---|---|
caption |
str |
-- | Group name |
object_id |
int \| None |
None |
Unique ID, or None for href references |
expanded |
bool |
True |
Whether the group is expanded in the UI |
children |
list[GroupInfo \| LayerInfo] |
[] |
Child nodes |
LayerInfo¶
A single layer (<FreeMesh> element) with fills and optional mask.
| Field | Type | Default | Description |
|---|---|---|---|
caption |
str |
-- | Layer name |
object_id |
int \| None |
None |
Unique ID |
visible |
bool |
True |
Whether the layer is visible |
mask |
MaskInfo \| None |
None |
Mask settings |
fills |
list[FillNode] |
[] |
Ordered fill algorithms |
grid_edges |
list[dict[str, str]] |
[] |
Mesh deformation data |
Each entry in grid_edges is a dict with a "type" key ("row_grid_edge" or "col_grid_edge") plus all XML attributes as string key-value pairs.
FillNode¶
A single fill algorithm instance inside a layer.
| Field | Type | Default | Description |
|---|---|---|---|
xml_tag |
str |
-- | Original XML tag (e.g. "LinearStrokesTmpl") |
caption |
str |
-- | Fill name as shown in the UI |
params |
FillParams |
-- | All fill parameters |
object_id |
int \| None |
None |
Unique ID |
FillParams¶
Numeric and colour parameters for a fill algorithm.
| Field | Type | Default | Description |
|---|---|---|---|
fill_type |
str |
-- | Algorithm name (e.g. "linear", "circular") |
color |
str |
-- | Normalised hex colour (#RRGGBB or #RRGGBBAA) |
interval |
float |
0.0 |
Line spacing in mm |
angle |
float |
0.0 |
Stroke angle in degrees |
thickness |
float |
0.0 |
Stroke thickness (from XML thick_gap) |
thickness_min |
float |
0.0 |
Minimum thickness (from XML base_width) |
smoothness |
float |
0.0 |
Curve smoothness factor |
uplimit |
float |
0.0 |
Upper brightness threshold (0--255) |
downlimit |
float |
255.0 |
Lower brightness threshold (0--255) |
multiplier |
float |
1.0 |
Width multiplier |
base_width |
float |
0.0 |
Baseline stroke width in mm |
dispersion |
float |
0.0 |
Random perpendicular offset |
shear |
float |
0.0 |
Shear distortion angle in degrees |
raw |
dict[str, str] |
{} |
All original XML attributes |
raw includes every attribute from the XML element, including algorithm-specific keys not promoted to named fields (e.g. vert_disp, enbl_dotted, type_conv). See the File Format reference for the complete attribute catalogue.
MaskInfo¶
Mask settings from a <MaskData> element.
| Field | Type | Default | Description |
|---|---|---|---|
mask_type |
int |
0 |
Mask mode: 0 = none, 1 = raster |
invert |
bool |
False |
Whether the mask is inverted |
tolerance |
float |
0.0 |
Edge tolerance |
Maps from XML: invert_mask -> invert (any value other than "0" is True).
Constants¶
FILL_TAG_MAP¶
dict[str, str] mapping XML element tags to human-readable fill type names.
from vexy_lines import FILL_TAG_MAP
FILL_TAG_MAP["LinearStrokesTmpl"] # "linear"
FILL_TAG_MAP["SigmoidStrokesTmpl"] # "wave"
FILL_TAG_MAP["CircleStrokesTmpl"] # "circular"
FILL_TAG_MAP["RadialStrokesTmpl"] # "radial"
FILL_TAG_MAP["SpiralStrokesTmpl"] # "spiral"
FILL_TAG_MAP["ScribbleStrokesTmpl"] # "scribble"
FILL_TAG_MAP["HalftoneStrokesTmpl"] # "halftone"
FILL_TAG_MAP["FreeCurveStrokesTmpl"] # "handmade"
FILL_TAG_MAP["PeanoStrokesTmpl"] # "fractals"
FILL_TAG_MAP["TracedAreaTmpl"] # "trace"
FILL_TAG_MAP["SourceStrokes"] # "source_strokes"
Note: FreeCurveStrokesTmpl resolves to "trace" at parse time when type_conv="9". The map holds the base mapping ("handmade"); the parser applies the override.
FILL_TAGS¶
set[str] of all recognised XML fill element tag names (keys of FILL_TAG_MAP).
from vexy_lines import FILL_TAGS
"LinearStrokesTmpl" in FILL_TAGS # True
"UnknownElement" in FILL_TAGS # False
NUMERIC_PARAMS¶
list[str] of XML attribute names whose values are numeric and can be interpolated between two fills of the same type.
from vexy_lines import NUMERIC_PARAMS
print(NUMERIC_PARAMS)
# ['interval', 'angle', 'thick_gap', 'smoothness', 'uplimit',
# 'downlimit', 'multiplier', 'base_width', 'dispersion',
# 'vert_disp', 'shear']
These are the XML attribute names (not the Python field names). Most map directly to FillParams fields; vert_disp is only available in FillParams.raw.
Error handling¶
The parser is lenient where possible and strict where data integrity matters.
Lenient behaviour:
- Missing numeric attributes default to
0.0(or field-specific defaults like255.0fordownlimit) - Missing
color_namedefaults to"#000000" - Unparseable numeric strings fall back to the default value
- Missing
<Document>element produces a defaultDocumentProps() - Failed source/preview image decoding logs a warning and sets the field to
None
Strict behaviour:
parse()raisesFileNotFoundErrorif the path does not existparse()raisesET.ParseErrorif the XML is malformedextract_source_image()/extract_preview_image()raiseValueErrorif no image is embedded
Pattern for safe parsing:
from vexy_lines import parse
try:
doc = parse("artwork.lines")
except FileNotFoundError:
print("File not found")
except Exception as e:
print(f"Parse error: {e}")
else:
if doc.source_image_data:
print(f"Source image: {len(doc.source_image_data)} bytes")
else:
print("No source image embedded")
Thread safety¶
The parser is stateless and safe to call from multiple threads concurrently. Each call to parse() or parse_string() creates its own XML tree and dataclass instances with no shared mutable state.
The loguru logger used internally is thread-safe.
replace_source_image() performs file I/O (copy + XML write) and is not safe to call concurrently on the same output file.
Performance¶
Parsing performance depends on file size, which is dominated by embedded images:
- XML parsing:
xml.etree.ElementTree(C-accelerated in CPython) handles the structural parsing. Typical layer trees with hundreds of fills parse in under 10ms. - Image decoding: The base64 decode + zlib decompress of the source image is the main cost. A 5MB JPEG source adds ~50--100ms.
- Memory: The decoded JPEG and PNG bytes are held in memory as
bytesobjects on theLinesDocument. For files with large embedded images, expect memory usage roughly 2x the uncompressed image size (compressed + decompressed copies during decode, then only decompressed is retained).
Tips for large files:
- If you only need metadata (fills, layer tree), the overhead is the image decoding. The parser currently always decodes images when present. Access
doc.groupsanddoc.propswithout touching the image fields. - For batch processing many files, parse in a process pool to parallelise the zlib decompression.
parse_string()avoids the file I/O overhead when you already have the XML in memory.
.lines File Format¶
The .lines format is XML. A single file holds the complete Vexy Lines project: layer tree, fill parameters, document properties, the original source image, and a rendered preview.
This page documents every element and attribute observed in real .lines files, verified against the vexy-lines-py parser source code and test data.
Document structure¶
<Project>
<form_data> (internal, ignored by parser)
<Objects> layer tree root
<LrSection> group
<Objects>
<FreeMesh> layer
<Objects>
<*StrokesTmpl> fill
<MaskData> optional mask
<row_grid_edge> mesh row
<col_grid_edge> mesh column
<SourcePict> embedded source image (JPEG, compressed)
<Document> canvas dimensions, stroke limits
<Workspace> viewport state (ignored by parser)
<PreviewDoc> embedded preview image (PNG)
</Project>
Root element: <Project>¶
<Project caption="My Art" version="3.0.1" app="vexylines" dpi="300"
object_id="2" expanded="1" type="16777602"
is_transparent="0" fusion_of_templates="0">
| Attribute | Type | Description |
|---|---|---|
caption |
string | Project name |
version |
string | Vexy Lines app version that created the file |
app |
string | Application identifier, always "vexylines" |
dpi |
int | Document resolution in dots per inch |
object_id |
int | Unique object ID for the root node |
expanded |
"0" / "1" |
Whether the root is expanded in the UI |
type |
int | Internal type code (16777602) |
is_transparent |
"0" / "1" |
Background transparency flag |
fusion_of_templates |
"0" / "1" |
Internal rendering flag |
The parser reads caption, version, and dpi. Other attributes are preserved in the XML but not promoted to dataclass fields.
<Document> element¶
Canvas dimensions and global stroke limits.
<Document width_mm="210.0" height_mm="297.0" dpi="300"
thicknessMin="0" thicknessMax="5.66"
intervalMin="0.283" intervalMax="5.66"
termNodesMax="62.16"
current_unit="0"
source_opacity="0.44"
project_back_color="4294967295"
selected_color="4288616596"
frame_color="4281492680"
freehand_color="4280221440"
single_workspace="0"
type="16777219" />
| Attribute | Type | Parsed | Description |
|---|---|---|---|
width_mm |
float | yes | Canvas width in millimetres |
height_mm |
float | yes | Canvas height in millimetres |
dpi |
int | yes | Document resolution (default 300) |
thicknessMin |
float | yes | Minimum stroke thickness (mm) |
thicknessMax |
float | yes | Maximum stroke thickness (mm) |
intervalMin |
float | yes | Minimum line spacing (mm) |
intervalMax |
float | yes | Maximum line spacing (mm) |
termNodesMax |
float | no | Maximum terminal node size |
current_unit |
int | no | Display unit: 0=mm, 1=cm, 2=inches, 3=points |
source_opacity |
float | no | Source image overlay opacity (0.0--1.0) |
project_back_color |
decimal ARGB | no | Background colour (decimal integer) |
selected_color |
decimal ARGB | no | Selection highlight colour |
frame_color |
decimal ARGB | no | Frame border colour |
freehand_color |
decimal ARGB | no | Freehand drawing colour |
single_workspace |
"0" / "1" |
no | Single workspace mode flag |
type |
int | no | Internal type code (16777219) |
Unparsed attributes are accessible via the raw XML when using xml.etree.ElementTree directly.
Layer tree¶
The <Objects> element directly under <Project> is the root of the layer tree. It contains two node types: groups and layers.
Groups: <LrSection>¶
<LrSection caption="Group 1" object_id="5" expanded="1"
type="16777602" dpi="0"
is_transparent="0" fusion_of_templates="0">
<Objects>
<!-- child layers and sub-groups -->
</Objects>
</LrSection>
| Attribute | Type | Parsed | Description |
|---|---|---|---|
caption |
string | yes | Group name |
object_id |
int | yes | Unique ID |
expanded |
"0" / "1" |
yes | Whether group is expanded in the UI tree |
type |
int | no | Internal type code (16777602) |
dpi |
int | no | Group-level DPI override (usually 0) |
is_transparent |
"0" / "1" |
no | Transparency flag |
fusion_of_templates |
"0" / "1" |
no | Template fusion flag |
Groups nest recursively. A group's <Objects> child can contain both <FreeMesh> (layers) and nested <LrSection> (sub-groups).
Layers: <FreeMesh>¶
<FreeMesh caption="Layer 1" object_id="936" visible="1"
expanded="1" selected="1"
type="16793857" dpi="0"
z_mask_enbl="0" z_mask_mode="0" z_mask_quality="6"
thickness_mul="1" interval_mul="1" rotation_mul="0"
is_unbounded="1" mask_by_form="0"
cx="114.84" cy="153.12">
<Objects>
<!-- fill elements -->
</Objects>
<MaskData ... />
<row_grid_edge ... />
<col_grid_edge ... />
</FreeMesh>
| Attribute | Type | Parsed | Description |
|---|---|---|---|
caption |
string | yes | Layer name |
object_id |
int | yes | Unique ID |
visible |
"0" / "1" |
yes | "0" hides the layer; absent means visible |
expanded |
"0" / "1" |
no | Tree expansion state |
selected |
"0" / "1" |
no | Whether layer is selected |
type |
int | no | Internal type code (16793857) |
dpi |
int | no | Layer-level DPI |
cx, cy |
float | no | Layer centre coordinates (pixels) |
thickness_mul |
float | no | Thickness multiplier for all fills in this layer |
interval_mul |
float | no | Interval multiplier for all fills |
rotation_mul |
float | no | Rotation multiplier |
z_mask_enbl |
"0" / "1" |
no | Z-depth mask enabled |
z_mask_mode |
int | no | Z-depth mask mode |
z_mask_quality |
int | no | Z-depth mask quality (1--10) |
is_unbounded |
"0" / "1" |
no | Whether fills extend beyond canvas |
mask_by_form |
"0" / "1" |
no | Mask by vector form |
locked |
"0" / "1" |
no | Editing lock |
Fill elements¶
Each fill is an XML element inside a layer's <Objects>. The tag name identifies the algorithm.
Fill tag to algorithm mapping¶
| XML Tag | fill_type |
Algorithm |
|---|---|---|
LinearStrokesTmpl |
linear |
Parallel straight lines |
SigmoidStrokesTmpl |
wave |
Sinusoidal wave strokes |
CircleStrokesTmpl |
circular |
Concentric circles |
RadialStrokesTmpl |
radial |
Lines radiating from centre |
SpiralStrokesTmpl |
spiral |
Spiral from centre outward |
ScribbleStrokesTmpl |
scribble |
Randomised scribble paths |
HalftoneStrokesTmpl |
halftone |
Grid-based halftone dots/shapes |
FreeCurveStrokesTmpl |
handmade |
Freehand curves (default) |
FreeCurveStrokesTmpl (with type_conv="9") |
trace |
Edge-tracing curves |
PeanoStrokesTmpl |
fractals |
Space-filling Peano/fractal curves |
TracedAreaTmpl |
trace |
Traced area fills |
SourceStrokes |
source_strokes |
Strokes imported from source vector |
The FreeCurveStrokesTmpl tag covers two algorithms. When its type_conv attribute equals "9", the parser resolves it to "trace". All other type_conv values (including absent) resolve to "handmade".
Common fill attributes¶
These attributes appear on most or all fill element tags. The parser promotes a subset to named FillParams fields; the rest are available in FillParams.raw.
Core parameters (promoted to FillParams fields)¶
| XML Attribute | FillParams Field |
Type | Default | Description |
|---|---|---|---|---|
color_name |
color |
#AARRGGBB |
"#000000" |
Stroke colour (see Colour encoding) |
interval |
interval |
float | 0.0 |
Line spacing in mm |
angle |
angle |
float | 0.0 |
Stroke angle in degrees |
thick_gap |
thickness |
float | 0.0 |
Stroke thickness / gap ratio |
base_width |
thickness_min, base_width |
float | 0.0 |
Baseline stroke width in mm |
smoothness |
smoothness |
float | 0.0 |
Curve smoothness factor |
uplimit |
uplimit |
float | 0.0 |
Upper brightness threshold (0--255) |
downlimit |
downlimit |
float | 255.0 |
Lower brightness threshold (0--255) |
multiplier |
multiplier |
float | 1.0 |
Width multiplier applied to strokes |
dispersion |
dispersion |
float | 0.0 |
Random perpendicular offset |
shear |
shear |
float | 0.0 |
Shear distortion angle in degrees |
Note: base_width maps to both FillParams.thickness_min and FillParams.base_width (they read the same XML attribute).
Width and thickness control (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
vert_disp |
float | Vertical displacement of strokes |
enbl_width |
"0" / "1" |
Enable width variation from source image brightness |
smooth_width |
float | Width variation smoothness (higher = smoother transitions) |
width_mode |
int | Width calculation mode: 0=standard, 2=alternate |
static_stroke |
"0" / "1" |
Use uniform stroke width (ignore brightness) |
Bas-relief effect (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
enbl_basrelief |
"0" / "1" |
Enable bas-relief shading effect |
bsrf_rise |
float | Bas-relief height/rise factor |
bsrf_smoothness |
float | Bas-relief smoothness |
bsrf_front |
"0" / "1" |
Bas-relief front lighting |
Dotted line control (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
enbl_dotted |
"0" / "1" |
Enable dotted/dashed stroke mode |
null_in_cut |
"0" / "1" |
Insert nulls at intersection cuts |
null_tails_count |
float | Number of null segments at stroke tails |
invert_dotted |
"0" / "1" |
Invert dot/dash pattern |
length_black |
float | Length of the dash (black) segment |
length_white |
float | Length of the gap (white) segment |
edged_dashes |
"0" / "1" |
Sharpen dash edges |
edged_strokes |
"0" / "1" |
Sharpen stroke edges |
dashes_cup |
"0" / "1" |
Rounded dash caps |
dashes_orientation |
int | Dash orientation mode |
dash_comb_thick |
"0" / "1" |
Combine dash with thickness variation |
dash_dots_mode |
int | Dash/dot combination mode |
Edge and contour (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
is_edge |
"0" / "1" |
Enable edge detection mode |
edge_global |
"0" / "1" |
Use global edge detection |
edge_mul |
float | Edge detection multiplier |
Colour mode (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
color_mode |
int | 0=solid, 1=source palette, 2=single, 3=monochrome |
color_seg_len |
float | Colour segment length for multi-colour modes |
channel_mode |
int | Channel interpretation mode |
channel_invert |
"0" / "1" |
Invert channel for brightness calculation |
channel_mask |
int | Channel mask for brightness extraction |
invert_cont |
"0" / "1" |
Invert contrast mapping |
invert_wdth |
"0" / "1" |
Invert width mapping |
Image processing (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
image_contrast |
float | Pre-processing contrast adjustment |
image_brightness |
float | Pre-processing brightness adjustment |
Stroke caps and joins (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
curve_cup_front |
"0" / "1" |
Rounded cap at stroke front |
curve_cup_back |
"0" / "1" |
Rounded cap at stroke back |
thick_cup |
"0" / "1" |
Thickness-dependent caps |
join_cup |
"0" / "1" |
Rounded joins |
Clipping bounds (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
cb_t |
float | Clipping bound top |
cb_b |
float | Clipping bound bottom |
cb_l |
float | Clipping bound left |
cb_r |
float | Clipping bound right |
White segment control (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
white_down_limit |
float | Lower brightness limit for white gaps (0--255) |
white_max_len |
float | Maximum white segment length |
white_min_const_len |
float | Minimum constant white segment length |
black_max_len |
float | Maximum black segment length |
black_min_constlen |
float | Minimum constant black segment length |
Miscellaneous (in raw)¶
| XML Attribute | Type | Description |
|---|---|---|
object_id |
int | Unique object ID |
caption |
string | Fill display name |
type |
int | Internal type code |
selected |
"0" / "1" |
Whether fill is currently selected |
visible |
"0" / "1" |
Whether fill is visible |
expanded |
"0" / "1" |
Tree node expansion state |
locked |
"0" / "1" |
Editing lock |
parity |
"0" / "1" |
Stroke parity (alternating direction) |
crossed_dir |
"0" / "1" |
Enable cross-hatching (strokes in both directions) |
random_continuity |
"0" / "1" |
Randomise stroke continuity |
min_length |
float | Minimum stroke length before culling |
push_strength |
float | Stroke push/repulsion strength |
Algorithm-specific attributes¶
Beyond the common set, individual fill types carry attributes specific to their algorithm. These are always available in FillParams.raw.
FreeCurveStrokesTmpl (handmade / trace)¶
| XML Attribute | Type | Description |
|---|---|---|
type_conv |
int | Sub-algorithm: 9=trace, 0=manual, 1=blend, 2=balanced |
averaning |
float | Curve averaging/smoothing passes |
is_clone_strokes |
"true" / "false" |
Clone strokes from another fill |
is_expand_curves |
"0" / "1" |
Expand curves to outlines |
is_imported |
"0" / "1" |
Strokes were imported from external data |
is_ordered |
"0" / "1" |
Maintain stroke ordering |
HalftoneStrokesTmpl (halftone)¶
| XML Attribute | Type | Description |
|---|---|---|
halftone_mode |
int | Grid mode: 0=square, 1=hexagonal |
cell_size |
float | Halftone cell width |
cell_height |
float | Halftone cell height |
morphing_mode |
int | Shape morphing: 0=none, 1=circle-to-square |
contrast |
float | Halftone contrast adjustment |
rotation_mode |
int | Cell rotation mode |
rotation_mul |
float | Cell rotation multiplier |
randomization_dot |
float | Random dot position offset |
base_x0, base_y0 |
float | Grid origin X/Y |
base_x1, base_y1 |
float | Grid end X/Y |
ScribbleStrokesTmpl (scribble)¶
| XML Attribute | Type | Description |
|---|---|---|
complexity |
float | Scribble path complexity |
curviness |
float | Scribble curve amplitude |
variety |
float | Stroke variation amount |
scribble_length |
float | Target scribble path length |
trace_density |
float | Tracing density |
TracedAreaTmpl (trace area)¶
| XML Attribute | Type | Description |
|---|---|---|
clearing_level |
float | Area clearing/simplification level |
detailing |
float | Detail preservation level |
mask_gen |
"0" / "1" |
Generate mask from traced area |
SourceStrokes (source strokes)¶
Shares the same attribute set as FreeCurveStrokesTmpl. Source strokes represent imported vector paths that are treated as fill data.
SigmoidStrokesTmpl (wave)¶
Uses the common attribute set. Wave behaviour is controlled by smoothness (wave amplitude) and interval (wave period). Not observed in the current test data set; the tag name is defined in FILL_TAG_MAP.
CircleStrokesTmpl (circular), RadialStrokesTmpl (radial), SpiralStrokesTmpl (spiral)¶
These use the common attribute set. The tag name determines the geometric pattern. Not observed in the current test data; their fill tag names are defined in FILL_TAG_MAP.
PeanoStrokesTmpl (fractals)¶
Uses the common attribute set. The Peano space-filling curve behaviour is determined by interval (recursion scale) and smoothness (curve smoothing). No additional algorithm-specific attributes observed beyond the common set.
Colour encoding¶
Vexy Lines uses two colour formats in XML attributes:
Hex: #AARRGGBB (alpha first)¶
The native format stores alpha before the RGB channels: the opposite of the CSS convention.
| Raw value | Meaning | Parser output |
|---|---|---|
#ff112233 |
Opaque (ff alpha), RGB 112233 |
#112233 |
#80112233 |
50% alpha (80), RGB 112233 |
#11223380 |
#aabbcc |
Already 6-digit, no alpha | #aabbcc (pass-through) |
The parser normalises #AARRGGBB to standard #RRGGBB (stripping ff alpha) or #RRGGBBAA (moving non-opaque alpha to the end).
Decimal ARGB integer¶
Some non-fill attributes (like project_back_color, pen_color, selected_color) store colour as a decimal integer encoding ARGB:
4294967295 = 0xFFFFFFFF = opaque white
4278190080 = 0xFF000000 = opaque black
Bit layout:
bits 31-24: alpha (0x00=transparent, 0xFF=opaque)
bits 23-16: red
bits 15-8: green
bits 7-0: blue
The parser's _normalise_color() function handles both formats and outputs #RRGGBB or #RRGGBBAA.
Embedded images¶
Source image: <SourcePict>¶
The original raster image used as input for the fill algorithms. Encoded with compression.
<SourcePict caption="__is_empty" width="1025" height="1025"
object_id="927" type="16777729"
h_resolution="4.1667" v_resolution="4.1667">
<ImageData width="1025" height="1025" pict_format="jpg">
base64-encoded-data
</ImageData>
</SourcePict>
<SourcePict> attributes:
| Attribute | Type | Description |
|---|---|---|
width |
int | Image width in pixels |
height |
int | Image height in pixels |
caption |
string | Internal label (often "__is_empty") |
object_id |
int | Unique ID |
type |
int | Internal type code (16777729) |
h_resolution |
float | Horizontal resolution (pixels per mm) |
v_resolution |
float | Vertical resolution (pixels per mm) |
<ImageData> attributes:
| Attribute | Type | Description |
|---|---|---|
width |
int | Image width in pixels |
height |
int | Image height in pixels |
pict_format |
string | Always "jpg" |
Decoding the image data:
base64 decode -> [ 4-byte big-endian uint32: uncompressed size ] [ zlib-compressed JPEG ]
| |
v v
used for validation zlib.decompress() -> raw JPEG bytes
In Python:
import base64, struct, zlib
raw = base64.b64decode(image_data_text)
expected_size = struct.unpack(">I", raw[:4])[0]
jpeg_bytes = zlib.decompress(raw[4:])
Preview image: <PreviewDoc>¶
The rendered preview thumbnail. There is no compression wrapper, only base64-encoded PNG.
<PreviewDoc width="984" height="984"
pict_format="png" pict_compressed="0">
base64-encoded-PNG
</PreviewDoc>
| Attribute | Type | Description |
|---|---|---|
width |
int | Preview width in pixels |
height |
int | Preview height in pixels |
pict_format |
string | Always "png" |
pict_compressed |
"0" / "1" |
Compression flag (always "0" in observed files) |
Decoding:
import base64
png_bytes = base64.b64decode(preview_doc_text)
<MaskData> element¶
Each layer can have an optional mask controlling which areas produce strokes.
<MaskData mask_type="1" invert_mask="0" tolerance="0"
joined_mask="1" transsparency="0"
mask_resolution_dpi="0" />
| Attribute | Type | Parsed | Description |
|---|---|---|---|
mask_type |
int | yes | 0=none, 1=raster mask |
invert_mask |
"0" / "1" |
yes | Invert the mask (strokes where mask is dark) |
tolerance |
float | yes | Edge tolerance for mask application |
joined_mask |
"0" / "1" |
no | Join mask with adjacent layers |
transsparency |
float | no | Mask transparency (note: typo is in the format) |
mask_resolution_dpi |
int | no | Mask rasterisation DPI (0=use document DPI) |
Mesh deformation¶
Layers can have warp meshes stored as <row_grid_edge> and <col_grid_edge> elements. These define a grid of control points that deform the fill output.
<row_grid_edge width="0" allocation_t="0.5"
compressed="1" enbl_width_func="1"
nodes_cnt="2" object_id="15073"
pen_color="4278190080" type="16786432">
<Nodes>base64-encoded-control-point-data</Nodes>
</row_grid_edge>
| Attribute | Type | Description |
|---|---|---|
width |
float | Edge line width |
allocation_t |
float | Allocation parameter (0.0--1.0) |
compressed |
"0" / "1" |
Whether <Nodes> data is compressed |
enbl_width_func |
"0" / "1" |
Enable width function on this edge |
nodes_cnt |
int | Number of control point nodes |
object_id |
int | Unique ID for this edge |
pen_color |
decimal ARGB | Edge display colour (decimal integer) |
type |
int | Internal type code (16786432) |
The <Nodes> child contains base64-encoded binary control point data. When compressed="1", the data is zlib-compressed after base64 decoding.
The parser captures grid edges as raw attribute dictionaries in LayerInfo.grid_edges:
layer.grid_edges[0]
# {"type": "row_grid_edge", "width": "0", "allocation_t": "0.5", ...}
Rows define horizontal grid lines; columns define vertical grid lines. Together they form the deformation mesh.
Href references¶
Some elements use href_id to reference objects defined elsewhere in the tree. These are lightweight pointer nodes: they carry only href_id and type attributes with no children.
<FreeMesh type="16793857" href_id="936" />
<LrSection type="16777602" href_id="5" />
<SourcePict type="16777729" href_id="927">
The parser detects href elements via the presence of href_id and skips them. They appear in the <Document> element's internal <model> tree (a mirror of the layer tree used by the app's rendering engine).
Internal elements (ignored by parser)¶
| Element | Description |
|---|---|
<form_data> / <data> |
Internal form/bezier path data. Present on <Project>, <LrSection>, <FreeMesh>, and fill elements. |
<Workspace> |
Viewport state: scroll position, zoom, visibility toggles. |
<Images> |
Image container inside <Document>. |
<model> |
Internal rendering model (contains href copies of the layer tree). |
<doc_pict> |
Internal document picture reference. |
Complete example¶
A minimal but structurally complete .lines file:
<?xml version="1.0" encoding="utf-8"?>
<Project caption="Example" version="3.0.1" app="vexylines" dpi="300"
object_id="1" expanded="1" type="16777602">
<Objects>
<LrSection caption="Background" object_id="2" expanded="1"
type="16777602">
<Objects>
<FreeMesh caption="Lines Layer" object_id="10" visible="1"
type="16793857" thickness_mul="1" interval_mul="1">
<Objects>
<LinearStrokesTmpl caption="Linear" object_id="100"
color_name="#ff000000" interval="2.28" angle="40"
thick_gap="0" base_width="0.16" smoothness="0"
uplimit="0" downlimit="255" multiplier="1"
dispersion="0" shear="0" vert_disp="0"
enbl_width="1" width_mode="0" smooth_width="2"
enbl_basrelief="0" bsrf_rise="1" bsrf_smoothness="2"
enbl_dotted="0" null_in_cut="1" null_tails_count="1"
channel_invert="0" channel_mode="0" color_mode="3"
crossed_dir="1" type="16781569" />
</Objects>
<MaskData mask_type="1" invert_mask="0" tolerance="0" />
<row_grid_edge width="0" allocation_t="0.5" compressed="1"
nodes_cnt="2" object_id="200"
pen_color="4278190080" type="16786432"
enbl_width_func="1">
<Nodes>base64data</Nodes>
</row_grid_edge>
<col_grid_edge width="0" allocation_t="0.5" compressed="1"
nodes_cnt="2" object_id="201"
pen_color="4278190080" type="16786432"
enbl_width_func="1">
<Nodes>base64data</Nodes>
</col_grid_edge>
</FreeMesh>
</Objects>
</LrSection>
</Objects>
<SourcePict caption="__is_empty" width="1025" height="1025"
object_id="900" type="16777729"
h_resolution="4.1667" v_resolution="4.1667">
<ImageData width="1025" height="1025" pict_format="jpg">
<!-- base64( uint32-BE-uncompressed-size + zlib(JPEG) ) -->
</ImageData>
</SourcePict>
<Document width_mm="86.78" height_mm="86.78" dpi="300"
thicknessMin="0" thicknessMax="5.66"
intervalMin="0.28" intervalMax="5.66"
project_back_color="4294967295" type="16777219" />
<PreviewDoc width="984" height="984"
pict_format="png" pict_compressed="0">
<!-- base64( raw PNG ) -->
</PreviewDoc>
</Project>
Fill type internal type codes¶
Each fill tag has an associated type attribute containing an integer type code. These are not used by the parser but are part of the format:
| Fill Tag | type value |
|---|---|
LinearStrokesTmpl |
16781569 |
HalftoneStrokesTmpl |
16781574 |
PeanoStrokesTmpl |
16781576 |
TracedAreaTmpl |
16781577 |
FreeCurveStrokesTmpl |
16781578 |
ScribbleStrokesTmpl |
16781579 |
SourceStrokes |
16781578 |
Data Model¶
vexy-lines-py represents a parsed .lines document as a tree of typed
dataclasses. All types are importable from vexy_lines directly.
Type hierarchy¶
LinesDocument
├── caption: str project name
├── version: str app version that wrote the file
├── dpi: int root-level DPI (from <Project dpi="...">)
├── props: DocumentProps canvas dimensions and stroke limits
├── groups: list[GroupInfo | LayerInfo] top-level layer tree
├── source_image_data: bytes | None first document-scope JPEG (convenience)
├── source_images: list[SourceImageInfo] all decoded <SourcePict> payloads
└── preview_image_data: bytes | None decoded PNG preview thumbnail
DocumentProps
├── width_mm: float
├── height_mm: float
├── dpi: int
├── thickness_min: float
├── thickness_max: float
├── interval_min: float
└── interval_max: float
GroupInfo maps to <LrSection>
├── caption: str
├── object_id: int | None
├── expanded: bool
└── children: list[GroupInfo | LayerInfo] recursive
LayerInfo maps to <FreeMesh>
├── caption: str
├── object_id: int | None
├── visible: bool
├── mask: MaskInfo | None
├── fills: list[FillNode]
└── grid_edges: list[dict[str, str]] raw row_grid_edge / col_grid_edge attrs
FillNode one fill algorithm instance
├── xml_tag: str original XML element name
├── caption: str
├── object_id: int | None
├── params: FillParams
└── image_filters: list[ImageFilterEntry]
FillParams
├── fill_type: str e.g. "linear", "circular", "handmade"
├── color: str normalised hex: #RRGGBB or #RRGGBBAA
├── interval: float line spacing in mm
├── angle: float stroke angle in degrees
├── thickness: float XML thick_gap
├── thickness_min: float XML base_width
├── smoothness: float
├── uplimit: float upper brightness threshold (0–255)
├── downlimit: float lower brightness threshold (0–255)
├── multiplier: float width multiplier
├── base_width: float same source as thickness_min
├── dispersion: float random perpendicular offset
├── shear: float shear distortion angle in degrees
└── raw: dict[str, str] all XML attributes (unmodified)
ImageFilterEntry one entry in a fill's filter chain
├── type_id: int upstream numeric type (0–9)
├── name: str MCP-compatible name e.g. "brightness"
├── params: dict[str, bool|int|float|str] typed parameter values
└── raw: dict[str, str] original XML attributes
MaskInfo from <MaskData>
├── mask_type: int 0=none, 1=raster
├── invert: bool
└── tolerance: float
SourceImageInfo one decoded <SourcePict> payload
├── index: int 1-based position in source_images list
├── data: bytes decoded JPEG bytes
├── scope: str "document" or "group"
├── caption: str
├── object_id: int | None
├── owner_caption: str
├── owner_path: str slash-separated group path
├── width: int | None pixels
└── height: int | None pixels
Walking the layer tree¶
LinesDocument.groups is a flat list of top-level nodes. Each node is either
a GroupInfo (with its own children list) or a LayerInfo (with a fills
list). Groups nest recursively.
from vexy_lines import parse, GroupInfo, LayerInfo
doc = parse("artwork.lines")
def walk(nodes, depth=0):
indent = " " * depth
for node in nodes:
if isinstance(node, GroupInfo):
print(f"{indent}[group] {node.caption!r}")
walk(node.children, depth + 1)
elif isinstance(node, LayerInfo):
vis = "" if node.visible else " (hidden)"
print(f"{indent}[layer] {node.caption!r}{vis}")
for fill in node.fills:
p = fill.params
print(f"{indent} [{p.fill_type}] {p.color}")
walk(doc.groups)
Fill type names¶
The fill_type field on FillParams is the MCP-compatible algorithm name:
fill_type |
XML element |
|---|---|
"linear" |
LinearStrokesTmpl |
"wave" |
SigmoidStrokesTmpl |
"circular" |
CircleStrokesTmpl |
"radial" |
RadialStrokesTmpl |
"spiral" |
SpiralStrokesTmpl |
"scribble" |
ScribbleStrokesTmpl |
"halftone" |
HalftoneStrokesTmpl |
"handmade" |
FreeCurveStrokesTmpl (default) |
"trace" |
FreeCurveStrokesTmpl with type_conv="9", or TracedAreaTmpl |
"fractals" |
PeanoStrokesTmpl |
"source_strokes" |
SourceStrokes |
The complete mapping is in vexy_lines.types.FILL_TAG_MAP.
Image filter chain¶
Each fill can carry an ordered list of ImageFilterEntry objects that are
applied before stroke rendering. Filter IDs 0–9 map to named operations:
from vexy_lines.types import IMAGE_FILTER_TYPE_MAP
# {0: "brightness", 1: "contrast", 2: "blur", 3: "sharpen",
# 4: "levels", 5: "shadows_highlights", 6: "invert",
# 7: "remove_background", 8: "color", 9: "gradient"}
Parameter values are typed: bool for "inverted", int for "left" /
"right" / "direction", str for "color", float for everything else.
for fill in layer.fills:
for f in fill.image_filters:
print(f.name, f.params)
# "brightness" {"value": -12.5}
# "levels" {"left": 12, "right": 224}
Source images¶
A .lines file can embed more than one source image: one at document level
and one per group. LinesDocument.source_images lists them all:
for img in doc.source_images:
print(img.index, img.scope, img.owner_path,
img.width, img.height, len(img.data), "bytes")
# 1 document "" 1025 1025 48392 bytes
# 2 group "Background" 512 512 12000 bytes
LinesDocument.source_image_data is a convenience shortcut to the first
document-scope image's bytes (or None when absent).
Accessing raw attributes¶
Every FillParams.raw dict and every LayerInfo.grid_edges entry holds the
unmodified XML attribute strings for attributes the parser does not promote to
named fields. This is the escape hatch for algorithm-specific or
undocumented parameters:
fill.params.raw.get("vert_disp") # "0.5"
fill.params.raw.get("crossed_dir") # "1"
layer.grid_edges[0]["allocation_t"] # "0.5"
Examples¶
Inspect a .lines file¶
from vexy_lines import parse
doc = parse("artwork.lines")
print(f"Project: {doc.caption}")
print(f"Created with Vexy Lines {doc.version}")
print(f"Canvas: {doc.props.width_mm:.0f} x {doc.props.height_mm:.0f} mm @ {doc.dpi} dpi")
print(f"Source image: {'yes' if doc.source_image_data else 'no'}")
print(f"Preview image: {'yes' if doc.preview_image_data else 'no'}")
Count layers and fills¶
from vexy_lines import parse, GroupInfo, LayerInfo
doc = parse("artwork.lines")
groups = 0
layers = 0
fills = 0
def count(nodes):
global groups, layers, fills
for node in nodes:
if isinstance(node, GroupInfo):
groups += 1
count(node.children)
elif isinstance(node, LayerInfo):
layers += 1
fills += len(node.fills)
count(doc.groups)
print(f"{groups} groups, {layers} layers, {fills} fills")
Walk all fills (reusable generator)¶
A generator that yields every FillNode in the tree. Useful as a building block for the examples below.
from vexy_lines import parse, GroupInfo, LayerInfo, FillNode
def walk_fills(nodes):
"""Yield every FillNode in the layer tree."""
for node in nodes:
if isinstance(node, GroupInfo):
yield from walk_fills(node.children)
elif isinstance(node, LayerInfo):
yield from node.fills
doc = parse("artwork.lines")
for fill in walk_fills(doc.groups):
p = fill.params
print(f"{fill.caption}: {p.fill_type}, color={p.color}, "
f"interval={p.interval}, angle={p.angle}")
Filter fills by type¶
Find all halftone fills across the project:
from vexy_lines import parse, GroupInfo, LayerInfo
def walk_fills(nodes):
for node in nodes:
if isinstance(node, GroupInfo):
yield from walk_fills(node.children)
elif isinstance(node, LayerInfo):
yield from node.fills
doc = parse("artwork.lines")
halftones = [f for f in walk_fills(doc.groups) if f.params.fill_type == "halftone"]
for h in halftones:
p = h.params
cell_size = p.raw.get("cell_size", "?")
morphing = p.raw.get("morphing_mode", "?")
print(f"{h.caption}: cell_size={cell_size}, morphing_mode={morphing}, "
f"color={p.color}, interval={p.interval}")
List all fill types and colours¶
from vexy_lines import parse, GroupInfo, LayerInfo
doc = parse("artwork.lines")
def walk_fills(nodes):
for node in nodes:
if isinstance(node, GroupInfo):
yield from walk_fills(node.children)
elif isinstance(node, LayerInfo):
for fill in node.fills:
yield fill
for fill in walk_fills(doc.groups):
p = fill.params
print(f"{fill.caption}: {p.fill_type}, color={p.color}, "
f"interval={p.interval}, angle={p.angle}")
Extract the source image¶
from vexy_lines import extract_source_image
path = extract_source_image("artwork.lines", "source.jpg")
print(f"Saved source image to {path}")
Extract the preview image¶
from vexy_lines import extract_preview_image
path = extract_preview_image("artwork.lines", "preview.png")
print(f"Saved preview to {path}")
Batch extract previews from a directory¶
from pathlib import Path
from vexy_lines import parse
input_dir = Path("./artwork")
output_dir = Path("./thumbnails")
output_dir.mkdir(exist_ok=True)
for lines_file in sorted(input_dir.glob("*.lines")):
doc = parse(lines_file)
if doc.preview_image_data:
out = output_dir / f"{lines_file.stem}.png"
out.write_bytes(doc.preview_image_data)
print(f"{lines_file.name} -> {out.name}")
else:
print(f"{lines_file.name}: no preview embedded")
Access raw XML attributes¶
Every FillParams object carries a raw dict with all original XML attributes, including algorithm-specific keys that don't have dedicated fields:
from vexy_lines import parse, GroupInfo, LayerInfo
doc = parse("artwork.lines")
for node in doc.groups:
if isinstance(node, LayerInfo):
for fill in node.fills:
# Algorithm-specific attributes live in raw
vert_disp = fill.params.raw.get("vert_disp", "0")
enbl_dotted = fill.params.raw.get("enbl_dotted", "0")
width_mode = fill.params.raw.get("width_mode", "0")
print(f"{fill.caption}: vert_disp={vert_disp}, "
f"enbl_dotted={enbl_dotted}, width_mode={width_mode}")
Build a JSON catalogue¶
import json
from vexy_lines import parse, GroupInfo, LayerInfo
def walk_fills(nodes):
for node in nodes:
if isinstance(node, GroupInfo):
yield from walk_fills(node.children)
elif isinstance(node, LayerInfo):
yield from node.fills
doc = parse("artwork.lines")
catalogue = {
"caption": doc.caption,
"version": doc.version,
"dpi": doc.dpi,
"width_mm": doc.props.width_mm,
"height_mm": doc.props.height_mm,
"fills": [
{
"caption": f.caption,
"type": f.params.fill_type,
"color": f.params.color,
"interval": f.params.interval,
"angle": f.params.angle,
}
for f in walk_fills(doc.groups)
],
}
with open("catalogue.json", "w") as fp:
json.dump(catalogue, fp, indent=2)
Replace the source image¶
Swap the source photo in a .lines template to produce a new project with the same fill structure but different content:
from vexy_lines import replace_source_image
replace_source_image(
"template.lines", # existing .lines with desired fill style
"new_photo.jpg", # replacement source image
"output.lines", # new .lines file
target_size=(1025, 1025) # resize to match template dimensions
)
Rename objects and isolate a single fill¶
Both helpers edit a .lines file by object_id while preserving everything else byte-for-byte. Object IDs come from the parsed tree (GroupInfo.object_id, LayerInfo.object_id, FillNode.object_id).
from vexy_lines import parse, rename_objects, set_visibility, GroupInfo, LayerInfo
doc = parse("artwork.lines")
# Rename a couple of objects by id (in place). Returns the count actually changed.
renamed = rename_objects("artwork.lines", "artwork.lines", {
1: "Background",
10: "Sky lines",
})
print(f"Renamed {renamed} object(s)")
# Collect every fill's object id.
def fill_ids(nodes):
for node in nodes:
if isinstance(node, GroupInfo):
yield from fill_ids(node.children)
elif isinstance(node, LayerInfo):
for fill in node.fills:
yield fill.object_id
all_fills = [fid for fid in fill_ids(doc.groups) if fid is not None]
# Write a copy where only fill 10 is visible (everything else hidden).
# Vexy Lines bakes `visible="0"/"1"` into the XML; toggling it live over MCP
# does NOT change the export, but re-opening this copy does.
target = 10
changed = set_visibility(
"artwork.lines",
"fill_10_only.lines",
{fid: (fid == target) for fid in all_fills},
)
print(f"Set visibility on {changed} object(s) -> open fill_10_only.lines and export")
Compare two .lines files¶
Check structural differences between two projects:
from vexy_lines import parse, GroupInfo, LayerInfo
def structure_summary(nodes, depth=0):
"""Return a list of (depth, type, caption) tuples."""
result = []
for node in nodes:
if isinstance(node, GroupInfo):
result.append((depth, "group", node.caption))
result.extend(structure_summary(node.children, depth + 1))
elif isinstance(node, LayerInfo):
result.append((depth, "layer", node.caption))
for fill in node.fills:
result.append((depth + 1, fill.params.fill_type, fill.caption))
return result
doc_a = parse("artwork_v1.lines")
doc_b = parse("artwork_v2.lines")
struct_a = structure_summary(doc_a.groups)
struct_b = structure_summary(doc_b.groups)
if struct_a == struct_b:
print("Identical structure")
else:
print(f"Structure A: {len(struct_a)} nodes")
print(f"Structure B: {len(struct_b)} nodes")
# Show first difference
for i, (a, b) in enumerate(zip(struct_a, struct_b)):
if a != b:
indent_a = " " * a[0]
indent_b = " " * b[0]
print(f"First difference at position {i}:")
print(f" A: {indent_a}{a[1]} '{a[2]}'")
print(f" B: {indent_b}{b[1]} '{b[2]}'")
break
Generate a visual report¶
Print an indented tree showing the full project structure:
from vexy_lines import parse, GroupInfo, LayerInfo
doc = parse("artwork.lines")
def print_tree(nodes, depth=0):
indent = " " * depth
for node in nodes:
if isinstance(node, GroupInfo):
state = "[-]" if node.expanded else "[+]"
print(f"{indent}{state} {node.caption}")
print_tree(node.children, depth + 1)
elif isinstance(node, LayerInfo):
vis = "visible" if node.visible else "hidden"
mask = " [masked]" if node.mask and node.mask.mask_type > 0 else ""
print(f"{indent} {node.caption} ({vis}{mask})")
for fill in node.fills:
p = fill.params
print(f"{indent} [{p.fill_type}] {fill.caption} "
f"color={p.color} interval={p.interval:.2f}")
print(f"Project: {doc.caption} (v{doc.version}, {doc.dpi} dpi)")
print(f"Canvas: {doc.props.width_mm:.1f} x {doc.props.height_mm:.1f} mm")
print()
print_tree(doc.groups)
Output:
Project: chameleon (v3.0.1, 300 dpi)
Canvas: 84.7 x 84.7 mm
[-] Background
Layer 1 (visible [masked])
[linear] Linear color=#000000 interval=2.28
Generate thumbnails with Pillow¶
If you have Pillow installed, create contact sheets from preview images:
from pathlib import Path
from io import BytesIO
from PIL import Image
from vexy_lines import parse
files = sorted(Path("./artwork").glob("*.lines"))
thumbs = []
for f in files:
doc = parse(f)
if doc.preview_image_data:
img = Image.open(BytesIO(doc.preview_image_data))
img.thumbnail((200, 200))
thumbs.append((f.stem, img))
if not thumbs:
print("No previews found")
else:
# Build a contact sheet: 4 columns
cols = 4
rows = (len(thumbs) + cols - 1) // cols
cell = 220
sheet = Image.new("RGB", (cols * cell, rows * cell), "white")
for i, (name, img) in enumerate(thumbs):
x = (i % cols) * cell + (cell - img.width) // 2
y = (i // cols) * cell + (cell - img.height) // 2
sheet.paste(img, (x, y))
sheet.save("contact_sheet.png")
print(f"Saved contact sheet with {len(thumbs)} thumbnails")
Parse from a string (no file needed)¶
Useful for testing or when the XML comes from a database or API:
from vexy_lines import parse_string
xml = """<?xml version="1.0" encoding="utf-8"?>
<Project caption="Test" version="3.0.1" dpi="300">
<Document width_mm="100" height_mm="100" dpi="300"
thicknessMin="0" thicknessMax="5"
intervalMin="0.5" intervalMax="5" />
<Objects>
<FreeMesh caption="Layer 1" object_id="1" visible="1">
<Objects>
<LinearStrokesTmpl caption="Lines" object_id="10"
color_name="#ff000000" interval="2" angle="0" />
</Objects>
</FreeMesh>
</Objects>
</Project>"""
doc = parse_string(xml)
print(doc.caption) # "Test"
print(len(doc.groups)) # 1
print(doc.groups[0].fills[0].params.fill_type) # "linear"
Export fill parameters to CSV¶
import csv
from vexy_lines import parse, GroupInfo, LayerInfo
def walk_fills(nodes, path=""):
for node in nodes:
if isinstance(node, GroupInfo):
yield from walk_fills(node.children, f"{path}/{node.caption}")
elif isinstance(node, LayerInfo):
for fill in node.fills:
yield path, node.caption, fill
doc = parse("artwork.lines")
with open("fills.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["group_path", "layer", "fill", "type", "color",
"interval", "angle", "multiplier"])
for group_path, layer_name, fill in walk_fills(doc.groups):
p = fill.params
writer.writerow([group_path, layer_name, fill.caption,
p.fill_type, p.color, p.interval, p.angle,
p.multiplier])
Changelog¶
See CHANGELOG.md for the full release history.
Topics¶
Find related pages by topic.
¶
¶
¶
Source API¶
Signatures and documentation are read from the current Python source during the build.
vexy_lines.parser
¶
Parse Vexy Lines .lines XML files into typed dataclasses.
A .lines file contains the full project: layer tree (groups, layers,
fills), document properties, and two optional embedded images.
Embedded image encodings:
- Source image: base64( 4-byte BE uint32 uncompressed-size + zlib(JPEG) )
- Preview image: base64( raw PNG )
The public API is three functions: :func:parse, :func:extract_source_image,
and :func:extract_preview_image.
extract_preview_image(path, output)
¶
Parse a .lines file and save its embedded preview image as PNG.
Args:
path: Path to the .lines file.
output: Destination path for the PNG file.
Returns:
The resolved output :class:~pathlib.Path.
Raises: FileNotFoundError: If path does not exist. ValueError: If no preview image is embedded in the file.
Source code in src/vexy_lines/parser.py
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 | |
extract_source_image(path, output)
¶
Parse a .lines file and save its embedded source image as JPEG.
Args:
path: Path to the .lines file.
output: Destination path for the JPEG file.
Returns:
The resolved output :class:~pathlib.Path.
Raises: FileNotFoundError: If path does not exist. ValueError: If no source image is embedded in the file.
Source code in src/vexy_lines/parser.py
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 | |
extract_source_images(path, output_dir)
¶
Extract all document and group source images from a .lines file.
Args:
path: Path to the .lines file.
output_dir: Directory where JPEG files will be written.
Returns: Output paths in extraction order. The document source is first when present, followed by group sources in XML traversal order.
Raises: FileNotFoundError: If path does not exist. ValueError: If no source images are embedded in the file.
Source code in src/vexy_lines/parser.py
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 | |
parse(path)
¶
Parse a .lines file and return a :class:~vexy_lines.types.LinesDocument.
This is the main entry point for file-based parsing. The operation is
entirely offline: no network access, no Vexy Lines app, and no
platform-specific libraries are required. Corrupt or missing embedded
images (<SourcePict>, <PreviewDoc>) are handled gracefully — a
warning is logged and the corresponding field is set to None rather
than raising an exception.
Args:
path: Path to the .lines file (str or Path).
Returns:
Fully populated :class:~vexy_lines.types.LinesDocument.
Raises: FileNotFoundError: If path does not exist. ET.ParseError: If the file is not valid XML (e.g. truncated or corrupt at the XML level).
Source code in src/vexy_lines/parser.py
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | |
parse_string(xml)
¶
Parse a .lines XML string and return a :class:~vexy_lines.types.LinesDocument.
Use this when you already have the XML content in memory (e.g. from a network response or database) instead of a file path.
Args:
xml: Raw XML string from a .lines file.
Returns:
Fully populated :class:~vexy_lines.types.LinesDocument.
Raises: ET.ParseError: If xml is not valid XML.
Source code in src/vexy_lines/parser.py
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 | |
