cadrender 0.1.0__cp310-abi3-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cadrender/__init__.py +179 -0
- cadrender/_cadrender.pyd +0 -0
- cadrender/_cadrender.pyi +33 -0
- cadrender/_errors.py +49 -0
- cadrender/_options.py +92 -0
- cadrender/py.typed +0 -0
- cadrender-0.1.0.dist-info/METADATA +206 -0
- cadrender-0.1.0.dist-info/RECORD +12 -0
- cadrender-0.1.0.dist-info/WHEEL +4 -0
- cadrender-0.1.0.dist-info/licenses/LICENSE-APACHE +201 -0
- cadrender-0.1.0.dist-info/licenses/LICENSE-MIT +21 -0
- cadrender-0.1.0.dist-info/sboms/cadrender-py.cyclonedx.json +1860 -0
cadrender/__init__.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""cadrender: very fast DXF (and soon DWG) to PNG/SVG rendering.
|
|
2
|
+
|
|
3
|
+
Open a drawing once, then render its sheets (layout tabs) as often as you
|
|
4
|
+
like::
|
|
5
|
+
|
|
6
|
+
import cadrender
|
|
7
|
+
doc = cadrender.open("drawing.dxf")
|
|
8
|
+
print(doc.sheets)
|
|
9
|
+
png = doc.render(doc.sheets[0], width=2000) # bytes
|
|
10
|
+
summary = doc.render_all("out/", threads=4) # all sheets, in parallel
|
|
11
|
+
|
|
12
|
+
Reading, drawing and PNG encoding run in Rust with the GIL (Python's global
|
|
13
|
+
lock) released, so other Python threads keep running.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Callable, Iterable, Literal, Mapping, Sequence
|
|
21
|
+
|
|
22
|
+
from . import _cadrender
|
|
23
|
+
from ._errors import (
|
|
24
|
+
DrawingNotFoundError,
|
|
25
|
+
Error,
|
|
26
|
+
OpenError,
|
|
27
|
+
OptionsError,
|
|
28
|
+
RenderError,
|
|
29
|
+
SheetNotFoundError,
|
|
30
|
+
UnsupportedFormatError,
|
|
31
|
+
)
|
|
32
|
+
from ._options import RenderOptions, merge
|
|
33
|
+
|
|
34
|
+
__version__: str = _cadrender.__version__
|
|
35
|
+
|
|
36
|
+
#: ``True`` once this build can write SVG. Until then ``format="svg"`` raises
|
|
37
|
+
#: ``NotImplementedError``.
|
|
38
|
+
SVG_AVAILABLE: bool = _cadrender.SVG_AVAILABLE
|
|
39
|
+
|
|
40
|
+
Format = Literal["png", "svg"]
|
|
41
|
+
PathLike = str | os.PathLike[str]
|
|
42
|
+
Options = RenderOptions | Mapping[str, Any] | None
|
|
43
|
+
|
|
44
|
+
#: Names accepted by the ``preset`` option.
|
|
45
|
+
PRESETS: tuple[str, ...] = tuple(_cadrender.presets())
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def open(path: PathLike, *, font: str | PathLike | None = None) -> Document: # noqa: A001 - mirrors builtins.open on purpose
|
|
49
|
+
"""Read a drawing file and return a :class:`Document`.
|
|
50
|
+
|
|
51
|
+
path: a ``.dxf`` file (ASCII DXF). ``.dwg`` goes through the same call
|
|
52
|
+
once the library reads DWG; until then it raises
|
|
53
|
+
:class:`UnsupportedFormatError`.
|
|
54
|
+
font: the one sans font used for all text (the font policy):
|
|
55
|
+
``"auto"`` (default: Arial if installed, else the built-in
|
|
56
|
+
Liberation Sans), ``"liberation"``, or the path of a ``.ttf`` file.
|
|
57
|
+
Fonts are part of the opened drawing, so they are chosen here and not
|
|
58
|
+
per render.
|
|
59
|
+
|
|
60
|
+
Raises :class:`DrawingNotFoundError` if the file does not exist and
|
|
61
|
+
:class:`OpenError` if it is not a drawing we can read.
|
|
62
|
+
"""
|
|
63
|
+
return Document(_cadrender.open(os.fspath(path), None if font is None else os.fspath(font)))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Document:
|
|
67
|
+
"""One opened drawing. Read once; render many times, also from many threads."""
|
|
68
|
+
|
|
69
|
+
__slots__ = ("_doc",)
|
|
70
|
+
|
|
71
|
+
def __init__(self, native: _cadrender.Document) -> None:
|
|
72
|
+
self._doc = native
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def path(self) -> Path:
|
|
76
|
+
"""The file this document was read from."""
|
|
77
|
+
return Path(self._doc.path)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def sheets(self) -> list[str]:
|
|
81
|
+
"""Sheet (layout tab) names in tab order. Model space is not a sheet."""
|
|
82
|
+
return self._doc.sheets
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def info(self) -> dict[str, Any]:
|
|
86
|
+
"""Facts about the file: ``version``, ``size_bytes``, ``parse_ms``,
|
|
87
|
+
``font``, counts (``entities``, ``blocks``, ``layers``),
|
|
88
|
+
``entity_counts``, ``skipped_types`` and ``reader_warnings``."""
|
|
89
|
+
return self._doc.info
|
|
90
|
+
|
|
91
|
+
def __repr__(self) -> str:
|
|
92
|
+
return repr(self._doc)
|
|
93
|
+
|
|
94
|
+
def render(self, sheet: str, width: int = 2000, format: Format = "png", *, options: Options = None, **kwargs: Any) -> bytes: # noqa: A002
|
|
95
|
+
"""Render one sheet and return the file bytes (PNG or SVG).
|
|
96
|
+
|
|
97
|
+
sheet: a name from :attr:`sheets`.
|
|
98
|
+
width: picture width in pixels; the height follows the drawing.
|
|
99
|
+
format: ``"png"`` or ``"svg"``.
|
|
100
|
+
options / kwargs: see :class:`RenderOptions` (keywords win).
|
|
101
|
+
|
|
102
|
+
Raises :class:`SheetNotFoundError`, :class:`OptionsError` or
|
|
103
|
+
:class:`RenderError`.
|
|
104
|
+
"""
|
|
105
|
+
return self._doc.render(sheet, format, merge(options, width, kwargs))
|
|
106
|
+
|
|
107
|
+
def render_to(self, sheet: str, path: PathLike, width: int = 2000, format: Format | None = None, *, options: Options = None, **kwargs: Any) -> dict[str, Any]: # noqa: A002
|
|
108
|
+
"""Render one sheet into a file and return its result dict
|
|
109
|
+
(``ms``, ``width``, ``height``, ``warnings``, ...).
|
|
110
|
+
|
|
111
|
+
format: ``"png"`` or ``"svg"``; by default taken from the file
|
|
112
|
+
extension (``.svg`` means SVG, anything else PNG). The file is written
|
|
113
|
+
to a temporary name first and then renamed, so it never exists half
|
|
114
|
+
written.
|
|
115
|
+
"""
|
|
116
|
+
path = os.fspath(path)
|
|
117
|
+
if format is None:
|
|
118
|
+
format = "svg" if path.lower().endswith(".svg") else "png"
|
|
119
|
+
return self._doc.render_to(sheet, path, format, merge(options, width, kwargs))
|
|
120
|
+
|
|
121
|
+
def render_all(
|
|
122
|
+
self,
|
|
123
|
+
out_dir: PathLike,
|
|
124
|
+
width: int = 2000,
|
|
125
|
+
formats: Iterable[Format] = ("png",),
|
|
126
|
+
threads: int | None = None,
|
|
127
|
+
sheets: Sequence[str] | None = None,
|
|
128
|
+
skip_existing: bool = False,
|
|
129
|
+
on_sheet: Callable[[str, dict[str, Any]], object] | None = None,
|
|
130
|
+
*,
|
|
131
|
+
stem: str | None = None,
|
|
132
|
+
options: Options = None,
|
|
133
|
+
**kwargs: Any,
|
|
134
|
+
) -> dict[str, Any]:
|
|
135
|
+
"""Render many sheets in parallel into ``out_dir``.
|
|
136
|
+
|
|
137
|
+
Files are named ``<stem>__<sheet>.<ext>`` (``/`` and ``\\`` in a sheet
|
|
138
|
+
name become ``_``); ``stem`` defaults to the drawing's file name
|
|
139
|
+
without extension.
|
|
140
|
+
|
|
141
|
+
threads: worker threads; ``None`` = all cores.
|
|
142
|
+
sheets: only these sheets (tab order is kept). A name that is not in
|
|
143
|
+
the file is reported in ``failed``.
|
|
144
|
+
skip_existing: leave a sheet alone when all its files exist already.
|
|
145
|
+
on_sheet: ``on_sheet(name, result)`` after each sheet (also failed
|
|
146
|
+
ones), called from a worker thread while holding the GIL. If it
|
|
147
|
+
raises, sheets not started yet are cancelled and the exception is
|
|
148
|
+
raised when the running ones are done.
|
|
149
|
+
|
|
150
|
+
One bad sheet never stops the others. Returns a dict with ``done``,
|
|
151
|
+
``skipped`` (lists of names), ``failed`` (name -> error), ``sheets``
|
|
152
|
+
(one result dict per sheet with ``ok``, ``files``, ``ms``,
|
|
153
|
+
``render_ms``, ``encode_ms``, ``write_ms``, ``error``, ...) and the
|
|
154
|
+
times ``parse_ms``, ``prepare_ms``, ``render_wall_ms``, ``total_ms``.
|
|
155
|
+
"""
|
|
156
|
+
if stem is None:
|
|
157
|
+
stem = self.path.stem
|
|
158
|
+
fmts: list[str] = [formats] if isinstance(formats, str) else list(formats)
|
|
159
|
+
return self._doc.render_all(
|
|
160
|
+
os.fspath(out_dir), stem, fmts, merge(options, width, kwargs),
|
|
161
|
+
threads, None if sheets is None else list(sheets), skip_existing, on_sheet,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
__all__ = [
|
|
166
|
+
"open",
|
|
167
|
+
"Document",
|
|
168
|
+
"RenderOptions",
|
|
169
|
+
"Error",
|
|
170
|
+
"OpenError",
|
|
171
|
+
"DrawingNotFoundError",
|
|
172
|
+
"UnsupportedFormatError",
|
|
173
|
+
"SheetNotFoundError",
|
|
174
|
+
"OptionsError",
|
|
175
|
+
"RenderError",
|
|
176
|
+
"SVG_AVAILABLE",
|
|
177
|
+
"PRESETS",
|
|
178
|
+
"__version__",
|
|
179
|
+
]
|
cadrender/_cadrender.pyd
ADDED
|
Binary file
|
cadrender/_cadrender.pyi
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Type stubs for the compiled module. Use the wrappers in ``cadrender``;
|
|
2
|
+
this low-level API may change."""
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Callable
|
|
6
|
+
|
|
7
|
+
__version__: str
|
|
8
|
+
SVG_AVAILABLE: bool
|
|
9
|
+
|
|
10
|
+
def open(path: str, font: str | None = None) -> Document: ...
|
|
11
|
+
def presets() -> list[str]: ...
|
|
12
|
+
def option_names() -> list[str]: ...
|
|
13
|
+
|
|
14
|
+
class Document:
|
|
15
|
+
@property
|
|
16
|
+
def sheets(self) -> list[str]: ...
|
|
17
|
+
@property
|
|
18
|
+
def path(self) -> Path: ...
|
|
19
|
+
@property
|
|
20
|
+
def info(self) -> dict[str, Any]: ...
|
|
21
|
+
def render(self, sheet: str, format: str, options: dict[str, Any] | None = None) -> bytes: ...
|
|
22
|
+
def render_to(self, sheet: str, path: str, format: str, options: dict[str, Any] | None = None) -> dict[str, Any]: ...
|
|
23
|
+
def render_all(
|
|
24
|
+
self,
|
|
25
|
+
out_dir: str,
|
|
26
|
+
stem: str,
|
|
27
|
+
formats: list[str],
|
|
28
|
+
options: dict[str, Any] | None = None,
|
|
29
|
+
threads: int | None = None,
|
|
30
|
+
sheets: list[str] | None = None,
|
|
31
|
+
skip_existing: bool = False,
|
|
32
|
+
on_sheet: Callable[[str, dict[str, Any]], object] | None = None,
|
|
33
|
+
) -> dict[str, Any]: ...
|
cadrender/_errors.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Errors raised by cadrender. All of them are subclasses of :class:`Error`.
|
|
2
|
+
|
|
3
|
+
The compiled module raises these classes by name, so do not rename them.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Error(Exception):
|
|
10
|
+
"""Base class of every cadrender error."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class OpenError(Error, OSError):
|
|
14
|
+
"""The file could not be opened or read as a drawing."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class DrawingNotFoundError(OpenError, FileNotFoundError):
|
|
18
|
+
"""The file does not exist."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UnsupportedFormatError(OpenError):
|
|
22
|
+
"""The file type is not read by this build (yet), for example ``.dwg``
|
|
23
|
+
before DWG support lands."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SheetNotFoundError(Error, KeyError):
|
|
27
|
+
"""There is no sheet (layout tab) with this name."""
|
|
28
|
+
|
|
29
|
+
def __str__(self) -> str: # KeyError would show the message in quotes
|
|
30
|
+
return str(self.args[0]) if self.args else ""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class OptionsError(Error, ValueError):
|
|
34
|
+
"""An option name or value is wrong."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class RenderError(Error):
|
|
38
|
+
"""Drawing one sheet failed (or its file could not be written)."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"Error",
|
|
43
|
+
"OpenError",
|
|
44
|
+
"DrawingNotFoundError",
|
|
45
|
+
"UnsupportedFormatError",
|
|
46
|
+
"SheetNotFoundError",
|
|
47
|
+
"OptionsError",
|
|
48
|
+
"RenderError",
|
|
49
|
+
]
|
cadrender/_options.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Render options as a small Python class.
|
|
2
|
+
|
|
3
|
+
You can give options as keyword arguments (``doc.render(s, color="true")``)
|
|
4
|
+
or as a :class:`RenderOptions` object (``doc.render(s, options=opts)``), or
|
|
5
|
+
both: keyword arguments win. A field left as ``None`` keeps the value of the
|
|
6
|
+
preset. The compiled module checks every name and value, so a typo raises
|
|
7
|
+
:class:`cadrender.OptionsError`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import asdict, dataclass, field, replace
|
|
13
|
+
from typing import Any, Literal, Mapping, Sequence, Union
|
|
14
|
+
|
|
15
|
+
Color = Union[str, Sequence[int]]
|
|
16
|
+
Clean = Union[bool, Mapping[str, Sequence[str]]]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class RenderOptions:
|
|
21
|
+
"""Everything that changes how a sheet is drawn (not the picture width).
|
|
22
|
+
|
|
23
|
+
preset: ``"preview"`` (default: grey look, paper lineweights, the
|
|
24
|
+
``Defpoints`` layer left out) or ``"none"`` (true colour, no clean
|
|
25
|
+
rules). Applied first.
|
|
26
|
+
color: ``"mono"`` (grey levels) or ``"true"`` (real colours).
|
|
27
|
+
background: page colour: ``"#RRGGBB"``, ``"#RRGGBBAA"``, ``"white"``,
|
|
28
|
+
``"black"``, ``"transparent"`` or ``(r, g, b[, a])``.
|
|
29
|
+
lineweight: ``"paper"`` (true plot width), ``"preview"`` (ezdxf's mm as
|
|
30
|
+
points at ``dpi``) or ``"hairline"`` (every line ``min_lw_px``).
|
|
31
|
+
default_lw: lineweight for "default" layers, in 1/100 mm (25 = 0.25 mm).
|
|
32
|
+
min_lw_px: thinnest pen in pixels.
|
|
33
|
+
dpi: dots per inch for the ``"preview"`` lineweight rule (150).
|
|
34
|
+
frame: ``"extents"`` (what is drawn, plus ``margin``) or ``"paper"``.
|
|
35
|
+
margin: margin around the extents, part of the size (0.05 = 5 %).
|
|
36
|
+
max_height: highest picture height in pixels.
|
|
37
|
+
full_detail: ``True`` turns level of detail off (no dots, no grey bars
|
|
38
|
+
for tiny text, no tint for dense hatches).
|
|
39
|
+
lod: change single level-of-detail limits, for example
|
|
40
|
+
``{"dot_px": 0.5}``. Keys: enabled, dot_px, text_hide_px,
|
|
41
|
+
text_greek_px, hatch_tint_px, dash_min_period_px.
|
|
42
|
+
clean: ``False`` (no clean rules), ``True`` (the preset's rules) or your
|
|
43
|
+
own rules: ``{"layers": [...], "block_keywords": [...]}``.
|
|
44
|
+
draw_order: respect the draw order table (SORTENTS).
|
|
45
|
+
text_masks: draw MTEXT background masks.
|
|
46
|
+
wipeout_frames: ``False`` never draws WIPEOUT frames; ``True`` (default)
|
|
47
|
+
draws them as the file says (WIPEOUTFRAME).
|
|
48
|
+
parallel_viewports: draw the viewports of one sheet in parallel.
|
|
49
|
+
max_depth, max_visits: safety limits for deep or huge block trees.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
preset: Literal["preview", "none"] | None = None
|
|
53
|
+
color: Literal["mono", "true"] | None = None
|
|
54
|
+
background: Color | None = None
|
|
55
|
+
lineweight: Literal["paper", "preview", "hairline"] | None = None
|
|
56
|
+
default_lw: int | None = None
|
|
57
|
+
min_lw_px: float | None = None
|
|
58
|
+
dpi: float | None = None
|
|
59
|
+
frame: Literal["extents", "paper"] | None = None
|
|
60
|
+
margin: float | None = None
|
|
61
|
+
max_height: int | None = None
|
|
62
|
+
full_detail: bool | None = None
|
|
63
|
+
lod: Mapping[str, float | bool] | None = field(default=None)
|
|
64
|
+
clean: Clean | None = None
|
|
65
|
+
draw_order: bool | None = None
|
|
66
|
+
text_masks: bool | None = None
|
|
67
|
+
wipeout_frames: bool | None = None
|
|
68
|
+
parallel_viewports: bool | None = None
|
|
69
|
+
max_depth: int | None = None
|
|
70
|
+
max_visits: int | None = None
|
|
71
|
+
|
|
72
|
+
def to_dict(self) -> dict[str, Any]:
|
|
73
|
+
"""Only the fields that are set (not ``None``)."""
|
|
74
|
+
return {k: v for k, v in asdict(self).items() if v is not None}
|
|
75
|
+
|
|
76
|
+
def replace(self, **changes: Any) -> RenderOptions:
|
|
77
|
+
"""A copy with some fields changed."""
|
|
78
|
+
return replace(self, **changes)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def merge(options: RenderOptions | Mapping[str, Any] | None, width: int | None, extra: Mapping[str, Any]) -> dict[str, Any]:
|
|
82
|
+
"""One plain dict for the compiled module: options, then keywords, then width."""
|
|
83
|
+
if options is None:
|
|
84
|
+
d: dict[str, Any] = {}
|
|
85
|
+
elif isinstance(options, RenderOptions):
|
|
86
|
+
d = options.to_dict()
|
|
87
|
+
else:
|
|
88
|
+
d = {k: v for k, v in dict(options).items() if v is not None}
|
|
89
|
+
d.update({k: v for k, v in extra.items() if v is not None})
|
|
90
|
+
if width is not None:
|
|
91
|
+
d["width"] = width
|
|
92
|
+
return d
|
cadrender/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cadrender
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Classifier: Development Status :: 4 - Beta
|
|
5
|
+
Classifier: Intended Audience :: Developers
|
|
6
|
+
Classifier: Intended Audience :: Science/Research
|
|
7
|
+
Classifier: Programming Language :: Rust
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
11
|
+
Classifier: Operating System :: MacOS
|
|
12
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
13
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
14
|
+
Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Dist: pytest>=8 ; extra == 'test'
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
License-File: LICENSE-MIT
|
|
20
|
+
License-File: LICENSE-APACHE
|
|
21
|
+
Summary: Very fast DXF and DWG to PNG and SVG renderer, written in Rust
|
|
22
|
+
Keywords: dxf,dwg,cad,autocad,svg,png,render,preview,thumbnail,ezdxf
|
|
23
|
+
Home-Page: https://github.com/hameddavodi/cadrender
|
|
24
|
+
Author: The cadrender contributors
|
|
25
|
+
License-Expression: MIT OR Apache-2.0
|
|
26
|
+
Requires-Python: >=3.10
|
|
27
|
+
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
28
|
+
Project-URL: Changelog, https://github.com/hameddavodi/cadrender/releases
|
|
29
|
+
Project-URL: Homepage, https://github.com/hameddavodi/cadrender
|
|
30
|
+
Project-URL: Issues, https://github.com/hameddavodi/cadrender/issues
|
|
31
|
+
Project-URL: Repository, https://github.com/hameddavodi/cadrender
|
|
32
|
+
|
|
33
|
+
# cadrender for Python
|
|
34
|
+
|
|
35
|
+
`cadrender` turns DXF and DWG drawings into PNG and SVG pictures, one
|
|
36
|
+
picture per sheet (layout tab). It is written in Rust and is very fast:
|
|
37
|
+
about 10 ms per sheet, so a drawing with 16 sheets takes well under half a
|
|
38
|
+
second.
|
|
39
|
+
|
|
40
|
+
This package is a thin Python layer over the Rust library. It uses
|
|
41
|
+
**PyO3** (a tool to call Rust from Python) and **maturin** (a tool to build
|
|
42
|
+
a Python wheel from Rust). A **wheel** is the file `pip` installs.
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
pip install cadrender
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Quick start
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import cadrender
|
|
52
|
+
|
|
53
|
+
doc = cadrender.open("drawing.dxf") # read the file once (.dxf or .dwg)
|
|
54
|
+
print(doc.sheets) # ['01', '02', ...] in tab order
|
|
55
|
+
print(doc.info["version"], doc.info["parse_ms"])
|
|
56
|
+
|
|
57
|
+
png = doc.render("01", width=2000) # bytes of a PNG file
|
|
58
|
+
doc.render_to("01", "out/01.png") # or straight into a file
|
|
59
|
+
doc.render_to("01", "out/01.svg") # SVG: the format comes from the extension
|
|
60
|
+
|
|
61
|
+
summary = doc.render_all("out/", threads=4) # all sheets, in parallel
|
|
62
|
+
print(summary["done"], summary["failed"])
|
|
63
|
+
for s in summary["sheets"]:
|
|
64
|
+
print(s["sheet"], s["ms"], s["files"])
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## The API
|
|
68
|
+
|
|
69
|
+
| Call | What it does |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `cadrender.open(path, font=None)` | Read a drawing. `font`: `"auto"` (Arial if installed, else Liberation Sans), `"liberation"`, or a `.ttf` path. |
|
|
72
|
+
| `doc.sheets` | Sheet names in tab order. Model space is not a sheet. |
|
|
73
|
+
| `doc.info` | A dict: `version`, `size_bytes`, `parse_ms`, `font`, counts, `skipped_types`, `reader_warnings`. |
|
|
74
|
+
| `doc.render(sheet, width=2000, format="png", **options)` | One sheet as `bytes`. |
|
|
75
|
+
| `doc.render_to(sheet, path, width=2000, format=None, **options)` | One sheet into a file. The format comes from the file extension. Returns the sheet's result dict. |
|
|
76
|
+
| `doc.render_all(out_dir, width=2000, formats=("png",), threads=None, sheets=None, skip_existing=False, on_sheet=None, **options)` | Many sheets in parallel. Returns a summary dict. |
|
|
77
|
+
|
|
78
|
+
`render_all` details:
|
|
79
|
+
|
|
80
|
+
- File names are `<stem>__<sheet>.png`. `stem` is the drawing's file name
|
|
81
|
+
without extension (you can pass `stem=...`). A `/` or `\` in a sheet
|
|
82
|
+
name becomes `_`.
|
|
83
|
+
- **One bad sheet never stops the others.** The summary has `done` and
|
|
84
|
+
`skipped` (lists of names), `failed` (name -> error text) and `sheets`
|
|
85
|
+
(one dict per sheet: `ok`, `error`, `files`, `ms`, `render_ms`,
|
|
86
|
+
`encode_ms`, `write_ms`, `width`, `height`, `warnings`, `stats`).
|
|
87
|
+
- `threads=None` uses all cores. `threads=1` is one core.
|
|
88
|
+
- `sheets=[...]` renders only these sheets. A name that is not in the file
|
|
89
|
+
is listed in `failed`.
|
|
90
|
+
- `skip_existing=True` leaves a sheet alone when its files already exist.
|
|
91
|
+
- `on_sheet(name, result)` is called after each sheet. It runs in a worker
|
|
92
|
+
thread. If it raises, sheets that have not started are cancelled, and the
|
|
93
|
+
exception is raised at the end.
|
|
94
|
+
|
|
95
|
+
Files are written to a temporary name first and then renamed. So a file
|
|
96
|
+
never exists half written, even if the process is killed.
|
|
97
|
+
|
|
98
|
+
## Options
|
|
99
|
+
|
|
100
|
+
Give options as keyword arguments, or as a `RenderOptions` object, or both
|
|
101
|
+
(keyword arguments win):
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from cadrender import RenderOptions
|
|
105
|
+
|
|
106
|
+
opts = RenderOptions(preset="none", color="true", background="#202020", full_detail=True)
|
|
107
|
+
png = doc.render("01", options=opts, lineweight="hairline")
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
| Option | Values |
|
|
111
|
+
|---|---|
|
|
112
|
+
| `preset` | `"preview"` (default: grey look, paper lineweights, the `Defpoints` layer left out) or `"none"` (true colour, no clean rules) |
|
|
113
|
+
| `color` | `"mono"` (grey levels) or `"true"` (real colours) |
|
|
114
|
+
| `background` | `"#RRGGBB"`, `"#RRGGBBAA"`, `"white"`, `"black"`, `"transparent"` or `(r, g, b[, a])` |
|
|
115
|
+
| `lineweight` | `"paper"` (true plot width), `"preview"` (ezdxf's rule, uses `dpi`), `"hairline"` |
|
|
116
|
+
| `default_lw`, `min_lw_px`, `dpi` | default lineweight (1/100 mm), thinnest pen (px), dpi for the `"preview"` rule |
|
|
117
|
+
| `frame`, `margin`, `max_height` | `"extents"` or `"paper"`; margin around the extents (0.05 = 5 %); highest picture height |
|
|
118
|
+
| `full_detail` | `True` = no level-of-detail shortcuts (no dots, no grey bars for tiny text, no tint for dense hatches) |
|
|
119
|
+
| `lod` | single limits, for example `{"dot_px": 0.5}` |
|
|
120
|
+
| `clean` | `False` (no clean rules), `True` (the preset's), or `{"layers": [...], "block_keywords": [...]}` |
|
|
121
|
+
| `draw_order`, `text_masks`, `wipeout_frames`, `parallel_viewports` | `True` / `False` |
|
|
122
|
+
| `max_depth`, `max_visits` | safety limits for very deep or very big block trees |
|
|
123
|
+
|
|
124
|
+
A wrong name or value raises `cadrender.OptionsError`. Typos are never
|
|
125
|
+
ignored silently. The font is chosen in `open()`, because fonts are part of
|
|
126
|
+
the opened drawing.
|
|
127
|
+
|
|
128
|
+
## Errors
|
|
129
|
+
|
|
130
|
+
All errors are subclasses of `cadrender.Error`:
|
|
131
|
+
|
|
132
|
+
| Error | When | Also a |
|
|
133
|
+
|---|---|---|
|
|
134
|
+
| `OpenError` | the file cannot be read as a drawing | `OSError` |
|
|
135
|
+
| `DrawingNotFoundError` | the file does not exist | `FileNotFoundError` |
|
|
136
|
+
| `UnsupportedFormatError` | a file type cadrender does not read | `OpenError` |
|
|
137
|
+
| `SheetNotFoundError` | no sheet with that name | `KeyError` |
|
|
138
|
+
| `OptionsError` | a wrong option name or value | `ValueError` |
|
|
139
|
+
| `RenderError` | one sheet could not be drawn or written (`render`, `render_to`) | |
|
|
140
|
+
|
|
141
|
+
SVG: `cadrender.SVG_AVAILABLE` is `True` in every release build.
|
|
142
|
+
`format="svg"` (or a `.svg` file name) writes SVG with real `<text>`
|
|
143
|
+
elements.
|
|
144
|
+
|
|
145
|
+
## Threads and the GIL
|
|
146
|
+
|
|
147
|
+
The **GIL** is Python's global lock: only one thread runs Python code at a
|
|
148
|
+
time. cadrender lets go of the GIL while it reads, draws and writes. So
|
|
149
|
+
other Python threads keep running, and you can call `render` on the same
|
|
150
|
+
`Document` from many threads at once. `on_sheet` takes the GIL again, only
|
|
151
|
+
for the call.
|
|
152
|
+
|
|
153
|
+
## Speed
|
|
154
|
+
|
|
155
|
+
Measured on an Apple M4 (best of 3, width 2000, PNG):
|
|
156
|
+
|
|
157
|
+
| Drawing | Sheets | 1 thread | all threads | CLI, all threads |
|
|
158
|
+
|---|---|---|---|---|
|
|
159
|
+
| real-world drawing, 12 MB DXF | 10 | 0.17 s | 0.06 s | 0.09 s |
|
|
160
|
+
| real-world drawing, 52 MB DXF | 16 | 0.43 s | 0.18 s | 0.21 s |
|
|
161
|
+
|
|
162
|
+
For comparison, an ezdxf + matplotlib pipeline took 162 s for one
|
|
163
|
+
hatch-heavy sheet of the second drawing. The PNG files are byte for byte
|
|
164
|
+
the same as the CLI's.
|
|
165
|
+
|
|
166
|
+
## Build and test
|
|
167
|
+
|
|
168
|
+
You need Rust (stable) and [uv](https://docs.astral.sh/uv/) (or pip).
|
|
169
|
+
|
|
170
|
+
```sh
|
|
171
|
+
cd crates/cadrender-py
|
|
172
|
+
uv venv .venv --python 3.12 # .venv is gitignored
|
|
173
|
+
uv pip install --python .venv/bin/python "maturin>=1.9.4,<2" pytest
|
|
174
|
+
.venv/bin/maturin build --release --out dist -i .venv/bin/python
|
|
175
|
+
uv pip install --python .venv/bin/python --reinstall dist/cadrender-*.whl
|
|
176
|
+
.venv/bin/python -m pytest -q # tests use the installed wheel
|
|
177
|
+
CADRENDER_SAMPLES=/path/to/folder .venv/bin/python -m pytest -q tests/test_real_samples.py # opt-in
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
The wheel is **abi3**: one wheel works on every CPython from 3.10 up.
|
|
181
|
+
The release workflow (`.github/workflows/release.yml`) builds wheels for
|
|
182
|
+
Linux x86_64 and aarch64 (manylinux), macOS x86_64 and arm64, and Windows
|
|
183
|
+
x86_64.
|
|
184
|
+
|
|
185
|
+
`CADRENDER_SAMPLES` is optional: point it at a folder with your own `.dxf`
|
|
186
|
+
and `.dwg` files, and the test renders every sheet of every file.
|
|
187
|
+
|
|
188
|
+
The test drawing `tests/data/three_sheets.dxf` is made by
|
|
189
|
+
`tests/data/gen.py`. The tests also open every hand-made DXF in
|
|
190
|
+
`crates/*/tests/data/`.
|
|
191
|
+
|
|
192
|
+
## Files
|
|
193
|
+
|
|
194
|
+
```
|
|
195
|
+
Cargo.toml, build.rs Rust crate (PyO3); never links libpython
|
|
196
|
+
pyproject.toml maturin settings: module cadrender._cadrender
|
|
197
|
+
src/lib.rs open(), module setup
|
|
198
|
+
src/doc.rs Document: sheets, info, render, render_to, render_all
|
|
199
|
+
src/batch.rs render_all: rayon threads, callbacks, summary
|
|
200
|
+
src/render.rs one sheet -> bytes / files, result dicts
|
|
201
|
+
src/options.rs option dict -> RenderOptions (checks every key)
|
|
202
|
+
src/svg.rs the SVG switch
|
|
203
|
+
python/cadrender/ the Python API, errors, RenderOptions, stubs
|
|
204
|
+
tests/ pytest
|
|
205
|
+
```
|
|
206
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
cadrender/__init__.py,sha256=LgJwyxEKMe-qPwdMclD5tIqyuUq5mUsGZKH3pYMZXhE,6904
|
|
2
|
+
cadrender/_cadrender.pyd,sha256=_zBOw3JuWmNy53BwekGbOk_YSd_aQEecWiGIHI8VOyA,2999296
|
|
3
|
+
cadrender/_cadrender.pyi,sha256=K_JxsQWGIO2NimwlMEXpQ3T-mUrPqN33_FTHTwdJLgs,1129
|
|
4
|
+
cadrender/_errors.py,sha256=drF9DA6HLzaH1qndjM_JBrexECNddbuSLZ4G364EoWQ,1240
|
|
5
|
+
cadrender/_options.py,sha256=rYIHDPkjM3kVGCAZrfRLQKWS9hE7iTfyhVb2Jn4jNpg,4222
|
|
6
|
+
cadrender/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
cadrender-0.1.0.dist-info/METADATA,sha256=kHsu0o3JmLVXAfQY6v2O2p5qDf-voIfO3wAs0JWcXvs,9463
|
|
8
|
+
cadrender-0.1.0.dist-info/WHEEL,sha256=TzjyIyBUptJHnlQyOymQYLWjtXe7MGI0m3QvmcG7PpI,96
|
|
9
|
+
cadrender-0.1.0.dist-info/licenses/LICENSE-APACHE,sha256=fP1zjFPWHHnwfjSPYiv3cHyQhCNwVNN_vgd4inX1iBw,11048
|
|
10
|
+
cadrender-0.1.0.dist-info/licenses/LICENSE-MIT,sha256=s2Sp3hztfWuKGw1l5LprbZqqbdGL_8rSFLbc1_C-94s,1104
|
|
11
|
+
cadrender-0.1.0.dist-info/sboms/cadrender-py.cyclonedx.json,sha256=l8BXr6zecx0FIcevLAe01I1-bGacZz-jwcEevZO_cC4,58202
|
|
12
|
+
cadrender-0.1.0.dist-info/RECORD,,
|