[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73HGYP9JAA9FCT1KYXDAXSN":3,"skill-same:01M73HGYP9JAA9FCT1KYXDAXSN":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73HGYP9JAA9FCT1KYXDAXSN","nnunet-segmentation",null,"Medical image segmentation with nnU-Net's self-configuring framework — auto-selects architecture, preprocessing, training for any modality. CT, MRI, microscopy, ultrasound in 2D, 3D full-res, 3D low-res, cascade. Pipeline: convert → plan\u002Fpreprocess → train (5-fold CV) → best config → predict → ensemble. Use when classical segmentation fails and annotated data exists.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fnnunet-segmentation\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"nnunet-segmentation\"\ndescription: \"Medical image segmentation with nnU-Net's self-configuring framework — auto-selects architecture, preprocessing, training for any modality. CT, MRI, microscopy, ultrasound in 2D, 3D full-res, 3D low-res, cascade. Pipeline: convert → plan\u002Fpreprocess → train (5-fold CV) → best config → predict → ensemble. Use when classical segmentation fails and annotated data exists.\"\nlicense: \"Apache-2.0\"\n---\n\n# nnU-Net Automated Medical Image Segmentation\n\n## Overview\n\nnnU-Net (no-new-Net) is a self-configuring deep learning framework for biomedical image segmentation. Given a labeled training dataset, nnU-Net automatically determines the optimal network architecture (2D, 3D full-resolution, or 3D cascade), preprocessing steps (resampling, normalization, patch size), training schedule, and post-processing. It consistently achieves state-of-the-art performance across diverse imaging modalities and anatomical structures without manual hyperparameter tuning. nnU-Net v2 (`nnunetv2`) is the current release with a Python API for inference alongside the standard CLI.\n\n## When to Use\n\n- Segmenting anatomical structures in CT or MRI scans (organs, tumors, lesions) when you have 20+ annotated training cases\n- Automating cell or nucleus segmentation in 3D fluorescence or electron microscopy volumes\n- Establishing a strong baseline for any new segmentation challenge without manually tuning a U-Net\n- Running inference on new images using a pretrained nnU-Net model from a published challenge\n- Comparing segmentation methods: nnU-Net's auto-configured ensembles serve as a rigorous baseline\n- Building production segmentation pipelines where training is done once and inference is repeated on many new cases\n- Use **Cellpose** (`cellpose-cell-segmentation`) instead for 2D fluorescence cell segmentation without labeled training data; nnU-Net requires annotated training cases\n- Use **SimpleITK** (`simpleitk-image-registration`) instead for rule-based segmentation with classical thresholding and region growing on images where deep learning training data is unavailable\n\n## Prerequisites\n\n- **Python packages**: `nnunetv2>=2.2`, `torch>=2.0` (with CUDA for GPU training)\n- **Data requirements**: Images in NIfTI format (`.nii.gz`); binary or multi-class label masks; minimum 20 training cases recommended (50+ for best performance)\n- **Environment variables**: `nnUNet_raw`, `nnUNet_preprocessed`, `nnUNet_results` must be set\n- **Hardware**: GPU with 8+ GB VRAM recommended for training; CPU inference is supported but slow\n- **Environment**: Python 3.9+; Linux or macOS (Windows supported but not officially recommended)\n\n```bash\npip install nnunetv2\n\n# Verify installation\nnnUNetv2_train --help\n\n# Set required environment variables (add to ~\u002F.bashrc or ~\u002F.zshrc)\nexport nnUNet_raw=\u002Fdata\u002FnnUNet_raw\nexport nnUNet_preprocessed=\u002Fdata\u002FnnUNet_preprocessed\nexport nnUNet_results=\u002Fdata\u002FnnUNet_results\n\nmkdir -p $nnUNet_raw $nnUNet_preprocessed $nnUNet_results\n```\n\n## Quick Start\n\n```bash\n# Minimal end-to-end pipeline: convert dataset → preprocess → train → predict\n# Assumes dataset is in Medical Segmentation Decathlon format\n\n# 1. Set environment\nexport nnUNet_raw=\u002Fdata\u002FnnUNet_raw\nexport nnUNet_preprocessed=\u002Fdata\u002FnnUNet_preprocessed\nexport nnUNet_results=\u002Fdata\u002FnnUNet_results\n\n# 2. Convert Medical Segmentation Decathlon dataset (dataset ID 7 = Pancreas)\nnnUNetv2_convert_MSD_dataset -i \u002Fdata\u002FTask07_Pancreas -overwrite_id 7\n\n# 3. Plan preprocessing and verify dataset integrity\nnnUNetv2_plan_and_preprocess -d 7 --verify_dataset_integrity\n\n# 4. Train 3D full-res model, fold 0 (of 5-fold cross-validation)\nnnUNetv2_train 7 3d_fullres 0 --npz\n\n# 5. Predict on new images\nnnUNetv2_predict -i \u002Fdata\u002Ftest_images\u002F -o \u002Fdata\u002Fpredictions\u002F -d 7 -c 3d_fullres -f 0\necho \"Segmentation predictions saved to \u002Fdata\u002Fpredictions\u002F\"\n```\n\n## Workflow\n\n### Step 1: Prepare Dataset in nnU-Net Format\n\nnnU-Net requires images in NIfTI format organized in a specific directory structure with a `dataset.json` descriptor.\n\n```bash\n# Dataset directory structure (Dataset007_Pancreas as example):\n# $nnUNet_raw\u002F\n# └── Dataset007_Pancreas\u002F\n#     ├── dataset.json          ← metadata descriptor\n#     ├── imagesTr\u002F             ← training images\n#     │   ├── pancreas_001_0000.nii.gz   (0000 = channel\u002Fmodality index)\n#     │   └── pancreas_002_0000.nii.gz\n#     ├── labelsTr\u002F             ← training segmentation masks\n#     │   ├── pancreas_001.nii.gz\n#     │   └── pancreas_002.nii.gz\n#     └── imagesTs\u002F             ← test images (no labels required)\n#         └── pancreas_101_0000.nii.gz\n\n# For Medical Segmentation Decathlon datasets, convert automatically:\nnnUNetv2_convert_MSD_dataset -i \u002Fdata\u002FTask07_Pancreas -overwrite_id 7\n\necho \"Dataset 7 created at $nnUNet_raw\u002FDataset007_Pancreas\u002F\"\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport shutil\n\n# Create dataset.json for a custom dataset (single CT modality, 2-class segmentation)\ndataset_id = 8\ndataset_name = f\"Dataset{dataset_id:03d}_MyOrgan\"\ndataset_dir = Path(f\"{dataset_name}\")\n(dataset_dir \u002F \"imagesTr\").mkdir(parents=True, exist_ok=True)\n(dataset_dir \u002F \"labelsTr\").mkdir(parents=True, exist_ok=True)\n(dataset_dir \u002F \"imagesTs\").mkdir(parents=True, exist_ok=True)\n\ndataset_json = {\n    \"channel_names\": {\n        \"0\": \"CT\"           # for MRI: \"0\": \"T1\", \"1\": \"T2\" (multi-modal = multiple channels)\n    },\n    \"labels\": {\n        \"background\": 0,\n        \"organ\": 1          # add more classes: \"tumor\": 2, \"vessel\": 3\n    },\n    \"numTraining\": 50,      # number of training cases\n    \"file_ending\": \".nii.gz\"\n}\n\nwith open(dataset_dir \u002F \"dataset.json\", \"w\") as f:\n    json.dump(dataset_json, f, indent=2)\n\nprint(f\"Created dataset.json with {dataset_json['numTraining']} training cases\")\nprint(f\"Labels: {dataset_json['labels']}\")\nprint(f\"Channels: {dataset_json['channel_names']}\")\nprint(f\"\\nPlace training images as: imagesTr\u002Fcase_NNN_0000.nii.gz\")\nprint(f\"Place training labels as:  labelsTr\u002Fcase_NNN.nii.gz\")\n```\n\n### Step 2: Plan and Preprocess\n\nnnU-Net analyzes the dataset fingerprint (image intensities, spacings, sizes) to automatically configure architectures and preprocessing. This step can take 30–120 minutes for large datasets.\n\n```bash\n# Plan preprocessing for dataset 7 with integrity checks\nnnUNetv2_plan_and_preprocess -d 7 --verify_dataset_integrity\n\n# This creates:\n# $nnUNet_preprocessed\u002FDataset007_Pancreas\u002F\n# ├── nnUNetPlans.json           ← architecture configurations (patch size, batch size, etc.)\n# ├── dataset_fingerprint.json   ← image statistics used for auto-configuration\n# ├── nnUNetPlans_2d\u002F            ← preprocessed 2D slices\n# ├── nnUNetPlans_3d_fullres\u002F    ← preprocessed 3D full-resolution patches\n# └── nnUNetPlans_3d_lowres\u002F     ← preprocessed 3D low-resolution patches (if applicable)\n\necho \"Preprocessing complete. Plans stored in $nnUNet_preprocessed\u002FDataset007_Pancreas\u002F\"\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport os\n\n# Inspect the auto-generated plans to understand what nnU-Net configured\npreprocessed_dir = Path(os.environ[\"nnUNet_preprocessed\"])\nplans_file = preprocessed_dir \u002F \"Dataset007_Pancreas\" \u002F \"nnUNetPlans.json\"\n\nwith open(plans_file) as f:\n    plans = json.load(f)\n\nprint(\"nnU-Net auto-configuration summary:\")\nprint(f\"  Dataset name: {plans['dataset_name']}\")\nprint(f\"  Original spacing (mm): {plans['original_median_spacing_after_transp']}\")\n\nfor config_name, config in plans[\"configurations\"].items():\n    print(f\"\\n  Configuration: {config_name}\")\n    print(f\"    Patch size:     {config.get('patch_size', 'N\u002FA')}\")\n    print(f\"    Batch size:     {config.get('batch_size', 'N\u002FA')}\")\n    print(f\"    Spacing:        {config.get('spacing', 'N\u002FA')}\")\n    print(f\"    Network arch:   {config.get('network_arch_class_name', 'N\u002FA')}\")\n```\n\n### Step 3: Train (5-Fold Cross-Validation)\n\nnnU-Net uses 5-fold cross-validation by default. Train all 5 folds per configuration for the best ensemble performance, or train fold 0 only for a quick first model.\n\n```bash\n# Train 3D full-resolution configuration, fold 0 (on GPU)\n# --npz saves softmax predictions for ensembling\nnnUNetv2_train 7 3d_fullres 0 --npz\n\n# Train all 5 folds (submit as 5 parallel jobs on a cluster)\nfor fold in 0 1 2 3 4; do\n    nnUNetv2_train 7 3d_fullres $fold --npz\ndone\n\n# Also train 2D configuration for potential ensemble\nnnUNetv2_train 7 2d 0 --npz\n\necho \"Training outputs in $nnUNet_results\u002FDataset007_Pancreas\u002F\"\n```\n\n```bash\n# Resume training from a checkpoint (if interrupted)\nnnUNetv2_train 7 3d_fullres 0 --npz --c\n\n# Training on CPU only (slow — for testing only)\nnnUNetv2_train 7 3d_fullres 0 --npz --device cpu\n\n# Monitor GPU memory and training progress\nwatch -n 10 nvidia-smi\n\n# Check training log for loss curves\ntail -f $nnUNet_results\u002FDataset007_Pancreas\u002FnnUNetTrainer__nnUNetPlans__3d_fullres\u002Ffold_0\u002Ftraining_log.txt\n```\n\n### Step 4: Find Best Configuration\n\nAfter training, nnU-Net evaluates all trained configurations and their ensembles to recommend the best single model or ensemble.\n\n```bash\n# Determine which configuration or ensemble performs best on validation folds\n# Must have trained multiple folds (0-4) for accurate comparison\nnnUNetv2_find_best_configuration 7 -c 2d 3d_fullres\n\n# Output example:\n# Best configuration: 3d_fullres\n# Best ensemble: 2d + 3d_fullres (Dice = 0.823 vs 3d_fullres alone = 0.814)\n# Recommended: ensemble of 2d + 3d_fullres\n\n# Also run post-processing determination\n# (removes small connected components if it helps validation Dice)\nnnUNetv2_apply_postprocessing --help\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport os\n\n# Parse cross-validation results to see per-fold performance\nresults_dir = Path(os.environ[\"nnUNet_results\"])\nsummary_file = results_dir \u002F \"Dataset007_Pancreas\" \u002F \\\n    \"nnUNetTrainer__nnUNetPlans__3d_fullres\" \u002F \"fold_0\" \u002F \"validation\" \u002F \"summary.json\"\n\nif summary_file.exists():\n    with open(summary_file) as f:\n        summary = json.load(f)\n\n    metrics = summary[\"foreground_mean\"]\n    print(\"3D full-res fold_0 validation metrics:\")\n    for metric_name, value in metrics.items():\n        print(f\"  {metric_name}: {value:.4f}\")\n    # Expected output:\n    # Dice: 0.81\n    # IoU: 0.68\n    # HD95: 12.3 (mm)\nelse:\n    print(f\"Summary not found at {summary_file}\")\n    print(\"Run nnUNetv2_train first to generate validation metrics\")\n```\n\n### Step 5: Predict on New Images\n\nRun inference on a folder of new images using the trained model.\n\n```bash\n# Predict using the best single configuration (fold 0 only, fast)\nnnUNetv2_predict \\\n    -i \u002Fdata\u002Ftest_images\u002F \\\n    -o \u002Fdata\u002Fpredictions_3d\u002F \\\n    -d 7 \\\n    -c 3d_fullres \\\n    -f 0 \\\n    --save_probabilities    # save softmax probabilities for later ensembling\n\n# Predict using all 5 folds (better performance, slower)\nnnUNetv2_predict \\\n    -i \u002Fdata\u002Ftest_images\u002F \\\n    -o \u002Fdata\u002Fpredictions_allfolds\u002F \\\n    -d 7 \\\n    -c 3d_fullres \\\n    -f 0 1 2 3 4\n\necho \"Predictions saved to \u002Fdata\u002Fpredictions_allfolds\u002F\"\n```\n\n```python\nimport torch\nfrom nnunetv2.inference.predict_from_raw_data import nnUNetPredictor\nfrom pathlib import Path\nimport os\n\n# Python API for inference — useful for integration into custom pipelines\nresults_dir = os.environ[\"nnUNet_results\"]\nmodel_folder = f\"{results_dir}\u002FDataset007_Pancreas\u002FnnUNetTrainer__nnUNetPlans__3d_fullres\"\n\n# Initialize predictor\npredictor = nnUNetPredictor(\n    tile_step_size=0.5,      # overlap fraction between tiles (higher = better quality, slower)\n    use_gaussian=True,       # Gaussian weighting at tile edges (reduces boundary artifacts)\n    use_mirroring=True,      # test-time augmentation with flips (improves accuracy)\n    device=torch.device(\"cuda\", 0),  # use GPU 0; set to torch.device(\"cpu\") for CPU\n    verbose=False,\n    allow_tqdm=True,\n)\n\npredictor.initialize_from_trained_model_folder(\n    model_folder,\n    use_folds=(0,),          # which folds to use; (0,1,2,3,4) for ensemble of all folds\n    checkpoint_name=\"checkpoint_best.pth\",  # or \"checkpoint_final.pth\"\n)\n\n# Predict from files\ninput_folder = \"\u002Fdata\u002Ftest_images\u002F\"\noutput_folder = \"\u002Fdata\u002Fpredictions\u002F\"\nPath(output_folder).mkdir(exist_ok=True)\n\npredictor.predict_from_files(\n    list_of_lists_or_source_folder=input_folder,\n    output_folder_or_list_of_truncated_output_files=output_folder,\n    save_probabilities=False,\n    overwrite=True,\n    num_processes_preprocessing=2,\n    num_processes_segmentation_export=2,\n)\nprint(f\"Python API inference complete → {output_folder}\")\n```\n\n### Step 6: Ensemble Predictions\n\nCombine predictions from multiple configurations (e.g., 2D + 3D full-res) or folds to improve segmentation accuracy.\n\n```bash\n# Ensemble predictions from two configurations\n# Both must have been predicted with --save_probabilities\nnnUNetv2_ensemble \\\n    -i \u002Fdata\u002Fpredictions_2d\u002F \u002Fdata\u002Fpredictions_3d\u002F \\\n    -o \u002Fdata\u002Fpredictions_ensemble\u002F \\\n    -np 4\n\necho \"Ensemble predictions saved to \u002Fdata\u002Fpredictions_ensemble\u002F\"\n\n# Apply post-processing (e.g., remove small connected components)\n# Post-processing file generated during nnUNetv2_find_best_configuration\nnnUNetv2_apply_postprocessing \\\n    -i \u002Fdata\u002Fpredictions_ensemble\u002F \\\n    -o \u002Fdata\u002Fpredictions_final\u002F \\\n    -pp_pkl_file $nnUNet_results\u002FDataset007_Pancreas\u002FnnUNetTrainer__nnUNetPlans__3d_fullres\u002Fcrossval_results_folds_0_1_2_3_4\u002Fpostprocessing.pkl \\\n    -np 4 \\\n    -plans_json $nnUNet_preprocessed\u002FDataset007_Pancreas\u002FnnUNetPlans.json\n\necho \"Post-processing complete → \u002Fdata\u002Fpredictions_final\u002F\"\n```\n\n### Step 7: Evaluate Segmentation Quality\n\nCompute Dice scores and Hausdorff distances between predicted and ground-truth segmentations.\n\n```python\nimport SimpleITK as sitk\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\n\ndef compute_dice(pred_path: str, gt_path: str, label_value: int = 1) -> dict:\n    \"\"\"Compute Dice coefficient and Hausdorff distance for a single case.\"\"\"\n    pred = sitk.GetArrayFromImage(sitk.ReadImage(pred_path))\n    gt = sitk.GetArrayFromImage(sitk.ReadImage(gt_path))\n\n    pred_bin = (pred == label_value).astype(bool)\n    gt_bin = (gt == label_value).astype(bool)\n\n    intersection = (pred_bin & gt_bin).sum()\n    dice = 2.0 * intersection \u002F (pred_bin.sum() + gt_bin.sum() + 1e-8)\n\n    # Surface distance for Hausdorff (using SimpleITK)\n    pred_sitk = sitk.ReadImage(pred_path)\n    gt_sitk = sitk.ReadImage(gt_path)\n    pred_label = sitk.BinaryThreshold(pred_sitk, label_value, label_value, 1, 0)\n    gt_label = sitk.BinaryThreshold(gt_sitk, label_value, label_value, 1, 0)\n\n    hausdorff_filter = sitk.HausdorffDistanceImageFilter()\n    hausdorff_filter.Execute(pred_label, gt_label)\n    hd95 = hausdorff_filter.GetAverageHausdorffDistance()\n\n    return {\n        \"dice\": dice,\n        \"hd_avg_mm\": hd95,\n        \"pred_volume_ml\": pred_bin.sum() * np.prod(pred_sitk.GetSpacing()) \u002F 1000,\n        \"gt_volume_ml\": gt_bin.sum() * np.prod(gt_sitk.GetSpacing()) \u002F 1000,\n    }\n\n# Evaluate all predictions\npred_dir = Path(\"\u002Fdata\u002Fpredictions_ensemble\u002F\")\ngt_dir = Path(\"\u002Fdata\u002Ftest_labels\u002F\")\n\nrows = []\nfor pred_file in sorted(pred_dir.glob(\"*.nii.gz\")):\n    gt_file = gt_dir \u002F pred_file.name\n    if gt_file.exists():\n        metrics = compute_dice(str(pred_file), str(gt_file), label_value=1)\n        metrics[\"case\"] = pred_file.stem\n        rows.append(metrics)\n\ndf = pd.DataFrame(rows)\nprint(\"Segmentation evaluation summary:\")\nprint(df[[\"case\", \"dice\", \"hd_avg_mm\", \"pred_volume_ml\", \"gt_volume_ml\"]].to_string(index=False))\nprint(f\"\\nMean Dice:      {df['dice'].mean():.3f} ± {df['dice'].std():.3f}\")\nprint(f\"Mean Avg HD:    {df['hd_avg_mm'].mean():.1f} ± {df['hd_avg_mm'].std():.1f} mm\")\ndf.to_csv(\"segmentation_evaluation.csv\", index=False)\nprint(\"Saved: segmentation_evaluation.csv\")\n```\n\n### Step 8: Visualize Segmentation Results\n\nOverlay predicted segmentations on input images for visual quality control.\n\n```python\nimport SimpleITK as sitk\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\nfrom pathlib import Path\n\ndef visualize_segmentation(image_path: str, pred_path: str, gt_path: str = None,\n                            output_path: str = \"segmentation_qc.png\",\n                            n_slices: int = 5, label_value: int = 1):\n    \"\"\"Create a multi-slice overlay figure for visual QC.\"\"\"\n    image = sitk.GetArrayFromImage(sitk.ReadImage(image_path))  # shape: (z, y, x)\n    pred = sitk.GetArrayFromImage(sitk.ReadImage(pred_path))\n\n    # Select evenly spaced slices where segmentation is present\n    label_slices = np.where((pred == label_value).any(axis=(1, 2)))[0]\n    if len(label_slices) == 0:\n        print(\"No foreground voxels found in prediction\")\n        return\n    step = max(1, len(label_slices) \u002F\u002F n_slices)\n    selected_slices = label_slices[::step][:n_slices]\n\n    n_cols = n_slices\n    n_rows = 2 if gt_path is None else 3\n    fig, axes = plt.subplots(n_rows, n_cols, figsize=(4 * n_cols, 4 * n_rows))\n\n    # Normalize image for display\n    vmin, vmax = np.percentile(image, [1, 99])\n    cmap_label = mcolors.ListedColormap([\"none\", \"#FF4500\"])   # orange-red for prediction\n\n    for col, z in enumerate(selected_slices):\n        ax_img = axes[0, col] if n_rows > 1 else axes[col]\n        ax_img.imshow(image[z], cmap=\"gray\", vmin=vmin, vmax=vmax)\n        ax_img.imshow((pred[z] == label_value), cmap=cmap_label, alpha=0.5, vmin=0, vmax=1)\n        ax_img.set_title(f\"Pred z={z}\", fontsize=9)\n        ax_img.axis(\"off\")\n\n        if gt_path is not None:\n            gt = sitk.GetArrayFromImage(sitk.ReadImage(gt_path))\n            ax_gt = axes[1, col]\n            ax_gt.imshow(image[z], cmap=\"gray\", vmin=vmin, vmax=vmax)\n            ax_gt.imshow((gt[z] == label_value), cmap=cmap_label, alpha=0.5, vmin=0, vmax=1)\n            ax_gt.set_title(f\"GT z={z}\", fontsize=9)\n            ax_gt.axis(\"off\")\n\n    plt.tight_layout()\n    plt.savefig(output_path, dpi=150, bbox_inches=\"tight\")\n    plt.close()\n    print(f\"QC figure saved: {output_path}\")\n\n# Generate QC plots for first 3 test cases\npred_dir = Path(\"\u002Fdata\u002Fpredictions_ensemble\u002F\")\nimage_dir = Path(\"\u002Fdata\u002Ftest_images\u002F\")\ngt_dir = Path(\"\u002Fdata\u002Ftest_labels\u002F\")\n\nfor i, pred_file in enumerate(sorted(pred_dir.glob(\"*.nii.gz\"))[:3]):\n    case_id = pred_file.stem.replace(\".nii\", \"\")\n    image_file = image_dir \u002F f\"{case_id}_0000.nii.gz\"\n    gt_file = gt_dir \u002F pred_file.name\n\n    if image_file.exists():\n        visualize_segmentation(\n            image_path=str(image_file),\n            pred_path=str(pred_file),\n            gt_path=str(gt_file) if gt_file.exists() else None,\n            output_path=f\"qc_{case_id}.png\",\n            n_slices=5\n        )\n```\n\n## Key Parameters\n\n| Parameter | Default | Range \u002F Options | Effect |\n|-----------|---------|-----------------|--------|\n| `-c` (configuration) | — | `2d`, `3d_fullres`, `3d_lowres`, `3d_cascade_fullres` | Network architecture; 3d_fullres is the standard starting point |\n| `-f` (fold) | — | `0`, `1`, `2`, `3`, `4`, `all` | Cross-validation fold(s) to train or use for inference |\n| `--npz` (train) | off | flag | Save softmax probability maps during training; required for ensembling |\n| `tile_step_size` (Python API) | `0.5` | `0.3`–`0.9` | Overlap between inference tiles; larger values improve accuracy at cost of speed |\n| `use_mirroring` (Python API) | `True` | `True`, `False` | Test-time augmentation with axis flips; disable for 2–4× speedup with slight Dice drop |\n| `--num_epochs` (train) | `1000` | `250`–`2000` | Training epochs; default 1000 is suitable for most datasets |\n| `checkpoint_name` (Python API) | `\"checkpoint_best.pth\"` | `\"checkpoint_best.pth\"`, `\"checkpoint_final.pth\"` | Which saved checkpoint to load; `_best` is the highest-validation-Dice snapshot |\n| `-np` (ensemble\u002Fpostproc) | `3` | `1`–CPU count | Number of parallel processes for ensemble or post-processing |\n| `minimumObjectSize` (postprocessing) | auto | voxel count | Minimum connected component size kept; determined automatically by `find_best_configuration` |\n| `--device` (train) | `cuda` | `cuda`, `cpu`, `mps` | Training device; `mps` for Apple Silicon GPU |\n\n## Common Recipes\n\n### Recipe: Inference with a Pretrained Community Model\n\nWhen to use: A published challenge model exists for your anatomy (e.g., abdominal organs, brain tumors). Download and apply without retraining.\n\n```python\nimport torch\nfrom nnunetv2.inference.predict_from_raw_data import nnUNetPredictor\nfrom pathlib import Path\n\n# Use a downloaded pretrained model folder\n# Community models: https:\u002F\u002Fzenodo.org\u002Frecord\u002F7783116 (abdominal organs)\nmodel_folder = \"\u002Fdata\u002Fpretrained_models\u002FDataset003_Liver\u002FnnUNetTrainer__nnUNetPlans__3d_fullres\"\n\npredictor = nnUNetPredictor(\n    tile_step_size=0.5,\n    use_gaussian=True,\n    use_mirroring=True,\n    device=torch.device(\"cuda\", 0),\n    allow_tqdm=True,\n)\npredictor.initialize_from_trained_model_folder(\n    model_folder,\n    use_folds=(0, 1, 2, 3, 4),          # ensemble all folds\n    checkpoint_name=\"checkpoint_best.pth\",\n)\n\ninput_dir = \"\u002Fdata\u002Fnew_ct_scans\u002F\"\noutput_dir = \"\u002Fdata\u002Fliver_predictions\u002F\"\nPath(output_dir).mkdir(exist_ok=True)\n\npredictor.predict_from_files(\n    list_of_lists_or_source_folder=input_dir,\n    output_folder_or_list_of_truncated_output_files=output_dir,\n    save_probabilities=False,\n    overwrite=True,\n    num_processes_preprocessing=4,\n    num_processes_segmentation_export=4,\n)\nprint(f\"Inference complete → {output_dir}\")\n```\n\n### Recipe: Multi-Channel (Multi-Modal) Dataset Setup\n\nWhen to use: Training with multiple imaging modalities for the same case (e.g., T1+T2+FLAIR for brain tumor segmentation).\n\n```python\nimport json\nfrom pathlib import Path\nimport shutil\n\n# Multi-channel dataset: T1 + T2 + FLAIR brain MRI\ndataset_dir = Path(\"Dataset001_BrainTumor\")\nfor subdir in [\"imagesTr\", \"labelsTr\", \"imagesTs\"]:\n    (dataset_dir \u002F subdir).mkdir(parents=True, exist_ok=True)\n\n# File naming convention: case_{ID}_{channel_index}.nii.gz\n# For case 001: T1=001_0000, T2=001_0001, FLAIR=001_0002\n# Rename your files accordingly:\ncase_id = \"001\"\nmodalities = {\"T1\": \"0000\", \"T2\": \"0001\", \"FLAIR\": \"0002\"}\nfor modality, idx in modalities.items():\n    src = Path(f\"\u002Fdata\u002Fraw\u002F{case_id}_{modality}.nii.gz\")\n    dst = dataset_dir \u002F \"imagesTr\" \u002F f\"BrainTumor_{case_id}_{idx}.nii.gz\"\n    if src.exists():\n        shutil.copy(src, dst)\n        print(f\"Copied {modality} → {dst.name}\")\n\n# dataset.json with multiple channels\ndataset_json = {\n    \"channel_names\": {\"0\": \"T1\", \"1\": \"T2\", \"2\": \"FLAIR\"},\n    \"labels\": {\"background\": 0, \"edema\": 1, \"non_enhancing_tumor\": 2, \"enhancing_tumor\": 3},\n    \"numTraining\": 200,\n    \"file_ending\": \".nii.gz\"\n}\nwith open(dataset_dir \u002F \"dataset.json\", \"w\") as f:\n    json.dump(dataset_json, f, indent=2)\n\nprint(\"Multi-channel dataset.json created\")\nprint(f\"Channels: {dataset_json['channel_names']}\")\nprint(f\"Classes:  {dataset_json['labels']}\")\n```\n\n### Recipe: Cascade Training for Large Structures\n\nWhen to use: The structure to segment is very large relative to the image (e.g., whole brain, large organ in low-resolution CT), making 3D full-res training impractical due to memory.\n\n```bash\n# First train the low-res model (predicts a coarse segmentation)\nnnUNetv2_train 7 3d_lowres 0 --npz\nnnUNetv2_train 7 3d_lowres 1 --npz\nnnUNetv2_train 7 3d_lowres 2 --npz\nnnUNetv2_train 7 3d_lowres 3 --npz\nnnUNetv2_train 7 3d_lowres 4 --npz\n\n# Then train the high-res cascade (refines the low-res prediction)\n# The cascade uses the low-res output as additional input\nnnUNetv2_train 7 3d_cascade_fullres 0 --npz\nnnUNetv2_train 7 3d_cascade_fullres 1 --npz\nnnUNetv2_train 7 3d_cascade_fullres 2 --npz\nnnUNetv2_train 7 3d_cascade_fullres 3 --npz\nnnUNetv2_train 7 3d_cascade_fullres 4 --npz\n\n# Predict with cascade: automatically uses lowres then cascade_fullres\nnnUNetv2_predict -i \u002Fdata\u002Ftest\u002F -o \u002Fdata\u002Fcascade_preds\u002F \\\n    -d 7 -c 3d_cascade_fullres -f 0 1 2 3 4\n\necho \"Cascade prediction complete\"\n```\n\n## Expected Outputs\n\n| Output | Location | Description |\n|--------|----------|-------------|\n| `nnUNetPlans.json` | `$nnUNet_preprocessed\u002FDatasetXXX\u002F` | Auto-configured architecture, patch size, batch size, spacing |\n| `dataset_fingerprint.json` | `$nnUNet_preprocessed\u002FDatasetXXX\u002F` | Dataset statistics used for auto-configuration |\n| `checkpoint_best.pth` | `$nnUNet_results\u002F...\u002Ffold_N\u002F` | Model snapshot with highest validation Dice score |\n| `checkpoint_final.pth` | `$nnUNet_results\u002F...\u002Ffold_N\u002F` | Final model checkpoint after all training epochs |\n| `training_log.txt` | `$nnUNet_results\u002F...\u002Ffold_N\u002F` | Per-epoch train\u002Fvalidation loss and Dice scores |\n| `summary.json` | `$nnUNet_results\u002F...\u002Ffold_N\u002Fvalidation\u002F` | Dice, IoU, Hausdorff distance on validation fold |\n| `{case}.nii.gz` | Prediction output folder | Integer label map (0=background, 1,2,...=classes) |\n| `{case}.npz` | Prediction folder (if `--save_probabilities`) | Softmax probability map for each class |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `RuntimeError: CUDA out of memory` | GPU VRAM insufficient for patch size | Reduce patch size in `nnUNetPlans.json` (edit `patch_size` and `batch_size`); use 2D configuration instead of 3D |\n| `FileNotFoundError: nnUNet_raw not set` | Environment variable missing | `export nnUNet_raw=\u002Fpath\u002Fto\u002Fraw`; verify with `echo $nnUNet_raw` |\n| Dataset integrity check fails | Mismatched image\u002Flabel sizes or naming | Ensure every `labelsTr\u002Fcase_NNN.nii.gz` has a matching `imagesTr\u002Fcase_NNN_0000.nii.gz`; check spacing matches |\n| Low Dice after training | Too few training cases or poor labels | Minimum 20 cases; verify label quality visually; check class imbalance in `dataset.json` |\n| Training plateau (loss not decreasing after epoch 200) | Learning rate too high or too low | nnU-Net uses auto LR schedule; if plateau persists, increase `numTraining` examples or check data augmentation |\n| `ValueError: images contain incorrect pixel type` | Images not in float or uint format | Convert to float32 with SimpleITK: `sitk.Cast(image, sitk.sitkFloat32)` before placing in `imagesTr\u002F` |\n| Prediction is all background | Wrong model folder or checkpoint path | Verify `model_folder` path; check that `checkpoint_best.pth` exists; confirm dataset ID matches the trained model |\n| Very slow inference (>10 min per case) | CPU inference or large patch with full mirroring | Set `device=torch.device(\"cuda\",0)`; set `use_mirroring=False` for 4× speedup; reduce `tile_step_size` to 0.3 |\n\n## References\n\n- [nnU-Net GitHub](https:\u002F\u002Fgithub.com\u002FMIC-DKFZ\u002FnnUNet) — official source code, installation instructions, and documentation\n- [Isensee F et al. (2021) Nature Methods 18:203–211](https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-020-01008-z) — original nnU-Net paper: \"nnU-Net: a self-configuring method for deep learning-based biomedical image segmentation\"\n- [nnU-Net v2 documentation](https:\u002F\u002Fgithub.com\u002FMIC-DKFZ\u002FnnUNet\u002Ftree\u002Fmaster\u002Fdocumentation) — migration guide, dataset format, inference API, custom trainers\n- [Medical Segmentation Decathlon](http:\u002F\u002Fmedicaldecathlon.com\u002F) — 10 benchmark datasets in nnU-Net-compatible format for training and validation\n- [Zenodo: pretrained nnU-Net models](https:\u002F\u002Fzenodo.org\u002Frecord\u002F7783116) — community-shared pretrained models for abdominal organs and other structures\n","# nnU-Net Automated Medical Image Segmentation\n\n## Overview\n\nnnU-Net (no-new-Net) is a self-configuring deep learning framework for biomedical image segmentation. Given a labeled training dataset, nnU-Net automatically determines the optimal network architecture (2D, 3D full-resolution, or 3D cascade), preprocessing steps (resampling, normalization, patch size), training schedule, and post-processing. It consistently achieves state-of-the-art performance across diverse imaging modalities and anatomical structures without manual hyperparameter tuning. nnU-Net v2 (`nnunetv2`) is the current release with a Python API for inference alongside the standard CLI.\n\n## When to Use\n\n- Segmenting anatomical structures in CT or MRI scans (organs, tumors, lesions) when you have 20+ annotated training cases\n- Automating cell or nucleus segmentation in 3D fluorescence or electron microscopy volumes\n- Establishing a strong baseline for any new segmentation challenge without manually tuning a U-Net\n- Running inference on new images using a pretrained nnU-Net model from a published challenge\n- Comparing segmentation methods: nnU-Net's auto-configured ensembles serve as a rigorous baseline\n- Building production segmentation pipelines where training is done once and inference is repeated on many new cases\n- Use **Cellpose** (`cellpose-cell-segmentation`) instead for 2D fluorescence cell segmentation without labeled training data; nnU-Net requires annotated training cases\n- Use **SimpleITK** (`simpleitk-image-registration`) instead for rule-based segmentation with classical thresholding and region growing on images where deep learning training data is unavailable\n\n## Prerequisites\n\n- **Python packages**: `nnunetv2>=2.2`, `torch>=2.0` (with CUDA for GPU training)\n- **Data requirements**: Images in NIfTI format (`.nii.gz`); binary or multi-class label masks; minimum 20 training cases recommended (50+ for best performance)\n- **Environment variables**: `nnUNet_raw`, `nnUNet_preprocessed`, `nnUNet_results` must be set\n- **Hardware**: GPU with 8+ GB VRAM recommended for training; CPU inference is supported but slow\n- **Environment**: Python 3.9+; Linux or macOS (Windows supported but not officially recommended)\n\n```bash\npip install nnunetv2\n\n# Verify installation\nnnUNetv2_train --help\n\n# Set required environment variables (add to ~\u002F.bashrc or ~\u002F.zshrc)\nexport nnUNet_raw=\u002Fdata\u002FnnUNet_raw\nexport nnUNet_preprocessed=\u002Fdata\u002FnnUNet_preprocessed\nexport nnUNet_results=\u002Fdata\u002FnnUNet_results\n\nmkdir -p $nnUNet_raw $nnUNet_preprocessed $nnUNet_results\n```\n\n## Quick Start\n\n```bash\n# Minimal end-to-end pipeline: convert dataset → preprocess → train → predict\n# Assumes dataset is in Medical Segmentation Decathlon format\n\n# 1. Set environment\nexport nnUNet_raw=\u002Fdata\u002FnnUNet_raw\nexport nnUNet_preprocessed=\u002Fdata\u002FnnUNet_preprocessed\nexport nnUNet_results=\u002Fdata\u002FnnUNet_results\n\n# 2. Convert Medical Segmentation Decathlon dataset (dataset ID 7 = Pancreas)\nnnUNetv2_convert_MSD_dataset -i \u002Fdata\u002FTask07_Pancreas -overwrite_id 7\n\n# 3. Plan preprocessing and verify dataset integrity\nnnUNetv2_plan_and_preprocess -d 7 --verify_dataset_integrity\n\n# 4. Train 3D full-res model, fold 0 (of 5-fold cross-validation)\nnnUNetv2_train 7 3d_fullres 0 --npz\n\n# 5. Predict on new images\nnnUNetv2_predict -i \u002Fdata\u002Ftest_images\u002F -o \u002Fdata\u002Fpredictions\u002F -d 7 -c 3d_fullres -f 0\necho \"Segmentation predictions saved to \u002Fdata\u002Fpredictions\u002F\"\n```\n\n## Workflow\n\n### Step 1: Prepare Dataset in nnU-Net Format\n\nnnU-Net requires images in NIfTI format organized in a specific directory structure with a `dataset.json` descriptor.\n\n```bash\n# Dataset directory structure (Dataset007_Pancreas as example):\n# $nnUNet_raw\u002F\n# └── Dataset007_Pancreas\u002F\n#     ├── dataset.json          ← metadata descriptor\n#     ├── imagesTr\u002F             ← training images\n#     │   ├── pancreas_001_0000.nii.gz   (0000 = channel\u002Fmodality index)\n#     │   └── pancreas_002_0000.nii.gz\n#     ├── labelsTr\u002F             ← training segmentation masks\n#     │   ├── pancreas_001.nii.gz\n#     │   └── pancreas_002.nii.gz\n#     └── imagesTs\u002F             ← test images (no labels required)\n#         └── pancreas_101_0000.nii.gz\n\n# For Medical Segmentation Decathlon datasets, convert automatically:\nnnUNetv2_convert_MSD_dataset -i \u002Fdata\u002FTask07_Pancreas -overwrite_id 7\n\necho \"Dataset 7 created at $nnUNet_raw\u002FDataset007_Pancreas\u002F\"\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport shutil\n\n# Create dataset.json for a custom dataset (single CT modality, 2-class segmentation)\ndataset_id = 8\ndataset_name = f\"Dataset{dataset_id:03d}_MyOrgan\"\ndataset_dir = Path(f\"{dataset_name}\")\n(dataset_dir \u002F \"imagesTr\").mkdir(parents=True, exist_ok=True)\n(dataset_dir \u002F \"labelsTr\").mkdir(parents=True, exist_ok=True)\n(dataset_dir \u002F \"imagesTs\").mkdir(parents=True, exist_ok=True)\n\ndataset_json = {\n    \"channel_names\": {\n        \"0\": \"CT\"           # for MRI: \"0\": \"T1\", \"1\": \"T2\" (multi-modal = multiple channels)\n    },\n    \"labels\": {\n        \"background\": 0,\n        \"organ\": 1          # add more classes: \"tumor\": 2, \"vessel\": 3\n    },\n    \"numTraining\": 50,      # number of training cases\n    \"file_ending\": \".nii.gz\"\n}\n\nwith open(dataset_dir \u002F \"dataset.json\", \"w\") as f:\n    json.dump(dataset_json, f, indent=2)\n\nprint(f\"Created dataset.json with {dataset_json['numTraining']} training cases\")\nprint(f\"Labels: {dataset_json['labels']}\")\nprint(f\"Channels: {dataset_json['channel_names']}\")\nprint(f\"\\nPlace training images as: imagesTr\u002Fcase_NNN_0000.nii.gz\")\nprint(f\"Place training labels as:  labelsTr\u002Fcase_NNN.nii.gz\")\n```\n\n### Step 2: Plan and Preprocess\n\nnnU-Net analyzes the dataset fingerprint (image intensities, spacings, sizes) to automatically configure architectures and preprocessing. This step can take 30–120 minutes for large datasets.\n\n```bash\n# Plan preprocessing for dataset 7 with integrity checks\nnnUNetv2_plan_and_preprocess -d 7 --verify_dataset_integrity\n\n# This creates:\n# $nnUNet_preprocessed\u002FDataset007_Pancreas\u002F\n# ├── nnUNetPlans.json           ← architecture configurations (patch size, batch size, etc.)\n# ├── dataset_fingerprint.json   ← image statistics used for auto-configuration\n# ├── nnUNetPlans_2d\u002F            ← preprocessed 2D slices\n# ├── nnUNetPlans_3d_fullres\u002F    ← preprocessed 3D full-resolution patches\n# └── nnUNetPlans_3d_lowres\u002F     ← preprocessed 3D low-resolution patches (if applicable)\n\necho \"Preprocessing complete. Plans stored in $nnUNet_preprocessed\u002FDataset007_Pancreas\u002F\"\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport os\n\n# Inspect the auto-generated plans to understand what nnU-Net configured\npreprocessed_dir = Path(os.environ[\"nnUNet_preprocessed\"])\nplans_file = preprocessed_dir \u002F \"Dataset007_Pancreas\" \u002F \"nnUNetPlans.json\"\n\nwith open(plans_file) as f:\n    plans = json.load(f)\n\nprint(\"nnU-Net auto-configuration summary:\")\nprint(f\"  Dataset name: {plans['dataset_name']}\")\nprint(f\"  Original spacing (mm): {plans['original_median_spacing_after_transp']}\")\n\nfor config_name, config in plans[\"configurations\"].items():\n    print(f\"\\n  Configuration: {config_name}\")\n    print(f\"    Patch size:     {config.get('patch_size', 'N\u002FA')}\")\n    print(f\"    Batch size:     {config.get('batch_size', 'N\u002FA')}\")\n    print(f\"    Spacing:        {config.get('spacing', 'N\u002FA')}\")\n    print(f\"    Network arch:   {config.get('network_arch_class_name', 'N\u002FA')}\")\n```\n\n### Step 3: Train (5-Fold Cross-Validation)\n\nnnU-Net uses 5-fold cross-validation by default. Train all 5 folds per configuration for the best ensemble performance, or train fold 0 only for a quick first model.\n\n```bash\n# Train 3D full-resolution configuration, fold 0 (on GPU)\n# --npz saves softmax predictions for ensembling\nnnUNetv2_train 7 3d_fullres 0 --npz\n\n# Train all 5 folds (submit as 5 parallel jobs on a cluster)\nfor fold in 0 1 2 3 4; do\n    nnUNetv2_train 7 3d_fullres $fold --npz\ndone\n\n# Also train 2D configuration for potential ensemble\nnnUNetv2_train 7 2d 0 --npz\n\necho \"Training outputs in $nnUNet_results\u002FDataset007_Pancreas\u002F\"\n```\n\n```bash\n# Resume training from a checkpoint (if interrupted)\nnnUNetv2_train 7 3d_fullres 0 --npz --c\n\n# Training on CPU only (slow — for testing only)\nnnUNetv2_train 7 3d_fullres 0 --npz --device cpu\n\n# Monitor GPU memory and training progress\nwatch -n 10 nvidia-smi\n\n# Check training log for loss curves\ntail -f $nnUNet_results\u002FDataset007_Pancreas\u002FnnUNetTrainer__nnUNetPlans__3d_fullres\u002Ffold_0\u002Ftraining_log.txt\n```\n\n### Step 4: Find Best Configuration\n\nAfter training, nnU-Net evaluates all trained configurations and their ensembles to recommend the best single model or ensemble.\n\n```bash\n# Determine which configuration or ensemble performs best on validation folds\n# Must have trained multiple folds (0-4) for accurate comparison\nnnUNetv2_find_best_configuration 7 -c 2d 3d_fullres\n\n# Output example:\n# Best configuration: 3d_fullres\n# Best ensemble: 2d + 3d_fullres (Dice = 0.823 vs 3d_fullres alone = 0.814)\n# Recommended: ensemble of 2d + 3d_fullres\n\n# Also run post-processing determination\n# (removes small connected components if it helps validation Dice)\nnnUNetv2_apply_postprocessing --help\n```\n\n```python\nimport json\nfrom pathlib import Path\nimport os\n\n# Parse cross-validation results to see per-fold performance\nresults_dir = Path(os.environ[\"nnUNet_results\"])\nsummary_file = results_dir \u002F \"Dataset007_Pancreas\" \u002F \\\n    \"nnUNetTrainer__nnUNetPlans__3d_fullres\" \u002F \"fold_0\" \u002F \"validation\" \u002F \"summary.json\"\n\nif summary_file.exists():\n    with open(summary_file) as f:\n        summary = json.load(f)\n\n    metrics = summary[\"foreground_mean\"]\n    print(\"3D full-res fold_0 validation metrics:\")\n    for metric_name, value in metrics.items():\n        print(f\"  {metric_name}: {value:.4f}\")\n    # Expected output:\n    # Dice: 0.81\n    # IoU: 0.68\n    # HD95: 12.3 (mm)\nelse:\n    print(f\"Summary not found at {summary_file}\")\n    print(\"Run nnUNetv2_train first to generate validation metrics\")\n```\n\n### Step 5: Predict on New Images\n\nRun inference on a folder of new images using the trained model.\n\n```bash\n# Predict using the best single configuration (fold 0 only, fast)\nnnUNetv2_predict \\\n    -i \u002Fdata\u002Ftest_images\u002F \\\n    -o \u002Fdata\u002Fpredictions_3d\u002F \\\n    -d 7 \\\n    -c 3d_fullres \\\n    -f 0 \\\n    --save_probabilities    # save softmax probabilities for later ensembling\n\n# Predict using all 5 folds (better performance, slower)\nnnUNetv2_predict \\\n    -i \u002Fdata\u002Ftest_images\u002F \\\n    -o \u002Fdata\u002Fpredictions_allfolds\u002F \\\n    -d 7 \\\n    -c 3d_fullres \\\n    -f 0 1 2 3 4\n\necho \"Predictions saved to \u002Fdata\u002Fpredictions_allfolds\u002F\"\n```\n\n```python\nimport torch\nfrom nnunetv2.inference.predict_from_raw_data import nnUNetPredictor\nfrom pathlib import Path\nimport os\n\n# Python API for inference — useful for integration into custom pipelines\nresults_dir = os.environ[\"nnUNet_results\"]\nmodel_folder = f\"{results_dir}\u002FDataset007_Pancreas\u002FnnUNetTrainer__nnUNetPlans__3d_fullres\"\n\n# Initialize predictor\npredictor = nnUNetPredictor(\n    tile_step_size=0.5,      # overlap fraction between tiles (higher = better quality, slower)\n    use_gaussian=True,       # Gaussian weighting at tile edges (reduces boundary artifacts)\n    use_mirroring=True,      # test-time augmentation with flips (improves accuracy)\n    device=torch.device(\"cuda\", 0),  # use GPU 0; set to torch.device(\"cpu\") for CPU\n    verbose=False,\n    allow_tqdm=True,\n)\n\npredictor.initialize_from_trained_model_folder(\n    model_folder,\n    use_folds=(0,),          # which folds to use; (0,1,2,3,4) for ensemble of all folds\n    checkpoint_name=\"checkpoint_best.pth\",  # or \"checkpoint_final.pth\"\n)\n\n# Predict from files\ninput_folder = \"\u002Fdata\u002Ftest_images\u002F\"\noutput_folder = \"\u002Fdata\u002Fpredictions\u002F\"\nPath(output_folder).mkdir(exist_ok=True)\n\npredictor.predict_from_files(\n    list_of_lists_or_source_folder=input_folder,\n    output_folder_or_list_of_truncated_output_files=output_folder,\n    save_probabilities=False,\n    overwrite=True,\n    num_processes_preprocessing=2,\n    num_processes_segmentation_export=2,\n)\nprint(f\"Python API inference complete → {output_folder}\")\n```\n\n### Step 6: Ensemble Predictions\n\nCombine predictions from multiple configurations (e.g., 2D + 3D full-res) or folds to improve segmentation accuracy.\n\n```bash\n# Ensemble predictions from two configurations\n# Both must have been predicted with --save_probabilities\nnnUNetv2_ensemble \\\n    -i \u002Fdata\u002Fpredictions_2d\u002F \u002Fdata\u002Fpredictions_3d\u002F \\\n    -o \u002Fdata\u002Fpredictions_ensemble\u002F \\\n    -np 4\n\necho \"Ensemble predictions saved to \u002Fdata\u002Fpredictions_ensemble\u002F\"\n\n# Apply post-processing (e.g., remove small connected components)\n# Post-processing file generated during nnUNetv2_find_best_configuration\nnnUNetv2_apply_postprocessing \\\n    -i \u002Fdata\u002Fpredictions_ensemble\u002F \\\n    -o \u002Fdata\u002Fpredictions_final\u002F \\\n    -pp_pkl_file $nnUNet_results\u002FDataset007_Pancreas\u002FnnUNetTrainer__nnUNetPlans__3d_fullres\u002Fcrossval_results_folds_0_1_2_3_4\u002Fpostprocessing.pkl \\\n    -np 4 \\\n    -plans_json $nnUNet_preprocessed\u002FDataset007_Pancreas\u002FnnUNetPlans.json\n\necho \"Post-processing complete → \u002Fdata\u002Fpredictions_final\u002F\"\n```\n\n### Step 7: Evaluate Segmentation Quality\n\nCompute Dice scores and Hausdorff distances between predicted and ground-truth segmentations.\n\n```python\nimport SimpleITK as sitk\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\n\ndef compute_dice(pred_path: str, gt_path: str, label_value: int = 1) -> dict:\n    \"\"\"Compute Dice coefficient and Hausdorff distance for a single case.\"\"\"\n    pred = sitk.GetArrayFromImage(sitk.ReadImage(pred_path))\n    gt = sitk.GetArrayFromImage(sitk.ReadImage(gt_path))\n\n    pred_bin = (pred == label_value).astype(bool)\n    gt_bin = (gt == label_value).astype(bool)\n\n    intersection = (pred_bin & gt_bin).sum()\n    dice = 2.0 * intersection \u002F (pred_bin.sum() + gt_bin.sum() + 1e-8)\n\n    # Surface distance for Hausdorff (using SimpleITK)\n    pred_sitk = sitk.ReadImage(pred_path)\n    gt_sitk = sitk.ReadImage(gt_path)\n    pred_label = sitk.BinaryThreshold(pred_sitk, label_value, label_value, 1, 0)\n    gt_label = sitk.BinaryThreshold(gt_sitk, label_value, label_value, 1, 0)\n\n    hausdorff_filter = sitk.HausdorffDistanceImageFilter()\n    hausdorff_filter.Execute(pred_label, gt_label)\n    hd95 = hausdorff_filter.GetAverageHausdorffDistance()\n\n    return {\n        \"dice\": dice,\n        \"hd_avg_mm\": hd95,\n        \"pred_volume_ml\": pred_bin.sum() * np.prod(pred_sitk.GetSpacing()) \u002F 1000,\n        \"gt_volume_ml\": gt_bin.sum() * np.prod(gt_sitk.GetSpacing()) \u002F 1000,\n    }\n\n# Evaluate all predictions\npred_dir = Path(\"\u002Fdata\u002Fpredictions_ensemble\u002F\")\ngt_dir = Path(\"\u002Fdata\u002Ftest_labels\u002F\")\n\nrows = []\nfor pred_file in sorted(pred_dir.glob(\"*.nii.gz\")):\n    gt_file = gt_dir \u002F pred_file.name\n    if gt_file.exists():\n        metrics = compute_dice(str(pred_file), str(gt_file), label_value=1)\n        metrics[\"case\"] = pred_file.stem\n        rows.append(metrics)\n\ndf = pd.DataFrame(rows)\nprint(\"Segmentation evaluation summary:\")\nprint(df[[\"case\", \"dice\", \"hd_avg_mm\", \"pred_volume_ml\", \"gt_volume_ml\"]].to_string(index=False))\nprint(f\"\\nMean Dice:      {df['dice'].mean():.3f} ± {df['dice'].std():.3f}\")\nprint(f\"Mean Avg HD:    {df['hd_avg_mm'].mean():.1f} ± {df['hd_avg_mm'].std():.1f} mm\")\ndf.to_csv(\"segmentation_evaluation.csv\", index=False)\nprint(\"Saved: segmentation_evaluation.csv\")\n```\n\n### Step 8: Visualize Segmentation Results\n\nOverlay predicted segmentations on input images for visual quality control.\n\n```python\nimport SimpleITK as sitk\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\nfrom pathlib import Path\n\ndef visualize_segmentation(image_path: str, pred_path: str, gt_path: str = None,\n                            output_path: str = \"segmentation_qc.png\",\n                            n_slices: int = 5, label_value: int = 1):\n    \"\"\"Create a multi-slice overlay figure for visual QC.\"\"\"\n    image = sitk.GetArrayFromImage(sitk.ReadImage(image_path))  # shape: (z, y, x)\n    pred = sitk.GetArrayFromImage(sitk.ReadImage(pred_path))\n\n    # Select evenly spaced slices where segmentation is present\n    label_slices = np.where((pred == label_value).any(axis=(1, 2)))[0]\n    if len(label_slices) == 0:\n        print(\"No foreground voxels found in prediction\")\n        return\n    step = max(1, len(label_slices) \u002F\u002F n_slices)\n    selected_slices = label_slices[::step][:n_slices]\n\n    n_cols = n_slices\n    n_rows = 2 if gt_path is None else 3\n    fig, axes = plt.subplots(n_rows, n_cols, figsize=(4 * n_cols, 4 * n_rows))\n\n    # Normalize image for display\n    vmin, vmax = np.percentile(image, [1, 99])\n    cmap_label = mcolors.ListedColormap([\"none\", \"#FF4500\"])   # orange-red for prediction\n\n    for col, z in enumerate(selected_slices):\n        ax_img = axes[0, col] if n_rows > 1 else axes[col]\n        ax_img.imshow(image[z], cmap=\"gray\", vmin=vmin, vmax=vmax)\n        ax_img.imshow((pred[z] == label_value), cmap=cmap_label, alpha=0.5, vmin=0, vmax=1)\n        ax_img.set_title(f\"Pred z={z}\", fontsize=9)\n        ax_img.axis(\"off\")\n\n        if gt_path is not None:\n            gt = sitk.GetArrayFromImage(sitk.ReadImage(gt_path))\n            ax_gt = axes[1, col]\n            ax_gt.imshow(image[z], cmap=\"gray\", vmin=vmin, vmax=vmax)\n            ax_gt.imshow((gt[z] == label_value), cmap=cmap_label, alpha=0.5, vmin=0, vmax=1)\n            ax_gt.set_title(f\"GT z={z}\", fontsize=9)\n            ax_gt.axis(\"off\")\n\n    plt.tight_layout()\n    plt.savefig(output_path, dpi=150, bbox_inches=\"tight\")\n    plt.close()\n    print(f\"QC figure saved: {output_path}\")\n\n# Generate QC plots for first 3 test cases\npred_dir = Path(\"\u002Fdata\u002Fpredictions_ensemble\u002F\")\nimage_dir = Path(\"\u002Fdata\u002Ftest_images\u002F\")\ngt_dir = Path(\"\u002Fdata\u002Ftest_labels\u002F\")\n\nfor i, pred_file in enumerate(sorted(pred_dir.glob(\"*.nii.gz\"))[:3]):\n    case_id = pred_file.stem.replace(\".nii\", \"\")\n    image_file = image_dir \u002F f\"{case_id}_0000.nii.gz\"\n    gt_file = gt_dir \u002F pred_file.name\n\n    if image_file.exists():\n        visualize_segmentation(\n            image_path=str(image_file),\n            pred_path=str(pred_file),\n            gt_path=str(gt_file) if gt_file.exists() else None,\n            output_path=f\"qc_{case_id}.png\",\n            n_slices=5\n        )\n```\n\n## Key Parameters\n\n| Parameter | Default | Range \u002F Options | Effect |\n|-----------|---------|-----------------|--------|\n| `-c` (configuration) | — | `2d`, `3d_fullres`, `3d_lowres`, `3d_cascade_fullres` | Network architecture; 3d_fullres is the standard starting point |\n| `-f` (fold) | — | `0`, `1`, `2`, `3`, `4`, `all` | Cross-validation fold(s) to train or use for inference |\n| `--npz` (train) | off | flag | Save softmax probability maps during training; required for ensembling |\n| `tile_step_size` (Python API) | `0.5` | `0.3`–`0.9` | Overlap between inference tiles; larger values improve accuracy at cost of speed |\n| `use_mirroring` (Python API) | `True` | `True`, `False` | Test-time augmentation with axis flips; disable for 2–4× speedup with slight Dice drop |\n| `--num_epochs` (train) | `1000` | `250`–`2000` | Training epochs; default 1000 is suitable for most datasets |\n| `checkpoint_name` (Python API) | `\"checkpoint_best.pth\"` | `\"checkpoint_best.pth\"`, `\"checkpoint_final.pth\"` | Which saved checkpoint to load; `_best` is the highest-validation-Dice snapshot |\n| `-np` (ensemble\u002Fpostproc) | `3` | `1`–CPU count | Number of parallel processes for ensemble or post-processing |\n| `minimumObjectSize` (postprocessing) | auto | voxel count | Minimum connected component size kept; determined automatically by `find_best_configuration` |\n| `--device` (train) | `cuda` | `cuda`, `cpu`, `mps` | Training device; `mps` for Apple Silicon GPU |\n\n## Common Recipes\n\n### Recipe: Inference with a Pretrained Community Model\n\nWhen to use: A published challenge model exists for your anatomy (e.g., abdominal organs, brain tumors). Download and apply without retraining.\n\n```python\nimport torch\nfrom nnunetv2.inference.predict_from_raw_data import nnUNetPredictor\nfrom pathlib import Path\n\n# Use a downloaded pretrained model folder\n# Community models: https:\u002F\u002Fzenodo.org\u002Frecord\u002F7783116 (abdominal organs)\nmodel_folder = \"\u002Fdata\u002Fpretrained_models\u002FDataset003_Liver\u002FnnUNetTrainer__nnUNetPlans__3d_fullres\"\n\npredictor = nnUNetPredictor(\n    tile_step_size=0.5,\n    use_gaussian=True,\n    use_mirroring=True,\n    device=torch.device(\"cuda\", 0),\n    allow_tqdm=True,\n)\npredictor.initialize_from_trained_model_folder(\n    model_folder,\n    use_folds=(0, 1, 2, 3, 4),          # ensemble all folds\n    checkpoint_name=\"checkpoint_best.pth\",\n)\n\ninput_dir = \"\u002Fdata\u002Fnew_ct_scans\u002F\"\noutput_dir = \"\u002Fdata\u002Fliver_predictions\u002F\"\nPath(output_dir).mkdir(exist_ok=True)\n\npredictor.predict_from_files(\n    list_of_lists_or_source_folder=input_dir,\n    output_folder_or_list_of_truncated_output_files=output_dir,\n    save_probabilities=False,\n    overwrite=True,\n    num_processes_preprocessing=4,\n    num_processes_segmentation_export=4,\n)\nprint(f\"Inference complete → {output_dir}\")\n```\n\n### Recipe: Multi-Channel (Multi-Modal) Dataset Setup\n\nWhen to use: Training with multiple imaging modalities for the same case (e.g., T1+T2+FLAIR for brain tumor segmentation).\n\n```python\nimport json\nfrom pathlib import Path\nimport shutil\n\n# Multi-channel dataset: T1 + T2 + FLAIR brain MRI\ndataset_dir = Path(\"Dataset001_BrainTumor\")\nfor subdir in [\"imagesTr\", \"labelsTr\", \"imagesTs\"]:\n    (dataset_dir \u002F subdir).mkdir(parents=True, exist_ok=True)\n\n# File naming convention: case_{ID}_{channel_index}.nii.gz\n# For case 001: T1=001_0000, T2=001_0001, FLAIR=001_0002\n# Rename your files accordingly:\ncase_id = \"001\"\nmodalities = {\"T1\": \"0000\", \"T2\": \"0001\", \"FLAIR\": \"0002\"}\nfor modality, idx in modalities.items():\n    src = Path(f\"\u002Fdata\u002Fraw\u002F{case_id}_{modality}.nii.gz\")\n    dst = dataset_dir \u002F \"imagesTr\" \u002F f\"BrainTumor_{case_id}_{idx}.nii.gz\"\n    if src.exists():\n        shutil.copy(src, dst)\n        print(f\"Copied {modality} → {dst.name}\")\n\n# dataset.json with multiple channels\ndataset_json = {\n    \"channel_names\": {\"0\": \"T1\", \"1\": \"T2\", \"2\": \"FLAIR\"},\n    \"labels\": {\"background\": 0, \"edema\": 1, \"non_enhancing_tumor\": 2, \"enhancing_tumor\": 3},\n    \"numTraining\": 200,\n    \"file_ending\": \".nii.gz\"\n}\nwith open(dataset_dir \u002F \"dataset.json\", \"w\") as f:\n    json.dump(dataset_json, f, indent=2)\n\nprint(\"Multi-channel dataset.json created\")\nprint(f\"Channels: {dataset_json['channel_names']}\")\nprint(f\"Classes:  {dataset_json['labels']}\")\n```\n\n### Recipe: Cascade Training for Large Structures\n\nWhen to use: The structure to segment is very large relative to the image (e.g., whole brain, large organ in low-resolution CT), making 3D full-res training impractical due to memory.\n\n```bash\n# First train the low-res model (predicts a coarse segmentation)\nnnUNetv2_train 7 3d_lowres 0 --npz\nnnUNetv2_train 7 3d_lowres 1 --npz\nnnUNetv2_train 7 3d_lowres 2 --npz\nnnUNetv2_train 7 3d_lowres 3 --npz\nnnUNetv2_train 7 3d_lowres 4 --npz\n\n# Then train the high-res cascade (refines the low-res prediction)\n# The cascade uses the low-res output as additional input\nnnUNetv2_train 7 3d_cascade_fullres 0 --npz\nnnUNetv2_train 7 3d_cascade_fullres 1 --npz\nnnUNetv2_train 7 3d_cascade_fullres 2 --npz\nnnUNetv2_train 7 3d_cascade_fullres 3 --npz\nnnUNetv2_train 7 3d_cascade_fullres 4 --npz\n\n# Predict with cascade: automatically uses lowres then cascade_fullres\nnnUNetv2_predict -i \u002Fdata\u002Ftest\u002F -o \u002Fdata\u002Fcascade_preds\u002F \\\n    -d 7 -c 3d_cascade_fullres -f 0 1 2 3 4\n\necho \"Cascade prediction complete\"\n```\n\n## Expected Outputs\n\n| Output | Location | Description |\n|--------|----------|-------------|\n| `nnUNetPlans.json` | `$nnUNet_preprocessed\u002FDatasetXXX\u002F` | Auto-configured architecture, patch size, batch size, spacing |\n| `dataset_fingerprint.json` | `$nnUNet_preprocessed\u002FDatasetXXX\u002F` | Dataset statistics used for auto-configuration |\n| `checkpoint_best.pth` | `$nnUNet_results\u002F...\u002Ffold_N\u002F` | Model snapshot with highest validation Dice score |\n| `checkpoint_final.pth` | `$nnUNet_results\u002F...\u002Ffold_N\u002F` | Final model checkpoint after all training epochs |\n| `training_log.txt` | `$nnUNet_results\u002F...\u002Ffold_N\u002F` | Per-epoch train\u002Fvalidation loss and Dice scores |\n| `summary.json` | `$nnUNet_results\u002F...\u002Ffold_N\u002Fvalidation\u002F` | Dice, IoU, Hausdorff distance on validation fold |\n| `{case}.nii.gz` | Prediction output folder | Integer label map (0=background, 1,2,...=classes) |\n| `{case}.npz` | Prediction folder (if `--save_probabilities`) | Softmax probability map for each class |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `RuntimeError: CUDA out of memory` | GPU VRAM insufficient for patch size | Reduce patch size in `nnUNetPlans.json` (edit `patch_size` and `batch_size`); use 2D configuration instead of 3D |\n| `FileNotFoundError: nnUNet_raw not set` | Environment variable missing | `export nnUNet_raw=\u002Fpath\u002Fto\u002Fraw`; verify with `echo $nnUNet_raw` |\n| Dataset integrity check fails | Mismatched image\u002Flabel sizes or naming | Ensure every `labelsTr\u002Fcase_NNN.nii.gz` has a matching `imagesTr\u002Fcase_NNN_0000.nii.gz`; check spacing matches |\n| Low Dice after training | Too few training cases or poor labels | Minimum 20 cases; verify label quality visually; check class imbalance in `dataset.json` |\n| Training plateau (loss not decreasing after epoch 200) | Learning rate too high or too low | nnU-Net uses auto LR schedule; if plateau persists, increase `numTraining` examples or check data augmentation |\n| `ValueError: images contain incorrect pixel type` | Images not in float or uint format | Convert to float32 with SimpleITK: `sitk.Cast(image, sitk.sitkFloat32)` before placing in `imagesTr\u002F` |\n| Prediction is all background | Wrong model folder or checkpoint path | Verify `model_folder` path; check that `checkpoint_best.pth` exists; confirm dataset ID matches the trained model |\n| Very slow inference (>10 min per case) | CPU inference or large patch with full mirroring | Set `device=torch.device(\"cuda\",0)`; set `use_mirroring=False` for 4× speedup; reduce `tile_step_size` to 0.3 |\n\n## References\n\n- [nnU-Net GitHub](https:\u002F\u002Fgithub.com\u002FMIC-DKFZ\u002FnnUNet) — official source code, installation instructions, and documentation\n- [Isensee F et al. (2021) Nature Methods 18:203–211](https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-020-01008-z) — original nnU-Net paper: \"nnU-Net: a self-configuring method for deep learning-based biomedical image segmentation\"\n- [nnU-Net v2 documentation](https:\u002F\u002Fgithub.com\u002FMIC-DKFZ\u002FnnUNet\u002Ftree\u002Fmaster\u002Fdocumentation) — migration guide, dataset format, inference API, custom trainers\n- [Medical Segmentation Decathlon](http:\u002F\u002Fmedicaldecathlon.com\u002F) — 10 benchmark datasets in nnU-Net-compatible format for training and validation\n- [Zenodo: pretrained nnU-Net models](https:\u002F\u002Fzenodo.org\u002Frecord\u002F7783116) — community-shared pretrained models for abdominal organs and other structures\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Fnnunet-segmentation",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill nnunet-segmentation",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill nnunet-segmentation",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill nnunet-segmentation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fnnunet-segmentation\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]