kicad monkey v2026.11.30
On This Page (5)

Examples Showcase / sexp_filters_and_pipeline

Lossless S-Expression Repair & KiCadFilterPipeline

Query and repair malformed footprint pads with parse_sexp(), find_all_elements(), normalize_unsafe_footprint_pad_sizes(), and KiCadFilterPipeline without disturbing untouched tokens.

pcbfootprintsexpsexpfiltersmutationroundtrip

Demonstrate lossless S-expression inspection and repair using parse_sexp(), find_all_elements(), format_sexp(), normalize_unsafe_footprint_pad_sizes(), and KiCadFilterPipeline on a footprint extracted from hlr_test.kicad_pcb, preserving untouched graphics and embedded 3D STEP data.

What It Shows

  1. Extracting a standalone KiCadFootprint from a board with extract_footprints_from_pcb()
  2. Parsing and querying native KiCad S-expressions via parse_sexp(), find_all_elements(), and format_sexp()
  3. Repairing malformed zero-size pads with normalize_unsafe_footprint_pad_sizes()
  4. Running KiCadFilterPipeline.filter_footprint() and verifying embedded 3D models survive intact

Input

text
examples/assets/projects/hlr_sot23/hlr_test.kicad_pcb

Run

From the repository root:

sh
uv run python examples/sexp_filters_and_pipeline/sexp_filters_and_pipeline.py

Output

text
examples/sexp_filters_and_pipeline/output/original_footprint.kicad_mod
examples/sexp_filters_and_pipeline/output/unsafe_pad_footprint.kicad_mod
examples/sexp_filters_and_pipeline/output/repaired_pad_footprint.kicad_mod
examples/sexp_filters_and_pipeline/output/filtered_footprint.kicad_mod
examples/sexp_filters_and_pipeline/output/sexp_pipeline_report.json

Source Code

examples/sexp_filters_and_pipeline/sexp_filters_and_pipeline.py
"""Lossless S-expression queries, KiCadFilterPipeline, and pad-size normalization."""

from __future__ import annotations

import json
from pathlib import Path

from kicad_monkey import (
    KiCadFilterPipeline,
    KiCadFootprint,
    build_sexp,
    find_all_elements,
    format_sexp,
    normalize_unsafe_footprint_pad_sizes,
    parse_sexp,
)
from kicad_monkey.kicad_footprint_extractor import extract_footprints_from_pcb

HERE = Path(__file__).resolve().parent
INPUT_PCB = HERE.parent / "assets" / "projects" / "hlr_sot23" / "hlr_test.kicad_pcb"
OUT_DIR = HERE / "output"


def main() -> None:
    OUT_DIR.mkdir(parents=True, exist_ok=True)

    # 1. Extract standalone .kicad_mod footprints from hlr_test.kicad_pcb
    extracted_dir = OUT_DIR / "extracted"
    extracted_dir.mkdir(parents=True, exist_ok=True)
    count = extract_footprints_from_pcb(INPUT_PCB, extracted_dir, overwrite=True)
    extracted_files = sorted(extracted_dir.glob("*.kicad_mod"))
    assert count > 0 and extracted_files, "Expected at least one footprint in hlr_test.kicad_pcb"

    raw_mod = OUT_DIR / "original_footprint.kicad_mod"
    raw_mod.write_text(extracted_files[0].read_text(encoding="utf-8"), encoding="utf-8")
    first_fp = KiCadFootprint.from_file(raw_mod)

    # 2. Introduce an unsafe zero-dimension pad in an S-expression copy to demonstrate repair
    sexp_tree = parse_sexp(raw_mod.read_text(encoding="utf-8"))
    pad_nodes = find_all_elements(sexp_tree, "pad")
    for pad_node in pad_nodes[:1]:
        for child in pad_node:
            if isinstance(child, list) and child and child[0] == "size":
                child[1] = 0.0  # Simulate a malformed 0-width pad from a third-party converter

    broken_mod = OUT_DIR / "unsafe_pad_footprint.kicad_mod"
    broken_mod.write_text(format_sexp(build_sexp(sexp_tree)) + "\n", encoding="utf-8")

    # 3. Repair unsafe pad dimensions directly on the S-expression AST
    norm = normalize_unsafe_footprint_pad_sizes(parse_sexp(broken_mod.read_text(encoding="utf-8")))
    repaired_mod = OUT_DIR / "repaired_pad_footprint.kicad_mod"
    repaired_mod.write_text(format_sexp(build_sexp(norm.expression)) + "\n", encoding="utf-8")

    # 4. Run the full KiCadFilterPipeline over the footprint file
    filtered_mod = OUT_DIR / "filtered_footprint.kicad_mod"
    KiCadFilterPipeline().filter_footprint(broken_mod, filtered_mod)

    # 5. Compare pad counts and sizes before vs after without disturbing untouched tokens
    fp_before = KiCadFootprint.from_file(broken_mod)
    fp_after = KiCadFootprint.from_file(filtered_mod)

    report = {
        "footprint_name": first_fp.name,
        "pad_count": len(pad_nodes),
        "normalization_changes": [
            {
                "pad_name": c.pad_name,
                "original_size": list(c.original_size),
                "replacement_size": list(c.replacement_size),
            }
            for c in norm.changes
        ],
        "pad_1_before_mm": [fp_before.pads[0].size_x, fp_before.pads[0].size_y],
        "pad_1_after_mm": [fp_after.pads[0].size_x, fp_after.pads[0].size_y],
        "models_preserved": len(fp_after.models),
        "embedded_files_preserved": len(fp_after.embedded_files),
    }
    (OUT_DIR / "sexp_pipeline_report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")

    print(
        f"Processed {first_fp.name}: {len(norm.changes)} unsafe pad(s) normalized "
        f"({report['pad_1_before_mm']} -> {report['pad_1_after_mm']} mm), "
        f"{report['embedded_files_preserved']} embedded 3D file(s) preserved"
    )


if __name__ == "__main__":
    main()
kicad-monkey v2026.11.30·Docs updated 2026.12.01 15:43 UTC (fd9b75b)