/spark-to-paper:ts-figure-optimizefrom spark-to-paper
Vectorizes raster scientific figures (PNG/JPG) into editable SVGs, PDFs, and PPTXs using DrawAI's hybrid approach — keeps the raster pixel-exact while overlaying editable text labels.
Ships in spark-to-paper. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
This is the suite's only figure vectorizer, and it runs DrawAI's key-free HYBRID: SAM3 segments
the layout and PaddleOCR reads the text locally (on a GPU box, no Claude/Codex account), then a
deterministic build keeps the approved render pixel-exact and lays an editable <text> overlay
on top — exported as a self-contained SVG + vector PDF + editable PPTX (~0.91 SSIM; ~63 editable text
boxes on the test figure). The figure's richness is preserved EXACTLY (the graphics ARE the approved
render) while every label becomes editable.
Hybrid is the ONLY mode used. The engine also contains a legacy Codex full-vector redraw
(run_reconstruction.py) — it is off: it needs an LLM account, and a full redraw of a dense figure
measurably loses fidelity vs the exact render (~0.67 vs 0.91 SSIM). So the suite rule is HYBRID, or
else keep the approved PNG — never redraw.
It does NOT just embed the bitmap into a slide: it reads every label and re-lays it as editable text over the exact render. The genuinely complex graphics stay as the render raster (that is the point — pixel-exact richness), not a lossy trace.
You have a single raster figure (e.g. an approved gpt-image schematic) and want it editable without losing any richness. Input: a PNG/JPG path. If the DrawAI runtime can't be provisioned, the caller keeps the approved PNG as-is — there is no lightweight redraw fallback.
The DrawAI source (~5 MB, includes the MPS guard fix) is vendored inside this skill at
engine/ — so the skill is self-contained for code and needs no separate DrawAI checkout. The
heavy runtime is NOT vendored: ~4 GB model weights (SAM3/PaddleOCR/RMBG) + a runtime venv are
provisioned on deploy by scripts/setup_drawai.py (below). The orchestrator points at engine/ by
default (override with --drawai-repo/DRAWAI_REPO). Updates are manual — re-vendor engine/
from upstream DrawAI yourself when you want a newer version (see references/drawai_adapter.md; the
vendored commit is recorded in engine/ENGINE_VERSION.txt).
scripts/setup_drawai.pyThe model runtime (SAM3 / PaddleOCR / RMBG weights + venv, ~8 GB) is deployed inside this skill at
ts-figure-optimize/engine/.local/drawai_runtime/ (gitignored — code is in git, the multi-GB weights are
provisioned on disk under the skill, never committed). It is self-contained under spark-to-paper-skills,
not borrowed from any outer checkout. run_hybrid.py AUTO-DEPLOYS it before running if it's missing,
so you normally don't call setup manually — but you can:
python scripts/setup_drawai.py --device cpu # download ~4GB models + build the runtime venv (under the skill)
python scripts/setup_drawai.py --check-only # verify the runtime is ready (drawai doctor)
python scripts/setup_drawai.py --reuse-runtime <path> # reuse an existing .local/drawai_runtime (skip download)
It tries DrawAI's official setup local first, and falls back to the validated manual install (paddle
from PyPI, CPU torch, openai-codex via pypi.org/simple, editable engine + runtime deps, sam3, triton)
when the official bootstrap can't reach its indexes. (Codex auth is needed ONLY for the legacy pure-A
redraw — the HYBRID path below is key-free.)
✅ VERIFIED key-free GPU recipe — ModelScope, NO HF token (validated 2026-06-23 on a 6×A40 box). The
HYBRID path needs no LLM key at all; models come from ModelScope (default --source modelscope,
which is NOT gated — this is why no HF_TOKEN is required):
pip install uv (any env), then python scripts/setup_drawai.py --device gpu → builds the runtime venv
(Python 3.12, torch+cu12x, paddlepaddle CPU) and downloads sam3.pt (~3.3 GB) / RMBG-2.0 / PP-OCRv5 from
ModelScope. No HF_TOKEN, no Codex login for the hybrid. (~13 GB on disk under engine/.local/.)PaddlePaddle/PP-OCRv5_* is empty on ModelScope). If
<runtime>/models/paddlex/official_models/PP-OCRv5_server_{det,rec}/inference.pdiparams are missing,
copy them from PaddleOCR's standard cache (it fetches them on first use):
cp -rn ~/.paddlex/official_models/PP-OCRv5_server_{det,rec} <runtime>/models/paddlex/official_models/.--device gpu; run_hybrid.py now
maps SAM3/RMBG→cuda and paddle→cpu automatically.pip install python-pptx cairosvg numpy Pillow into the interpreter that runs
build_hybrid_pptx.py (it uses the HOST python, not the runtime venv).drawai doctor flags Chrome + Codex auth missing — IGNORE for the hybrid (those are only for the
legacy pure-A redraw; the hybrid uses cairosvg + no LLM).python scripts/run_hybrid.py --image fig.png --run-name <n> --device gpu --no-text-gpt
(--no-text-gpt skips the only optional LLM step — GPT text-correction; have Claude do that
per-region text correction instead if you want OCR subscript/case fixes, keeping the whole flow key-free).python scripts/setup_drawai.py --check-only → doctor: OK.
If not: python scripts/setup_drawai.py --device cpu (provisions the vendored engine/:
downloads SAM3/PaddleOCR/RMBG ~4 GB + builds the runtime venv). The DrawAI source is already
vendored at engine/ (no separate checkout needed).~/.codex/auth.json or OPENAI_API_KEY) — DrawAI's SVG/run0 agent
(gpt-5.5) needs it. (Measured comparison showed Codex/gpt-5.5 outperforms a Claude-CLI agent for
this generation task, so Codex is the engine here.)soffice) enables the PPTX render gate; if absent the PPTX
render is NOT_RUN and the run cannot auto-PASS (still produces SVG/PPTX/PDF).scripts/run_hybrid.py — Codex-free preprocessing + HYBRID exportThis is the production path. It was validated head-to-head against pure-A on the same fresh run: HYBRID ≈ 0.91 SSIM vs pure-A ≈ 0.67, and it is much cheaper because it SKIPS the Codex vector redraw entirely. One figure:
python scripts/run_hybrid.py --image <figure.png> --run-name <name> [--runs-root runs] [--device cpu] \
[--runtime-root .local/drawai_runtime] [--no-text-gpt]
Flow:
run_preprocess_ir.py: prepare → SAM3 → OCR → Box-IR).verify_text_gpt.py) — fixes OCR-dropped subscripts/case.build_hybrid_pptx.py): pixel-exact graphics raster + editable text boxes (real
sub/superscripts) → final/editable_hybrid.{pptx,pdf,svg}.runs/<name>/: source/source.png, ir/ (box_ir + ocr), final/editable_hybrid.*,
comparisons/ (corrected_texts.json, hybrid_report.json, pptx_hybrid.json).scripts/run_reconstruction.pyKept for the rare case where you need every element (incl. graphics) as editable vector, accepting the lower fidelity (~0.67–0.8) and the Codex cost. It runs the full DrawAI Codex redraw + measured loop. Do NOT use it as the default — the hybrid flow above is better and cheaper.
python scripts/run_reconstruction.py --image <fig.png> --run-name <name> --device cpu --max-rounds 10 [--no-repair]
It drives DrawAI's full pipeline (normalize → SAM3 → OCR → Box-IR → classify → Codex SVG → validate →
native PPTX), then a measured best-of-rounds loop (SSIM/region/OCR/formula + RASTER_BACKGROUND_MATCH /
WAVEFORM_STYLE gates). Output: svg/semantic.svg, pptx/editable.pptx, pdf/publication_figure.pdf.
After the base reconstruction, run a targeted refinement loop whose goal is structural/logical correctness, NOT pixel-identity. Fonts, anti-aliasing, and exact colours MAY differ (that gap is accepted and unfixable for an editable redraw). What MUST be fixed: wrong/missing/extra arrows or reversed data-flow, misalignment, wrong relative positions of panels/icons/pictures, inconsistent / wrong / missing / duplicated icons, and any incoherence vs the original.
Loop (Claude is the judge+editor; the scripts are guides — edits are on the SVG master = the PPTX shapes 1:1, then the PPTX is re-exported):
1. render the current SVG (scripts/render_svg.py)
2. PER-REGION VISION COMPARE (the core — metrics CANNOT see semantic defects):
AUTOMATED: scripts/vision_region_diff.py sends each region's [SOURCE | RENDER] pair (upscaled) to a
vision model (gpt-5.5; OpenAI-compatible, key from ~/.codex/auth.json) and writes a structured
comparisons/vision_defects.json with the defect categories below. Use a GRID (`--grid 3/4`) so cells
span ADJACENT elements (inter-element overlaps like matrix-vs-colourbar are only visible across a
boundary; tight per-element Box-IR crops miss them). Do NOT pass temperature (gpt-5.5 rejects it).
MANUAL fallback: scripts/region_crops.py emits the same pairs for the skill executor (Claude) to READ
and emit the same JSON by hand. Either way, judge each region against this SEMANTIC checklist
(ignore font/AA/colour-shade):
- text OVERFLOWING / spilling outside its box or panel
- any element OVERLAPPING/colliding with another (arrow over a figure; matrix over its colourbar)
- WRONG ICON semantics (a cycle/loop ↻ drawn as a straight arrow; ↔ drawn as →; garbled icon)
- MISALIGNED / unevenly-sized repeated shapes (encoder bars, rows, badges)
- MISSING / DUPLICATED / wrongly-POSITIONED elements vs source
(scripts/diff_overlay.py heatmap + scripts/compare_regions.py SSIM only say WHERE to look first.)
3. Build the defect list from the per-region vision pass (NOT from SSIM — SSIM misses all of the above).
4. FIX — two strategies per defect:
(a) VECTOR surgical edit (preferred, stays editable): redirect/add/remove an arrow, add a marker-end
arrowhead, move/resize a box so text fits, shift the colourbar/label off the matrix, align the bars.
(b) RASTER-CROP-EMBED fallback (when a shape/icon is too complex to redraw faithfully — e.g. an
intricate loop ↻ glyph, a detailed sub-figure): `scripts/crop_region.py --source <orig> --bbox …
--out asset.png --nobg` crops that ONE element from the ORIGINAL image and removes its background,
then embed it as a coordinated sub-region `<image>` at the right position. It MUST pass
`RASTER_BACKGROUND_MATCH` (transparent / panel-matched, no visible rectangle) so it blends. Use for
SUB-regions only, never the whole canvas.
Do not regenerate the whole figure.
5. re-render; re-view that region's pair: defect gone AND no new overlap/overflow introduced AND untouched
regions unchanged. Keep the edit only if its region's defect list shrank with no regression.
6. repeat per region / per round until the per-region semantic-defect list is EMPTY (or budget).
Acceptance = the per-region semantic-defect checklist is empty (report any remaining as author-review),
NOT a pixel-SSIM threshold — SSIM does not move for these fixes (a hat, a redirected arrow, a separated
colourbar barely change pixels), which is exactly why the vision pass is mandatory. Pixel SSIM is only a coarse "where to look" guide — a faithful redraw tops out
around ~0.8x vs the original raster because of accepted font/AA/colour differences. Re-export the PPTX
from the refined SVG when done (drawai --from-stage svg_to_ppt_exported).
scripts/build_hybrid_pptx.py) — when visual fidelity matters mostAn alternative to the LLM redraw that reaches ~0.90 SSIM (the editable-redraw ceiling) cheaply and deterministically (no Codex): keep the source figure's GRAPHICS as a pixel-exact raster with the text removed, and re-create every OCR'd text run as a genuinely editable PPTX text box (and selectable PDF/SVG text). For "faithful + editable text" this beats the full vector redraw (~0.67–0.8) at near-zero cost and with zero text doubling/offset.
python scripts/build_hybrid_pptx.py --source <run>/source/source.png \
--ocr <run>/ir/ocr_boxes.json --box-ir <run>/ir/box_ir.json \
--out-pptx <run>/final/editable_hybrid.pptx --out-pdf <run>/final/editable_hybrid.pdf \
--out-svg <run>/final/editable_hybrid.svg --report <run>/comparisons/hybrid_report.json
sx=W_src/canvas.width, sy=H_src/canvas.height). This scale is mandatory —
skipping it shifts/oversizes the text and is exactly what causes duplication/offset. Works at any input
resolution as long as ocr_boxes.json + box_ir.json come from the same DrawAI run.ink = lum<bg_lum-22 OR colour-dist>60) repaints text pixels with the local
bg; text colour from the box's CENTRAL vertical band (0.22–0.78, darkest 30%); horizontal position from
the actual ink start, size fitted to the ink WIDTH (capped by box height) so loose OCR boxes don't
oversize small labels; sub/superscripts are rendered as real baseline-shifted runs (font-independent,
truly editable, no missing-glyph "tofu").onset Ot, Za, Zsa). Run scripts/verify_text_gpt.py FIRST — it sends each text region's source
crop to a vision model and returns the exact text (case + Unicode sub/superscripts), written to
corrected_texts.json; pass it to build_hybrid_pptx.py --text-overrides corrected_texts.json. This is
TARGETED per-region transcription (reliable), unlike the stochastic whole-figure defect detector.
python scripts/verify_text_gpt.py --source <run>/source/source.png --ocr <run>/ir/ocr_boxes.json \
--box-ir <run>/ir/box_ir.json --out <run>/comparisons/corrected_texts.json
Even at PASS, show: source, rendered SVG, rendered PPTX, combined score, lowest-scoring regions, formula verification, remaining raster assets. Do not finalize without explicit approval.
Orchestrators: run_hybrid.py (DEFAULT — Codex-free IR + hybrid export) and run_preprocess_ir.py
(its Codex-free IR step, runs in the runtime venv); run_reconstruction.py is the LEGACY pure-A entry.
render_svg.py (SVG→PNG), render_pptx.py (LibreOffice→PNG or NOT_RUN), measure_similarity.py,
compare_regions.py, verify_text_and_formulas.py, verify_pptx_editability.py,
fix_raster_backgrounds.py (RASTER_BACKGROUND_MATCH), verify_waveforms.py + waveform_primitive.py
(WAVEFORM_STYLE), diff_overlay.py (Stage R heatmap/worst-cells), region_crops.py (Stage R region pairs), vision_region_diff.py (Stage R automated gpt-vision per-region defect detector),
build_hybrid_pptx.py (high-fidelity HYBRID export: exact graphics raster + editable text boxes w/ real sub/superscripts, ~0.90 SSIM, no Codex — see section above),
verify_text_gpt.py (GPT-vision per-region text correction: fixes OCR-dropped subscripts/case → corrected_texts.json for build_hybrid_pptx.py --text-overrides),
build_report.py, and export_paper_figure.py (map a finished run into the ts-paper
figure contract: self-contained figures/<label>.svg + .pdf + kept .png).
ts-paper-figure calls this as the sole vectorizer for free-form image-model schematics: run the
hybrid on the approved PNG (run_hybrid.py --no-text-gpt), then export_paper_figure.py to drop the
self-contained figures/<label>.svg + .pdf (+ kept .png) into figures/, then lint via the shared
gate (scripts/check_vector_pdf.py lint --type <type> --render-check). If the DrawAI runtime can't be
provisioned, ts-paper-figure keeps the approved PNG as-is — there is NO redraw fallback. The main
method-overview schematic is results-independent → vectorize it ONCE at the proposal/first-draft figure
stage, never deferred to a post-experiment re-run.
references/workflow.md, references/quality_metrics.md, references/text_and_formula_rules.md,
references/local_repair_strategy.md, references/drawai_adapter.md, references/failure_handling.md.
run_reconstruction.py with repair ON and the default --max-rounds (the measured best-of-rounds
SSIM/region loop + Stage-R structural-defect pass); never pass --no-repair or --max-rounds 1
to cut the loop short unless the user has explicitly opted into a fast/degraded pass. A single-pass
redraw is acceptable only on explicit user request, and the degradation must be stated.<text>.engine/ENGINE_VERSION.txt (opens in a new tab)engine/LICENSE (opens in a new tab)engine/README.md (opens in a new tab)engine/configs/drawai/config.template.yaml (opens in a new tab)engine/configs/drawai/config.yaml (opens in a new tab)engine/configs/drawai/config_fast_poster.yaml (opens in a new tab)engine/configs/drawai/harbor_smoke_2048.yaml (opens in a new tab)engine/pyproject.toml (opens in a new tab)engine/scripts/assets_visualization.py (opens in a new tab)engine/scripts/bootstrap_drawai_local_runtime.sh (opens in a new tab)engine/scripts/build_assemble_debug_report.py (opens in a new tab)engine/scripts/build_drawai_run_comparison.py (opens in a new tab)engine/scripts/build_editability_paper_figure.py (opens in a new tab)engine/scripts/build_element_distribution_map.py (opens in a new tab)engine/scripts/build_scheme_a_overview_figure.py (opens in a new tab)engine/scripts/download_drawai_local_models.sh (opens in a new tab)engine/scripts/ensure_local_codex_gateway.py (opens in a new tab)engine/scripts/run_codex_element_analysis.py (opens in a new tab)engine/scripts/run_codex_python_sdk_imagegen.py (opens in a new tab)engine/scripts/run_codex_python_sdk_svg_stage.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Generated from the plugin's indexed repository (spark-to-paper-skills/spark-to-paper-skills) — no native marketplace selected
npx claudepluginhub p/spark-to-paper-skills-spark-to-paper14 skills in this plugin
/ts-figure-svgPaperBanana+ — turn a paper's figure brief into a native, editable, publication-grade SVG. Stage 1 runs the OFFICIAL PaperBanana (dwzhu-pku/PaperBanana, pulled by `setup_paperbanana.py`, its own Retriever→Planner→Stylist→Visualizer→Critic pipeline) to produce candidate PNGs. Stage 2 is the "+": Claude LOOKS at the chosen PNG, extracts its DESIGN LANGUAGE (palette, type scale, spacing, idiom) into a style sheet, then redraws the figure FROM THE PAPER'S FACTS as real <rect>/<path>/<text> objects — never tracing pixels, never embedding the PNG. Stage 3 is a measured repair loop: `audit_svg.py` (stdlib, no renderer needed) catches overflow, text-on-text, icons cutting labels, stroke-scaled and canvas-clipped arrowheads, dangling connectors, sub-legible type, font-fallback glyphs, CSS-cascade colour traps and traced path-soup; ≥4 rounds, no upper bound while defects remain. Ends on a vector PDF verified on the real compiled page. Use when a figure must be editable and correct, not merely pretty.
/ts-idea2storyTurn a raw research idea into a compelling, well-grounded research STORY (an 8-field structured proposal) ready to feed the ts-paper pipeline. Claude does almost everything natively — idea packaging, recall reasoning over a knowledge graph, agentic external literature search (WebSearch/WebFetch), story generation, and a critique→refine→fusion loop; tiny scripts do only embeddings/recall math and the schema gate. Emits story.json + story_proposal.md + retrieved_papers.json (a citation seed the cite stage reuses, so paper-writing searches less). Use when the user has an idea (not yet a full proposal) and wants a paper-ready story.
/ts-kg-buildBuild a reusable research-PATTERN knowledge graph from a paper corpus, so ts-idea2story can recall prior problem→solution→story patterns. Claude does the reasoning (story-first pattern extraction, cluster naming + summaries); small scripts do the irreducible math (embeddings via a USER-SUPPLIED endpoint, clustering, graph assembly). Best-effort and honestly optional — without an embedding endpoint it degrades to a flat in-context "pattern shelf". Use to (re)build the KG for a domain, or skip it and let ts-idea2story rely on web search alone.
/ts-paperGenerate a complete, publication-format journal/conference paper (LaTeX → compiled PDF) from whatever the user drops — a one-line idea, a proposal, or a proposal WITH real results. It ROUTES the input (idea→idea2story; proposal→proposal mode; results-present→data-aware mode), then runs plan→cite→write→refine→review→figure→latex using Claude's native abilities (reasoning, WebSearch, vision, file I/O, running Python) instead of a heavyweight per-call pipeline. Template-agnostic (ts_iieta + neurips bundled). Use for "write the paper", "proposal to paper", "turn this idea/report into a paper". Integrity is absolute: in proposal mode never fabricate numbers; in data-aware mode every number must trace to the user's real data.
/ts-paper-citeStage 2 of the ts-paper suite. Build a complete, REAL refs.bib for a Traitement du Signal paper — using the user's provided references first and Claude's native WebSearch/WebFetch only for genuine gaps. Every entry must have full metadata (authors, year, venue, vol(issue):pages, DOI); never a title-only stub; reference count is driven by real evidence, not a quota. Use when assembling or fixing the bibliography of a TS paper, or whenever citations must be real and complete.
/ts-paper-dataDATA-AWARE mode for the ts-paper suite. Activated by the orchestrator's router ONLY when the input ships REAL measured results (results_mode == "data_aware"); the proposal/no-numbers path is unchanged. Claude reads the user's data in ANY form (CSV / JSON / a pasted table / numbers in prose), judges it directly — there is NO fixed results schema — fills the result tables itself with real numbers in past tense, and writes the per-section text from the evidence. Two thin code backstops keep it honest: a schema-agnostic number-audit (draft_lint) and matplotlib results figures (plot_results.py). Use when a proposal/report comes with real experimental data.
Other plugins' skills for the same job