Nv Generate Ct Rflow
NVIDIAOfficialCreated by NVIDIA MedTech Team
- Skill
- Tool integration
- Science and research
- Apache-2.0
- Medium risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The nv-generate-ct-rflow skill provides a standardized interface for the NVIDIA-Medtech NV-Generate-CTMR rectified-flow synthesis pipeline. It manages configuration staging, output path handling, and validation for generating synthetic CT volumes and paired masks. The skill includes helper utilities for anatomy lookup, diagnostic mask generation, and image-only synthesis, while delegating core inference and sampling to the upstream repository.
What it does
- Generates synthetic CT volumes and corresponding label masks.
- Supports controllable anatomy generation for specific tumor types.
- Provides diagnostic tools for raw mask generation and image-from-mask synthesis.
- Validates input configurations against schema bounds and anatomy constraints.
- Produces summary cards for visual inspection of generated outputs.
- Maps paired output labels back to standard MAISI label IDs.
When to use it
- When you need to generate synthetic CT image data for research purposes.
- When you require paired CT volumes and segmentation masks.
- When you need to perform controllable synthesis of specific anatomical regions or tumors.
- When you need to validate configuration files before executing large-scale inference.
Advantages
- Automates environment setup and dependency management for the upstream pipeline.
- Ensures consistent output structure and metadata recording.
- Provides built-in preflight checks to prevent common configuration errors.
- Simplifies complex inference workflows through standardized wrapper commands.
Usage examples
- “Generate a synthetic CT volume using the chest lung tumor controllable configuration.”
- The agent executes the wrapper script with the specified configuration, producing synthetic CT volumes and masks in the designated output directory.
- “List all available chest anatomies for generation.”
- The agent runs the anatomy lookup tool and returns a list of 132-class labels grouped by the chest region.
- “Validate the abdomen liver and spleen configuration without running full inference.”
- The agent performs a preflight check on the configuration file and reports any schema or constraint violations without generating image data.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/nvidia/nv-generate-ct-rflow/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip nv-generate-ct-rflow.zip -d .agents/skills
Documentation by NVIDIA MedTech Team
NV-Generate-CT (rflow-ct)
Purpose
Used for generating synthetic CT volumes and masks with NV-Generate-CTMR rflow-ct. Not for production training data without review.
Use the wrapper exactly as documented; do not replace the upstream entrypoint with a handwritten implementation.
Do not write custom inference code for normal runs. The wrapper owns config staging, output paths, label mapping evidence, and validation.
Manifest I/O: inputs are
config_infer_override; outputs aresynthetic_ct_volumesandresult_json.
Instructions
Read
skill_manifest.yamlbefore changing arguments, side effects, or validation gates.Run
scripts/run_rflow_ct.pythrough the documented command below; keep outputs under a caller-provided run directory.If a host agent exposes
run_script, userun_script("scripts/run_rflow_ct.py", args=[...]); otherwise run the Bash/Python command shown below.Emit a single bash code block, and keep the
python -m pip install -r "$NV_GENERATE_ROOT/requirements.txt"step in that same command — the runtime may be a fresh environment withoutnibabel/MONAI, so dropping the install fails withModuleNotFoundError.Do not add
rm,mkdir, or any cleanup of--output-dir; the wrapper creates it. Use a fresh--output-dirinstead of deleting one.Check the emitted JSON and paired verifier guidance before treating the run as evidence.
Available Scripts
| Script | Purpose | Arguments |
|---|---|---|
scripts/_anatomy.py | Internal helper used by the primary entrypoint. | Imported only; do not call directly. |
scripts/_summary_card.py | Internal helper used by the primary entrypoint. | Imported only; do not call directly. |
scripts/list_anatomies.py | Helper command for catalog or anatomy lookup. | [--region REGION] [--filter TEXT] [--controllable] |
scripts/run_rflow_ct.py | Primary entrypoint declared by skill_manifest.yaml. | CONFIG_INFER.json --output-dir OUT_DIR [--random-seed N] [--version rflow-ct] [--yes] |
scripts/run_ct_mask.py | Advanced diagnostic helper for standalone raw MAISI mask generation. | REQUEST.json --output-dir OUT_DIR [--random-seed N] [--preflight-only] [--yes] |
scripts/run_ct_from_mask.py | Advanced helper for CT image generation from a MAISI label mask. | REQUEST.json --output-dir OUT_DIR [--random-seed N] [--yes] |
scripts/run_ct_image.py | Advanced helper for CT image-only generation without paired labels. | MODEL_CONFIG.json --output-dir OUT_DIR [--version rflow-ct] [--random-seed N] [--yes] |
Prerequisites
Required environment variables:
NV_GENERATE_ROOT.Runtime requirements: GPU/CUDA when declared by the manifest; Python packages listed in
runtime.side_effects.pip_packages.Side effects: writes generated outputs under the caller's
--output-dir, may cache model assets under~/.cache/huggingface/, and may contacthttps://huggingface.coorhttps://github.comduring setup.Run commands from the repository root unless an existing section below says otherwise.
Limitations
This is a thin wrapper. Inference, sampling, and decoding are delegated entirely to NVIDIA-Medtech/NV-Generate-CTMR's
scripts.inference. Do not modify code under $NV_GENERATE_ROOT.rflow-ct requires CUDA and ≈ 16 GB VRAM minimum for the default 256³ output_size. Larger output_size (e.g. 512×512×768) needs an A100/H100.
Output volumes are synthetic. They are not safe to use as training data for production medtech models without an independent quality review.
Not for clinical deployment, clinical interpretation, autonomous diagnosis, regulatory submission.
Troubleshooting
| Error | Cause | Fix |
|---|---|---|
| Missing dependency or import error | Runtime package drift from skill_manifest.yaml. | Install the packages declared in the manifest or use the documented setup command. |
| Empty or schema-invalid output | Wrong input path, unsupported modality, or upstream failure. | Re-run with a known fixture and inspect the wrapper JSON plus stderr. |
| Validation gate failure | Output violated a declared engineering invariant. | Keep the failed evidence pack and use the gate message to repair inputs or wrapper code. |
Wraps the upstream
NVIDIA-Medtech/NV-Generate-CTMR
rectified-flow synthesis pipeline. The wrapper does not reimplement diffusion,
sampling, or autoencoder decoding — it shells out to the upstream
scripts.inference entry point exactly as the project's README documents and
inspects the produced image/mask pairs.
Preconditions
If
NV_GENERATE_ROOTalready names a local checkout, the wrapper uses it and records its current commit in the result. Otherwise, create the recommended pinned default checkout (one-time):if [ -z "${NV_GENERATE_ROOT:-}" ]; then export NV_GENERATE_COMMIT=61c4ec709b84cad468852243c48e250bec732074 export NV_GENERATE_ROOT="$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-61c4ec7" if [ ! -d "$NV_GENERATE_ROOT/.git" ]; then git clone https://github.com/NVIDIA-Medtech/NV-Generate-CTMR.git "$NV_GENERATE_ROOT" git -C "$NV_GENERATE_ROOT" checkout --detach "$NV_GENERATE_COMMIT" fi fi python -m pip install -r "$NV_GENERATE_ROOT/requirements.txt"Download the
rflow-ctweights and the mask-candidate datasets into the clone (one-time, ≈ 5.5 GB):cd "$NV_GENERATE_ROOT" python -m scripts.download_model_data --version rflow-ct --root_dir "./"The mask candidates (
datasets/all_masks_flexible_size_and_spacing_4000) condition the diffusion sampler; omitting them via--model_onlywill make the inference script fail with a missing-file error at startup. The anatomy-size condition file is also part of the full CT download and is needed for controllable mask generation.NVIDIA GPU with ≥ 16 GB VRAM and CUDA. There is no CPU fallback.
For agent-generated user run commands, prefer the short wrapper command in
Usage. Do not prepend clone or model-download setup steps when NV_GENERATE_ROOT
or the repo-local upstream cache is already present. In a fresh Python
environment, still include python -m pip install -r "$NV_GENERATE_ROOT/requirements.txt"
before the wrapper unless the active environment has already proven those
imports are available; cached weights do not imply cached Python packages. Run
the wrapper from the medical-AI-skills repo root. If setup requires cd "$NV_GENERATE_ROOT", return to the Medical AI Skills repo before invoking
skills/nv-generate-ct-rflow/scripts/run_rflow_ct.py.
Usage
export NV_GENERATE_ROOT="${NV_GENERATE_ROOT:-$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-61c4ec7}" && \
python -m pip install -r "$NV_GENERATE_ROOT/requirements.txt" && \
python skills/nv-generate-ct-rflow/scripts/run_rflow_ct.py \
PATH_TO_CONFIG_INFER.json \
--output-dir runs/nv_generate_ct_rflow_demo \
--random-seed 0 \
--version rflow-ctReplace PATH_TO_CONFIG_INFER.json with the user's actual request/config
path. Do not copy the fixture path from this document unless the user
explicitly asked to run that fixture. If the user says "the case request is at
runs/.../chest_lung_tumor_controllable.json", that exact path is the first
positional argument to scripts/run_rflow_ct.py.
The fixture argument is a config_infer.json override file: it can replace
num_output_samples, body_region, anatomy_list, controllable_anatomy_size,
output_size, and spacing. Pass default to use the upstream config
verbatim. The wrapper stages the override into the upstream tree before
running.
Fixture catalog
fixtures/ ships curated configs for common paired synthesis use cases: chest
lung lobes, chest with controllable lung tumor, abdomen solid organs,
abdomen with controllable hepatic tumor, head + cervical spine, pelvis.
See fixtures/README.md for the full table.
Helper commands
# Browse the 132-class label_dict grouped by body region.
python skills/nv-generate-ct-rflow/scripts/list_anatomies.py --region chest
python skills/nv-generate-ct-rflow/scripts/list_anatomies.py --controllable
python skills/nv-generate-ct-rflow/scripts/list_anatomies.py --filter tumor
# Validate a fixture and preview cost without launching inference.
NV_GENERATE_ROOT=$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-61c4ec7 \
python skills/nv-generate-ct-rflow/scripts/run_rflow_ct.py \
skills/nv-generate-ct-rflow/fixtures/abdomen_liver_spleen.json \
--output-dir runs/preview --preflight-onlyAdvanced helpers stay inside this skill for debugging and less-common CT generation modes. Use them only when the user explicitly asks for that mode:
# Raw MAISI mask diagnostic, useful for checking lung tumor -> label 23.
python skills/nv-generate-ct-rflow/scripts/run_ct_mask.py \
skills/nv-generate-ct-rflow/fixtures/ct_mask_lung_tumor.json \
--output-dir runs/ct_mask_debug --preflight-only
# CT image from an existing MAISI label mask with body label 200.
python skills/nv-generate-ct-rflow/scripts/run_ct_from_mask.py \
skills/nv-generate-ct-rflow/fixtures/ct_from_mask_request_example.json \
--output-dir runs/ct_from_mask_demo
# CT image-only generation without paired labels.
python skills/nv-generate-ct-rflow/scripts/run_ct_image.py \
skills/nv-generate-ct-rflow/fixtures/ct_image_only_default.json \
--output-dir runs/ct_image_only_demo --version rflow-ctThe wrapper runs preflight on every invocation (regardless of
--preflight-only): config-schema bounds, anatomy names matched
against the upstream label_dict, body_region in the supported set,
controllable_anatomy_size constraints, upstream CT output-size/spacing
contracts, body-region-aware x/y FOV minimums, dataset presence under
$NV_GENERATE_ROOT/datasets/, CUDA available, and an estimated peak VRAM /
wall-time. Runs estimated to exceed 5 min wall-time or 30 GB VRAM peak require
--yes to proceed.
Each invocation runs python -m scripts.inference -t configs/config_network_rflow.json -i configs/config_infer.json -e configs/environment_rflow-ct.json --random-seed <s> --version rflow-ct. Output evidence records the upstream git commit, model
checkpoint hashes, the rendered config, per-sample image/mask geometry, mask
label set, image HU range summary, and per-class voxel volumes.
When controllable_anatomy_size is non-empty, upstream ignores the broader
anatomy_list for the saved paired label map and filters labels to the
controllable anatomy names. The saved paired label values are local 1..N
ordinals, not raw MAISI label IDs. Read output.output_label_mapping in
result_json to map saved output labels back to source labels; for example,
output label 1 can represent MAISI label 23 (lung tumor).
For curated lung-tumor examples, prefer a controllable size around 0.5 or
larger; smaller requests such as 0.2 can produce absent or extremely small
label-23 components for some seeds.
For FOV and setup details, see references/fov-and-downloads.md. For
advanced helper label-space details, see
references/ct-mask-label-space.md and references/ct-from-mask-format.md.
Visual sample card
Alongside the NIfTI pairs, the wrapper writes summary.html to the
output directory: a per-sample mid-slice triptych (axial / coronal /
sagittal) with label overlay, plus a table of the rendered config and
verifier-facing aggregates. Lets you eyeball the result without firing
up 3D Slicer. Pass --no-summary-card to skip.
Anatomy plausibility (label-set sanity, voxel HU range as CT, image/mask
geometry match, declared output labels present, lung-lobe HU floor) is checked by
verifiers/ct_synthesis_quality_v1.
Not for clinical interpretation, training data for production deployment, or any non-synthetic-research use.
Files
- ATTRIBUTION.mdAdded by AutoGineer931 B
- BENCHMARK.md3.9 KiB
- LICENSELicence file added by AutoGineer11.2 KiB
- SKILL.md12.0 KiB
- evals/evals.json1.4 KiB
- fixtures/README.md4.4 KiB
- fixtures/abdomen_hepatic_tumor.json787 B
- fixtures/abdomen_liver_spleen.json747 B
- fixtures/chest_lung_lobes.json680 B
- fixtures/chest_lung_tumor_controllable.json850 B
- fixtures/ct_from_mask_request_example.json204 B
- fixtures/ct_image_only_default.json284 B
- fixtures/ct_mask_lung_tumor.json413 B
- fixtures/default_config_infer.json679 B
- fixtures/head_brain.json710 B
- fixtures/pelvis.json707 B
- references/ct-from-mask-format.md672 B
- references/ct-mask-label-space.md761 B
- references/fov-and-downloads.md2.0 KiB
- scripts/_anatomy.pyScript11.8 KiB
- scripts/_summary_card.pyScript10.9 KiB
- scripts/list_anatomies.pyScript4.5 KiB
- scripts/run_ct_from_mask.pyScript17.5 KiB
- scripts/run_ct_image.pyScript20.4 KiB
- scripts/run_ct_mask.pyScript20.0 KiB
- scripts/run_rflow_ct.pyScript38.6 KiB
- scripts/wrapper_utils.pyScript2.1 KiB
- skill-card.md4.2 KiB
- skill.oms.sig11.1 KiB
- skill_manifest.yaml7.9 KiB
- tests/test_run_ct_from_mask.pyScript2.7 KiB
- tests/test_run_ct_image.pyScript3.2 KiB
- tests/test_run_ct_mask.pyScript2.9 KiB
- tests/test_run_rflow_ct.pyScript12.0 KiB
- validators/output_schema.json6.4 KiB
scripts/run_ct_from_mask.py
#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""NV-Generate-CTMR image-from-mask wrapper.
Runs upstream `python -m scripts.infer_image_from_mask` after validating that
the input mask is an integer MAISI-style NIfTI label map with body envelope
evidence. The wrapper stages configs under the caller's output directory.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import time
from pathlib import Path
from typing import Any
import nibabel as nib
import numpy as np
import typer
_SCRIPT_DIR = Path(__file__).resolve().parent
_SKILLS_DIR = _SCRIPT_DIR.parent.parent
if str(_SKILLS_DIR) not in sys.path:
sys.path.insert(0, str(_SKILLS_DIR))
if str(_SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPT_DIR))
from wrapper_utils import ( # noqa: E402
emit,
file_sha256_safe,
git_commit,
tail,
)
SKILL_NAME = "nv_generate_ct_rflow_ct_from_mask"
MODEL_REPO = "https://github.com/NVIDIA-Medtech/NV-Generate-CTMR"
MODEL_WEIGHTS_REPO = "https://huggingface.co/nvidia/NV-Generate-CT"
NETWORK_CONFIG = "configs/config_network_rflow.json"
INFER_CONFIG = "configs/config_infer.json"
ENV_CONFIG = "configs/environment_rflow-ct.json"
MODEL_FILES = (
"models/autoencoder_v1.pt",
"models/diff_unet_3d_rflow-ct.pt",
"models/controlnet_3d_rflow-ct.pt",
)
OVERRIDE_KEYS = (
"num_inference_steps",
"autoencoder_sliding_window_infer_size",
"autoencoder_sliding_window_infer_overlap",
"cfg_guidance_scale",
"modality",
)
MAISI_VALID_LABELS = set(range(0, 133)) | {200}
app = typer.Typer(add_completion=False)
def _load_json(path: Path) -> dict[str, Any]:
return json.loads(path.read_text())
def _valid_upstream_root(path: Path) -> bool:
return (path / NETWORK_CONFIG).is_file() and (
path / "scripts/infer_image_from_mask.py"
).is_file()
def _candidate_upstream_roots(env_value: str) -> list[Path]:
candidates: list[Path] = []
if env_value:
candidates.append(Path(env_value).expanduser())
candidates.extend(
[
Path(__file__).resolve().parents[3] / ".workbench_data/upstreams/NV-Generate-CTMR",
Path.home() / "NV-Generate-CTMR",
Path.home() / "nv-generate-ctmr",
]
)
deduped: list[Path] = []
seen: set[str] = set()
for candidate in candidates:
key = str(candidate)
if key not in seen:
seen.add(key)
deduped.append(candidate)
return deduped
def _resolve_upstream_root(env_value: str) -> tuple[Path | None, list[str]]:
checked: list[str] = []
for candidate in _candidate_upstream_roots(env_value):
resolved = candidate.resolve()
checked.append(str(resolved))
if _valid_upstream_root(resolved):
return resolved, checked
return None, checked
def _load_request(request_arg: str) -> tuple[dict[str, Any], Path | None]:
if request_arg == "default":
raise typer.BadParameter("ct-from-mask requires a JSON request containing mask_path")
request_path = Path(request_arg).expanduser().resolve()
if not request_path.is_file():
raise typer.BadParameter(f"request JSON not found: {request_arg}")
request = json.loads(request_path.read_text())
if "mask_path" not in request:
raise typer.BadParameter("request JSON must contain mask_path")
unknown = sorted(
k for k in request if not k.startswith("_") and k not in ("mask_path", *OVERRIDE_KEYS)
)
if unknown:
raise typer.BadParameter(
f"request contains unknown key(s): {unknown}. Allowed: mask_path plus {OVERRIDE_KEYS}"
)
return {k: v for k, v in request.items() if not k.startswith("_")}, request_path
def _resolve_mask_path(mask_value: str, request_path: Path | None) -> Path:
path = Path(mask_value).expanduser()
if not path.is_absolute() and request_path is not None:
path = request_path.parent / path
return path.resolve()
def _round(values: Any, ndigits: int = 6) -> Any:
if isinstance(values, (list, tuple, np.ndarray)):
return [round(float(v), ndigits) for v in values]
return round(float(values), ndigits)
def _summarize_mask(mask_path: Path) -> dict[str, Any]:
record: dict[str, Any] = {
"mask_path": str(mask_path),
"mask_exists": mask_path.is_file(),
"mask_readable": False,
}
if not mask_path.is_file():
return record
try:
img = nib.load(str(mask_path))
data = np.asarray(img.get_fdata())
rounded = np.rint(data)
integer_like = bool(np.allclose(data, rounded))
labels = sorted(int(v) for v in np.unique(rounded).tolist())
unknown = [v for v in labels if v not in MAISI_VALID_LABELS]
record.update(
{
"mask_readable": True,
"mask_shape": [int(v) for v in data.shape],
"mask_spacing": _round(img.header.get_zooms()[:3]),
"label_ids_present": labels,
"foreground_label_ids_present": [v for v in labels if v != 0],
"label_id_count": len([v for v in labels if v != 0]),
"integer_like": integer_like,
"unknown_label_ids": unknown,
"all_labels_in_maisi_vocab": not unknown,
"body_label_200_present": 200 in labels,
}
)
except Exception as exc:
record["mask_error"] = repr(exc)
return record
def _validate_mask_summary(summary: dict[str, Any], allow_missing_body_label: bool) -> list[str]:
errors: list[str] = []
if not summary.get("mask_exists"):
errors.append(f"mask file not found: {summary.get('mask_path')}")
return errors
if not summary.get("mask_readable"):
errors.append(f"mask is not a readable NIfTI: {summary.get('mask_path')}")
return errors
if not summary.get("integer_like"):
errors.append("mask voxels must be integer-like label ids")
if not summary.get("all_labels_in_maisi_vocab"):
errors.append(
f"mask has labels outside MAISI vocabulary: {summary.get('unknown_label_ids')}"
)
if not summary.get("body_label_200_present") and not allow_missing_body_label:
errors.append(
"mask is missing label 200 body envelope; add it before CT image-from-mask inference"
)
if summary.get("label_id_count", 0) < 1:
errors.append("mask has no foreground labels")
return errors
def _stage_configs(
upstream_root: Path,
stage_dir: Path,
request: dict[str, Any],
output_dir: Path,
) -> tuple[dict[str, Any], dict[str, Any], Path, Path]:
stage_dir.mkdir(parents=True, exist_ok=True)
infer = _load_json(upstream_root / INFER_CONFIG)
override = {k: v for k, v in request.items() if k in OVERRIDE_KEYS}
infer.update(override)
infer["modality"] = 1
infer_path = stage_dir / "config_infer_from_mask.json"
infer_path.write_text(json.dumps(infer, indent=2))
env = _load_json(upstream_root / ENV_CONFIG)
env["output_dir"] = str(output_dir)
env_path = stage_dir / "environment_rflow-ct_from_mask.json"
env_path.write_text(json.dumps(env, indent=2))
return infer, env, infer_path, env_path
def _model_inventory(upstream_root: Path) -> dict[str, Any]:
files: list[dict[str, Any]] = []
all_present = True
for rel in MODEL_FILES:
path = upstream_root / rel
present = path.is_file()
files.append(
{
"path": rel,
"present": present,
"bytes": path.stat().st_size if present else None,
"sha256": file_sha256_safe(path) if present else "",
}
)
all_present = all_present and present
return {"all_present": all_present, "files": files}
def _detect_cuda() -> dict[str, Any]:
info: dict[str, Any] = {"available": False, "device_name": None, "total_memory_gb": None}
try:
import torch # noqa: PLC0415
info["torch_version"] = torch.__version__
info["available"] = bool(torch.cuda.is_available())
if info["available"]:
props = torch.cuda.get_device_properties(0)
info["device_name"] = props.name
info["total_memory_gb"] = round(props.total_memory / (1024**3), 1)
info["cuda_version"] = torch.version.cuda
except Exception as exc:
info["import_error"] = repr(exc)
return info
def _build_command(
mask_path: Path, staged_infer_path: Path, staged_env_path: Path, seed: int
) -> list[str]:
return [
sys.executable,
"-m",
"scripts.infer_image_from_mask",
"--mask",
str(mask_path),
"-t",
f"./{NETWORK_CONFIG}",
"-e",
str(staged_env_path),
"-i",
str(staged_infer_path),
"--random-seed",
str(seed),
]
def _scan_outputs(output_dir: Path, run_started: float) -> list[Path]:
if not output_dir.is_dir():
return []
paths: list[Path] = []
for path in output_dir.rglob("*_image.nii*"):
if not path.is_file():
continue
try:
if path.stat().st_size > 0 and path.stat().st_mtime >= run_started - 1:
paths.append(path)
except OSError:
continue
return sorted(paths)
def _summarize_image(path: Path) -> dict[str, Any]:
record: dict[str, Any] = {"image_path": str(path), "image_readable": False}
try:
img = nib.load(str(path))
data = np.asarray(img.get_fdata(), dtype=np.float32)
finite = data[np.isfinite(data)]
record["image_readable"] = True
record["image_shape"] = [int(v) for v in data.shape]
record["image_spacing"] = _round(img.header.get_zooms()[:3])
record["all_finite"] = bool(finite.size == data.size)
if finite.size:
record["image_hu_min"] = _round(float(finite.min()), 3)
record["image_hu_max"] = _round(float(finite.max()), 3)
record["image_nonconstant"] = bool(finite.max() - finite.min() > 1.0)
record["image_hu_negative_present"] = bool((finite < -500).any())
record["image_hu_bone_present"] = bool((finite > 200).any())
except Exception as exc:
record["image_error"] = repr(exc)
return record
def _aggregate(samples: list[dict[str, Any]]) -> dict[str, Any]:
n = len(samples)
return {
"num_samples": n,
"all_images_readable": bool(n) and all(s.get("image_readable") for s in samples),
"all_images_finite": bool(n) and all(s.get("all_finite") for s in samples),
"all_images_nonconstant": bool(n) and all(s.get("image_nonconstant") for s in samples),
"all_images_hu_like": bool(n)
and all(
s.get("image_hu_negative_present") and s.get("image_hu_bone_present") for s in samples
),
}
@app.command()
def main(
request_json: str = typer.Argument(
..., help="JSON containing mask_path and optional inference overrides."
),
output_dir: Path | None = typer.Option(None, "--output-dir", "-o"),
seed: int = typer.Option(0, "--random-seed", "-s"),
timeout_seconds: float = typer.Option(3600.0, "--timeout-seconds"),
preflight_only: bool = typer.Option(False, "--preflight-only"),
allow_missing_body_label: bool = typer.Option(False, "--allow-missing-body-label"),
yes: bool = typer.Option(False, "--yes", "-y"),
) -> None:
upstream_root, checked_roots = _resolve_upstream_root(
os.environ.get("NV_GENERATE_ROOT", "").strip()
)
if upstream_root is None:
emit(
{
"skill": SKILL_NAME,
"error": "NV_GENERATE_ROOT layout invalid",
"checked_roots": checked_roots,
}
)
raise typer.Exit(2)
output_dir = (output_dir or upstream_root / "output").expanduser().resolve()
output_dir.mkdir(parents=True, exist_ok=True)
request, request_path = _load_request(request_json)
mask_path = _resolve_mask_path(str(request["mask_path"]), request_path)
mask_summary = _summarize_mask(mask_path)
errors = _validate_mask_summary(mask_summary, allow_missing_body_label)
rendered_infer, rendered_env, infer_path, env_path = _stage_configs(
upstream_root,
output_dir / "_staged_configs",
request,
output_dir,
)
inventory = _model_inventory(upstream_root)
if not inventory["all_present"]:
errors.append(
"missing CT image/controlnet weights. Run `python -m scripts.download_model_data "
"--version rflow-ct --root_dir ./ --model_only` from $NV_GENERATE_ROOT."
)
cuda = _detect_cuda()
if not cuda["available"]:
errors.append("CUDA not available. CT image-from-mask inference needs an NVIDIA GPU.")
if errors:
emit(
{
"skill": SKILL_NAME,
"error": "preflight validation failed",
"preflight_errors": errors,
"input": {"request_json": str(request_path), "mask": mask_summary},
"invocation": {"model_inventory": inventory},
"cuda": cuda,
}
)
raise typer.Exit(2)
if preflight_only:
emit(
{
"skill": SKILL_NAME,
"preflight": "ok",
"input": {"request_json": str(request_path), "mask": mask_summary},
"model_inventory": inventory,
"rendered_infer_config": rendered_infer,
"rendered_env_config": rendered_env,
"cuda": cuda,
}
)
raise typer.Exit(0)
if not yes and int(rendered_infer.get("num_inference_steps", 30)) > 60:
emit(
{
"skill": SKILL_NAME,
"error": "cost gate: high step count; re-run with --yes to proceed",
}
)
raise typer.Exit(2)
cmd = _build_command(mask_path, infer_path, env_path, seed)
run_env = os.environ.copy()
run_env.setdefault("MONAI_DATA_DIRECTORY", str(upstream_root / "temp_work_dir"))
run_env.setdefault("PYTORCH_CUDA_ALLOC_CONF", "max_split_size_mb:128,expandable_segments:True")
run_started = time.time()
t0 = time.monotonic()
try:
proc = subprocess.run(
cmd,
cwd=str(upstream_root),
env=run_env,
capture_output=True,
text=True,
timeout=timeout_seconds,
check=False,
)
rc = proc.returncode
stdout = proc.stdout
stderr = proc.stderr
except subprocess.TimeoutExpired as exc:
rc = 124
stdout = exc.stdout.decode() if isinstance(exc.stdout, bytes) else (exc.stdout or "")
stderr_raw = exc.stderr.decode() if isinstance(exc.stderr, bytes) else (exc.stderr or "")
stderr = stderr_raw + f"\n[TIMEOUT after {timeout_seconds}s]"
elapsed = time.monotonic() - t0
samples = [_summarize_image(p) for p in _scan_outputs(output_dir, run_started)]
aggregate = _aggregate(samples)
failure_reasons: list[str] = []
if rc != 0:
failure_reasons.append(f"upstream scripts.infer_image_from_mask exited {rc}")
if not samples:
failure_reasons.append("upstream scripts.infer_image_from_mask produced zero images")
payload: dict[str, Any] = {
"skill": SKILL_NAME,
"model": "NVIDIA-Medtech/NV-Generate-CTMR (rflow-ct image-from-mask)",
"model_repo": MODEL_REPO,
"model_weights_repo": MODEL_WEIGHTS_REPO,
"license": "Wrapper Apache-2.0; CT weights use NVIDIA Open Model License.",
"input": {
"request_json": str(request_path),
"request": request,
"mask": mask_summary,
"random_seed": seed,
"version": "rflow-ct",
},
"output": {"directory": str(output_dir), "samples": samples, **aggregate},
"invocation": {
"official_entrypoint": "python -m scripts.infer_image_from_mask",
"upstream_root": str(upstream_root),
"upstream_commit": git_commit(upstream_root),
"command": cmd,
"exit_code": rc,
"subprocess_seconds": round(elapsed, 3),
"model_inventory": inventory,
"rendered_infer_config": rendered_infer,
"rendered_env_output_dir": rendered_env.get("output_dir"),
},
"runtime": {"subprocess_seconds": round(elapsed, 3), "device": "cuda"},
"logs": {"stdout_tail": tail(stdout), "stderr_tail": tail(stderr)},
"preflight": {"cuda": cuda},
"intended_use_disclaimer": (
"Engineering verification only. Output is synthetic and NOT clinically meaningful. "
"This wrapper invokes upstream scripts.infer_image_from_mask."
),
}
if failure_reasons:
payload["error"] = "; ".join(failure_reasons)
payload["failure_reasons"] = failure_reasons
emit(payload)
if failure_reasons:
raise typer.Exit(rc if 0 < rc < 256 else 1)
raise typer.Exit(0)
if __name__ == "__main__":
app()
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Needs a command-line tool, Needs Python
Security
What our scanner noticed· Medium risk
- Large base64-encoded blobs
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- NVIDIA MedTech Team
- Publisher
- NVIDIA (Official)
- Source
- NVIDIA/skills · skills/nv-generate-ct-rflow · commit fce3cca
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE-APACHE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by NVIDIA MedTech Team or NVIDIA.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download nv-generate-ct-rflow.zip