### Install visual-compare extra with pip Source: https://hbmartin.github.io/pyldraw3/visual-comparison Install the optional visual-comparison tool and its dependencies. This extra is not part of the base installation. ```bash pip install "pyldraw3[visual-compare]" ``` -------------------------------- ### CLI commands for parts catalog, validation, and BOM Source: https://hbmartin.github.io/pyldraw3/guide Command-line examples for searching parts, getting part info, validating models, generating BOMs, and inspecting/validating instructions. ```bash ldraw parts search "cowboy" ldraw parts info 3629 ldraw validate my_model.ldr ldraw bom my_model.mpd ldraw instructions inspect my_model.mpd --parts ldraw instructions validate my_model.mpd --strict ``` -------------------------------- ### Run an example script and redirect output to an LDraw file Source: https://hbmartin.github.io/pyldraw3/examples Run the `figures.py` example and redirect its standard output to `figures.ldr`. Assumes the LDraw library has been downloaded and generated (`ldraw download --yes && ldraw generate --yes`) so that `ldraw.library.*` imports resolve. ```bash python examples/figures.py > figures.ldr ``` -------------------------------- ### ldraw instructions inspect command example Source: https://hbmartin.github.io/pyldraw3/cli Shows the command and its output for inspecting a model file. The command requires the configured parts catalog; otherwise it prints the ldraw download installation hint and exits 1. Section selection is case-insensitive. ```bash $ ldraw instructions inspect model.mpd --section module.ldr --parts section step direct expanded cumulative rotation camera callouts group page suppressed module.ldr 1 2 2 2 - - 0 - - - qty part colour description 2 3001 Red Brick 2 x 4 ``` -------------------------------- ### Setup and LDraw data download/generation with uv Source: https://hbmartin.github.io/pyldraw3/cli Sync dependencies, activate the virtual environment, then download and generate LDraw data using the ldraw CLI. ```bash uv sync source .venv/bin/activate uv run ldraw download --yes uv run ldraw generate --yes ``` -------------------------------- ### discover_libraries() Source: https://hbmartin.github.io/pyldraw3/upgrading-1.5 Identifies complete and partial installations of the parts library. ```APIDOC ## discover_libraries() ### Description Identifies complete and partial installations of the parts library. ### Method discover_libraries ### Endpoint discover_libraries() ### Parameters None ### Response Returns a list of library installations with status (complete or partial). ``` -------------------------------- ### Install pyldraw3 with uv Source: https://hbmartin.github.io/pyldraw3 Install the pyldraw3 package using the uv package manager. ```bash uv add pyldraw3 ``` -------------------------------- ### Use LDrawSession to inspect and control setup steps Source: https://hbmartin.github.io/pyldraw3/upgrading-1.2 Lower-level handle for inspecting state and controlling steps individually. Use state() to check readiness and branch on needs_generation or needs_index_rebuild. ```python from ldraw import LDrawSession session = LDrawSession() # uses Config.load() by default state = session.state() if state.ready: parts = session.load() else: if state.needs_generation: ... # call ensure_library() to fix, or regenerate if state.needs_index_rebuild: parts = session.rebuild_index() ``` -------------------------------- ### Install and set up PyLDraw3 environment Source: https://hbmartin.github.io/pyldraw3/guide Run these commands to sync dependencies, activate the virtual environment, download the LDraw parts library version 2018-02, and generate the necessary files. ```bash uv sync source .venv/bin/activate uv run ldraw download --version 2018-02 --yes uv run ldraw generate --yes ``` -------------------------------- ### inspect_library() Source: https://hbmartin.github.io/pyldraw3/upgrading-1.5 Inspects a specific library installation for completeness and details. ```APIDOC ## inspect_library() ### Description Inspects a specific library installation for completeness and details. ### Method inspect_library ### Endpoint inspect_library() ### Parameters - **library_path** (string) - Required - Path to the library installation. ### Response Returns installation details including completeness and diagnostics. ``` -------------------------------- ### Generate LDraw library Source: https://hbmartin.github.io/pyldraw3/guide Run this command to generate the LDraw library after installation or when imports fail. ```bash uv run ldraw generate --yes ``` -------------------------------- ### Part reference case preservation example Source: https://hbmartin.github.io/pyldraw3/upgrading-1.1 Shows how Piece.place() preserves case in 1.1.0, with comments showing 1.0.0 vs 1.1.0 output. ```python from ldraw.pieces import Piece piece = Piece.place("3001") piece.reference # 1.0.0: "3001.DAT" # 1.1.0: "3001.dat" parsed = Piece.place("Sub-Assembly.LDR") parsed.reference # 1.0.0: "SUB-ASSEMBLY.LDR" # 1.1.0: "Sub-Assembly.LDR" (exactly as written) ``` -------------------------------- ### Query part bounding box and stud positions with Parts Source: https://hbmartin.github.io/pyldraw3/upgrading-1.1 Shows how to use the new Parts methods to get a part's bounding box and stud positions. Requires a parts.lst file path. The bounding box returns min/max corners and size in LDU (multiply by 0.4 for mm). studs() returns all stud primitives including underside tubes, while stud_positions() pre-filters to top studs. ```python from ldraw import Parts parts = Parts.get("path/to/parts.lst") box = parts.bounding_box("3001") # 2 x 4 brick box.min, box.max # Vector(-40, -4, -20), Vector(40, 24, 20) box.size # Vector(80, 28, 40) — LDU; multiply by 0.4 for mm studs = parts.studs("3001") # every stud primitive, incl. underside tubes tops = parts.stud_positions("3001") # 8 top-stud positions for a 2 x 4 brick ``` -------------------------------- ### Report progress events during setup Source: https://hbmartin.github.io/pyldraw3/upgrading-1.2 Pass an on_progress callback to ensure_library to receive typed ProgressEvent at each stage. The callback prints stage, message, and optional current/total counts. ```python from ldraw import ProgressEvent, ProgressStage, ensure_library def report(event: ProgressEvent) -> None: if event.total: print(f"[{event.stage}] {event.message}: {event.current}/{event.total}") else: print(f"[{event.stage}] {event.message}") ensure_library(on_progress=report) ``` -------------------------------- ### Query connection features and metadata with Parts.connections and Parts.connection_metadata Source: https://hbmartin.github.io/pyldraw3/upgrading-1.6 Use prepare_catalog() to get a prepared catalog, then iterate over connection features for a part code and print the metadata report. The report includes coverage, source count, and diagnostics. ```python from ldraw import prepare_catalog prepared = prepare_catalog() parts = prepared.parts for feature in parts.connections("3001"): print(feature.kind, feature.role, feature.position, feature.source) report = parts.connection_metadata("3001") print(report.coverage, report.source_count, report.diagnostics) ``` -------------------------------- ### inspect_library(path: str | Path) -> LibraryInspection Source: https://hbmartin.github.io/pyldraw3/api Inspects a candidate installation without building its catalog. Returns a LibraryInspection object. ```APIDOC ## inspect_library(path: str | Path) -> LibraryInspection ### Description Inspect a candidate installation without building its catalog. ### Method inspect_library ### Signature inspect_library(path: str | Path) -> LibraryInspection ### Parameters - **path** (str | Path) - Required - The path to the candidate installation. ### Returns - **LibraryInspection** - The inspection result. ``` -------------------------------- ### Run visual comparison with regions Source: https://hbmartin.github.io/pyldraw3/visual-comparison Invokes the visual comparison script with a reference image, a render image, an output directory, and a regions JSON file. Each region gets reference, aligned, overlay, and difference crops under 'regions/', plus its own metrics in 'comparison.json'. ```bash uv run --extra visual-compare python scripts/visual_compare.py compare \ reference.png render.png \ --output-dir comparison --regions regions.json ``` -------------------------------- ### Parts.get Source: https://hbmartin.github.io/pyldraw3/api Class method to get a memoized Parts instance keyed by parts list and optional content fingerprints. Omitting parts_lst_md5 memoizes under a different key than passing it, so mixing both styles for one file parses it twice. ```APIDOC ## Parts.get ### Description Get a memoized Parts keyed by list and optional content fingerprints. Omitting `parts_lst_md5` memoizes under a different key than passing it, so mixing both styles for one file parses it twice. Directory connection sources are deliberately not walked on cache lookup; call `fresh` after editing their nested contents. ### Method classmethod ### Signature ``` get( parts_lst: str | Path, *, tree_fingerprint: str | None = None, parts_lst_md5: str | None = None, connection_shadows: Iterable[str | Path] = (), studio_metadata: Iterable[str | Path] = (), ) -> Parts ``` ### Parameters - **parts_lst** (str | Path) - Required - Path to the parts list file. - **tree_fingerprint** (str | None) - Optional - Fingerprint of the directory tree. - **parts_lst_md5** (str | None) - Optional - MD5 hash of the parts list file. - **connection_shadows** (Iterable[str | Path]) - Optional - Iterable of connection shadow paths. - **studio_metadata** (Iterable[str | Path]) - Optional - Iterable of studio metadata paths. ### Returns - **Parts** - A memoized Parts instance. ``` -------------------------------- ### Run parts geometry and inspect commands Source: https://hbmartin.github.io/pyldraw3/cli Example invocations of `ldraw parts geometry` and `ldraw inspect` with various options. The first command outputs JSON for part 3001. The second inspects a model with chronological ordering and a gap threshold. The third inspects a model with shadow and studio metadata files. ```bash ldraw parts geometry 3001 --format json ldraw inspect model.mpd --chronological --gap-threshold 5 -o inspection.txt ldraw inspect model.mpd --ldcad-shadow shadow.csl --studio-metadata studio.json ``` -------------------------------- ### Query Helpers: find_pieces, iter_pieces, bill_of_materials Source: https://hbmartin.github.io/pyldraw3/guide Shows how to query a model for pieces by part or colour, iterate over pieces, and get a bill of materials. These helpers work on both built and parsed models. ```python model.find_pieces(part="3001") model.find_pieces(colour=4) model.find_pieces(colour=4, recursive=True) list(model.iter_pieces()) model.bill_of_materials() ``` -------------------------------- ### Build and preview documentation with uv Source: https://hbmartin.github.io/pyldraw3/cli Sync the docs group, serve the documentation locally with zensical, and build it cleanly with strict mode. ```bash uv sync --group docs uv run zensical serve uv run zensical build --clean --strict ``` -------------------------------- ### Build instructions with InstructionBuilder Source: https://hbmartin.github.io/pyldraw3 Create an instruction document with a note and step, then iterate over the instruction steps. ```python from ldraw import InstructionBuilder, Model, Piece model = Model(name="model.ldr", objects=[Piece.place("3001", colour=4)]) builder = InstructionBuilder(model) builder.note("Attach the red brick") builder.step() for step in model.iter_instruction_steps(): print(step.number, step.added_bill_of_materials()) ``` -------------------------------- ### Set up LDraw library Source: https://hbmartin.github.io/pyldraw3 Activate the virtual environment and set up the LDraw library by downloading and generating the library modules. ```bash source .venv/bin/activate ldraw download --yes ldraw generate --yes ``` -------------------------------- ### Install pyldraw3 1.3.0 with pip Source: https://hbmartin.github.io/pyldraw3/upgrading-1.3 Alternative upgrade command using pip. Both commands install the same package version. ```bash pip install -U pyldraw3 ``` -------------------------------- ### Prepare the catalog once with prepare_catalog() Source: https://hbmartin.github.io/pyldraw3/upgrading-1.5 Replaces separate readiness and loading passes. Checks only requested capabilities, computes one reusable filesystem fingerprint, loads or rebuilds the SQLite index, and returns before/after state plus a CatalogBuildReport and diagnostics. Progress events carry explicit ProgressUnit values; pass a CancellationToken to cancel safely. Generated modules are not checked unless LDrawCapability.GENERATED_MODULES is requested. ```python from ldraw import CancellationToken, LDrawCapability, prepare_catalog token = CancellationToken() result = prepare_catalog( capabilities=(LDrawCapability.CATALOG,), on_progress=lambda event: print( event.stage, event.current, event.total, event.unit ), cancellation=token, ) parts = result.parts ``` -------------------------------- ### valid_module: claim only ldraw.library namespace Source: https://hbmartin.github.io/pyldraw3/dynamic-imports Static method that returns True only for ldraw.library or its submodules (rest empty or starting with '.'). Rejects names like ldraw.librarything that merely start with the prefix. ```python VIRTUAL_MODULE = "ldraw.library" @staticmethod def valid_module(fullname: str) -> bool: if fullname.startswith(VIRTUAL_MODULE): rest = fullname[len(VIRTUAL_MODULE) :] return not rest or rest.startswith(".") return False ``` -------------------------------- ### ldraw version Source: https://hbmartin.github.io/pyldraw3/cli Shows the installed pyldraw3 version. ```APIDOC ## ldraw version ### Description Prints the installed `pyldraw3` version. ### Usage `ldraw version` ``` -------------------------------- ### Install LEGO Model Builder skill via npx Source: https://hbmartin.github.io/pyldraw3/lego-model-builder Use this command to install the lego-model-builder skill directly from GitHub in coding agents that support the Agent Skills format. The command is `npx skills add hbmartin/pyldraw3 --skill lego-model-builder`. ```bash npx skills add hbmartin/pyldraw3 --skill lego-model-builder ``` -------------------------------- ### Build semantic instructions with InstructionBuilder Source: https://hbmartin.github.io/pyldraw3/guide Creates a Model and InstructionBuilder, adds pieces, notes, steps, camera state, and rotation steps. Iterates instruction steps to print step number, rotation, camera, and added bill of materials. ```python from ldraw import CameraState, InstructionBuilder, Model, Piece, RotationMode from ldraw.instructions import InstructionScope model = Model(name="main.ldr") builder = InstructionBuilder(model) model.add(Piece.place("3001", colour=4)) builder.note("PDF page 1") builder.step() model.add(Piece.place("3005", colour=1)) builder.set_camera(CameraState(fov=35), scope=InstructionScope.LOCAL) builder.rotation_step(0, 90, 0, mode=RotationMode.ADDITIVE) for step in model.iter_instruction_steps(): print(step.number, step.rotation, step.camera) print(step.added_bill_of_materials()) ``` -------------------------------- ### Parts.get_category Source: https://hbmartin.github.io/pyldraw3/api Instance method to get the category of a part based on its description. ```APIDOC ## Parts.get_category ### Description Get the category of a part based on its description. ### Method instance ### Signature ``` get_category(part_description: str) -> PartCategory | None ``` ### Parameters - **part_description** (str) - Required - The part description. ### Returns - **PartCategory | None** - The part category if found, otherwise None. ``` -------------------------------- ### Create a piece with Piece.place Source: https://hbmartin.github.io/pyldraw3 Create a piece using the keyword-first constructor Piece.place with sensible defaults. ```python from ldraw import Piece piece = Piece.place("3005", colour=4) ``` -------------------------------- ### Parts.studs Source: https://hbmartin.github.io/pyldraw3/api Retrieves the studs of a part. This method is used to get the stud positions of a part. ```APIDOC ## Parts.studs ### Description Retrieves the studs of a part. ### Method GET ### Endpoint Parts.studs ### Parameters - **code** (string) - Required - The part code. ### Response #### Success Response - **studs** (list) - A list of stud positions. #### Response Example ```json { "studs": [] } ``` ``` -------------------------------- ### InstructionBuilder.highlight() Source: https://hbmartin.github.io/pyldraw3/api Highlights an existing placement using proximity-safe metadata. ```APIDOC ## InstructionBuilder.highlight() ### Description Highlights an existing placement using proximity-safe metadata. ### Method highlight ### Signature ``` highlight(piece: Piece) -> None ``` ### Parameters - **piece** (Piece) - Required - The piece to highlight. ### Returns None ``` -------------------------------- ### Configure authoritative metadata sources with connection_shadows and studio_metadata Source: https://hbmartin.github.io/pyldraw3/upgrading-1.6 Pass connection_shadows and studio_metadata to prepare_catalog() to register LDCad shadow and Studio metadata sources. The same keywords are available on other catalog preparation methods. ```python from ldraw import prepare_catalog prepared = prepare_catalog( connection_shadows=("LDCadShadowLibrary.csl",), studio_metadata=("studio-connectivity.json",), ) parts = prepared.parts report = parts.connection_metadata("32000") print(report.coverage, report.source_count, report.diagnostics) ``` -------------------------------- ### PartsCatalog.module_sections Source: https://hbmartin.github.io/pyldraw3/api Retrieves the module sections of the catalog. This method is used to get the sections defined in the catalog. ```APIDOC ## PartsCatalog.module_sections ### Description Retrieves the module sections of the catalog. ### Method GET ### Endpoint PartsCatalog.module_sections ### Parameters None ### Response #### Success Response - **sections** (list) - A list of module sections. #### Response Example ```json { "sections": [] } ``` ``` -------------------------------- ### Parts.fresh() Source: https://hbmartin.github.io/pyldraw3/upgrading-1.6 Same keywords as prepare_catalog() for configuring authoritative metadata. ```APIDOC ## Parts.fresh() ### Description Same keywords as `prepare_catalog()` for configuring authoritative metadata. ### Method GET ### Endpoint `Parts.fresh()` ### Parameters #### Request Body - **connection_shadows** (tuple of strings) - Optional - A tuple of LDCad shadow library source filenames. - **studio_metadata** (tuple of strings) - Optional - A tuple of Studio metadata source filenames. ### Request Example ```python # No direct example provided in source ``` ### Response #### Success Response (200) - **parts** (Parts) - The parts object. #### Response Example ```python # No example provided in source ``` ``` -------------------------------- ### Parts.references_for Source: https://hbmartin.github.io/pyldraw3/api Retrieves the references for a part. This method is used to get the subparts and primitives referenced by a part. ```APIDOC ## Parts.references_for ### Description Retrieves the references for a part. ### Method GET ### Endpoint Parts.references_for ### Parameters - **code** (string) - Required - The part code. ### Response #### Success Response - **references** (list) - A list of part references. #### Response Example ```json { "references": [] } ``` ``` -------------------------------- ### InstructionDocument.from_model(model, *, parts=None) Source: https://hbmartin.github.io/pyldraw3/api Builds a semantic instruction document from a Model object. Optionally accepts a Parts object. ```APIDOC ## InstructionDocument.from_model ### Description Build a semantic instruction document from `model`. ### Method classmethod ### Signature ```python from_model(model: Model, *, parts: Parts | None = None) -> InstructionDocument ``` ### Parameters - **model** (Model) - Required - The model to build the instruction document from. - **parts** (Parts | None) - Optional - The parts to associate with the document. ### Returns - **InstructionDocument** - The constructed instruction document. ``` -------------------------------- ### Parts.stud_positions Source: https://hbmartin.github.io/pyldraw3/api Retrieves the stud positions of a part. This method is used to get the positions of studs on a part. ```APIDOC ## Parts.stud_positions ### Description Retrieves the stud positions of a part. ### Method GET ### Endpoint Parts.stud_positions ### Parameters - **code** (string) - Required - The part code. ### Response #### Success Response - **positions** (list) - A list of stud positions. #### Response Example ```json { "positions": [] } ``` ``` -------------------------------- ### Use ensure_library() to set up pyldraw Source: https://hbmartin.github.io/pyldraw3/upgrading-1.2 One-call entry point that downloads, generates, and indexes as needed, then wires up the importer. Returns a session with load() and open_model() methods. ```python from ldraw import ensure_library session = ensure_library() # download + generate + index as needed parts = session.load() # ready to use model = session.open_model("castle.mpd") ``` -------------------------------- ### Parts.connections Source: https://hbmartin.github.io/pyldraw3/api Retrieves the connection points of a part. This method is used to get the connection metadata for a part. ```APIDOC ## Parts.connections ### Description Retrieves the connection points of a part. ### Method GET ### Endpoint Parts.connections ### Parameters - **code** (string) - Required - The part code. ### Response #### Success Response - **connections** (list) - A list of connection points. #### Response Example ```json { "connections": [] } ``` ``` -------------------------------- ### Parts.bounding_box Source: https://hbmartin.github.io/pyldraw3/api Computes the bounding box for a given part. This method is used to get the geometric bounds of a part. ```APIDOC ## Parts.bounding_box ### Description Computes the bounding box for a given part. ### Method GET ### Endpoint Parts.bounding_box ### Parameters - **code** (string) - Required - The part code. ### Response #### Success Response - **bounds** (object) - The bounding box coordinates. #### Response Example ```json { "bounds": {} } ``` ``` -------------------------------- ### Parts.get_category Source: https://hbmartin.github.io/pyldraw3/api Retrieves the category information for a given category name. This method is used to get category details. ```APIDOC ## Parts.get_category ### Description Retrieves the category information for a given category name. ### Method GET ### Endpoint Parts.get_category ### Parameters - **category** (string) - Required - The category name. ### Response #### Success Response - **category** (object) - The category details. #### Response Example ```json { "category": {} } ``` ``` -------------------------------- ### Parts.from_catalog Source: https://hbmartin.github.io/pyldraw3/api Class method to construct a Parts instance that adopts a prebuilt catalog, skipping the expensive per-part categorization pass. ```APIDOC ## Parts.from_catalog ### Description Construct a Parts that adopts a prebuilt catalog. Skips the expensive per-part categorization pass. ### Method classmethod ### Signature ``` from_catalog( parts_lst: str | Path, catalog: PartsCatalog ) -> Parts ``` ### Parameters - **parts_lst** (str | Path) - Required - Path to the parts list file. - **catalog** (PartsCatalog) - Required - A prebuilt PartsCatalog instance. ### Returns - **Parts** - A Parts instance that adopts the given catalog. ``` -------------------------------- ### Parts.get() Source: https://hbmartin.github.io/pyldraw3/upgrading-1.6 Same keywords as prepare_catalog() for configuring authoritative metadata. ```APIDOC ## Parts.get() ### Description Same keywords as `prepare_catalog()` for configuring authoritative metadata. ### Method GET ### Endpoint `Parts.get()` ### Parameters #### Request Body - **connection_shadows** (tuple of strings) - Optional - A tuple of LDCad shadow library source filenames. - **studio_metadata** (tuple of strings) - Optional - A tuple of Studio metadata source filenames. ### Request Example ```python # No direct example provided in source ``` ### Response #### Success Response (200) - **parts** (Parts) - The parts object. #### Response Example ```python # No example provided in source ``` ``` -------------------------------- ### discover_libraries Source: https://hbmartin.github.io/pyldraw3/api Discovers valid and partial LDraw library installations in configured/common locations. Returns a tuple of LibraryInspection objects. ```APIDOC ## discover_libraries ### Description Discover valid and partial installations in configured/common locations. ### Method Function call ### Signature ``` discover_libraries( paths: Iterable[str | Path] | None = None, *, on_progress: ProgressCallback | None = None, cancellation: CancellationToken | None = None, ) -> tuple[LibraryInspection, ...] ``` ### Parameters - **paths** (Iterable[str | Path] | None) - Optional - Paths to search for libraries. If None, uses configured/common locations. - **on_progress** (ProgressCallback | None) - Optional - Callback for progress updates. - **cancellation** (CancellationToken | None) - Optional - Token to cancel the operation. ### Returns - **tuple[LibraryInspection, ...]** - A tuple of LibraryInspection objects representing discovered libraries. ``` -------------------------------- ### Building Models Programmatically: Model.from_pieces, add_group, add_submodel Source: https://hbmartin.github.io/pyldraw3/guide Builds a model from pieces, adds a group with a figure, adds a submodel, and saves to a file. Shows how to use from_pieces, add_group, add_submodel, and save. ```python from ldraw import Group, Model, Person, Piece, Vector model = Model.from_pieces( [Piece.place("3001", colour=4)], name="scene.ldr", description="A scene", author="you", ) group = Group() figure = Person(position=Vector(0, -48, 0), group=group) figure.head(colour=14) figure.torso(colour=4) model.add_group(group) wheels = Model.from_pieces([Piece.place("3005", colour=0)], name="wheels.ldr") reference = model.add_submodel(wheels, position=Vector(0, -24, 0)) model.save("scene.ldr") ``` -------------------------------- ### Colour.rgb canonicalization examples Source: https://hbmartin.github.io/pyldraw3/upgrading-1.1 Shows how Colour.rgb is canonicalized to #RRGGBB in pyldraw 1.1.0. Malformed values raise ValueError immediately. ```python from ldraw.colour import Colour Colour(rgb="4b0082").rgb # "#4B0082" Colour(rgb="#4b0082").rgb # "#4B0082" Colour(rgb="nonsense") # ValueError, immediately ``` -------------------------------- ### Run visual_compare.py compare command Source: https://hbmartin.github.io/pyldraw3/visual-comparison Compare a reference image against a candidate render, writing outputs to the specified directory. The scale range is configurable via --min-scale, --max-scale, and --scale-steps. ```bash uv run --extra visual-compare python scripts/visual_compare.py compare \ references/front.png renders/scout.front.png \ --output-dir comparison/front \ --min-scale 0.75 --max-scale 1.30 --scale-steps 56 ``` -------------------------------- ### Progress Events Source: https://hbmartin.github.io/pyldraw3/upgrading-1.2 Structured events emitted during setup flows. Pass an on_progress callback to receive typed ProgressEvent at each stage. ```APIDOC ## Progress Events ### Description `ldraw.progress` defines structured events emitted during setup flows. Pass an `on_progress` callback to `ensure_library`, `download`, or `generate` to receive a typed `ProgressEvent` at each stage. ### Method Callback function ### Endpoint `from ldraw import ProgressEvent, ProgressStage, ensure_library` ### Parameters #### Callback Signature - **event** (ProgressEvent) - The event object containing stage, message, optional current/total byte counts, and optional path. ### Request Example python from ldraw import ProgressEvent, ProgressStage, ensure_library def report(event: ProgressEvent) -> None: if event.total: print(f"[{event.stage}] {event.message}: {event.current}/{event.total}") else: print(f"[{event.stage}] {event.message}") ensure_library(on_progress=report) ### Response #### Success Response - `ProgressStage` is a `StrEnum`: `DOWNLOAD`, `UNPACK`, `PARTS_LIST`, `LIBRARY_GENERATION`, `INDEX_REBUILD`, `DONE`. - `ProgressEvent` carries `stage`, `message`, optional `current`/`total` byte counts (for the download stage), and an optional `path`. #### Notes Download progress is throttled: at most one event per megabyte, with the first (`current=0`) and final byte counts always forced through. When no callback is supplied, no events are built at all. ``` -------------------------------- ### catalog.load_parts() Source: https://hbmartin.github.io/pyldraw3/upgrading-1.6 Same keywords as prepare_catalog() for configuring authoritative metadata. ```APIDOC ## catalog.load_parts() ### Description Same keywords as `prepare_catalog()` for configuring authoritative metadata. ### Method POST ### Endpoint `catalog.load_parts()` ### Parameters #### Request Body - **connection_shadows** (tuple of strings) - Optional - A tuple of LDCad shadow library source filenames. - **studio_metadata** (tuple of strings) - Optional - A tuple of Studio metadata source filenames. ### Request Example ```python # No direct example provided in source ``` ### Response #### Success Response (200) - **parts** (Parts) - The loaded parts object. #### Response Example ```python # No example provided in source ``` ``` -------------------------------- ### LibraryInspection Source: https://hbmartin.github.io/pyldraw3/api A dataclass that performs a non-mutating inspection of a possible LDraw installation. It provides properties to check overall validity and to list missing or corrupt components. ```APIDOC ## LibraryInspection ### Description A dataclass that performs a non-mutating inspection of a possible LDraw installation. ### Fields - **path** (Path) - The root path of the installation. - **ldraw_path** (Path) - The path to the LDraw directory. - **release** (str | None) - The release version, if known. - **components** (tuple[LibraryComponent, ...]) - The inspected components. - **diagnostics** (tuple[Diagnostic, ...]) - Optional diagnostics. Defaults to (). ### Properties - **valid** (bool) - Returns whether every required component is present and usable. - **missing_components** (tuple[str, ...]) - Returns names of components that were not found. - **corrupt_components** (tuple[str, ...]) - Returns names of present components that failed validation. ``` -------------------------------- ### builder.multi_step() Source: https://hbmartin.github.io/pyldraw3/guide Context manager for creating a multi-step section in the instruction builder. ```APIDOC ## builder.multi_step() ### Description Context manager for creating a multi-step section in the instruction builder. ### Method CALL ### Endpoint builder.multi_step() ### Parameters None ### Example ```python from ldraw.instructions import CalloutMode, InventoryTarget with builder.multi_step(), builder.ignore(InventoryTarget.PLI): model.add(Piece.place("3001")) builder.step() ``` ### Response Returns a context manager. ``` -------------------------------- ### Create and save a simple model Source: https://hbmartin.github.io/pyldraw3 Create a simple LDraw model with a single brick and write it to a .ldr file. ```python from ldraw import Group, Identity, Piece, Vector from ldraw.library.colours import Light_Grey from ldraw.library.parts.bricks import Brick1X2WithClassicSpaceLogoPattern model = Group() Piece( Light_Grey, Vector(-10, -32, -90), Identity(), Brick1X2WithClassicSpaceLogoPattern, model, ) with open("my_model.ldr", "w") as ldr_file: print(model, file=ldr_file) ``` -------------------------------- ### find_part(description: str | None = None, code: str | None = None) -> Part | None Source: https://hbmartin.github.io/pyldraw3/api Gets a Part from its description or code, or None when not found. ```APIDOC ## find_part(description: str | None = None, code: str | None = None) -> Part | None ### Description Get a Part from its description or code, or None when not found. ### Parameters - **description** (str | None) - Optional - The part description. - **code** (str | None) - Optional - The part code. ### Returns - **Part | None** - The Part object if found, otherwise None. ``` -------------------------------- ### LDrawSession.prepare_catalog() Source: https://hbmartin.github.io/pyldraw3/upgrading-1.6 Same keywords as prepare_catalog() for configuring authoritative metadata. ```APIDOC ## LDrawSession.prepare_catalog() ### Description Same keywords as `prepare_catalog()` for configuring authoritative metadata. ### Method POST ### Endpoint `LDrawSession.prepare_catalog()` ### Parameters #### Request Body - **connection_shadows** (tuple of strings) - Optional - A tuple of LDCad shadow library source filenames. - **studio_metadata** (tuple of strings) - Optional - A tuple of Studio metadata source filenames. ### Request Example ```python # No direct example provided in source ``` ### Response #### Success Response (200) - **prepared** (PreparedCatalog) - The prepared catalog object. #### Response Example ```python # No example provided in source ``` ``` -------------------------------- ### ensure_library() Source: https://hbmartin.github.io/pyldraw3/upgrading-1.2 One-call entry point to make the LDraw library ready. It downloads, generates, and indexes as needed, then returns a session ready for use. ```APIDOC ## ensure_library() ### Description One-call entry point to make the LDraw library ready. It inspects the current state and performs only the missing work: download the library if absent, regenerate `ldraw.library` if stale, rebuild the catalog index if stale, then wires up the importer. ### Method Function call ### Endpoint `from ldraw import ensure_library` ### Parameters #### Keyword Arguments - **config** (Config) - Optional - Supply an explicit Config instead of the default. - **config_file** (str) - Optional - Path to a config file instead of the default. - **version** (str) - Optional - Which LDraw release to download if one is missing (defaults to the complete release). - **force_generate** (bool) - Optional - If True, regenerate `ldraw.library` even if it looks fresh. - **write_config** (bool) - Optional - If True, persist the resolved configuration to disk. - **on_progress** (Callable) - Optional - A callback receiving `ProgressEvent`s. ### Request Example python from ldraw import ensure_library session = ensure_library() # download + generate + index as needed parts = session.load() # ready to use model = session.open_model("castle.mpd") ### Response #### Success Response Returns an `LDrawSession` object ready for use. #### Error Handling Setup failures are normalized to `RuntimeError` with a readable message, wrapping the underlying `requests`/zip/`UnwritableOutputError` cause. ``` -------------------------------- ### Iterate over confirmed connection graph edges Source: https://hbmartin.github.io/pyldraw3/upgrading-1.6 Shows how to use inspection.connection_graphs() to get the confirmed multigraph and iterate over its edges, printing occurrence indices and feature IDs. ```python from ldraw import inspect_model inspection = inspect_model(model, parts) graphs = inspection.connection_graphs() for edge in graphs.confirmed.edges: print(edge.first, edge.second, edge.first_feature_id, edge.second_feature_id) ``` -------------------------------- ### generate Source: https://hbmartin.github.io/pyldraw3/api Generates the library from the provided configuration. Returns None. ```APIDOC ## generate ### Description Generate the library from configuration. ### Method Function call ### Signature ``` generate( config: Config, *, force: bool = False, on_progress: ProgressCallback | None = None, fingerprint: str | None = None, cancellation: CancellationToken | None = None, ) -> None ``` ### Parameters - **config** (Config) - Required - The configuration to use for generation. - **force** (bool) - Optional - Whether to force regeneration. Defaults to False. - **on_progress** (ProgressCallback | None) - Optional - Callback for progress updates. - **fingerprint** (str | None) - Optional - A fingerprint to use for caching. - **cancellation** (CancellationToken | None) - Optional - Token to cancel the operation. ### Returns - **None** - This function does not return a value. ``` -------------------------------- ### LDrawSession Source: https://hbmartin.github.io/pyldraw3/upgrading-1.2 Lower-level handle to inspect or control the setup steps individually. Provides state inspection, path resolution, loading, index rebuilding, and model opening. ```APIDOC ## LDrawSession ### Description Lower-level handle when you want to inspect or control the setup steps individually. It uses `Config.load()` by default and provides methods to check state, load parts, rebuild the index, and open models. ### Method Class instantiation and method calls ### Endpoint `from ldraw import LDrawSession` ### Methods #### `state()` Returns an `LDrawState` classifying the library, catalog index, and generated package. Its booleans — `ready`, `library_available`, `needs_index_rebuild`, `needs_generation` — let you branch without catching exceptions or stat-ing files yourself. The exact cause is in `state.reasons` as `LDrawStateReason` members (`LIBRARY_MISSING`, `INDEX_STALE`, `GENERATED_LIBRARY_MISSING`, …). #### `paths` Returns `LDrawPaths` — the resolved `parts.lst`, generated-library, catalog-db, and other paths for the configuration. #### `load()` Loads `Parts`, building and persisting the catalog index when needed. #### `rebuild_index(force=..., on_progress=...)` Rebuilds the persistent index (unlinking a stale DB first) and returns the loaded parts. #### `open_model(path)` Thin wrapper over `read_model`. ### Request Example python from ldraw import LDrawSession session = LDrawSession() # uses Config.load() by default state = session.state() if state.ready: parts = session.load() else: if state.needs_generation: ... # call ensure_library() to fix, or regenerate if state.needs_index_rebuild: parts = session.rebuild_index() ### Response #### Success Response - `state()` returns an `LDrawState` object. - `paths` returns an `LDrawPaths` object. - `load()` returns `Parts`. - `rebuild_index()` returns loaded `Parts`. - `open_model(path)` returns a model. ``` -------------------------------- ### Use balanced context managers for callout, multi-step, and ignore Source: https://hbmartin.github.io/pyldraw3/guide Shows exception-safe structural authoring using builder.callout, builder.multi_step, and builder.ignore context managers. ```python from ldraw.instructions import CalloutMode, InventoryTarget with builder.callout(mode=CalloutMode.ROTATED): model.add_submodel(module) with builder.multi_step(), builder.ignore(InventoryTarget.PLI): model.add(Piece.place("3001")) builder.step() ```