From 04c5214ed0a3b0c3a9b95b36453ebaa8fb9e9c12 Mon Sep 17 00:00:00 2001 From: Microck Date: Thu, 3 Dec 2026 20:34:17 +0100 Subject: [PATCH 1/2] Add openvector CLI agent skill Document the native CLI workflows, tuning controls, edit plans, profiles, engine stages, and export behavior. Include reusable fitted-geometry and SVG-inspection helpers, and link the skill from the README. --- README.md | 9 + skills/openvector/SKILL.md | 106 +++++++++ skills/openvector/agents/openai.yaml | 14 ++ skills/openvector/assets/icon.svg | 6 + skills/openvector/references/cli.md | 166 ++++++++++++++ .../openvector/references/edits-and-tuning.md | 213 ++++++++++++++++++ skills/openvector/references/setup-and-api.md | 143 ++++++++++++ skills/openvector/references/stages.md | 188 ++++++++++++++++ skills/openvector/scripts/inspect_svg.py | 82 +++++++ skills/openvector/scripts/prepare_export.mjs | 129 +++++++++++ 10 files changed, 1056 insertions(+) create mode 100644 skills/openvector/SKILL.md create mode 100644 skills/openvector/agents/openai.yaml create mode 100644 skills/openvector/assets/icon.svg create mode 100644 skills/openvector/references/cli.md create mode 100644 skills/openvector/references/edits-and-tuning.md create mode 100644 skills/openvector/references/setup-and-api.md create mode 100644 skills/openvector/references/stages.md create mode 100644 skills/openvector/scripts/inspect_svg.py create mode 100644 skills/openvector/scripts/prepare_export.mjs diff --git a/README.md b/README.md index 2be8fc2..b04a868 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,15 @@ calls are synchronous. the [api guide](docs/usage.md) covers progress, cancellat batches, editing, snapshots, and profile storage. the package never downloads a binary or falls back to the javascript reference implementation on import. +## ai agents + +The [openvector skill](skills/openvector/SKILL.md) guides AI agents through the CLI, +including batch conversion, palettes, edit plans, profiles, tracing stages, and exports. +It includes detailed references and helpers for reusable fitted geometry and SVG inspection. + +Copy the complete `skills/openvector/` directory into your agent's skills directory, +or point the agent at its `SKILL.md`. Keep the references, scripts, and assets together. + ## development ```sh diff --git a/skills/openvector/SKILL.md b/skills/openvector/SKILL.md new file mode 100644 index 0000000..d6c472a --- /dev/null +++ b/skills/openvector/SKILL.md @@ -0,0 +1,106 @@ +--- +name: openvector +description: Use the openvector raster-to-vector CLI to trace images, tune palettes and curves, edit segmentation and backgrounds, manage saved profiles and recent settings, batch-convert assets, run individual tracing stages, and export SVG, PDF, EPS, AI, DXF, EMF or rendered bitmaps. Use when a task names openvector or calls for raster tracing with this tool, including logos, icons, scans, illustrations, transparent artwork, CAD paths, print exports and reproducible conversion pipelines. Includes native Node API bridges for reusable fitted geometry and headless EMF export. +--- + +# openvector + +## Start with the actual installation + +1. Locate the installed `openvector` executable or the project's `node_modules/.bin/openvector`. In a built source checkout, use `node bin/openvector.mjs`. Treat `openvector` below as that verified command prefix. +2. Run `openvector --version`, `openvector --help`, and the relevant command's help. Read [setup and API](references/setup-and-api.md) if installation, native loading, platform support, or format selection needs attention. Do not silently download another version while discovering the existing one. +3. Use these references as the baseline for version 0.1.8, checked against [source commit 36fefd1](https://github.com/Microck/openvector/tree/36fefd1783a0d1c9300975ad33878cd3165ff48e). If installed help differs, verify the installed implementation before using version-specific options. +4. Inspect the actual source image: dimensions, alpha, palette, antialiasing, fine details, holes and intended background. Preserve its filename suffix; it affects classification and shadow processing. Inspect a visual preview when available. +5. Establish the intended deliverable: vector or raster, format, physical versus CSS dimensions, transparency, editability and any exact palette. Infer ordinary defaults from the task; ask only when the missing choice changes the result materially. + +## Choose the right route + +| Need | Route | Read | +|---|---|---| +| One image, automatic tracing, vector or rendered bitmap | `vectorize` | [CLI](references/cli.md) | +| Several images with common controls | `batch` with explicit format and destination | [CLI](references/cli.md) | +| Exact brand palette or fixed color count, even for one image | One-input `batch --settings ...` | [CLI](references/cli.md), [tuning](references/edits-and-tuning.md) | +| Reusable advanced processing settings | `profiles show/save`, then `--profile` and `--profiles-file` | [CLI](references/cli.md), [tuning](references/edits-and-tuning.md) | +| Replay a previous basic result | `--recent-file` and `--recent-index` | [CLI](references/cli.md) | +| Recolor, repair regions, draw, undo, remove background | `vectorize --edits plan.json` | [edits and tuning](references/edits-and-tuning.md) | +| Inspect numerical stages or control the pipeline explicitly | JSON stage commands | [stages](references/stages.md) | +| Trace once, export many vector formats or use headless EMF | `scripts/prepare_export.mjs`, then `export-*` | Reuse fitted geometry below; [stages](references/stages.md) | +| Stateful palette selection, progress/cancellation callbacks, selective snapshots | Public native Node API | [setup and API](references/setup-and-api.md) | + +Do not invent flags such as `--colors`, `--preset`, `--quality`, `--recursive`, `--jobs`, `--background` or a generic `--json`. `vectorize` has no `--settings`; use the routes above. + +## Convert, inspect, then tune + +Start with one representative input and a new output path: + +```sh +openvector vectorize logo.png --output logo-baseline.svg +``` + +Prefer `--output` over shell redirection for normal conversion. It checks collisions before writing. Shell `>` can truncate an existing file or the source before openvector starts. Replace a result with `--force` only when replacement is within the user's requested scope. Keep outputs, input images, edit plans, profiles and recent-settings files at distinct paths; create required destination folders first. + +Evaluate the baseline before changing controls. Judge visible edges, holes, color fidelity, unwanted speckles, background and editable path complexity. Render SVG/PDF with an available renderer and compare at the intended size. For an approximate raster preview, rerun the same input and tracing controls with `--output preview.png`; this is another trace, not rendering the saved SVG. Use the actual SVG renderer when reviewing layout or thin-stroke effects. + +Use a small number of labeled variants; change one control group at a time: + +- Palette/category/quality: use explicit batch settings or a saved advanced profile. For exact colors, use advanced batch `paletteMode: 0` with normalized BGRA colors. A saved profile does not retain its palette array. +- Speckles and excess regions: investigate segmentation controls such as `minimumPixels`, `artifactRejection`, `complexity` and `clusterColors`. +- Edge shape and path complexity: investigate `smoothness`, `detectCorners`, `curveComplexity` and `smoothingAntiAlias`. +- Large images: use `--shrink-source` only when the detail tradeoff is acceptable. It changes processing dimensions above 1.6 megapixels; `--scale` only scales bitmap output. +- Background: distinguish preserving source alpha, flattening to a color, and hiding fitted regions. Apply region hiding after the last fit. + +Use the exact enum meanings, ranges, and processing order in [edits and tuning](references/edits-and-tuning.md). Avoid promising that a larger numerical value always improves quality. Retain the successful settings, command, package version and original input name so a result can be reproduced. + +## Keep these behaviors explicit + +- `vectorize`: defaults to SVG on stdout and `grouped-cutouts` for vector layout. An output suffix selects the format; `--format` overrides it. +- `batch`: defaults to AI, the last input's folder, skipped existing outputs and a white background. Always set `--format` and `--output-dir`; set `backgroundMode: 0` in batch JSON when transparency must be preserved. Native batch supports SVG/EPS/PDF/AI/DXF, not EMF or raster output. +- Palettes and edit colors use normalized BGRA, not RGBA. Opaque red is `[0,0,1,1]`; palettes are flat arrays repeating four channels. Decoded BGRA pixels and fitted-region BGRA use byte values instead. +- Basic/advanced document, profile and batch settings use integer enums. The standalone numeric `settings`/stage commands use string enums. These JSON objects are not interchangeable. +- Saved profile replay skips classification and uses stored palette metadata. Palette mode 3 does not process. Profile selection writes ordering to its explicit storage file; recent recording can persist before a later export fails. Serialize operations sharing either file. +- An edit `settings` patch selects controls; it does not run them. After segmentation changes, process smoothing and fitting. After tools change pixels, explicitly `finish` before background work. A final implicit refit uses the document's last committed controls, so do not rely on an unprocessed patch. +- SVG dimensions are points: 48 pt renders as 64 CSS px at 96 DPI. Set display CSS dimensions for web use without changing its viewBox. Decide physical output dimensions explicitly for print. +- PNG bitmap output preserves alpha. Non-PNG output may need `--flatten`; this acknowledges transparency loss, not an instruction to discover or remove a background. Raster exports redraw fitted paths. +- Low-level `export-*` defaults to `stacked`, unlike high-level conversion. Set `layout` explicitly when matching an existing result. `--thin-stroke` can change fine lines and holes; inspect the rendered result. +- Headless `vectorize --format emf` cannot supply display metrics. Use `export-emf` with explicit, meaningful `referenceDevice` measurements. + +## Reuse fitted geometry + +Resolve `OPENVECTOR_SKILL_DIR` to the directory containing this file. The bundled bridge uses the native public Node addon and writes a new JSON file with fitted geometry, source dimensions, segmentation palette, hidden regions, explicit layout and trace metadata. Run it from a project containing `openvector`, or supply `--module /absolute/path/to/openvector/npm/index.mjs` for a known installation/build. + +```sh +node "$OPENVECTOR_SKILL_DIR/scripts/prepare_export.mjs" logo.png --output fitted.json +``` + +Choose automatic processing by default, `--batch-settings batch.json` for explicit batch controls, or `--profile-record profile.json` for a record returned by `profiles show`. The latter two are mutually exclusive. Optional `--shrink-source` reduces input before tracing. This helper does not execute CLI edit plans or update profile/recent files. + +Feed the same JSON to `export-svg`, `export-pdf`, `export-eps`, `export-ai`, `export-dxf` or `export-emf`; add format-specific JSON options from [stages](references/stages.md). All exports write raw bytes to stdout. Capture bytes before creating a new output so failures do not truncate files: + +```python +from pathlib import Path +import subprocess + +cli = ["openvector"] # Or ["node", "/absolute/path/bin/openvector.mjs"]. +for fmt in ("svg", "pdf", "dxf"): + result = subprocess.run(cli + [f"export-{fmt}", "fitted.json"], + check=True, stdout=subprocess.PIPE) + with Path(f"logo.{fmt}").open("xb") as output: + output.write(result.stdout) +``` + +Keep the segmentation palette for DXF. For EMF, add `referenceDevice` with positive-int32 `[x,y]` pairs named `pixels`, `millimeters`, and `micrometers`; obtain the intended measurements rather than inventing a display. For requested output dimensions, supply both `outputWidth` and `outputHeight` as positive int32 values. + +## Validate and report the deliverable + +1. Check the process exit code and stderr. Conversion/stage errors return 1. Batch cancellation returns 130; parse its summary even when it exits nonzero. Inspect per-file failures, skips and cancellation instead of assuming every input was exported. +2. Confirm output paths exist, contain bytes, and match their format. For SVG, run: + + ```sh + python3 "$OPENVECTOR_SKILL_DIR/scripts/inspect_svg.py" logo-baseline.svg + ``` + + This reports XML structure, paths, image elements and point-to-CSS dimensions. It does not establish visual accuracy or valid cutting topology. +3. Render and inspect the chosen final output when the environment supports it. For SVG/PDF check holes and alpha on a contrasting background. For CAD/cutting inspect units, closed contours, duplicates and tool compatibility in the actual downstream workflow; successful export alone does not establish manufacturability. +4. Report the created files, settings that materially changed the result and any unverified part. Do not call an output visually verified when only its syntax or signature was checked. + +Read only the reference needed for the current route: [CLI](references/cli.md), [edits and tuning](references/edits-and-tuning.md), [numeric stages](references/stages.md), or [setup, formats and API](references/setup-and-api.md). diff --git a/skills/openvector/agents/openai.yaml b/skills/openvector/agents/openai.yaml new file mode 100644 index 0000000..a8e9cc5 --- /dev/null +++ b/skills/openvector/agents/openai.yaml @@ -0,0 +1,14 @@ +interface: + display_name: openvector + short_description: Trace, tune, edit, and export with the openvector CLI + default_prompt: Use $openvector to inspect my images, choose tracing settings, and + produce verified vector exports. + icon_small: assets/icon.svg + icon_large: assets/icon.svg +policy: + products: + - chatgpt + - codex + - api + - atlas + allow_implicit_invocation: true diff --git a/skills/openvector/assets/icon.svg b/skills/openvector/assets/icon.svg new file mode 100644 index 0000000..c782ded --- /dev/null +++ b/skills/openvector/assets/icon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/skills/openvector/references/cli.md b/skills/openvector/references/cli.md new file mode 100644 index 0000000..ec4b6d7 --- /dev/null +++ b/skills/openvector/references/cli.md @@ -0,0 +1,166 @@ +# CLI commands and automation contract + +Source baseline: `Microck/openvector` commit `36fefd1783a0d1c9300975ad33878cd3165ff48e`. Confirm the installed version and help before relying on newer options. + +Contents: [Parser and streams](#parser-and-streams) · [Single image](#single-image) · [Batch](#batch) · [Batch settings](#batch-settings) · [Saved profiles](#saved-profiles) · [Recent settings](#recent-settings) · [Sources](#sources). + +## Parser and streams + +- Discover with `openvector --version`, `openvector --help`, and `openvector COMMAND --help`. `openvector help COMMAND` also works for the four high-level commands. +- Recognize exactly four workflow commands: `vectorize`, `batch`, `profiles`, `recent-settings`. The sixteen JSON stage commands are documented in `stages.md`. +- Use long options as `--name value` or `--name=value`. Boolean switches take no value: `--force=false` is invalid. The only operational short aliases are `-o` for `--output` and `-f` for `--force`; their availability still depends on the command. Do not combine short switches. +- Use `--` before image positionals beginning with a hyphen; prefix a literal file named `--help` with `./` because help is detected anywhere before normal parsing. Repeated value options keep the last value. Unknown options fail. +- Capture stdout and stderr separately. `vectorize` emits raw file bytes to stdout unless `--output PATH` is supplied; writing a file does not print JSON. `batch`, profile/recent commands, and non-export stage commands print pretty JSON. `export-*` emits raw bytes. Do not request a nonexistent `--json` flag. +- Diagnostics go to stderr. High-level conversion progress text appears on stderr only when it is a terminal. Normal success is exit 0; errors are exit 1. Batch cancellation is 130. +- Prefer `--output PATH` for image conversion: it protects existing files. Shell `>` truncates its destination before the CLI runs and bypasses that protection. Capture numeric exports as bytes and create the destination exclusively, or write a fresh temporary file and publish only after success. +- Treat each invocation as a fresh engine session. Batch retains one document/random stream across its queue; do not promise byte identity between batch and separate invocations. + +## Single image + +```sh +openvector vectorize logo.png --output logo.svg +openvector vectorize logo.png --output logo.pdf --layout cutouts +openvector vectorize logo.png --output traced.png --scale 2 +openvector vectorize - --filename logo.png --output logo.svg < logo.png +``` + +Supply exactly one PNG, BMP, JPEG, GIF, or TIFF image, or `-` for binary stdin. + +| Option | Meaning and default | +|---|---| +| `-o, --output PATH` | Destination; omitted or `-` writes stdout. Parent directory must exist. | +| `--format FORMAT` | `svg`, `eps`, `pdf`, `ai`, `dxf`, `emf`, `bmp`, `jpeg`, `png`, `tiff`; format strings are lowercased. Bitmap aliases `jpg` and `tif` also work. Explicit format overrides suffix; otherwise infer suffix, or SVG for stdout. | +| `--filename NAME` | Required for binary stdin; rejected for file input. Keep the actual source filename/extension. | +| `--edits PATH` | JSON array of edit/processing commands; see `edits-and-tuning.md`. | +| `--shrink-source` | Reduce sources above 1.6 megapixels before tracing. Default is full size; the source file remains unchanged. | +| `--scale FACTOR` | Bitmap output only; positive finite number, default 1. It scales the rendered vector result. | +| `--flatten` | Explicitly acknowledge transparency loss for non-PNG bitmap output; rejected for PNG/vector output. | +| `--layout MODE` | `stacked`, `cutouts`, `grouped-cutouts`; default `grouped-cutouts`. | +| `--thin-stroke` | Add thin vector strokes; default off. | +| `--compact` | Compact EPS operators; default off. | +| `--dxf-mode MODE` | `splines`, `sparse-lines`, `dense-lines`; default `dense-lines`. | +| `--profile NAME --profiles-file PATH` | Replay an exact saved advanced profile instead of automatic conversion. Both options are required together. | +| `--recent-file PATH` | Record eligible fitting completions in explicit recent storage. | +| `--recent-index N` | Replay visible zero-based entry from `--recent-file`; incompatible with `--profile`. | +| `-f, --force` | Replace existing output. Use only when replacement is authorized. | + +All four vector export flags are rejected for bitmap output. `--compact` and `--dxf-mode` are accepted on other vector formats but only affect EPS and DXF respectively. There is no `vectorize --settings`, `--quality`, `--colors`, `--width`, `--height`, or `--dpi`; apply processing controls through edit plans/profiles and output dimensions through JSON export commands. + +Conversion and serialization complete before opening the destination. Input/output identity is rejected even with `--force`, including existing aliases. Profile storage, recent storage, and output must use distinct files. A write failure can still leave an incomplete new/replacement output; check exit status and the result. + +Binary stdin and JSON stdin cannot share one stream: when the image is `-`, use an actual file for `--edits`. EMF image conversion needs the current display's device measurements; use `export-emf` with explicit measurements for a headless workflow. + +## Batch + +```sh +mkdir -p vectors +openvector batch first.png second.jpg --format svg --output-dir vectors > batch-result.json +openvector batch first.png second.jpg --format pdf --output-dir vectors --settings batch.json +``` + +| Option | Meaning and default | +|---|---| +| `--output-dir DIRECTORY` | Existing output folder; default is the last admitted source file's folder. Explicitly set this for automation. | +| `--format FORMAT` | Only `svg`, `eps`, `pdf`, `ai`, `dxf`; default `ai`. | +| `--settings PATH` | JSON object of batch controls; `-` can read that JSON from stdin. | +| `--profile NAME --profiles-file PATH` | Apply saved advanced controls after `--settings`; preserve batch basic/background selections. | +| `--layout`, `--thin-stroke`, `--compact`, `--dxf-mode` | Same vector export options/defaults as single-image conversion. | +| `--overwrite DECISION` | `skip` default, `replace`, or `cancel`. Decision is consulted when preflight finds existing outputs. | + +Supply image filenames explicitly. The CLI has no directory recursion, glob expansion, worker-count, per-file settings, edit-plan, shrink, or bitmap-export switch for batch. Expand file lists in the caller, quote arguments, and use separate `vectorize` calls when those features are needed. + +Exact duplicate input strings are skipped with a stderr diagnostic. Same-stem outputs are disambiguated case-insensitively as `stem.ext`, `stem_1.ext`, and so on. The source extension is replaced. Do not assume input and output filenames are one-to-one without reading the summary. + +Read these actual JSON fields: + +```text +status: "complete" | "cancelled" | "no-files" | "empty" +converted, failed, skipped: integer counts +files: [{ filename, outputFilename, status, error? }, ...] +queue: { exportDirectory, exportFormat, processingIndex, acceptingEdits, + queue: [{filename, selected, outputFilename, shouldProcess, buttonIndex}, ...] } +log: detailed text +``` + +File status is `written`, `failed-load`, `failed-save`, `skipped`, or `pending`. Cancellation can leave pending files; exclude them from successful outputs. `no-files` commonly means every output was skipped, and is still exit 0. `empty` exists in the engine schema, but the CLI rejects an empty input list. + +Load/save failures are reported per file and the batch continues, returning exit 1 when any file failed. A fatal processing/configuration error can stop before a summary is printed; preserve stderr and check JSON validity. Outputs are guarded against aliases of any queued source. `replace` authorizes preflight collisions, not arbitrary outputs that appear later. + +One Ctrl-C requests cancellation at a numerical checkpoint/completed task boundary, returning 130 and a summary. A second forces exit without a summary and can interrupt a write. Completed files remain. Keep exit code, summary, and actual outputs together when reporting partial completion. + +## Batch settings + +Basic settings are integers, not the string enums of the `settings` stage command. + +| Field | Values | Default | +|---|---|---| +| `advanced` | Boolean | `false` | +| `category` | 0 photograph, 1 artwork with blending, 2 artwork without blending, 3 auto | 3 | +| `quality` | 0 high, 1 medium, 2 low, 3 auto | 3 | +| `paletteMode` | 1 fixed, 2 flexible/unlimited, 3 auto | 3 | +| `colorCount` | Basic: 0 auto or 2–12. Advanced: 2–24. | Basic 0; advanced 2 | +| `backgroundMode` | 0 preserve, 1 flatten to white, 3 auto | 1 | + +Example for a fixed two-color trace while preserving transparency: + +```json +{"category":2,"quality":0,"paletteMode":1,"colorCount":2,"backgroundMode":0} +``` + +With `advanced:true`, classification is skipped; set `paletteMode` explicitly rather than retaining the default auto sentinel. Only advanced `paletteMode:1` searches a palette, at exactly `colorCount`. Advanced `paletteMode:0` plus a normalized BGRA `palette` reuses explicit colors without generating them; this extra CLI capability is not offered in the GUI batch menu. Basic mode rejects palette mode 0. Advanced mode 2 uses flexible colors. + +```json +{"advanced":true,"paletteMode":0,"colorCount":2,"backgroundMode":0,"palette":[0,0,0,1,1,1,1,1]} +``` + +Advanced control defaults are `sensitivity:1`, `antiAlias:true`, `complexity:5`, `minimumPixels:0`, `artifactRejection:0`, `clusterColors:true`, `smoothness:6`, `detectCorners:true`, `curveComplexity:6`, `smoothingAntiAlias:true`. Sensitivity/artifact rejection use integers 0–2; complexity, smoothness and curve complexity use 1–12; minimum pixels is nonnegative int32. See `edits-and-tuning.md` for choosing and tuning them. An explicit palette is a flat array of normalized BGRA quadruples, at most 256 colors. Unknown batch keys fail. The batch default flattens to white, unlike a general promise of alpha preservation: set `backgroundMode` deliberately. + +## Saved profiles + +```sh +openvector profiles list --file profiles.json +openvector profiles show --file profiles.json --name "Default Advanced Settings" +openvector profiles save --file profiles.json --name Logo --input profile.json +openvector profiles select --file profiles.json --name Logo +openvector profiles rename --file profiles.json --name Logo --new-name Artwork +openvector profiles delete --file profiles.json --name Artwork +openvector vectorize logo.png --profile Logo --profiles-file profiles.json --output logo.svg +``` + +Use full profile JSON for `save`, not a batch-controls object; `--input -` reads it from stdin. Use `show` as the template source and see `edits-and-tuning.md` for profile construction. `--file` is mandatory and cannot be `-`; its parent must exist. Exact names preserve case, whitespace, and Unicode. + +| Operation | JSON stdout | Storage effect | +|---|---|---| +| `list` | Array of `{name, profile}` | Read only; rejects `--name`. | +| `show` | Full profile | Read only. | +| `save` | `{name, profile}` | Insert at front; `--force` permits replacing an exact name. | +| `select` | `{index, profile}` | Move selection to front and persist order. | +| `rename` | `{index, changed, replacedIndex}` | Keep source settings/position; `--force` removes a colliding destination. Empty/unchanged replacement labels do not write. | +| `delete` | `{index}` | Remove the exact entry without prompting. | + +Only `save` accepts `--input`; only `rename` accepts/requires `--new-name`; only `save`/`rename` accept `--force`. Missing names fail. Storage is exactly `{"profiles":[{"name":"…","profile":{…}}]}`. A missing file starts with `Default Advanced Settings`; each invocation prepends/restores that built-in profile. The list retains at most 200 entries. + +Persistence deliberately discards palette colors and makes stored background colors opaque. Saved profiles are settings recipes, not exact brand-palette storage. `vectorize --profile` persists selection after successful image load, before tracing; a later conversion failure can therefore still update profile order. Batch persists profile selection before queue execution. Fast Forward skips classification, and palette mode 3 does not process a single image. Do not assume profile selection is read only or transactional with export success. + +## Recent settings + +```sh +openvector vectorize logo.png --output logo.svg --recent-file recent.json +openvector recent-settings list --file recent.json +openvector recent-settings show --file recent.json --index 0 +openvector vectorize next.png --output next.svg --recent-file recent.json --recent-index 0 +openvector recent-settings clear --file recent.json +``` + +`list` returns `{label, visible, profile}` entries newest first. `show` returns one profile and requires `--index`; it can inspect the fifth stored entry. Only indices 0–3 are replayable by `vectorize`. Indices use ASCII digits only, with no sign/fraction/space. `clear` returns `{"removed":N}` and only writes when something was removed. These commands do not prompt. + +Storage is exactly `{"recentBasicSettings":[PROFILE,...]}`; missing storage is empty. Five entries are retained, four visible. Eligibility requires successful fitting that did work in a single-image workflow. Automatic conversion, profile/recent replay, edit finish, explicit fitting, and replacement-source conversion can each record; cached/failed fitting and batch do not. Records can persist before a later export failure. + +Labels are identity: recording an existing label moves its older stored profile first rather than replacing it with new settings. Persistence drops palette colors/makes backgrounds opaque. Recent replay turns advanced mode off, uses two/fixed/unlimited color behavior, and rejects hidden/nonprocessing entries. Fixed recent replay uses its exact stored count without a zero-count fallback. + +## Sources + +- [Command parser and profile/recent operations](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector-cli/src/main.rs). +- [Single-image and batch admission/execution](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector-cli/src/conversion.rs). +- [Batch naming and collisions](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/batch_queue.rs), [batch summaries](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/batch_runner.rs), [control validation](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/document_controls.rs). +- [Profile/recent persistence](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/saved_profiles.rs), [replay semantics](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/settings_profile.rs), [official usage](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/docs/usage.md). diff --git a/skills/openvector/references/edits-and-tuning.md b/skills/openvector/references/edits-and-tuning.md new file mode 100644 index 0000000..59f8241 --- /dev/null +++ b/skills/openvector/references/edits-and-tuning.md @@ -0,0 +1,213 @@ +# Edits, tuning, and reproducible profiles + +Source baseline: OpenVector 0.1.8, commit `36fefd1783a0d1c9300975ad33878cd3165ff48e`. + +## Contents + +- [Choose the control surface](#choose-the-control-surface) +- [Edit-plan schema](#edit-plan-schema) +- [Pointer gestures](#pointer-gestures) +- [Background regions](#background-regions) +- [Document controls](#document-controls) +- [Tune in stages](#tune-in-stages) +- [Saved profile records](#saved-profile-records) +- [Sources](#sources) + +## Choose the control surface + +Use automatic `vectorize` for a baseline. Use `batch --settings` for explicit image categories, fixed color counts, and reusable advanced controls; a batch can contain one file. Use `vectorize --edits` for selected-color palettes, local repair, background removal, or a staged change after automatic processing. Use a saved profile to replay processing controls. Use the Node API when one fitted result must supply several exports, when generated palettes must be inspected/selected, or when checkpoints are needed. + +Keep the two settings vocabularies separate. Document settings, edit-plan patches, profiles, and batch files use integer enums described below. Standalone numerical stage commands use string enums such as `mode: "advanced"` and `artifactRejection: "moderate"`; see [stages.md](stages.md). + +## Edit-plan schema + +Run `openvector vectorize input.png --edits edits.json --output edited.svg`. The plan is a JSON array, applied after automatic conversion or profile replay. Each entry must contain exactly one command selector from `tool`, `gesture`, `action`, `background`, `settings`, or `source`. + +| Entry | Required fields and effect | +|---|---| +| `{"tool":"fill","x":8,"y":8,"color":[0,0,1,1]}` | Recolor the connected displayed-color component at the pixel. `x`, `y` are signed int32 integers. | +| `{"tool":"zap","x":8,"y":8}` | Replace the component with neighboring colors chosen against source pixels. It is not a transparent eraser. Fails if the region has no neighboring color. | +| `{"tool":"pencil","from":[1.2,1.3],"to":[13.4,12.5],"color":[0,0,0,1]}` | Draw a sampled stroke between two finite coordinate pairs. No brush-radius field is exposed. | +| `{"gesture":{...}}` | Apply one pointer, tool-selection, or color-selection event; schema below. | +| `{"action":"undo"}` / `redo` / `revert` | Undo, redo, or revert pixel-edit history. | +| `{"action":"begin"}` | Open/re-enter the retained editor; required after a new segmentation pass before subsequent painting. | +| `{"action":"commit"}` | Commit edited pixels without refitting. Changed pixels invalidate contours, smoothing, and fitting. | +| `{"action":"restore-committed"}` | Restore the saved editing checkpoint, or initial history if none exists. | +| `{"action":"leave"}` | Select Pan and leave the interaction; retain pixels/history. | +| `{"action":"finish"}` | Commit pixel edits, smooth, and fit using the selected controls. | +| `{"action":"process","stage":"segmentation"}` | Run one of `classification`, `palette`, `segmentation`, `smoothing`, `fitting`. Palette additionally requires integer `lower`, `upper`, with `2 <= lower <= upper <= 24`. | +| `{"settings":{...}}` | Merge recognized document controls into selected settings. This does not itself run processing. | +| `{"source":"next.png"}` | Load and automatically process another image; resolve relative paths from the plan's directory. Drop the previous palette/background recommendation and editing state. | +| `{"background":{...}}` | Apply a separate vector-region visibility command; schema below. | + +Colors are flat normalized BGRA quadruples, each channel in `[0,1]`: red is `[0,0,1,1]`, blue is `[1,0,0,1]`, transparent black is `[0,0,0,0]`. Do not pass RGB hex strings, byte channels, or nested palette quadruples. Direct tool commands accept optional boolean `commit` (default `true`); keep the default for replayable history. Out-of-bounds paint targets can do nothing; inspect dimensions before choosing coordinates. `--shrink-source` changes the coordinate system to the reduced image. + +Observe state transitions: + +- The CLI opens an editor at the beginning of a plan. Re-segmentation clears that editor and all downstream geometry. Follow it with smoothing, fitting, and `begin` if more painting is needed. +- A settings patch only changes selected controls. Explicitly run the affected stages. A palette task calculates candidates; it does not select a generated palette into the plan's selected settings. +- At plan end, outstanding pixel edits are refitted using the last committed document settings. Use explicit `finish` to apply newly selected smoothing/fitting controls to edits. +- A plan ending with committed-but-unfitted edits fails export. `commit` alone is not a completed vectorization. +- A new fitting pass resets region visibility. Finish numerical processing and pixel repairs before hiding background regions. + +### Repair pixels and then remove a region + +Choose coordinates from the actual image; the following coordinates are illustrative. + +```json +[ + {"tool":"zap","x":8,"y":8}, + {"tool":"fill","x":18,"y":18,"color":[0,0,1,1]}, + {"action":"finish"}, + {"background":{"action":"begin"}}, + {"background":{"action":"toggle","point":[1.5,2]}}, + {"background":{"action":"finish"}} +] +``` + +### Apply a fixed manual palette + +Supply exact colors through an edit plan or advanced batch JSON. Saved named profiles discard colors when stored. This example replaces the automatic palette with black and red, reruns the necessary stages, and produces fitted geometry: + +```json +[ + {"settings":{"advanced":true,"paletteMode":1,"palette":[0,0,0,1,0,0,1,1]}}, + {"action":"process","stage":"segmentation"}, + {"action":"process","stage":"smoothing"}, + {"action":"process","stage":"fitting"} +] +``` + +For a batch, manual palette reuse instead requires `advanced: true, paletteMode: 0`; `paletteMode: 1` regenerates a palette at the requested `colorCount`. This is a different orchestration rule from profile replay. + +## Pointer gestures + +Prefer direct tools for simple deterministic repairs. Use gestures to reproduce tool selection, picking, and a pointer path. + +| Gesture | Schema | +|---|---| +| Select | `{"phase":"select","tool":"pan"}`; tools: `pan`, `pencil`, `fill`, `zap`, `picker`. Selecting the currently selected tool toggles back to Pan. | +| Set color | `{"phase":"color","color":[0,0,1,1]}` | +| Pointer | `{"phase":"press","point":[8,8],"buttons":1}`; phases: `press`, `move`, `release`. | + +`point` is two finite image coordinates. `buttons` is required; `button` and `modifiers` are optional and default to zero. All three are unsigned int32 bit masks. The low bit in `buttons` indicates the left button; use `1` for left-button press/drag and `0` for release. Fill/Zap act on a left press; Pencil acts on left press/move; Picker reads a pixel on release and returns to the previous tool. The CLI does not offer a stroke-width setting or GUI-only grouped undo behavior. + +```json +[ + {"gesture":{"phase":"select","tool":"pencil"}}, + {"gesture":{"phase":"color","color":[0,0,0,1]}}, + {"gesture":{"phase":"press","point":[2,2],"buttons":1}}, + {"gesture":{"phase":"move","point":[8,4],"buttons":1}}, + {"gesture":{"phase":"release","point":[8,4],"buttons":0}}, + {"action":"finish"} +] +``` + +## Background regions + +Hide fitted vector regions without repainting the segmentation. Background history is separate from pixel-edit history. Toggling the same region twice restores it. + +| Background entry | Effect | +|---|---| +| `{"background":{"action":"begin"}}` | Enter background editing; requires a vector result. | +| `{"background":{"action":"toggle","point":[1.5,2]}}` | Hit-test and toggle the region at finite image coordinates. | +| `{"background":{"action":"undo"}}` / `redo` / `revert` | Operate on visibility history. | +| `{"background":{"action":"finish"}}` | End background interaction; preserve hidden regions. | +| `{"background":{"action":"gesture","events":[...]}}` | Replay a nonempty array of events. Select only `pan` or `background`; pointer schema matches above. A left press with the background tool toggles a region. Color-selection events fail. | + +Do not assume the image corner is background: inspect it. Complete refitting first; otherwise a later fit or implicit closing refit can restore all regions. For hidden backgrounds exported as raster, prefer PNG when transparency is required. + +## Document controls + +These are complete `DocumentSettings` fields; edit-plan `settings` entries can patch a subset. Defaults below come from `defaultDocumentSettings()`, not from the automatic classifier or batch orchestration. + +| Field | Accepted values / meaning | Fresh default | +|---|---|---| +| `advanced` | Boolean; activate advanced processing controls | `false` | +| `category` | `-1` unclassified, `0` photograph, `1` artwork with blending, `2` artwork without blending, `3` batch auto sentinel | `-1` | +| `quality` | `0` high, `1` medium, `2` low, `3` batch auto sentinel | `1` | +| `sensitivity` | `0` high, `1` medium, `2` low color sensitivity | `1` | +| `antiAlias` | Boolean for advanced palette analysis | `true` | +| `backgroundMode` | `-1` unset, `0` preserve, `1` white composition, `2` custom composition; batch accepts only `0`, `1`, `3` (auto). The document validator accepts signed int32, but do not invent other modes. | `-1` | +| `background` | Four finite normalized BGRA channels; composition uses this color in document modes `1` and `2` | `[0,0,0,0]` | +| `complexity` | Integer `1..12`, segmentation detail control | `5` | +| `minimumPixels` | Integer `0..2147483647`, minimum-region control | `0` | +| `artifactRejection` | `0` none, `1` moderate, `2` aggressive | `0` | +| `clusterColors` | Boolean | `true` | +| `paletteMode` | `0` two-color metadata, `1` fixed, `2` flexible/unlimited, `3` auto-detect metadata; execution depends on the workflow | `1` | +| `palette` | Flat normalized BGRA array, length divisible by 4, up to 256 colors; fixed segmentation requires nonempty colors | `[]` | +| `smoothness` | Integer `1..12` | `6` | +| `detectCorners` | Boolean | `true` | +| `curveComplexity` | Integer `1..12` | `6` | +| `smoothingAntiAlias` | Boolean for smoothing/fitting; distinct from palette `antiAlias` | `true` | + +Do not run basic stages with unclassified/auto sentinels. Automatic mode replaces category, quality, palette choice, and recommended background. For explicit control, use a classified basic batch, an advanced profile, or an edit plan with staged processing. Setting `advanced: true` does not mean every control should be raised to 12. + +## Tune in stages + +Treat the following as comparison strategies, not guaranteed optimal presets. Keep a baseline, change one relevant control group, render candidates at the same size, and compare the actual source and vector edges. + +| Observed problem or goal | Compare | +|---|---| +| Too many unwanted colors | Fixed `colorCount` for generated palettes, or an explicit BGRA palette for required brand colors. | +| Tiny speckles / fragmented regions | Larger `minimumPixels`, stronger `artifactRejection`, or lower segmentation `complexity`; check for lost legitimate details. | +| Missing small features | Smaller `minimumPixels`, less artifact rejection, or greater `complexity`; check noise and path count. | +| Wavy/jagged boundaries | Greater `smoothness`, with `smoothingAntiAlias` chosen for the source; check corners and narrow gaps. | +| Too many curve segments | Lower `curveComplexity`; check geometric error. | +| Curves miss the intended contour | Greater `curveComplexity`; inspect whether the segmentation itself needs repair first. | +| Sharp corners rounded away | Keep `detectCorners: true`; compare smoothing strength. | +| Exact local correction | Fill, Zap, or Pencil on the displayed segmentation, then `finish`. | + +The source parameter tables increase smoothing regularization with `smoothness`, and decrease segmentation/fitting penalties as their complexity sliders increase. Actual visual results remain image-dependent. + +Run the earliest affected stage and all downstream stages: + +- Segmentation settings, selected palette, or background composition: segmentation -> smoothing -> fitting. +- `smoothness`, `detectCorners`, `smoothingAntiAlias`: smoothing -> fitting. +- Only `curveComplexity`: fitting. +- Pixel edits: `finish` (commit -> smoothing -> fitting). +- Visibility edits: no refit; export after background commands. + +For document flattening to a chosen color, explicitly set both fields, for example `{"settings":{"backgroundMode":2,"background":[1,1,1,1]}}`, then rerun segmentation/smoothing/fitting. `--flatten` is an acknowledgement for non-PNG bitmap output, not a document background-color option. + +## Saved profile records + +Obtain a complete record with `profiles show`, or create one with Node's `defaultAdvancedProfile()`. Do not pass a partial batch settings object to `profiles save`. + +```json +{ + "settings": { + "category": -1, "quality": 1, "sensitivity": 1, "advanced": true, + "antiAlias": true, "backgroundMode": -1, "background": [0,0,0,0], + "complexity": 5, "minimumPixels": 0, "artifactRejection": 0, + "clusterColors": true, "paletteMode": 1, "palette": [], + "smoothness": 6, "detectCorners": true, "curveComplexity": 6, + "smoothingAntiAlias": true + }, + "colorCount": 2, + "basicColorCount": 0, + "paletteColorCount": 2, + "recommendedBackgroundMode": -1 +} +``` + +All four top-level counters must be signed int32 integers. For a fixed generated N-color advanced profile, set both `colorCount` and `paletteColorCount` to N (`2..24`) and `settings.paletteMode` to `1`. The counters are independent of `settings.palette.length`; do not derive one from the other without considering the workflow. + +| Profile replay mode | `vectorize --profile` behavior | +|---|---| +| `paletteMode: 0` | Search exactly 2 colors. | +| `paletteMode: 1` | Search exactly `paletteColorCount`, or 2..12 when that counter is zero. | +| `paletteMode: 2` | Skip palette search; run flexible segmentation. | +| `paletteMode: 3` | No processing; CLI fails without output. | + +Advanced replay also validates `colorCount` in `2..24`. It skips classification and forces advanced mode. Saved storage removes the palette colors and makes the background color opaque. Keep exact manual colors in edit/batch JSON instead. Selecting a saved profile mutates its saved ordering; profiles are not an image-project format. + +Recent-basic replay turns advanced mode off, uses exactly 2 colors for mode 0, exactly `paletteColorCount` for mode 1 (no zero fallback), and unlimited colors for mode 2. Only indices 0..3 replay. A duplicate recent label retains the older profile. Use named advanced profiles for explicit advanced presets; do not treat recent entries as lossless snapshots of the latest settings. + +## Sources + +- [CLI plan dispatch and refit rules](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector-cli/src/conversion.rs) +- [Document controls and validation](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/document_controls.rs) +- [Document stage execution and edit lifetime](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/image_document.rs) +- [Direct tools](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/segmentation_editor.rs), [pointer validation](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/editor_input.rs), [background commands](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/background_editor.rs) +- [Profiles and replay](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/settings_profile.rs), [numeric control mapping](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/settings.rs), [parameter tables](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/src/parameter-data.json) diff --git a/skills/openvector/references/setup-and-api.md b/skills/openvector/references/setup-and-api.md new file mode 100644 index 0000000..280bee7 --- /dev/null +++ b/skills/openvector/references/setup-and-api.md @@ -0,0 +1,143 @@ +# Setup, formats, and API escape hatches + +Source baseline: OpenVector 0.1.8, commit `36fefd1783a0d1c9300975ad33878cd3165ff48e`. + +## Contents + +- [Discover and install](#discover-and-install) +- [Choose input and output](#choose-input-and-output) +- [Layouts and physical size](#layouts-and-physical-size) +- [Use the Node API when it saves work](#use-the-node-api-when-it-saves-work) +- [Troubleshooting](#troubleshooting) +- [Sources](#sources) + +## Discover and install + +Check the executable that will actually run: `openvector --version`, `openvector --help`, and the selected command's `--help`. In an existing npm project, prefer its installed `node_modules/.bin/openvector` or `node node_modules/openvector/bin/openvector.mjs`; avoid an unqualified `npx` discovery call that can fetch an unintended version. Inspect `package.json`/lockfile for the selected package version. If using a source checkout, its launcher is `node bin/openvector.mjs` and it still requires compiled native artifacts. + +When installation is needed, use the project's package manager and existing dependency policy. For a new disposable npm environment: + +```sh +npm install openvector@0.1.8 +./node_modules/.bin/openvector --version +./node_modules/.bin/openvector vectorize input.png --output output.svg +``` + +The pinned version is the inspected baseline, not a claim that it remains newest. Verify a newer version's local help and source before adding flags. For an explicitly global installation, `npm install -g openvector@0.1.8` exposes `openvector` on PATH. + +The npm launcher requires Node.js 22.19 or later. The published package includes native CLI/addon artifacts for Linux x64 and arm64, macOS x64 and arm64, and Windows x64. Windows ARM64 uses x64 Node.js for the shipped binary. Alpine/musl and native Windows ARM64 artifacts are not included. Linux releases are built/tested on Ubuntu 24.04; do not assume arbitrary older distributions work. + +The loader uses Node's `process.platform` and `process.arch`, then resolves `native/-/openvector[.exe]`. There is no JavaScript engine fallback, install-time binary download, or build-on-import. The npm install does not require Rust when matching native artifacts are present. The GUI is a separate download. + +For an authorized source build, the repository documents Node.js 22.19+, npm, Git, Rust/Cargo with `rust-docs`, and a C compiler/linker. Use `npm ci`, then `npm run build`; this builds the CLI and Node addon, not the GUI. Building can also require locked external Cargo/Git dependencies and platform toolchain notices. Read [building.md](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/docs/building.md) for cross-compilation; do not substitute the reference JavaScript engine when native execution is unavailable. + +## Choose input and output + +Decoders accept PNG, JPEG, BMP, GIF, and TIFF bytes. A filename influences classification/shadow-processing context even though image decoding detects the byte format. For stdin use `vectorize - --filename original.png`; preserve the actual filename and suffix case. The CLI normalizes lowercase `.jpg` to `.jpeg` and `.tif` to `.tiff`; source suffix comparisons remain case-sensitive. Do not assume WebP, AVIF, PDF, SVG, remote URLs, animated output, or arbitrary multipage import are supported. + +Use local supported files. Preserve the originals when preparing a separate compatible input. Automatic classification needs dimensions of at least 2 by 2. `--shrink-source` explicitly reduces images above 1.6 megapixels using block averaging before processing; it can discard fine detail and changes edit coordinates and exported source dimensions. It does not rewrite the input. `--scale` only scales a rendered bitmap after fitting and does not increase tracing detail. + +| Output | Use and implementation constraints | +|---|---| +| SVG | General editable/web vector output. Supports alpha and the layout options below; inspect point-based dimensions. | +| PDF | Vector document output; serializer writes PDF 1.4 with alpha resources. Verify in the intended consumer. | +| EPS | PostScript vector output. `--compact` uses abbreviated operators, not a quality setting. A local creation timestamp varies between runs. | +| AI | Illustrator-oriented vector output. Prefer when the receiving application specifically requests AI; do not promise every modern Illustrator feature. | +| DXF | CAD-oriented line/spline entities. `--dxf-mode dense-lines` is default; `sparse-lines` uses fewer line approximations; `splines` exports cubic spline entities. Verify receiver support and imported scale. | +| EMF | Metafile vector output. `vectorize` uses live display pixel/physical metrics. For a headless environment, use `export-emf` with explicit `referenceDevice` metrics and fitted geometry. | +| PNG | Rasterization of fitted paths; choose for a preview or transparent bitmap. | +| JPEG/BMP/TIFF | Rasterization of fitted paths; use `--flatten` only when accepting non-PNG transparency loss. | + +`vectorize` supports every row. `batch` supports only SVG, EPS, PDF, AI, DXF and defaults to AI. Use a controlled loop of `vectorize` for EMF/bitmap batches or per-image edit plans. Always choose batch `--format` and `--output-dir` explicitly; defaults may not match the task. + +With `vectorize`, the output suffix selects the format, `--format` overrides it, and stdout defaults to SVG. Keep suffix and explicit format consistent for downstream tools. Vector options cannot accompany bitmap output. `--scale` is positive and finite, defaults to 1, and is bitmap-only. `--flatten` is invalid for PNG and vector formats; it is not a recolor or universal white-background control. + +Use `--output` rather than shell redirection for normal deliverables: shell redirection can truncate an existing path before OpenVector's safety checks run. Binary stdout must be captured as bytes, not decoded as UTF-8. Create output folders first. Do not use an input, profile file, recent settings file, or edit plan as the destination. + +## Layouts and physical size + +| Layout | Geometry organization | +|---|---| +| `stacked` | Emit outer shapes without cutting child-hole paths; shapes can overlap in drawing order. | +| `cutouts` | Emit hole subpaths in enclosing shapes. | +| `grouped-cutouts` | Cutouts ordered/grouped by exact color; DXF uses color layers. Default for high-level conversion and Node export. | + +Standalone `export-*` commands default to `stacked`, unlike `vectorize`, `batch`, and Node `saveVector`. Set `layout` explicitly when matching workflows. + +Do not equate SVG cutouts with guaranteed nonoverlapping manufacturing paths. The current SVG writer can add opaque backing paths beneath holes to suppress seams. `--thin-stroke` adds same-color strokes (SVG width `0.09375`) and changes that backing behavior; it is not a centerline-tracing option. Inspect resulting paths before using them as cut geometry. + +SVG root dimensions are points at 72 points/inch. A 48x48 source yields `width="48pt" height="48pt" viewBox="0 0 48 48"`, displaying as 64x64 CSS pixels at 96 DPI. For a 48 CSS-pixel web placement, specify CSS width/height of `48px` while retaining the viewBox. A 1x bitmap export uses 48x48 pixels. Do not call this a tracing-scale defect or invent a `--dpi` flag. + +Only standalone export JSON exposes `outputWidth` and `outputHeight`, supplied as a pair of positive int32 values. High-level `vectorize` does not expose vector width/height flags. For exact print sizing, compute the desired dimensions, use the supported export layer or a deliberate SVG sizing adjustment, and validate in the target application. + +## Use the Node API when it saves work + +Prefer the CLI for ordinary conversion and plans. Use Node for one conversion with many outputs, inspecting classification/region metadata, choosing generated palettes, progress/cancellation, or retaining document caches and edit state. The public package has one root export; do not import imaginary `openvector/cli` or `openvector/core` subpaths. + +### Convert once, export several times + +```js +import { readFileSync, writeFileSync } from 'node:fs'; +import { CoreSession } from 'openvector'; + +const session = new CoreSession(); +const document = session.createDocument(); +document.setSource(readFileSync('input.png'), 'input.png'); +const result = document.runAutomatic({ extension: '.png' }); +if (result.fitting.status !== 0 || !result.state.fittingComplete) { + throw new Error('Fitting did not complete'); +} +for (const filename of ['result.svg', 'result.pdf']) { + const saved = document.saveVector(filename, { layout: 'grouped-cutouts' }); + if (saved.status !== 0 || saved.error) { + throw new Error(saved.error?.message ?? `Export failed: ${saved.status}`); + } +} +writeFileSync('preview.png', document.exportBitmap('png', 2), { flag: 'wx' }); +``` + +Use fresh destinations. `saveVector` creates a new file without overwriting; both `status` and `error` must be checked. DXF/EMF open failures can have status 0 with a non-null error. API suffix matching is exact lowercase. Export methods require fitted geometry. + +`setSource` receives encoded bytes and a filename; it does not read the file. `decodeImage(bytes)` returns `{width,height,bgra,hasAlpha,format}`. `runAutomatic` requires `extension` including the dot; normalize `.jpg`/`.tif` as the CLI does. `runAutomatic` chooses classification/background and forces basic mode, so use `runBatchImage` or explicit `runTask`/profile replay for controlled advanced processing. + +Create documents and runners from the intended `CoreSession`. It retains a random stream across operations; a batch or reused session is not equivalent to independent fresh CLI processes for byte-exact results. Processing is synchronous. Use a worker/process when nonblocking application behavior is required. + +### Inspect narrowly + +- `snapshot({})`: metadata only, including dimensions, settings, stage keys, availability, cancellation, and random state. +- `snapshot({segmentation:'regions'})`: region metadata without the label plane. +- `snapshot({rasters:['working'],segmentation:'full',contours:true,fitting:true})`: selected large arrays for a concrete analysis. +- `snapshot()` with no argument copies all sections and can be expensive. Requested unavailable sections are `null`; unrequested sections are absent. +- Raster/editor pixels are `Buffer`; labels/counts/color indices are `Int32Array`; palettes are `Float32Array`; masks are `Uint8Array`. Use `Array.from` when constructing JSON for a standalone CLI stage; `JSON.stringify(Buffer)` is not the stage's expected byte-array shape. + +`runTask('palette', settingsWithLowerUpper)` exposes candidates. Select/apply a palette through `applyPaletteCommand` or document settings, then run segmentation/smoothing/fitting. Manual palettes use `paletteEncoding: 'straight'` with `runTask` when provenance must be explicit, including a palette numerically equal to one generated earlier. Generated colors can be identified as `premultiplied`. Edit-plan settings do not expose this extra `runTask` field. + +Progress options are `{callback(event, checkpoint), capture?}`. Return `true` to continue or `false` to cancel. Use the supplied checkpoint; never call document methods reentrantly inside the callback. Automatic/profile/edit-finish cancellation throws; some individual stages instead return `state.status === 2`. Check cancellation and completion before exporting. A retry on the same document is supported. + +For edit lifecycles, profiles, recent collections, and batches, use [npm/index.d.mts](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/npm/index.d.mts) and [docs/usage.md](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/docs/usage.md). `SourceHistory` and `SourceDirectories` are in-memory bookkeeping, not filesystem readers or automatic persistence. + +The separate `openvector-wasm` package on this source branch is a browser/worker `convert(bytes,{layout,thinStroke})` -> SVG interface. It does not expose the native CLI's profiles, edit plans, batch controls, stage commands, or non-SVG formats. Do not silently substitute it for missing native capability. + +## Troubleshooting + +| Symptom | Next useful check | +|---|---| +| Native artifact inaccessible | Check Node platform/architecture, installed package contents and execute permission; use a matching supported package or an explicit source build. | +| `process.execve` unavailable | Check actual Node version; launcher needs 22.19+ on POSIX. | +| Decoder failure / unusual image | Read the matching image-input contract; prepare a separate supported input if conversion is authorized. Do not treat a renamed extension as a byte conversion. | +| Thin one-pixel image fails | Automatic classification and antialiased segmentation need at least 2x2 dimensions. | +| Result larger on the web | Check SVG point units and CSS placement dimensions. | +| EMF parses but renders blank or wrong | Check the actual target renderer, device metrics and record bounds; compare SVG/PDF exported from the same fitted graph. A valid header and exit 0 do not establish rendered compatibility. | +| Lost alpha | Check automatic/batch background choice, hidden regions, and output format. Batch defaults to white; PNG/SVG suit transparent deliverables. | +| No fitted vectors after an edit plan | Check `commit` without `finish`, segmentation without downstream stages, or an auto-detect saved profile. | +| Very large raster export fails | Reduce export scale; scan converter dimensions are bounded at 32767 per axis and buffers can be expensive. The GUI's 10000-pixel size control is not a universal CLI limit. | +| Byte comparison differs | Check CLI/package version, session reuse/order, source filename, palette provenance, settings, layout defaults, and EPS creation date. | + +The repository records decoder/parity gaps, including seven failing 16-bit Adam7 PNG comparisons. Treat those as known comparison limits, not a claim that every such image fails. Validate the actual requested output. A successful build, parser check, or file existence check does not establish visual fidelity or full format compatibility. + +## Sources + +- [Package installation and supported platforms](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/README.md), [native loader](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/npm/native.mjs), [launcher](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/bin/openvector.mjs) +- [CLI/API usage](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/docs/usage.md), [native build](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/docs/building.md), [verification limits](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/docs/verification.md) +- [SVG writer](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/svg.rs), [layout traversal](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/vector_output.rs), [PDF](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/pdf.rs), [DXF](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/dxf.rs) +- [Bitmap transparency rules](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/bitmap_export.rs), [raster limits](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/bitmap_raster.rs), [source shrinking](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/image_resize.rs) diff --git a/skills/openvector/references/stages.md b/skills/openvector/references/stages.md new file mode 100644 index 0000000..62c4262 --- /dev/null +++ b/skills/openvector/references/stages.md @@ -0,0 +1,188 @@ +# JSON engine stages + +Source baseline: `Microck/openvector` commit `36fefd1783a0d1c9300975ad33878cd3165ff48e`; opaque-pixel pipeline below was exercised with published CLI 0.1.8. + +Contents: [Data rules](#data-rules) · [Settings resolver](#settings-resolver) · [Command schemas](#command-schemas) · [Image analysis](#image-analysis) · [Geometry and export](#geometry-and-export) · [Complete stage pipeline](#complete-stage-pipeline) · [Sources](#sources). + +## Data rules + +Invoke `openvector COMMAND input.json`, or `openvector COMMAND -` with JSON on stdin. `fill` also requires two positional integers. There are no output/format options on these commands: capture stdout. Numeric stages return JSON; `export-*` returns raw file bytes. Errors use stderr and exit 1. Each call creates a fresh session; carry required state explicitly. + +Use the correct color representation: + +| Data | Representation | +|---|---| +| `bgra` raster | Flat row-major bytes, four channels per pixel: blue, green, red, alpha; length `width * height * 4`. | +| Input/output `palette` | Flat normalized BGRA floats, four values in `[0,1]` per color. | +| Region `bgra` inside geometry | Four byte channels, not normalized floats. | +| Segmentation `indices` | One connected-region identifier per pixel. | +| Palette assignment `indices` | One color identifier per pixel; do not substitute for segmentation region identifiers. | + +Use decoded/prepared pixels for stage commands, never encoded PNG/JPEG bytes. No CLI `decode` command exists. Use the installed package's `decodeImage` only when decoding is necessary, then preserve the preparation/alpha conventions for the selected pipeline. A manually assembled low-level pipeline does not automatically reproduce the high-level document's classification, preprocessing, alpha provenance, or retained state. Prefer `vectorize` for normal image files and the document API when those semantics matter. + +Keep dimensions, pixel arrays, region labels, palettes, and geometry from the same input/preparation. Classification and contour extraction require at least 2 by 2; positive int32 dimensions/pixel-count limits apply. Do not copy giant raster arrays into chat; process JSON files in the executor. + +## Settings resolver + +`openvector settings INPUT` takes `stage` plus controls and returns raw numeric engine parameters. These string enums differ from the integer enums in batch/edit/profile document settings. + +| Mode/stage | Required fields | +|---|---| +| `stage:"classification"` | No other control is required. | +| Basic palette/segmentation/smoothing/fitting | `mode:"basic"`, `category:"photograph"`, `"artwork-with-blending"`, or `"artwork-without-blending"`; `quality:"high"`, `"medium"`, or `"low"`. Palette additionally permits `category:"unclassified"`. | +| Advanced palette | `mode:"advanced"`, `colorSensitivity:"high"`, `"medium"`, or `"low"`; `antiAlias` boolean. | +| Advanced segmentation | `mode:"advanced"`, `complexity` integer 1–12, `minimumPixels` integer 0–2147483647, `artifactRejection:"none"`, `"moderate"`, or `"aggressive"`; `clusterColors` boolean. | +| Advanced smoothing/fitting | `mode:"advanced"`, `smoothness` and `curveComplexity` integers 1–12, `antiAlias` and `detectCorners` booleans. Both stages validate all four controls. | + +Example input: + +```json +{"stage":"segmentation","mode":"advanced","complexity":6,"minimumPixels":0,"artifactRejection":"moderate","clusterColors":true} +``` + +For `segment`, `trace-contours`, `smooth-contours`, and `fit-contours`, put those resolver controls under `settings` and omit `stage`; the command sets it. Do not supply raw resolved numeric parameters under `settings`. Conversely, `analyze-image.parameters` requires raw numeric parameters, not document controls. Unknown JSON keys are not uniformly rejected by stage readers; a command accepting a key does not establish that it affects processing. + +## Command schemas + +| Command | Required JSON | Result | +|---|---|---| +| `settings` | Resolver controls above | Raw parameter object. | +| `fill MAP SEED REPLACEMENT` | `{width,height,segments}` with one signed int32 label per pixel | `{width,height,segments}` after four-connected flood fill. Seed is a row-major pixel index; replacement must differ from its current value. | +| `assign-palette` | `{bgra,palette}` | JSON array of color indices. | +| `generate-palette` | `{bgra,colorCount,bins,connected,antiAlias}` | `{palette,indices,weights,passes}`. `bins` is 8 or 16; `connected`/`antiAlias` are booleans; `colorCount` is positive int32, not the document UI's 24-color cap. Choose a practical count. | +| `refine-palette` | `{bgra,palette,antiAlias}` | `{palette,indices,weights,passes}`. | +| `analyze-image` | See below | Classification, working dimensions, palette candidates, random state. | +| `segment` | `{width,height,bgra,settings}`, optional normalized `palette` | `{indices,counts,palette,colorIndices}`. | +| `trace-contours` | Same as `segment` | Raw shared `{nodes,regions}` graph. It performs segmentation itself; it does not accept a segmentation result as its entire input. | +| `smooth-contours` | `{width,height,bgra,indices,palette,geometry,settings}` | `{geometry,penaltyCounts}`. Use segmentation region indices and palette, plus matching raw contour geometry. | +| `fit-contours` | `{geometry,settings}` | Fitted graph. Use `geometry` from smoothing's result, not the entire smoothing wrapper. | +| `export-svg`, `export-eps`, `export-pdf`, `export-ai`, `export-dxf`, `export-emf` | Fitted graph wrapped as `{geometry,width,height,...}` | Raw format bytes; not a JSON string or base64. | + +For `generate-palette` and `refine-palette`, `antiAlias:true` additionally requires `width` and `height` for weighted analysis. Unweighted operation does not require dimensions. If segmentation resolver output enables `shadowing` (advanced `artifactRejection:"none"`), supply top-level integer `shadowControl`. Match the native filename rules: normalize lowercase `.jpg` to `.jpeg` and `.tif` to `.tiff`, then use 0 for `.gif`, 1 for `.jpeg`, 2 for `.png`, or -1 otherwise. Comparisons are case-sensitive; preserve the real filename. Do not select a different rejection setting merely to avoid this input. + +Example flood fill: + +```sh +printf '%s\n' '{"width":2,"height":2,"segments":[0,1,1,0]}' | openvector fill - 0 7 +``` + +Result: segments `[7,1,1,0]`; diagonal contact does not connect the zero-valued pixels. + +## Image analysis + +Supply this shape, with actual decoded pixel data: + +```text +{ + width, height, bgra, + hasAlpha: boolean, + extension: string, + mode: integer 0..3, + amount: integer 0..3, + parameters: resolved numeric parameters plus shadowing/clusterColors booleans, + paletteControls: {bins: 8|16, connected: boolean, costPerColor: finite float32} +} +``` + +`mode:0, amount:0` selects the base preparation. For an explicit analysis request, obtain `parameters` from `settings {"stage":"classification"}` and add deliberate `shadowing`/`clusterColors` switches; the resolver's result does not include them. Keep `Shared::is_anti_aliased` equal to 0 or 1. Existing edge scale/floor values in resolved parameters are required for analysis. Use the actual extension, such as `.png`. + +Read `imageClassification:{label,imageType,quality}`, `imageTypeCode`, `antiAlias`, `width`, `height`, `paletteClassification:{label,mode,colorCount}`, `candidates`, and `randomState`. Candidate entries contain `colorCount`, `palette`, `weights`, `error`, `colorCost`, `recommendationScore`. The returned dimensions describe the working image; the result does not include prepared pixel arrays or a reusable document session. + +## Geometry and export + +Preserve complete graph objects. These are shared topology, not independent path lists: + +```text +Raw/smoothed geometry: + nodes: [{x,y,kind,flags}, ...] + regions: [{pixelCount,colorIndex,bgra,parent,contour,boundary,neighbors}, ...] + boundary entries: three integers per contour sample + +Fitted geometry: + cubicStorageSlots: integer + cubics: [{index,points:[x0,y0,x1,y1,x2,y2,x3,y3]}, ...] + nodes: [{x,y,kind,cubic}, ...] + regions: [{pixelCount,colorIndex,bgra,parent,contour,edges}, ...] + edge: [index,type,neighbor,firstNode,lastNode,firstSample,lastSample] +``` + +Let the engine create and validate node/cubic/region identifiers, parent links, contours, and edges. Do not round/reorder identifiers or reinterpret `colorIndex` as a region ID. Export requires completed fitted geometry, not raw contours, an SVG path array, or a full document snapshot. + +| Export field | Contract | +|---|---| +| `geometry`, `width`, `height` | Fitted graph and positive int32 source dimensions. | +| `outputWidth`, `outputHeight` | Optional positive int32 pair; both or neither. Set both for a desired vector output size. | +| `hiddenRegions` | Optional list of existing nonnegative region IDs. | +| `layout` | `stacked` default for these stage exports; `cutouts` or `grouped-cutouts`. Set explicitly to match high-level defaults. | +| `thinStroke` | Boolean, default false. | +| EPS `compact`, `creationDate` | Boolean compact default false; optional 1–255 printable ASCII characters on one line. | +| DXF `palette`, `curveMode` | Segmentation palette is required. Curve mode `splines`, `sparse-lines`, or default `dense-lines`. | +| EMF `referenceDevice` | `{pixels:[x,y],millimeters:[x,y],micrometers:[x,y]}`; each component positive int32. Use actual or deliberately selected reference-device measurements, not inferred physical dimensions. | + +Do not pass `onProgress` in JSON; the CLI rejects it because a JSON value cannot be a function. Raw PDF/EMF output must stay binary. A single fitted graph can be exported repeatedly without retracing; retain its dimensions and palette. There is no `export-png` stage command: bitmap rendering is exposed by `vectorize` and the document API. + +## Complete stage pipeline + +Use this small opaque black/white fixture to exercise the exact CLI schemas. For real assets, replace only the prepared image/palette inputs with validated data and choose appropriate controls. Run in a fresh output directory; exclusive writes below refuse existing files. + +```js +import { spawnSync } from 'node:child_process'; +import { writeFileSync } from 'node:fs'; + +const cli = ['openvector']; // Or [process.execPath, '/absolute/path/bin/openvector.mjs']. +function run(command, input, json = true) { + const result = spawnSync(cli[0], [...cli.slice(1), command, '-'], { + input: JSON.stringify(input), maxBuffer: 128 * 1024 * 1024, + }); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`${command}: ${result.stderr.toString()}`); + return json ? JSON.parse(result.stdout.toString('utf8')) : result.stdout; +} + +const width = 16, height = 16, bgra = []; +for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + bgra.push(...(x < 8 ? [0,0,0,255] : [255,255,255,255])); + } +} +const segmentationSettings = { + mode:'advanced', complexity:5, minimumPixels:0, + artifactRejection:'moderate', clusterColors:false, +}; +const curveSettings = { + mode:'advanced', smoothness:6, curveComplexity:6, + antiAlias:false, detectCorners:true, +}; +const prepared = { + width, height, bgra, palette:[0,0,0,1, 1,1,1,1], + settings:segmentationSettings, +}; +const segmented = run('segment', prepared); +const contours = run('trace-contours', prepared); +const smoothed = run('smooth-contours', { + width, height, bgra, indices:segmented.indices, + palette:segmented.palette, geometry:contours, settings:curveSettings, +}); +const fitted = run('fit-contours', { + geometry:smoothed.geometry, settings:curveSettings, +}); +const document = { + geometry:fitted, width, height, palette:segmented.palette, + layout:'grouped-cutouts', hiddenRegions:[], +}; +for (const format of ['svg','pdf','eps','ai','dxf']) { + const bytes = run(`export-${format}`, document, false); + writeFileSync(`traced.${format}`, bytes, {flag:'wx'}); +} +``` + +The paired segmentation/trace calls use identical prepared input and explicit settings; trace computes segmentation again because the CLI exposes no separate contour-extraction-from-segmentation command. For large assets or retained random/state continuity, use the installed document API to avoid redundant work. + +For a headless EMF export, attach verified `referenceDevice` metrics to `document`, call `run('export-emf', document, false)`, and write its buffer. To compare output sizes, reuse `document` with both `outputWidth` and `outputHeight`; do not retrace solely to resize vectors. + +## Sources + +- [Exact native stage schemas](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector-cli/src/numeric.rs). +- [Resolver validation and enums](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/settings.rs), [image analysis](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/image_pipeline.rs), [palette generation](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/palette.rs), [filename/shadow context](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/image_input.rs). +- [Contour topology](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/contours.rs), [fitted topology](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/contour_fitting.rs), [export validation](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/rust/crates/openvector/src/vector_output.rs). +- [Public types](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/npm/index.d.mts), [usage and stage examples](https://github.com/Microck/openvector/blob/36fefd1783a0d1c9300975ad33878cd3165ff48e/docs/usage.md). diff --git a/skills/openvector/scripts/inspect_svg.py b/skills/openvector/scripts/inspect_svg.py new file mode 100644 index 0000000..0383641 --- /dev/null +++ b/skills/openvector/scripts/inspect_svg.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Report SVG structure and physical/CSS size without claiming visual fidelity.""" +import argparse +import json +import re +import sys +from collections import Counter +from pathlib import Path +from xml.etree import ElementTree as ET +from xml.parsers import expat + + +def css_pixels(value): + if value is None: + return None + match = re.fullmatch(r"\s*([+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(px|pt|in|cm|mm|pc)?\s*", value) + if not match: + return None + factors = {None: 1, "px": 1, "pt": 96 / 72, "in": 96, "cm": 96 / 2.54, "mm": 96 / 25.4, "pc": 16} + return float(match[1]) * factors[match[2]] + + +def reject_entity(*_): + raise ValueError("Custom XML entities are not supported.") + + +def inspect(path): + raw = path.read_bytes() + # Keep standard SVG doctypes, but reject entities before expansion in any encoding. + parser = expat.ParserCreate() + parser.EntityDeclHandler = reject_entity + parser.ExternalEntityRefHandler = reject_entity + parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER) + try: + parser.Parse(raw, True) + except expat.ExpatError as error: + raise ValueError(f"Invalid XML: {error}") from error + root = ET.fromstring(raw) + tag = lambda element: element.tag.rsplit("}", 1)[-1] + if tag(root) != "svg": + raise ValueError("Root element is not SVG.") + counts = Counter(tag(element) for element in root.iter()) + paths = [element for element in root.iter() if tag(element) == "path"] + refs = [] + for element in root.iter(): + for key, value in element.attrib.items(): + if key.rsplit("}", 1)[-1] == "href" and not value.startswith("#"): + refs.append({"element": tag(element), "kind": "data" if value.startswith("data:") else "external"}) + return { + "file": str(path), + "bytes": len(raw), + "width": root.get("width"), + "height": root.get("height"), + "viewBox": root.get("viewBox"), + "intrinsicCssPixelsAt96Dpi": {"width": css_pixels(root.get("width")), "height": css_pixels(root.get("height"))}, + "elements": dict(sorted(counts.items())), + "nonemptyPaths": sum(bool(element.get("d", "").strip()) for element in paths), + "pathDataCharacters": sum(len(element.get("d", "")) for element in paths), + "imageElements": counts["image"], + "nonFragmentHrefReferences": refs, + "validation": "XML structure only; render and compare for appearance, topology, or color fidelity.", + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("files", nargs="+", type=Path) + args = parser.parse_args() + results = [] + failed = False + for path in args.files: + try: + results.append(inspect(path)) + except (OSError, ValueError, ET.ParseError) as error: + results.append({"file": str(path), "error": str(error)}) + failed = True + print(json.dumps(results, indent=2)) + return int(failed) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/openvector/scripts/prepare_export.mjs b/skills/openvector/scripts/prepare_export.mjs new file mode 100644 index 0000000..7e24c54 --- /dev/null +++ b/skills/openvector/scripts/prepare_export.mjs @@ -0,0 +1,129 @@ +#!/usr/bin/env node +// Capture native fitted geometry for openvector export-* commands. +import { readFileSync, writeFileSync, existsSync } from 'node:fs'; +import { resolve, basename } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { createRequire } from 'node:module'; + +const help = `Usage: node prepare_export.mjs IMAGE --output DOCUMENT.json [options] + +Trace once with the installed openvector Node addon, then reuse the JSON with +openvector export-svg, export-pdf, export-eps, export-ai, export-dxf, export-emf. + + --output PATH Required new JSON file; never overwrite existing files. + --module PATH Explicit npm/index.mjs from an installed package or build. + --batch-settings PATH Run native batch controls on this one image instead of auto. + --profile-record PATH Replay a record from profiles show instead of auto. + --shrink-source Apply native source reduction before tracing. + --help Show this help. + +Run from a project containing the openvector package, or supply --module. +--batch-settings and --profile-record are mutually exclusive. This helper does +not execute CLI --edits plans. The output uses grouped-cutouts explicitly. +For EMF, add your actual referenceDevice metrics to the JSON before exporting. +`; + +function parse(argv) { + const options = {}; + const positional = []; + const values = new Set(['--output', '--module', '--batch-settings', '--profile-record']); + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--') { positional.push(...argv.slice(i + 1)); break; } + if (arg === '--help') return { help: true }; + if (arg === '--shrink-source') { options.shrink = true; continue; } + if (values.has(arg)) { + if (options[arg] !== undefined || !argv[i + 1] || argv[i + 1].startsWith('--')) { + throw new Error(`Supply exactly one value for ${arg}.`); + } + options[arg] = argv[++i]; + } else if (arg.startsWith('-')) { + throw new Error(`Unknown option: ${arg}`); + } else positional.push(arg); + } + if (positional.length !== 1 || !options['--output']) { + throw new Error('Supply one image and --output DOCUMENT.json. Use --help for syntax.'); + } + if (options['--batch-settings'] && options['--profile-record']) { + throw new Error('Choose --batch-settings or --profile-record.'); + } + return { ...options, image: resolve(positional[0]), output: resolve(options['--output']) }; +} + +function objectFile(path) { + const value = JSON.parse(readFileSync(path, 'utf8')); + if (!value || Array.isArray(value) || typeof value !== 'object') { + throw new Error(`${path} must contain a JSON object.`); + } + return value; +} + +async function main() { + const args = parse(process.argv.slice(2)); + if (args.help) { process.stdout.write(help); return; } + if (existsSync(args.output)) throw new Error(`Output already exists: ${args.output}`); + + const requireFromProject = createRequire(resolve(process.cwd(), 'openvector-skill-loader.cjs')); + let modulePath; + try { + modulePath = args['--module'] ? resolve(args['--module']) : requireFromProject.resolve('openvector'); + } catch { + throw new Error('Cannot resolve openvector from the current project. Install it locally or supply --module /absolute/path/to/npm/index.mjs.'); + } + const { CoreSession } = await import(pathToFileURL(modulePath).href); + const document = new CoreSession().createDocument(); + document.setSource(readFileSync(args.image), args.image); + if (args.shrink) document.shrinkSource(); + // Match resolve_image_filename exactly: suffix matching is case-sensitive. + let separator = args.image.lastIndexOf('/'); + if (separator < 0) separator = args.image.lastIndexOf('\\'); + const dot = args.image.lastIndexOf('.'); + let extension = dot >= 0 && dot >= separator ? args.image.slice(dot) : ''; + if (extension === '.jpg') extension = '.jpeg'; + if (extension === '.tif') extension = '.tiff'; + + let result; + let workflow; + if (args['--batch-settings']) { + workflow = 'batch'; + result = document.runBatchImage({ ...objectFile(args['--batch-settings']), extension }); + } else if (args['--profile-record']) { + workflow = 'advanced-profile'; + const profile = objectFile(args['--profile-record']); + document.commitSettings(profile.settings); + result = document.runAdvancedProfile(profile, { backup: [], customized: false }); + if (!result) throw new Error('This profile does not process. Choose a processing palette mode; see edits-and-tuning.md.'); + } else { + workflow = 'automatic'; + result = document.runAutomatic({ extension }); + } + if (result.state.status !== 0 || !result.state.fittingComplete) { + throw new Error(`Tracing did not complete successfully (status ${result.state.status}).`); + } + const snapshot = document.snapshot({ fitting: true, segmentation: 'regions' }); + if (!snapshot.fitting?.complete || !snapshot.segmentation) { + throw new Error('Native snapshot lacks completed fitting or segmentation.'); + } + const [width, height] = snapshot.dimensions.original; + const output = { + width, + height, + geometry: snapshot.fitting.geometry, + palette: Array.from(snapshot.segmentation.palette), + hiddenRegions: Array.from(document.background().hiddenRegions), + layout: 'grouped-cutouts', + thinStroke: false, + _trace: { + sourceFilename: basename(args.image), + extension, + workflow, + dimensions: snapshot.dimensions, + settings: snapshot.settings, + randomState: snapshot.randomState, + }, + }; + writeFileSync(args.output, JSON.stringify(output) + '\n', { flag: 'wx' }); + process.stderr.write(`Saved fitted geometry: ${args.output}\n`); +} + +main().catch(error => { process.stderr.write(`${error.message}\n`); process.exitCode = 1; }); From 56d0e96cda1b233075ffe30e905bafe09ddd46d9 Mon Sep 17 00:00:00 2001 From: Microck <45483921+Microck@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:19:36 +0000 Subject: [PATCH 2/2] Fix alpha in staged exports and SVG inspection errors Reuse the native vector presentation colors and matching palette. Report unknown XML encodings without losing other files in the batch. Skill size: 11,086 bytes before; 11,009 bytes after. --- docs/usage.md | 7 +++++ npm/index.d.mts | 10 +++++++ rust/crates/openvector-cli/src/conversion.rs | 2 +- rust/crates/openvector-node/src/document.rs | 14 ++++++++++ rust/crates/openvector-node/src/snapshot.rs | 4 +-- rust/crates/openvector/src/image_document.rs | 5 ++-- skills/openvector/SKILL.md | 4 +-- skills/openvector/scripts/inspect_svg.py | 2 +- skills/openvector/scripts/prepare_export.mjs | 20 +++++--------- test/automatic-alpha-regression.test.mjs | 28 ++++++++++++++++++++ 10 files changed, 74 insertions(+), 22 deletions(-) diff --git a/docs/usage.md b/docs/usage.md index 21520a9..8cffc59 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -182,6 +182,13 @@ other opens. Both export calls need completed fitted geometry. See the [bitmap export](bitmap-export-contract.json) and [vector output](vector-output-contract.json) contracts. +`vectorExportInput()` returns `{ width, height, geometry, palette, hiddenRegions }` +for the CLI's `export-*` commands. It needs completed fitted geometry and uses +the same straight-alpha colors and matching palette as `saveVector`. A +`snapshot({ fitting: true })` instead reports the engine's numerical state. +Set layout and format-specific options on the export input before writing it +as JSON. For headless EMF, supply `referenceDevice` explicitly. + ### Batches Create a batch with `session.createBatch(applicationDirectory, workingDirectory)`. diff --git a/npm/index.d.mts b/npm/index.d.mts index 60973ad..b0c3e27 100644 --- a/npm/index.d.mts +++ b/npm/index.d.mts @@ -124,6 +124,14 @@ export interface FittedGeometry { }[]; } +export interface VectorExportInput { + width: number; + height: number; + geometry: FittedGeometry; + palette: number[]; + hiddenRegions: number[]; +} + /** Unrequested bulk sections are absent; requested unavailable sections are null. */ export interface DocumentSnapshot extends DocumentSummary { original?: RasterImage | null; @@ -429,6 +437,8 @@ export declare class ImageDocument { exportBitmap(format: string, scale?: number, flatten?: boolean): Buffer; /** Writes atomically only if the destination does not exist. Cancellation leaves no final file. */ saveVector(filename: string, options: ExportOptions, progress?: (percent: number) => boolean): SaveVectorResult; + /** Returns straight-alpha fitted data for CLI export stages. Throws before fitting completes. */ + vectorExportInput(): VectorExportInput; reset(): void; } diff --git a/rust/crates/openvector-cli/src/conversion.rs b/rust/crates/openvector-cli/src/conversion.rs index 5673311..a754275 100644 --- a/rust/crates/openvector-cli/src/conversion.rs +++ b/rust/crates/openvector-cli/src/conversion.rs @@ -168,7 +168,7 @@ pub fn vectorize(args:&[String])->Result<()>{ let bytes=if let Some(format)=bitmap{ openvector::bitmap_export::export_bitmap(&BitmapExportInput{geometry:Some(&fitted),width:state.original.width as i64,height:state.original.height as i64,source_alpha_type:document.source_alpha_type(),background_mode:state.settings.background_mode,background_undo_count:background.undo.len(),hidden_regions:&hidden},&BitmapExportOptions{format,scale,flatten:args.flag("flatten")}).map_err(|e|match e{BitmapExportError::FlattenRequired=>"Non-PNG output may discard transparency. Use --flatten to continue, or --format png to preserve it.".into(),other=>other.to_string()})? }else{ - let mut request=json!({"width":state.original.width,"height":state.original.height,"palette":document.presentation_palette(),"hiddenRegions":hidden,"layout":export.layout.name(),"thinStroke":export.thin_stroke,"compact":export.compact,"curveMode":export.curve_mode.name()}); + let mut request=json!({"width":state.original.width,"height":state.original.height,"palette":document.presentation_palette(&fitted),"hiddenRegions":hidden,"layout":export.layout.name(),"thinStroke":export.thin_stroke,"compact":export.compact,"curveMode":export.curve_mode.name()}); if format=="emf"{ let device=openvector::emf::EmfDevice::current_display().map_err(|error|error.to_string())?; request["referenceDevice"]=json!({"pixels":device.pixels,"millimeters":device.millimeters,"micrometers":device.micrometers}); diff --git a/rust/crates/openvector-node/src/document.rs b/rust/crates/openvector-node/src/document.rs index fe9f25a..1cbee97 100644 --- a/rust/crates/openvector-node/src/document.rs +++ b/rust/crates/openvector-node/src/document.rs @@ -380,6 +380,20 @@ impl ImageDocument { json!({"message": error.to_string(), "osError": error.raw_os_error()}))})) } + #[napi] + pub fn vector_export_input<'env>(&self, env: Env) -> Result> { + let geometry = self.inner.presentation_geometry() + .ok_or_else(|| engine_error("Document export needs completed fitted geometry."))?; + let state = self.inner.state(); + let mut input = Object::new(&env)?; + input.set("width", state.original.width as u32)?; + input.set("height", state.original.height as u32)?; + input.set("geometry", snapshot::fitted_geometry(env, &geometry)?)?; + input.set("palette", self.inner.presentation_palette(&geometry))?; + input.set("hiddenRegions", snapshot::indices(&env, &self.inner.background_state().hidden_regions)?)?; + Ok(input) + } + #[napi] pub fn reset(&mut self) { self.inner.reset(); } } diff --git a/rust/crates/openvector-node/src/snapshot.rs b/rust/crates/openvector-node/src/snapshot.rs index 56ef079..0964f64 100644 --- a/rust/crates/openvector-node/src/snapshot.rs +++ b/rust/crates/openvector-node/src/snapshot.rs @@ -158,7 +158,7 @@ fn array<'env, T, U: ToNapiValue>(env: &'env Env, values: impl ExactSizeIterator Ok(output) } -fn indices<'env>(env: &'env Env, values: &[usize]) -> Result> { +pub(crate) fn indices<'env>(env: &'env Env, values: &[usize]) -> Result> { array(env, values.iter(), |&value| Ok(value as f64)) } @@ -183,7 +183,7 @@ fn contours<'env>(env: Env, geometry: &openvector::contours::Geometry) -> Result Ok(object) } -fn fitted_geometry<'env>(env: Env, geometry: &openvector::contour_fitting::FittedGeometry) -> Result> { +pub(crate) fn fitted_geometry<'env>(env: Env, geometry: &openvector::contour_fitting::FittedGeometry) -> Result> { let nodes = array(&env, geometry.nodes.iter(), |node| { let mut object = Object::new(&env)?; object.set("x", node.x)?; object.set("y", node.y)?; diff --git a/rust/crates/openvector/src/image_document.rs b/rust/crates/openvector/src/image_document.rs index 45632a4..79e0181 100644 --- a/rust/crates/openvector/src/image_document.rs +++ b/rust/crates/openvector/src/image_document.rs @@ -63,12 +63,11 @@ impl ImageDocument{ } /// Match the output geometry's color space in serializers that name colors /// from the palette (notably DXF layer tables). - pub fn presentation_palette(&self)->Vec{ + pub fn presentation_palette(&self,geometry:&FittedGeometry)->Vec{ let palette=self.state.segmentation.as_ref().map_or(&[][..],|s|s.palette.as_slice()); if self.automatic_palettes.is_empty()&&!self.segmentation_palette_premultiplied{return palette.to_vec();} // The mutable settings palette can differ from fitted edited regions. // DXF layer names must correspond to the exact colors it draws. - let Some(geometry)=self.presentation_geometry() else{return palette.to_vec()}; let mut seen=std::collections::HashSet::new(); let mut output=Vec::new(); for region in &geometry.regions{ @@ -271,7 +270,7 @@ impl ImageDocument{ if input.reference_device.is_none()&&path.as_os_str().as_encoded_bytes().ends_with(b".emf"){ input.reference_device=Some(crate::emf::EmfDevice::current_display().map_err(|e|e.to_string())?); } - let palette=self.presentation_palette(); + let palette=self.presentation_palette(&geometry); input.palette=&palette; input.dxf_curve_mode=match options.curve_mode{crate::export_options::CurveMode::Splines=>crate::dxf::DxfCurveMode::Splines,crate::export_options::CurveMode::SparseLines=>crate::dxf::DxfCurveMode::SparseLines,crate::export_options::CurveMode::DenseLines=>crate::dxf::DxfCurveMode::DenseLines}; let progress=&mut self.state.progress;let cancel=&self.cancel; diff --git a/skills/openvector/SKILL.md b/skills/openvector/SKILL.md index d6c472a..798b373 100644 --- a/skills/openvector/SKILL.md +++ b/skills/openvector/SKILL.md @@ -66,7 +66,7 @@ Use the exact enum meanings, ranges, and processing order in [edits and tuning]( ## Reuse fitted geometry -Resolve `OPENVECTOR_SKILL_DIR` to the directory containing this file. The bundled bridge uses the native public Node addon and writes a new JSON file with fitted geometry, source dimensions, segmentation palette, hidden regions, explicit layout and trace metadata. Run it from a project containing `openvector`, or supply `--module /absolute/path/to/openvector/npm/index.mjs` for a known installation/build. +Set `OPENVECTOR_SKILL_DIR` to this skill's directory. The helper needs a local package with `document.vectorExportInput()`. For a source build, pass `--module /absolute/path/to/openvector/npm/index.mjs`. OpenVector 0.1.8 supports [`saveVector`](references/setup-and-api.md#convert-once-export-several-times) but lacks this helper's API. ```sh node "$OPENVECTOR_SKILL_DIR/scripts/prepare_export.mjs" logo.png --output fitted.json @@ -88,7 +88,7 @@ for fmt in ("svg", "pdf", "dxf"): output.write(result.stdout) ``` -Keep the segmentation palette for DXF. For EMF, add `referenceDevice` with positive-int32 `[x,y]` pairs named `pixels`, `millimeters`, and `micrometers`; obtain the intended measurements rather than inventing a display. For requested output dimensions, supply both `outputWidth` and `outputHeight` as positive int32 values. +Keep the export palette for DXF. For EMF, add `referenceDevice` with positive-int32 `[x,y]` pairs named `pixels`, `millimeters`, and `micrometers`; obtain the intended measurements rather than inventing a display. For requested output dimensions, supply both `outputWidth` and `outputHeight` as positive int32 values. ## Validate and report the deliverable diff --git a/skills/openvector/scripts/inspect_svg.py b/skills/openvector/scripts/inspect_svg.py index 0383641..b737374 100644 --- a/skills/openvector/scripts/inspect_svg.py +++ b/skills/openvector/scripts/inspect_svg.py @@ -33,7 +33,7 @@ def inspect(path): parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER) try: parser.Parse(raw, True) - except expat.ExpatError as error: + except (expat.ExpatError, LookupError) as error: raise ValueError(f"Invalid XML: {error}") from error root = ET.fromstring(raw) tag = lambda element: element.tag.rsplit("}", 1)[-1] diff --git a/skills/openvector/scripts/prepare_export.mjs b/skills/openvector/scripts/prepare_export.mjs index 7e24c54..ee7669d 100644 --- a/skills/openvector/scripts/prepare_export.mjs +++ b/skills/openvector/scripts/prepare_export.mjs @@ -72,6 +72,9 @@ async function main() { } const { CoreSession } = await import(pathToFileURL(modulePath).href); const document = new CoreSession().createDocument(); + if (typeof document.vectorExportInput !== 'function') { + throw new Error('This helper requires an OpenVector build with vectorExportInput(). Build this checkout and supply --module.'); + } document.setSource(readFileSync(args.image), args.image); if (args.shrink) document.shrinkSource(); // Match resolve_image_filename exactly: suffix matching is case-sensitive. @@ -100,26 +103,17 @@ async function main() { if (result.state.status !== 0 || !result.state.fittingComplete) { throw new Error(`Tracing did not complete successfully (status ${result.state.status}).`); } - const snapshot = document.snapshot({ fitting: true, segmentation: 'regions' }); - if (!snapshot.fitting?.complete || !snapshot.segmentation) { - throw new Error('Native snapshot lacks completed fitting or segmentation.'); - } - const [width, height] = snapshot.dimensions.original; const output = { - width, - height, - geometry: snapshot.fitting.geometry, - palette: Array.from(snapshot.segmentation.palette), - hiddenRegions: Array.from(document.background().hiddenRegions), + ...document.vectorExportInput(), layout: 'grouped-cutouts', thinStroke: false, _trace: { sourceFilename: basename(args.image), extension, workflow, - dimensions: snapshot.dimensions, - settings: snapshot.settings, - randomState: snapshot.randomState, + dimensions: result.state.dimensions, + settings: result.state.settings, + randomState: result.state.randomState, }, }; writeFileSync(args.output, JSON.stringify(output) + '\n', { flag: 'wx' }); diff --git a/test/automatic-alpha-regression.test.mjs b/test/automatic-alpha-regression.test.mjs index d529221..387fc01 100644 --- a/test/automatic-alpha-regression.test.mjs +++ b/test/automatic-alpha-regression.test.mjs @@ -36,6 +36,34 @@ function fixture() { return Buffer.concat([Buffer.from('89504e470d0a1a0a', 'hex'), chunk('IHDR', header), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]); } + +test('vector export input projects automatic color without altering the snapshot', () => { + const document = new native.CoreSession().createDocument(); + assert.throws(() => document.vectorExportInput(), /completed fitted geometry/); + document.setSource(fixture(), 'transparent-red.png'); + document.runAutomatic({extension: '.png'}); + + const {width, height, geometry, palette, hiddenRegions} = document.vectorExportInput(); + assert.deepEqual([width, height], [48, 48]); + assert.deepEqual(hiddenRegions, []); + assert.deepEqual(geometry.regions.find(region => region.bgra[3] === 128).bgra, [0, 0, 255, 128]); + assert.ok(palette.some((_, i) => i % 4 === 0 && palette[i + 2] === 1 && palette[i + 3] === Math.fround(128 / 255))); + const snapshot = document.snapshot({fitting: true}); + assert.deepEqual(snapshot.fitting.geometry.regions.find(region => region.bgra[3] === 128).bgra, [0, 0, 128, 128]); +}); + +test('vector export input keeps straight custom palette colors', () => { + const document = new native.CoreSession().createDocument(); + document.setSource(fixture(), 'transparent-red.png'); + const palette = [0, 0, 0, 0, 0, 0, 0.8, 128 / 255]; + const {state} = document.runBatchImage({extension: '.png', advanced: true, category: 0, quality: 1, + paletteMode: 0, backgroundMode: 0, palette}); + assert.equal(state.status, 0); + const input = document.vectorExportInput(); + assert.deepEqual(input.palette, palette.map(Math.fround)); + assert.deepEqual(input.geometry.regions.find(region => region.bgra[3] === 128).bgra, [0, 0, 204, 128]); +}); + test('automatic transparent red remains straight RGB in SVG', () => { const document = new native.CoreSession().createDocument(); document.setSource(fixture(), 'transparent-red.png');