Skip to content

Conversation

@JoshuaSiraj
Copy link
Collaborator

@JoshuaSiraj JoshuaSiraj commented Jun 16, 2025

Summary by CodeRabbit

  • Tests
    • Introduced a comprehensive integration test suite for the nnunet_pipeline CLI, covering help message display, argument validation, and end-to-end functionality with real datasets and mask saving strategies.
  • Bug Fixes
    • Improved the construction of label mappings during dataset finalization to ensure the background label is preserved and new regions are added correctly.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 16, 2025

📝 Walkthrough

Walkthrough

This update modifies the way label dictionaries are constructed in the nnUNet output logic, ensuring the background label is preserved during in-place updates. Additionally, a comprehensive integration test suite for the nnunet_pipeline CLI is introduced, covering help output, argument validation, and end-to-end dataset processing with real data and external tool integration.

Changes

Files/Paths Change Summary
src/imgtools/io/nnunet_output.py Refactored label dictionary construction in finalize_dataset to update in-place and preserve background label.
tests/integration/cli/nnunet_pipeline_cli.py Added new integration test suite for the nnunet_pipeline CLI, including fixtures and end-to-end tests.

Suggested labels

hackathon


Feedback:
The in-place update to the labels dictionary improves clarity and reduces the risk of inadvertently dropping essential entries like the background label. The new integration tests are well-structured and use fixtures effectively, which enhances maintainability. Consider adding docstrings to test methods for easier navigation, and keep test data paths configurable to support broader environments.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@JoshuaSiraj
Copy link
Collaborator Author

@jjjermiah

Added testing with RADCURE, only issue is that nnunet is not available for py13.

@JoshuaSiraj
Copy link
Collaborator Author

The issue with env is nnunet install on py313(osx-64)

Copy link
Contributor

@jjjermiah jjjermiah left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks great to me, to address the py313 issue, I recommend having a check in the cli entry point that lets the user know

@JoshuaSiraj
Copy link
Collaborator Author

looks great to me, to address the py313 issue, I recommend having a check in the cli entry point that lets the user know

Thanks! How do I deal with the dependency issue? I need to add nnunetv2 to test as a dependency, instead should I add it only to py311 and py312?

@JoshuaSiraj JoshuaSiraj marked this pull request as ready for review June 30, 2025 15:52
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
tests/integration/cli/nnunet_pipeline_cli.py (1)

96-96: Consider implementing pytest-snapshot for consistent output validation.

As suggested in previous reviews, using pytest-snapshot would help ensure the generated outputs remain consistent across test runs and catch any unintended changes in the pipeline output format.

This would involve capturing and comparing the generated dataset structure, JSON configurations, and file contents against known good snapshots.

🧹 Nitpick comments (2)
tests/integration/cli/nnunet_pipeline_cli.py (2)

12-13: Fix class naming and docstring accuracy.

The class name should follow PEP 8 conventions, and the docstring mentions the wrong CLI command.

-class TestnnUNetCLI:
-    """Integration tests for the autopipeline CLI command using collections from the test data."""
+class TestNnUNetCLI:
+    """Integration tests for the nnunet_pipeline CLI command using collections from the test data."""

63-70: Consider moving YAML file creation to a fixture.

The temporary YAML file creation could be moved to a fixture for better test organization and reusability.

+    @pytest.fixture(scope="function")
+    def roi_yaml_file(self, tmp_path):
+        """Create a temporary ROI mapping YAML file."""
+        roi_dict = {
+            "BRAINSTEM": "Brainstem",
+            "SPINALCORD": "SpinalCord", 
+            "LARYNX": "Larynx",
+        }
+        roi_yaml_path = tmp_path / "roi_match.yaml"
+        with roi_yaml_path.open("w") as f:
+            yaml.dump(roi_dict, f)
+        return roi_yaml_path

Then use roi_yaml_file fixture in the test method instead of creating the file inline.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4df690a and 69e697e.

⛔ Files ignored due to path filters (2)
  • pixi.lock is excluded by !**/*.lock and included by none
  • pixi.toml is excluded by none and included by none
📒 Files selected for processing (2)
  • src/imgtools/io/nnunet_output.py (1 hunks)
  • tests/integration/cli/nnunet_pipeline_cli.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`src/**/*.py`: Review the Python code for compliance with PEP 8 and PEP 257 (doc...

src/**/*.py: Review the Python code for compliance with PEP 8 and PEP 257 (docstring conventions). Ensure the following: - Variables and functions follow meaningful naming conventions. - Docstrings are present, accurate, and align with the implementation. - Code is efficient and avoids redundancy while adhering to DRY principles. - Consider suggestions to enhance readability and maintainability. - Highlight any potential performance issues, edge cases, or logical errors. - Ensure all imported libraries are used and necessary.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • src/imgtools/io/nnunet_output.py
`tests/**/*`: Review the test code written with Pytest. Confirm: - Tests cover a...

tests/**/*: Review the test code written with Pytest. Confirm: - Tests cover all critical functionality and edge cases. - Test descriptions clearly describe their purpose. - Pytest best practices are followed, such as proper use of fixtures. - Ensure the tests are isolated and do not have external dependencies (e.g., network calls). - Verify meaningful assertions and avoidance of redundant tests. - Test code adheres to PEP 8 style guidelines.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • tests/integration/cli/nnunet_pipeline_cli.py
🧠 Learnings (3)
📓 Common learnings
Learnt from: jjjermiah
PR: bhklab/med-imagetools#145
File: src/imgtools/utils/nnunet.py:0-0
Timestamp: 2024-11-29T21:18:38.153Z
Learning: Suggestions to modify the `save_json` function in `src/imgtools/utils/nnunet.py` to fix type annotations or add error handling are considered out of scope.
src/imgtools/io/nnunet_output.py (1)
Learnt from: jjjermiah
PR: bhklab/med-imagetools#145
File: src/imgtools/utils/nnunet.py:0-0
Timestamp: 2024-11-29T21:18:38.153Z
Learning: Suggestions to modify the `save_json` function in `src/imgtools/utils/nnunet.py` to fix type annotations or add error handling are considered out of scope.
tests/integration/cli/nnunet_pipeline_cli.py (3)
Learnt from: jjjermiah
PR: bhklab/med-imagetools#137
File: src/imgtools/dicom/sort/parser.py:132-137
Timestamp: 2024-11-21T21:03:45.548Z
Learning: Assertions are allowed for input validation throughout the project, including in `src/imgtools/dicom/sort/parser.py`.
Learnt from: jjjermiah
PR: bhklab/med-imagetools#137
File: src/imgtools/dicom/sort/utils.py:66-67
Timestamp: 2024-11-21T16:24:04.091Z
Learning: In the `src/imgtools/dicom/sort/utils.py` file and throughout the codebase, assertions are preferred for input validation instead of explicit type checks or raising exceptions.
Learnt from: jjjermiah
PR: bhklab/med-imagetools#137
File: src/imgtools/dicom/sort/utils.py:168-169
Timestamp: 2024-11-21T16:24:13.275Z
Learning: In `src/imgtools/dicom/sort/utils.py`, it's acceptable to use `assert` statements for input validation in the `read_tags` function.
🧬 Code Graph Analysis (1)
src/imgtools/io/nnunet_output.py (1)
src/imgtools/coretypes/base_masks.py (1)
  • roi_keys (161-163)
🔇 Additional comments (1)
src/imgtools/io/nnunet_output.py (1)

301-303: LGTM: Preserves background label correctly.

The change from reassigning to updating the labels dictionary in-place is a good fix. This ensures the background label (0) is preserved while adding ROI keys with proper incremental indexing, which aligns with nnUNet's expected label format.

Comment on lines +87 to +94
nnunet_result = subprocess.run([
"nnUNetv2_extract_fingerprint",
"-d", "1",
"--verify_dataset_integrity",
],
env=env,
stdout=subprocess.PIPE
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve subprocess call robustness.

The subprocess call lacks timeout and proper error handling, which could cause tests to hang or hide important error information.

         nnunet_result = subprocess.run([
             "nnUNetv2_extract_fingerprint",
             "-d", "1",
             "--verify_dataset_integrity",
             ],
             env=env,
-            stdout=subprocess.PIPE
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            timeout=300,  # 5 minute timeout
+            text=True
         )

Also consider logging the stderr output when the command fails for better debugging:

-        assert nnunet_result.returncode == 0, "nnUNetv2_extract_fingerprint failed"
+        assert nnunet_result.returncode == 0, f"nnUNetv2_extract_fingerprint failed: {nnunet_result.stderr}"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
nnunet_result = subprocess.run([
"nnUNetv2_extract_fingerprint",
"-d", "1",
"--verify_dataset_integrity",
],
env=env,
stdout=subprocess.PIPE
)
nnunet_result = subprocess.run([
"nnUNetv2_extract_fingerprint",
"-d", "1",
"--verify_dataset_integrity",
],
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=300, # 5 minute timeout
text=True
)
assert nnunet_result.returncode == 0, f"nnUNetv2_extract_fingerprint failed: {nnunet_result.stderr}"
🤖 Prompt for AI Agents
In tests/integration/cli/nnunet_pipeline_cli.py around lines 87 to 94, the
subprocess.run call lacks a timeout and error handling, risking hangs and
obscured errors. Add a timeout parameter to prevent indefinite blocking, use
check=True to raise an exception on failure, and catch
subprocess.CalledProcessError to log stderr output for better debugging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants