From 85caca10bd2b9cf403731483a5c87931f792887c Mon Sep 17 00:00:00 2001 From: Oleg Date: Wed, 26 Aug 2026 23:18:17 +0300 Subject: [PATCH] feat: add active-view image import script --- AGENTS.md | 32 ++++ README.md | 2 + catalog.json | 56 ++++++ documentation/import_image_to_active_view.md | 77 ++++++++ documentation/import_image_to_active_view.py | 189 +++++++++++++++++++ 5 files changed, 356 insertions(+) create mode 100644 AGENTS.md create mode 100644 documentation/import_image_to_active_view.md create mode 100644 documentation/import_image_to_active_view.py diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ed4a014 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,32 @@ +# Revit Python Scripts Agent Instructions + +This repository is a reviewed catalog of reusable Revit scripts for BIMO Run Python and BIMO MCP. Agents may propose focused, generally useful scripts, but must preserve predictable discovery, approval, and execution contracts. + +## Before changing files + +1. Read [`README.md`](README.md) and [`CONTRIBUTING.md`](CONTRIBUTING.md) completely. +2. Inspect [`catalog.json`](catalog.json), the paired documentation for similar scripts, and [`schemas/catalog.schema.json`](schemas/catalog.schema.json). +3. Keep one focused user outcome per pull request. Do not add speculative frameworks or unrelated cleanup. +4. Work on a branch and open a draft pull request. Do not push script changes directly to `main`. + +## Adding a script + +- Choose an existing focused lowercase category or create one when no category fits. +- Add a descriptively named `lower_snake_case.py` file and a Markdown file with the same stem. +- Register the script in `catalog.json` and add it to the human-readable table in `README.md`. +- Follow the BIMO globals, `IN`, `OUT`, validation, transaction, rollback, and exception rules in [`CONTRIBUTING.md`](CONTRIBUTING.md). +- Document every model, file-system, network, selection, and input side effect. Avoid network access, credentials, machine-specific paths, and modal prompts unless the user explicitly requires them and the repository contract supports them. +- Keep existing script paths stable because saved BIMO presets may reference them. +- Never claim a Revit version is tested unless the exact repository script was run successfully in that version. Record partial or manual validation honestly in the pull request. + +## Required validation + +Run: + +```shell +python tools/validate_catalog.py +``` + +Also review the final diff for uncatalogued scripts, missing paired documentation, unrelated files, unsafe defaults, and model-changing behavior that is not represented by the catalog risk and documentation. + +The validator checks repository structure and CPython-parsable syntax; it does not prove Revit API compatibility. Model-changing scripts still require explicit BIMO approval and a manual test in an appropriate Revit model. diff --git a/README.md b/README.md index 1d20459..3adbe04 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ BIMO hosts the Python engine inside Revit, so users do not need a separate local | Script | Category | Engine | Risk | | --- | --- | --- | --- | +| [Import image to active view](documentation/import_image_to_active_view.md) | Documentation | IronPython | Writes model and optionally copies a file | | [Create Toposolid from model lines](modeling/create_toposolid_from_model_lines.md) | Modeling | IronPython | Writes model | | [Calculate selected lines length](miscellaneous/calculate_selected_lines_length_mm.md) | Miscellaneous | IronPython | Read-only | | [Calculate element volume](miscellaneous/calculate_element_volume.md) | Miscellaneous | IronPython | Read-only | @@ -30,6 +31,7 @@ The authoritative machine-readable index is [`catalog.json`](catalog.json). Its ```text catalog.json Machine-readable script index schemas/catalog.schema.json Catalog JSON Schema +documentation/ View documentation and image scripts modeling/ Model-creation and editing scripts miscellaneous/ General-purpose scripts tools/validate_catalog.py Dependency-free repository validator diff --git a/catalog.json b/catalog.json index 52e5380..5c24ce5 100644 --- a/catalog.json +++ b/catalog.json @@ -2,6 +2,62 @@ "$schema": "schemas/catalog.schema.json", "version": 1, "scripts": [ + { + "id": "documentation.import-image-to-active-view", + "name": "Import image to active view", + "summary": "Copies a raster image beside the active RVT when requested, then imports, centers, and proportionally scales it in the visible view.", + "category": "documentation", + "path": "documentation/import_image_to_active_view.py", + "documentation": "documentation/import_image_to_active_view.md", + "engine": "ironpython", + "revit": { + "minimum": 2024, + "tested": [] + }, + "risk": "write", + "requiresActiveDocument": true, + "selection": { + "required": false, + "description": "No selection is required; the image is placed in the active view." + }, + "inputs": [ + { + "index": 0, + "name": "image_path", + "type": "string", + "required": true, + "description": "Existing local raster-image path." + }, + { + "index": 1, + "name": "width_fraction", + "type": "number-string", + "required": false, + "default": "0.4", + "description": "Target image width as a fraction of the visible view width, from 0.01 to 1.0." + }, + { + "index": 2, + "name": "copy_to_document_folder", + "type": "boolean-string", + "required": false, + "default": "true", + "description": "Copy the image beside the saved active Revit document before import." + } + ], + "output": { + "format": "object", + "description": "Imported image IDs, view name, persistent source path, copy status, and final dimensions in feet." + }, + "tags": [ + "active-view", + "documentation", + "filesystem", + "image", + "import", + "raster" + ] + }, { "id": "modeling.create-toposolid-from-model-lines", "name": "Create Toposolid from model lines", diff --git a/documentation/import_image_to_active_view.md b/documentation/import_image_to_active_view.md new file mode 100644 index 0000000..eb761e7 --- /dev/null +++ b/documentation/import_image_to_active_view.md @@ -0,0 +1,77 @@ +# Import image to active view + +Imports a raster image into the active Revit view, centers it in the currently visible area, and scales it proportionally to the visible view width. + +By default, the source image is first copied beside the saved Revit document. Revit then imports that persistent copy into the project. + +## Compatibility + +- BIMO engine: `IronPython` +- Minimum Revit version: 2024 +- Active project document required +- Model-changing operation: yes +- External file-system write: yes, when `IN[2]` is enabled +- Tested Revit versions: not yet recorded for this exact repository script + +## Before running + +1. Save the active Revit project if the image should be copied beside it. +2. Open the target plan, elevation, section, drafting, or other view that supports raster images. +3. Make sure the visible area and zoom level represent the desired initial image placement. +4. Provide the source image path in `IN[0]`. +5. Run the script through BIMO Run Python with the inline **Script** field empty. + +No element selection is required. + +## Inputs + +BIMO passes preset `IN` values as strings. Inputs are positional. + +| Index | Meaning | Required | Default | +| --- | --- | --- | --- | +| `IN[0]` | Existing local raster-image path | Yes | None | +| `IN[1]` | Target image width as a fraction of the visible view width, from `0.01` to `1.0` | No | `0.4` | +| `IN[2]` | Copy the image beside the active Revit document before import | No | `true` | + +Accepted true values for `IN[2]` are `true`, `1`, `yes`, `y`, and `on`; accepted false values are `false`, `0`, `no`, `n`, and `off`. + +## Processing + +The script: + +1. validates the input path, width fraction, active view, and visible view extent; +2. when requested, copies the image beside the saved Revit document; +3. avoids overwriting an existing file by adding a numeric suffix; +4. creates an imported `ImageType` from the persistent path; +5. places an `ImageInstance` at the center of the visible area; +6. locks its proportions and scales it to the configured width fraction; +7. commits all Revit changes in one transaction and rolls that transaction back on failure. + +## Output + +`OUT` is an object with: + +- `imageInstanceId` and `imageTypeId`; +- `viewName`; +- `storedPath` used by the imported image type; +- `copiedBesideDocument`; +- final `widthFeet` and `heightFeet` in Revit internal units. + +Validation and Revit API failures are returned by BIMO as execution errors. + +## Limitations and safety + +- The image is imported into the RVT rather than linked, even though its source path is retained. +- Copying the source file is an external file-system effect and is not part of the Revit transaction. If Revit import later fails, the copied file may remain beside the document. +- The script never overwrites an existing image file; it chooses a suffixed name instead. +- Placement uses the current on-screen view extent. Change `IN[1]` or move and resize the image manually when exact real-world scaling is required. +- Unsupported image formats and views are rejected by Revit. + +## Manual Revit test + +1. Open and save a test project in Revit 2024 or newer. +2. Open a plan view and set a recognizable zoom extent. +3. Run with a JPG or PNG path in `IN[0]`, `0.4` in `IN[1]`, and `true` in `IN[2]`. +4. Confirm the image appears centered, preserves its proportions, and is approximately 40% of the visible view width. +5. Confirm a non-overwriting copy exists beside the RVT and `OUT.storedPath` points to it. +6. Undo the Revit transaction and remove the copied test file manually if it is no longer needed. diff --git a/documentation/import_image_to_active_view.py b/documentation/import_image_to_active_view.py new file mode 100644 index 0000000..ad81df6 --- /dev/null +++ b/documentation/import_image_to_active_view.py @@ -0,0 +1,189 @@ +"""Import a raster image into the active Revit view. + +BIMO Run Python contract: +- Engine: IronPython +- IN[0]: image file path (required) +- IN[1]: target width as a fraction of the visible view width (optional, default: 0.4) +- IN[2]: copy the image beside the active Revit document (optional, default: true) +- OUT: structured details about the imported image +""" + +from Autodesk.Revit.DB import ( + BoxPlacement, + ImageInstance, + ImagePlacementOptions, + ImageType, + ImageTypeOptions, + ImageTypeSource, + Transaction, +) +from System.IO import File, Path + + +MINIMUM_WIDTH_FRACTION = 0.01 +MAXIMUM_WIDTH_FRACTION = 1.0 +MAXIMUM_COLLISION_ATTEMPTS = 1000 + + +def _input(index, default_value=None): + if index >= len(IN): + return default_value + + value = IN[index] + if value is None or str(value).strip() == "": + return default_value + + return value + + +def _width_fraction(value): + try: + number = float(str(value).replace(",", ".")) + except (TypeError, ValueError): + raise ValueError("IN[1] width fraction must be a number.") + + if number < MINIMUM_WIDTH_FRACTION or number > MAXIMUM_WIDTH_FRACTION: + raise ValueError( + "IN[1] width fraction must be between {0} and {1}.".format( + MINIMUM_WIDTH_FRACTION, MAXIMUM_WIDTH_FRACTION + ) + ) + + return number + + +def _boolean(value, input_name): + normalized = str(value).strip().lower() + if normalized in ("true", "1", "yes", "y", "on"): + return True + if normalized in ("false", "0", "no", "n", "off"): + return False + + raise ValueError("{0} must be true or false.".format(input_name)) + + +def _available_target_path(directory, file_name): + candidate = Path.Combine(directory, file_name) + if not File.Exists(candidate): + return candidate + + stem = Path.GetFileNameWithoutExtension(file_name) + extension = Path.GetExtension(file_name) + for index in range(1, MAXIMUM_COLLISION_ATTEMPTS + 1): + candidate = Path.Combine( + directory, "{0}_{1}{2}".format(stem, index, extension) + ) + if not File.Exists(candidate): + return candidate + + raise ValueError( + "Could not choose a free file name beside the Revit document after {0} attempts.".format( + MAXIMUM_COLLISION_ATTEMPTS + ) + ) + + +def _prepare_image_path(source_path, copy_to_document_folder): + absolute_source = Path.GetFullPath(source_path) + if not File.Exists(absolute_source): + raise ValueError("Image file does not exist: {0}".format(absolute_source)) + + if not copy_to_document_folder: + return absolute_source, False + + document_path = str(__doc__.PathName or "").strip() + if not document_path: + raise ValueError( + "The active Revit document must be saved before the image can be copied beside it." + ) + + document_directory = Path.GetDirectoryName(Path.GetFullPath(document_path)) + source_directory = Path.GetDirectoryName(absolute_source) + if source_directory.lower() == document_directory.lower(): + return absolute_source, False + + target_path = _available_target_path( + document_directory, Path.GetFileName(absolute_source) + ) + File.Copy(absolute_source, target_path, False) + return target_path, True + + +def _active_view_placement(width_fraction): + view = __doc__.ActiveView + if view is None or not ImageInstance.IsValidView(view): + raise ValueError("The active view cannot contain raster images.") + + ui_views = [ + ui_view + for ui_view in __uidoc__.GetOpenUIViews() + if ui_view.ViewId == view.Id + ] + if not ui_views: + raise ValueError("The active UI view is not available for image placement.") + + corners = ui_views[0].GetZoomCorners() + first = corners[0] + second = corners[1] + center = (first + second) * 0.5 + visible_width = abs((second - first).DotProduct(view.RightDirection)) + if visible_width <= 0: + raise ValueError("The visible view width could not be determined.") + + return view, center, visible_width * width_fraction + + +def _import_image(): + source_path = str(_input(0, "")).strip() + if not source_path: + raise ValueError("IN[0] image file path is required.") + + width_fraction = _width_fraction(_input(1, 0.4)) + copy_to_document_folder = _boolean( + _input(2, True), "IN[2] copy-to-document-folder" + ) + + view, center, target_width = _active_view_placement(width_fraction) + image_path, copied = _prepare_image_path( + source_path, copy_to_document_folder + ) + + transaction = Transaction(__doc__, "Import image into active view") + started = False + try: + transaction.Start() + started = True + + type_options = ImageTypeOptions( + image_path, False, ImageTypeSource.Import + ) + image_type = ImageType.Create(__doc__, type_options) + placement = ImagePlacementOptions(center, BoxPlacement.Center) + image = ImageInstance.Create( + __doc__, view, image_type.Id, placement + ) + image.LockProportions = True + image.Width = target_width + + transaction.Commit() + started = False + except Exception: + if started: + try: + transaction.RollBack() + except Exception: + pass + raise + + return { + "imageInstanceId": image.Id.IntegerValue, + "imageTypeId": image_type.Id.IntegerValue, + "viewName": view.Name, + "storedPath": image_type.Path, + "copiedBesideDocument": copied, + "widthFeet": image.Width, + "heightFeet": image.Height, + } + + +OUT = _import_image()