Skip to content
cadkithome

cadkit for Python

Python bindings for cadkit (crates/cadkit-py), built with PyO3 (abi3-py39, one wheel per platform for Python 3.9+) and maturin. The extension module is cadkit._cadkit; the public package is cadkit. The distribution is published on PyPI as pycadkit (the name cadkit is taken there), so it installs as pycadkit and imports as cadkit.

The Python interface covers CAD file I/O, header inspection and document operations. It reads DWG, DGN V7/V8, DXF and CityGML 2.0; output includes DXF, seed-based DGN V8, CityGML 2.0, SVG and JSON. See the format matrix for limits. The standalone Rust geometry, scene and GPU modules are separate from this binding.

From PyPI: pip install pycadkit. Wheels cover Linux x86_64 and aarch64 (manylinux), macOS arm64 and x86_64, and Windows x64; other platforms build from the sdist, which needs a Rust toolchain.

From a checkout:

Terminal window
pip install maturin
cd crates/cadkit-py
maturin develop --release # editable install into the active virtualenv
maturin build --release # or build a wheel into target/wheels/

In this repository, route builds through the lock: python scripts/buildlock.py .venv/Scripts/maturin develop -m crates/cadkit-py/Cargo.toml.

import cadkit
doc = cadkit.read("plan.dgn") # str, os.PathLike or bytes
print(doc) # <cadkit.Document format=dgn_v8 version="V8" models=1 entities=1234>
for layer in doc.layers:
print(layer["name"], layer["visible"])
for e in doc.entities(): # model 0
if e["kind"]["type"] == "line":
print(e["kind"]["start"], e["kind"]["end"])
open("plan.svg", "w").write(doc.to_svg(width=1200))
data = doc.to_dict() # nested dicts/lists
text = doc.to_json(pretty=True)
try:
cadkit.read(b"not a drawing")
except cadkit.UnknownFormatError:
...
Item Description
read(source, *, keep_raw=False, codepage=None, max_input_bytes=None, max_decompressed_bytes=None, max_objects=None, max_depth=None) -> Document source is a path (str/PathLike) or bytes/bytearray/memoryview. keep_raw keeps original record bytes in entities (raw). codepage is a WHATWG label (e.g. "windows-1254") used for 8-bit text when the file declares none. The max_* keywords override the resource limits (None = default); exceeding one raises LimitExceededError.
inspect(source, *, codepage=None, max_input_bytes=None, max_decompressed_bytes=None, max_objects=None, max_depth=None) -> dict Header-only format/version/units metadata, with the same path and buffer inputs as read.
detect(data: bytes) -> str | None "dwg", "dxf", "dgn_v7", "dgn_v8", "city_gml", or None.
read_citygml(data: bytes, options_json: str | None = None) -> CityGmlDocument Reads CityGML 2.0 bytes into a native CityGmlDocument preserving IDs, references, and XML extensions (ReadOptions JSON).
Document.from_json(text: str) -> Document Constructs a format-neutral Document from its JSON contract.
Document.format / version / application / codepage Source info (format as above or "unknown", version e.g. "AC1032").
Document.units {"unit": "meter", "meters_per_unit": 1.0}.
Document.layers / blocks / models / warnings Lists of dicts, shaped like the Rust model serialized with serde.
Document.to_dict() Whole document as nested dicts.
Document.to_json(pretty=False) Whole document as JSON text.
Document.to_svg(model=0, width=1600, stroke=1.0, background="#ffffff", text=True, expand_blocks=True, images=True, include_hidden_layers=False) SVG text; hidden/frozen layers are excluded by default. background=None is transparent. width and stroke must be finite and > 0 (ValueError). Raises IndexError for a bad model index.
Document.to_dxf(version="r2018") ASCII DXF text; versions r12, r2000, r2004, r2007, r2010, r2013, r2018.
Document.to_dgn(seed: bytes | V8Seed, options_json: str | None = None) -> bytes Writes seed-based DGN V8 bytes (dgn::WriteOptions JSON).
Document.to_dxf_bytes(version="r2018", codepage=None) -> bytes DXF byte output, including legacy OEM code pages such as DOS857.
Document.explode_inserts(max_depth=32) -> Document New document with expanded block references; missing, cyclic or deeper inserts remain.
Document.convert_units(unit) -> Document New document with converted geometry and unit metadata ("mm", "meter", "ft", etc.); the source is unchanged.
V8Seed(source, *, codepage=None, max_input_bytes=None, max_decompressed_bytes=None, max_objects=None, max_depth=None) Reusable parsed single-design-model V8 seed; accepts paths, buffers, or another V8Seed. Properties: is_3d, units, is_nonempty, has_raster_template; methods: to_bytes(), prepare_document(doc, options_json=None).
strip_dgn_seed(seed, *, keep_controls=None, keep_raster_template=None, keep_cell_definitions=None, model_name=None, timestamp_ms=None, application=None, codepage=None, max_input_bytes=None, max_decompressed_bytes=None, max_objects=None, max_depth=None) -> tuple[bytes, dict] Copies a DGN V8 seed (bytes-like or V8Seed) without its model’s drawing content and identifying document properties; returns (seed_bytes, report_dict) (dgn::StripSeedOptions / StripSeedReport; None keeps a default). Names in the kept tables remain: review them.
Document.to_citygml(srs_name: str, lod: int = 1) -> bytes Writes generic CityGML 2.0 XML bytes with an explicit CRS and LoD.
Document.to_citygml_with_report(srs_name: str, lod: int = 1, metadata_only: bool = False) -> tuple[bytes, dict] Writes generic CityGML 2.0 XML bytes and returns (xml_bytes, report_dict); metadata_only=True retains unsupported entities as JSON metadata instead of raising UnsupportedError.
Document.entities(model=0) Iterator of entity dicts ({"id", "layer", "color", "kind": {"type": ...}, "props", ...}).
CityGmlDocument Native CityGML 2.0 model with from_json(text), to_json(), to_gml(options_json=None), to_document(lod=None), validate(options_json=None), and preflight_tkgm(profile).

Conventions follow the model: coordinates in drawing units, angles in radians (see docs/ARCHITECTURE.md). Format-specific data is under props keys prefixed dgn., dwg., dxf., gml..

CadkitError is the base class.

Exception Raised for
UnknownFormatError input is not a recognized drawing
UnsupportedError valid input using an unimplemented feature
LimitExceededError input exceeds a resource limit
InvalidDataError truncated or malformed data

Missing or unreadable files raise the usual OSError subclasses (FileNotFoundError, …).

  • The model stays in Rust. Dict conversion serializes with serde to JSON (GIL released) and decodes with the C json module. This avoids a second mapping layer (and a pythonize dependency) that would have to track every model change.
  • The GIL is released while parsing, serializing, rendering and writing, so threads can read files in parallel.
  • Document is immutable; dict-valued properties are rebuilt on each access, so cache them in a local variable inside hot loops.
  • Type information ships as .pyi stubs plus py.typed.
Terminal window
.venv/Scripts/python -m pytest crates/cadkit-py/tests -rs

Corpus tests skip when corpus/public is absent.

Document.from_json(text) constructs a neutral document. doc.to_dgn(seed_bytes, options_json=None) returns bytes; options follow Rust dgn::WriteOptions. doc.to_citygml(srs_name, lod=1) returns generic CityGML geometry as UTF-8 bytes, and doc.to_citygml_with_report(srs_name, lod=1, metadata_only=False) returns (xml_bytes, report_dict) with conversion diagnostics (metadata_only=True opts in to retaining unsupported entities as JSON metadata).

For semantic preservation use read_citygml(bytes, options_json=None) instead of the neutral reader. Its CityGmlDocument has to_gml(options_json=None), to_json(), from_json(text), validate(options_json=None), preflight_tkgm(profile), and to_document(lod=None). preflight_tkgm(profile) requires an explicit profile ("city-model-tender" or "digital-building-registration") and runs local structural/field checks only (report["acceptance_verified"] is always False). Native read options use Rust ReadOptions; native write and validation options use gml::ValidationOptions. Defaults validate geometry; {"geometry": false} explicitly permits preserving existing geometry defects. No schema or CRS is downloaded. See GML limits and DGN limits before choosing an export path.

seed = cadkit.V8Seed("blank.dgn")
prepared = seed.prepare_document(cadkit.read("plan.dxf"))
output = prepared.to_dgn(seed) # reuses the parsed seed

To make a seed from a drawing of your own:

seed_bytes, report = cadkit.strip_dgn_seed(open("template.dgn", "rb").read(), timestamp_ms=1.7e12)
print(report["named_levels"], report["tag_sets"], report["model_name_from_seed"])
seed = cadkit.V8Seed(seed_bytes) # empty: no clear_seed_model needed

The report counts what was removed and what remains (level, tag set and cell names, the model name and description, undecoded streams); the result is not anonymous. See obtaining a seed.

prepare_document returns a copy adjusted to seed units/dimensions/symbology; its optional JSON follows Rust dgn::SeedPrepareOptions. Existing non-empty-seed write checks still apply (clear_seed_model is an explicit write option). This API does not imply receiver application acceptance.

Block expansion raises a limit error if its work budget is exhausted; it does not return a silently partial copy. Missing, cyclic and deeper references remain as inserts.