cadbuildr-bom 0.1.0__tar.gz

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.
@@ -0,0 +1,54 @@
1
+ name: Publish to PyPI
2
+
3
+ # Publishes the package to PyPI when a version tag (vX.Y.Z) is pushed.
4
+ # Uses PyPI Trusted Publishing (OIDC) — no token stored in secrets. Configure the
5
+ # trusted publisher for project "cadbuildr-bom" at https://pypi.org/manage/account/publishing/.
6
+
7
+ on:
8
+ push:
9
+ tags:
10
+ - "v*"
11
+ workflow_dispatch:
12
+
13
+ permissions:
14
+ contents: read
15
+
16
+ jobs:
17
+ build:
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ - name: Install uv
22
+ uses: astral-sh/setup-uv@v6
23
+ - name: Set up Python
24
+ run: uv python install 3.12
25
+ - name: Build sdist + wheel
26
+ run: uv build
27
+ - name: Check the tag matches the package version
28
+ run: |
29
+ PKG_VERSION="$(python -c 'import tomllib; d=tomllib.load(open("pyproject.toml","rb")); print((d.get("project") or d["tool"]["poetry"])["version"])')"
30
+ TAG_VERSION="${GITHUB_REF_NAME#v}"
31
+ echo "package=$PKG_VERSION tag=$TAG_VERSION"
32
+ if [ "$PKG_VERSION" != "$TAG_VERSION" ]; then
33
+ echo "::error::Tag $TAG_VERSION does not match package version $PKG_VERSION"; exit 1
34
+ fi
35
+ - uses: actions/upload-artifact@v4
36
+ with:
37
+ name: dist
38
+ path: dist/
39
+
40
+ publish:
41
+ needs: build
42
+ runs-on: ubuntu-latest
43
+ environment:
44
+ name: pypi
45
+ url: https://pypi.org/p/cadbuildr-bom
46
+ permissions:
47
+ id-token: write # required for Trusted Publishing (OIDC)
48
+ steps:
49
+ - uses: actions/download-artifact@v4
50
+ with:
51
+ name: dist
52
+ path: dist/
53
+ - name: Publish to PyPI
54
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,26 @@
1
+ name: pytest
2
+
3
+ on:
4
+ push:
5
+ branches: ["main"]
6
+ pull_request:
7
+ branches: ["main"]
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.10"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - name: Install uv
18
+ uses: astral-sh/setup-uv@v6
19
+ with:
20
+ enable-cache: true
21
+ - name: Set up Python ${{ matrix.python-version }}
22
+ run: uv python install ${{ matrix.python-version }}
23
+ - name: Install dependencies
24
+ run: uv sync --dev
25
+ - name: Test with pytest
26
+ run: uv run pytest
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ *.egg-info/
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — 2026-07-28
4
+
5
+ First public release.
6
+
7
+ - `extract_bom(root)` walks `Part` / `Assembly` trees into a typed
8
+ `cadbuildr-bom@1` document (schema published at
9
+ `schemas/bom/cadbuildr-bom-1.schema.json` in the CADbuildr monorepo).
10
+ - Geometry-identity grouping: items group by (name, material,
11
+ geometry_hash), where the hash is a placement-free content hash of the
12
+ part DAG — so many parts derived from one generic parametric part still
13
+ collapse into one line when they are truly identical, and colliding
14
+ variants get stable `-<hash6>` id suffixes.
15
+ - Material resolved from an explicit name or the resolved paint color.
16
+ - `bom_to_csv(bom)` renders the CSV view.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 cadbuildr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: cadbuildr-bom
3
+ Version: 0.1.0
4
+ Summary: Bill-of-materials extraction for cadbuildr assemblies: traverse a foundation component tree into a typed, stable-id parts list (bom.json + CSV)
5
+ Author: Cadbuildr Team
6
+ License-File: LICENSE
7
+ Requires-Python: <4.0.0,>=3.10.0
8
+ Requires-Dist: cadbuildr-foundation<0.3.0,>=0.2.12
9
+ Description-Content-Type: text/markdown
10
+
11
+ # CADbuildr BOM
12
+
13
+ Bill-of-materials extraction for [`cadbuildr-foundation`](https://pypi.org/project/cadbuildr-foundation/)
14
+ assemblies: traverse a component tree into a typed, stable-id parts list.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install cadbuildr-bom
20
+ ```
21
+
22
+ ## Quick usage
23
+
24
+ ```python
25
+ from cadbuildr.bom import extract_bom, bom_to_csv
26
+ from my_project.chair import Chair
27
+
28
+ bom = extract_bom(Chair())
29
+ # {"schema": "cadbuildr-bom@1", "root": "chair", "total_part_count": 7,
30
+ # "unique_part_count": 3, "items": [{"id": "leg@beech", "name": "leg",
31
+ # "material": "beech", "quantity": 4, "example_path": "chair/leg_1"}, ...]}
32
+
33
+ print(bom_to_csv(bom))
34
+ ```
35
+
36
+ ## What it does
37
+
38
+ - Walks `Part` / `Assembly` trees (or already-converted `PartRoot` /
39
+ `AssemblyRoot`) recursively through nested assemblies.
40
+ - Groups identical leaf parts by **(base name, material)** — foundation's
41
+ auto-dedup suffixes (`table_leg_1`, `table_leg_2`) collapse back into one
42
+ line item with `quantity`.
43
+ - Emits **stable item ids** (`table_leg`, `leg@beech`). These ids are the
44
+ enumerator contract for per-part fan-out workflows (supplier sourcing,
45
+ per-part quoting/CAM/drawings) in the CADbuildr task infrastructure.
46
+
47
+ Output schema is versioned (`cadbuildr-bom@1`); breaking changes bump it.
48
+
49
+ ## Cloud task
50
+
51
+ On CADbuildr cloud this library powers the `bom@1` task: run it against any
52
+ project version and the `bom.json` + `bom.csv` land in the project's artifact
53
+ repository. See the platform docs for `create_task_run(task_type="bom")`.
@@ -0,0 +1,43 @@
1
+ # CADbuildr BOM
2
+
3
+ Bill-of-materials extraction for [`cadbuildr-foundation`](https://pypi.org/project/cadbuildr-foundation/)
4
+ assemblies: traverse a component tree into a typed, stable-id parts list.
5
+
6
+ ## Installation
7
+
8
+ ```bash
9
+ pip install cadbuildr-bom
10
+ ```
11
+
12
+ ## Quick usage
13
+
14
+ ```python
15
+ from cadbuildr.bom import extract_bom, bom_to_csv
16
+ from my_project.chair import Chair
17
+
18
+ bom = extract_bom(Chair())
19
+ # {"schema": "cadbuildr-bom@1", "root": "chair", "total_part_count": 7,
20
+ # "unique_part_count": 3, "items": [{"id": "leg@beech", "name": "leg",
21
+ # "material": "beech", "quantity": 4, "example_path": "chair/leg_1"}, ...]}
22
+
23
+ print(bom_to_csv(bom))
24
+ ```
25
+
26
+ ## What it does
27
+
28
+ - Walks `Part` / `Assembly` trees (or already-converted `PartRoot` /
29
+ `AssemblyRoot`) recursively through nested assemblies.
30
+ - Groups identical leaf parts by **(base name, material)** — foundation's
31
+ auto-dedup suffixes (`table_leg_1`, `table_leg_2`) collapse back into one
32
+ line item with `quantity`.
33
+ - Emits **stable item ids** (`table_leg`, `leg@beech`). These ids are the
34
+ enumerator contract for per-part fan-out workflows (supplier sourcing,
35
+ per-part quoting/CAM/drawings) in the CADbuildr task infrastructure.
36
+
37
+ Output schema is versioned (`cadbuildr-bom@1`); breaking changes bump it.
38
+
39
+ ## Cloud task
40
+
41
+ On CADbuildr cloud this library powers the `bom@1` task: run it against any
42
+ project version and the `bom.json` + `bom.csv` land in the project's artifact
43
+ repository. See the platform docs for `create_task_run(task_type="bom")`.
@@ -0,0 +1,31 @@
1
+ # cadbuildr-bom — agent skill
2
+
3
+ Extract a bill of materials from any foundation `Part`/`Assembly`.
4
+
5
+ ```python
6
+ from cadbuildr.bom import extract_bom, bom_to_csv
7
+
8
+ bom = extract_bom(assembly) # dict, schema "cadbuildr-bom@1"
9
+ csv_text = bom_to_csv(bom) # same items as CSV
10
+ ```
11
+
12
+ Key facts:
13
+
14
+ - Accepts `Part`, `Assembly`, `PartRoot`, or `AssemblyRoot`. Anything else
15
+ raises `TypeError`.
16
+ - Identical leaf parts group by (base name, material, geometry) into one
17
+ item with `quantity`; foundation's dedup suffixes (`leg_1`, `leg_2`) are
18
+ collapsed. Geometry identity is a placement-free hash of the part's DAG
19
+ (`items[*].geometry_hash`), so a generic parametric part reused at many
20
+ dimensions (a `beam` cut to leg/rail/stretcher lengths) yields one line
21
+ per distinct dimension set, not one merged line.
22
+ - `items[*].id` is stable across re-runs of the same model — use it as the
23
+ key when fanning out per-part work. When several geometry variants share
24
+ one (name, material), each id carries a `-<hash6>` suffix.
25
+ - `material` is the foundation `Material.name`, `None` when unset/default.
26
+ Paint parts (`part.paint("beech")`) to get materials into the BOM;
27
+ named-color paints resolve to `#rrggbb` (auto material names are
28
+ unstable and never used).
29
+ - Write outputs for promotion as `bom.json` (the dict, `json.dumps`) and
30
+ `bom.csv` (the CSV text). JSON schema:
31
+ `schemas/bom/cadbuildr-bom-1.schema.json`.
@@ -0,0 +1,3 @@
1
+ from pkgutil import extend_path
2
+
3
+ __path__ = extend_path(__path__, __name__)
@@ -0,0 +1,8 @@
1
+ from cadbuildr.bom.extract import (
2
+ SCHEMA_ID,
3
+ bom_to_csv,
4
+ extract_bom,
5
+ to_component_root,
6
+ )
7
+
8
+ __all__ = ["SCHEMA_ID", "bom_to_csv", "extract_bom", "to_component_root"]
@@ -0,0 +1,243 @@
1
+ """Bill-of-materials extraction from cadbuildr foundation component trees.
2
+
3
+ Traverses a ``Part`` / ``Assembly`` (or an already-converted ``PartRoot`` /
4
+ ``AssemblyRoot``) into a typed parts list: identical leaf parts are grouped
5
+ by (base name, material, geometry) with quantities, and every item gets a
6
+ **stable id** — the enumerator contract that per-part fan-out tasks
7
+ (supplier sourcing, per-part quoting/CAM/drawings) key on.
8
+
9
+ Grouping needs a geometry dimension because real projects derive many
10
+ distinct parts from one generic parametric part: joinery-chair builds all
11
+ 14 of its parts from a single ``beam``, so (name, material) alone collapses
12
+ back legs, rails, and stretchers into one line. The geometry signature
13
+ hashes the part's serialized DAG with placement (frames), display names,
14
+ and paint's unstable auto material-name counter neutralized — same
15
+ dimensions ⇒ same signature regardless of position in the assembly.
16
+
17
+ Output schema is versioned as ``cadbuildr-bom@1``:
18
+
19
+ {
20
+ "schema": "cadbuildr-bom@1",
21
+ "root": "<root component name>",
22
+ "total_part_count": 7,
23
+ "unique_part_count": 3,
24
+ "items": [
25
+ {"id": "table_leg", "name": "table_leg", "material": "beech",
26
+ "quantity": 4, "geometry_hash": "a1b2c3d4e5f6",
27
+ "example_path": "table/table_leg_1"},
28
+ ...
29
+ ]
30
+ }
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import csv
36
+ import hashlib
37
+ import io
38
+ import json
39
+ import re
40
+ from typing import Any
41
+
42
+ from cadbuildr.foundation.compute_functions import (
43
+ _convert_component_to_root,
44
+ _finalize_root_names,
45
+ )
46
+ from cadbuildr.foundation.dag_utils import show_dag
47
+ from cadbuildr.foundation.gen.models.assembly_root import AssemblyRoot
48
+ from cadbuildr.foundation.gen.models.part_root import PartRoot
49
+
50
+ SCHEMA_ID = "cadbuildr-bom@1"
51
+
52
+ # Names auto-deduplicated by foundation get 1-based numeric suffixes
53
+ # (table_leg_1, table_leg_2); strip those to group identical parts.
54
+ _DEDUP_SUFFIX_RE = re.compile(r"_(\d+)$")
55
+
56
+
57
+ def _name_of(root: Any) -> str:
58
+ name = getattr(root, "name", None)
59
+ value = getattr(name, "value", None)
60
+ return str(value) if value else "unnamed"
61
+
62
+
63
+ # paint() auto-names materials Material_<n> from a process-global counter —
64
+ # meaningless and unstable across runs. Fall back to the resolved color.
65
+ _AUTO_MATERIAL_RE = re.compile(r"^material_\d+$", re.IGNORECASE)
66
+
67
+
68
+ def _material_of(root: Any) -> str | None:
69
+ material = getattr(root, "material", None)
70
+ if material is None:
71
+ return None
72
+ name = getattr(material, "name", None)
73
+ if name and name != "default" and not _AUTO_MATERIAL_RE.match(str(name)):
74
+ return str(name)
75
+ color = getattr(getattr(material, "options", None), "diffuse_color", None)
76
+ if isinstance(color, (list, tuple)) and len(color) == 3:
77
+ r, g, b = color
78
+ if all(isinstance(c, (int, float)) for c in (r, g, b)):
79
+ if max(r, g, b) <= 1.0:
80
+ r, g, b = (round(c * 255) for c in (r, g, b))
81
+ return "#{:02x}{:02x}{:02x}".format(int(r) & 255, int(g) & 255, int(b) & 255)
82
+ if name and name != "default":
83
+ return str(name)
84
+ return None
85
+
86
+
87
+ def _base_name(name: str) -> str:
88
+ return _DEDUP_SUFFIX_RE.sub("", name)
89
+
90
+
91
+ def _item_id(base_name: str, material: str | None) -> str:
92
+ slug = re.sub(r"[^a-z0-9_]+", "_", base_name.lower()).strip("_") or "part"
93
+ if not material:
94
+ return slug
95
+ material_slug = re.sub(r"[^a-z0-9_]+", "", material.lower()) or "material"
96
+ return f"{slug}@{material_slug}"
97
+
98
+
99
+ _GEOMETRY_HASH_CHARS = 12
100
+
101
+
102
+ def _geometry_signature(node: Any) -> str | None:
103
+ """Placement-free content hash of a leaf part's geometry.
104
+
105
+ Serializes the part subtree through foundation's DAG converter, then
106
+ hashes a canonical form with the three non-geometric axes neutralized:
107
+
108
+ - ``name`` deps (foundation's ``_1``/``_2`` dedup names),
109
+ - frame-typed nodes (assembly placement lives on the part's frame),
110
+ - auto material names (paint's process-global ``Material_<n>`` counter).
111
+
112
+ Material *options* (color) stay in — a red and a blue variant of the
113
+ same beam are different BOM lines. Returns None when the part cannot
114
+ be serialized; callers fall back to (name, material) grouping.
115
+ """
116
+ try:
117
+ dag = show_dag(node)
118
+ nodes = dag["DAG"]
119
+ registry = dag.get("serializableNodes", {})
120
+ frame_types = {
121
+ idx for name, idx in registry.items() if "frame" in str(name).lower()
122
+ }
123
+ memo: dict[str, Any] = {}
124
+
125
+ def canon(node_id: Any) -> Any:
126
+ if node_id in memo:
127
+ return memo[node_id]
128
+ raw = nodes.get(node_id)
129
+ if not isinstance(raw, dict):
130
+ return {"missing": str(node_id)}
131
+ node_type = raw.get("type")
132
+ if node_type in frame_types:
133
+ out: Any = {"type": node_type, "frame": True}
134
+ memo[node_id] = out
135
+ return out
136
+ deps: dict[str, Any] = {}
137
+ for key, value in sorted(raw.get("deps", {}).items()):
138
+ if key == "name":
139
+ deps[key] = "<name>"
140
+ elif isinstance(value, list):
141
+ deps[key] = [canon(item) for item in value]
142
+ else:
143
+ deps[key] = canon(value)
144
+ params = raw.get("params", {})
145
+ if isinstance(params, dict) and _AUTO_MATERIAL_RE.match(
146
+ str(params.get("name", ""))
147
+ ):
148
+ params = {**params, "name": "<auto>"}
149
+ out = {"type": node_type, "params": params, "deps": deps}
150
+ memo[node_id] = out
151
+ return out
152
+
153
+ blob = json.dumps(canon(dag["rootNodeId"]), sort_keys=True, default=str)
154
+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:_GEOMETRY_HASH_CHARS]
155
+ except Exception: # noqa: BLE001 — a BOM must degrade, never crash the task
156
+ return None
157
+
158
+
159
+ def to_component_root(obj: Any) -> Any:
160
+ """Normalize any accepted input into a PartRoot/AssemblyRoot tree."""
161
+ if isinstance(obj, (PartRoot, AssemblyRoot)):
162
+ return _finalize_root_names(obj)
163
+ root = _convert_component_to_root(obj)
164
+ if root is None:
165
+ raise TypeError(
166
+ f"Cannot extract a BOM from {type(obj).__name__}: expected a "
167
+ "foundation Part, Assembly, PartRoot, or AssemblyRoot"
168
+ )
169
+ return _finalize_root_names(root)
170
+
171
+
172
+ def extract_bom(obj: Any) -> dict[str, Any]:
173
+ """Extract a ``cadbuildr-bom@1`` dict from a component tree."""
174
+ root = to_component_root(obj)
175
+ groups: dict[tuple[str, str], dict[str, Any]] = {}
176
+ total = 0
177
+
178
+ def _walk(node: Any, path: tuple[str, ...]) -> None:
179
+ nonlocal total
180
+ name = _name_of(node)
181
+ if isinstance(node, AssemblyRoot):
182
+ for child in node.components:
183
+ _walk(child, path + (name,))
184
+ return
185
+ total += 1
186
+ material = _material_of(node)
187
+ base = _base_name(name)
188
+ base_id = _item_id(base, material)
189
+ signature = _geometry_signature(node)
190
+ entry = groups.setdefault(
191
+ (base_id, signature or ""),
192
+ {
193
+ "id": base_id,
194
+ "name": base,
195
+ "material": material,
196
+ "quantity": 0,
197
+ "geometry_hash": signature,
198
+ "example_path": "/".join(path + (name,)),
199
+ },
200
+ )
201
+ entry["quantity"] += 1
202
+
203
+ _walk(root, ())
204
+
205
+ # Same (name, material) but different geometry — the generic-parametric-
206
+ # part case (all of joinery-chair is one `beam`). Ids must stay stable
207
+ # when a new variant appears later, so EVERY collided variant gets its
208
+ # geometry-hash suffix (no first-wins clean id that would be stolen).
209
+ by_base_id: dict[str, int] = {}
210
+ for entry in groups.values():
211
+ by_base_id[entry["id"]] = by_base_id.get(entry["id"], 0) + 1
212
+ items = []
213
+ for entry in groups.values():
214
+ if by_base_id[entry["id"]] > 1 and entry["geometry_hash"]:
215
+ entry = {**entry, "id": f"{entry['id']}-{entry['geometry_hash'][:6]}"}
216
+ items.append(entry)
217
+ items.sort(key=lambda item: item["id"])
218
+ return {
219
+ "schema": SCHEMA_ID,
220
+ "root": _name_of(root),
221
+ "total_part_count": total,
222
+ "unique_part_count": len(items),
223
+ "items": items,
224
+ }
225
+
226
+
227
+ def bom_to_csv(bom: dict[str, Any]) -> str:
228
+ """Render a ``cadbuildr-bom@1`` dict as CSV text."""
229
+ buffer = io.StringIO()
230
+ writer = csv.writer(buffer)
231
+ writer.writerow(["id", "name", "material", "quantity", "geometry_hash", "example_path"])
232
+ for item in bom.get("items", []):
233
+ writer.writerow(
234
+ [
235
+ item.get("id", ""),
236
+ item.get("name", ""),
237
+ item.get("material") or "",
238
+ item.get("quantity", 0),
239
+ item.get("geometry_hash") or "",
240
+ item.get("example_path", ""),
241
+ ]
242
+ )
243
+ return buffer.getvalue()
@@ -0,0 +1,36 @@
1
+ [project]
2
+ name = "cadbuildr-bom"
3
+ version = "0.1.0"
4
+ readme = "README.md"
5
+ description = "Bill-of-materials extraction for cadbuildr assemblies: traverse a foundation component tree into a typed, stable-id parts list (bom.json + CSV)"
6
+ requires-python = ">=3.10.0,<4.0.0"
7
+ authors = [
8
+ {name = "Cadbuildr Team"},
9
+ ]
10
+ dependencies = [
11
+ "cadbuildr-foundation>=0.2.12,<0.3.0",
12
+ ]
13
+
14
+ [tool.cadbuildr.dependencies]
15
+ cadbuildr-foundation = "^0.2.12"
16
+
17
+ [dependency-groups]
18
+ dev = [
19
+ "pytest>=8",
20
+ ]
21
+
22
+ [tool.pytest.ini_options]
23
+ testpaths = [
24
+ "tests",
25
+ ]
26
+
27
+ [tool.hatch.build.targets.wheel]
28
+ packages = [
29
+ "cadbuildr",
30
+ ]
31
+
32
+ [build-system]
33
+ requires = [
34
+ "hatchling>=1.27.0",
35
+ ]
36
+ build-backend = "hatchling.build"