-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Replace pyupgrade with builtin Ruff's UP rule
#8606
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
📝 WalkthroughWalkthroughThis PR applies widespread syntactic modernizations across many files: converts typing constructs to Python 3.9+/3.10+ built-in generics and PEP 604 unions (e.g., Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✨ Finishing touches
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. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Greptile Overview
Greptile Summary
This PR modernizes Python syntax across five files by replacing outdated string formatting methods (.format()) with f-strings and updating lru_cache(maxsize=None) to the modern cache decorator. The changes align with Ruff's UP (pyupgrade) rule, consolidating linting tools to reduce tooling complexity while maintaining code quality. All modifications are syntactically equivalent transformations that adopt Python 3.6+ (f-strings) and Python 3.9+ (cache) best practices. The affected files span profiling utilities, TensorBoard/stats handlers, metrics utilities, and deepgrow datasets—all converting legacy string formatting to the recommended f-string syntax without altering any logic or output.
Important Files Changed
| Filename | Score | Overview |
|---|---|---|
| tests/profile_subclass/profiling.py | 5/5 | Replaced .format() with f-string in a single print statement for profiling output |
| monai/handlers/tensorboard_handlers.py | 5/5 | Converted two warning messages from .format() to f-strings in TensorBoardStatsHandler |
| monai/handlers/stats_handler.py | 5/5 | Modernized two warning messages by replacing .format() with f-strings |
| monai/metrics/utils.py | 5/5 | Replaced lru_cache(maxsize=None) with cache decorator and updated import |
| monai/apps/deepgrow/dataset.py | 5/5 | Converted two logging.info statements from .format() to f-strings |
Confidence score: 5/5
- This PR is safe to merge with minimal risk—all changes are non-breaking syntax modernizations with identical functional behavior.
- Score reflects straightforward string formatting upgrades and standard library improvements that are well-established Python best practices with no logic changes or potential runtime issues.
- No files require special attention—all transformations are syntactically equivalent and maintain identical output.
5 files reviewed, 2 comments
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Greptile Overview
Greptile Summary
This review covers only the changes made since the last review, not the entire PR. Since the previous reviews, two critical issues were introduced: a fatal syntax error in monai/losses/dice.py (missing closing quote) that will break imports, and semantically incorrect type hints in monai/losses/sure_loss.py (parameters typed as | None but using non-None sentinel defaults). Additionally, a logical inconsistency exists in monai/losses/perceptual.py where an error message says "Adversarial Loss" instead of "Perceptual Loss" (pre-existing but now more visible). The remaining changes continue the PR's goal of replacing pyupgrade with Ruff's UP rules by modernizing string formatting (.format() → f-strings) and type annotations (Union[X, Y] → X | Y, Optional[X] → X | None, lru_cache(maxsize=None) → cache). These syntactic updates are safe and maintain backward compatibility via from __future__ import annotations already present throughout the codebase.
Important Files Changed
| Filename | Score | Overview |
|---|---|---|
| monai/losses/dice.py | 1/5 | BREAKING: Missing closing quote in f-string causes syntax error on line 497 |
| monai/losses/sure_loss.py | 2/5 | Incorrect type hints: eps and complex_input typed as | None but use non-None sentinel defaults |
| monai/losses/perceptual.py | 4/5 | String formatting updated but error message incorrectly says "Adversarial Loss" instead of "Perceptual Loss" |
| monai/handlers/tensorboard_handlers.py | 4/5 | Format string conversion loses space separator on line 260 (: becomes :) |
| monai/losses/ds_loss.py | 5/5 | Modernizes Union to pipe syntax; safe with postponed annotations |
| monai/losses/spatial_mask.py | 5/5 | Replaces Optional with PEP 604 syntax; functionally equivalent |
| monai/losses/focal_loss.py | 5/5 | Converts Optional to pipe syntax across four type annotations |
| monai/losses/adversarial_loss.py | 5/5 | Updates %-formatting to .format() in error message |
| monai/transforms/utility/array.py | 5/5 | Removes Union import and uses pipe syntax in two method signatures |
| monai/metrics/utils.py | 5/5 | Replaces lru_cache(maxsize=None) with Python 3.9+ cache decorator |
| monai/handlers/stats_handler.py | 5/5 | Converts two .format() calls to f-strings in warning messages |
| monai/apps/deepgrow/dataset.py | 5/5 | Updates logging statements to use f-strings instead of .format() |
| tests/profile_subclass/profiling.py | 5/5 | Replaces .format() with f-string in print statement |
Confidence score: 0/5
- This PR introduces a syntax error that will prevent the module from importing and break production code immediately.
- Score is 0/5 due to the fatal syntax error in
monai/losses/dice.py(missing quote) and semantically incorrect type hints inmonai/losses/sure_loss.pythat misrepresent the parameter contracts. Additional concerns include a copy-paste error inmonai/losses/perceptual.pyand a formatting inconsistency inmonai/handlers/tensorboard_handlers.py. - Critical attention required for
monai/losses/dice.py(line 497),monai/losses/sure_loss.py(lines 46-48, 153),monai/losses/perceptual.py(line 98), andmonai/handlers/tensorboard_handlers.py(line 260).
Additional Comments (1)
-
monai/apps/nnunet/nnunet_bundle.py, line 508-509 (link)style: Type annotations now use PEP 604 syntax but are redundant here since the string literals already enforce types. The
: strcan be removed from both lines
14 files reviewed, 8 comments
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Greptile Overview
Greptile Summary
This PR consolidates Python linting by replacing the standalone pyupgrade pre-commit hook with Ruff's built-in UP (pyupgrade) rules. The changes modernize Python syntax across the codebase: type hints are converted from typing.Union[A, B] and typing.Optional[T] to PEP 604 pipe-union syntax (A | B, T | None), .format() and % string formatting are replaced with f-strings, and functools.lru_cache(maxsize=None) is replaced with functools.cache. The .pre-commit-config.yaml removes the pyupgrade hook entirely and moves its exclusion patterns to the ruff hook, while pyproject.toml adds the UP rule to Ruff's lint selection. This architectural change reduces external dependencies, improves linting consistency, and simplifies CI/CD by unifying multiple syntax-modernization checks into a single tool.
Important Files Changed
| Filename | Score | Overview |
|---|---|---|
.pre-commit-config.yaml |
5/5 | Removes standalone pyupgrade hook and consolidates exclusions under ruff |
pyproject.toml |
5/5 | Adds Ruff's UP rule to lint selection, enabling built-in pyupgrade checks |
monai/losses/dice.py |
0/5 | String formatting update introduces syntax error (unclosed quote in error message) |
monai/losses/perceptual.py |
0/5 | String formatting update plus critical indexing bug (off-by-one in feature slice) |
tests/profile_subclass/profiling.py |
1/5 | F-string split across lines will truncate output (missing concatenation) |
monai/losses/sure_loss.py |
2/5 | Type hint conversions introduce incorrect None annotations for sentinel-value parameters |
monai/metrics/utils.py |
3/5 | Replaces lru_cache(maxsize=None) with cache, but function takes mutable default device=None |
monai/handlers/stats_handler.py |
3/5 | F-string replacements missing spacing in warning messages |
monai/handlers/tensorboard_handlers.py |
4/5 | F-string replacements missing spacing in warning messages |
monai/losses/focal_loss.py |
4/5 | Type hints modernized to `T |
monai/apps/deepgrow/dataset.py |
4.5/5 | Logging statements converted to multi-line f-strings correctly |
monai/losses/adversarial_loss.py |
5/5 | String formatting updated from % to .format() correctly |
monai/losses/ds_loss.py |
5/5 | Type hints modernized to PEP 604 union syntax correctly |
monai/losses/spatial_mask.py |
5/5 | Type hints modernized to `T |
monai/transforms/utility/array.py |
5/5 | Type hints modernized from Union to pipe-union syntax correctly |
monai/apps/nnunet/nnunet_bundle.py |
5/5 | Type hints modernized across all function signatures correctly |
Confidence score: 0/5
- This PR is NOT safe to merge due to critical syntax errors and logic bugs that will break production code immediately.
- Score reflects three blocking issues: unclosed string quote in
dice.py(syntax error), off-by-one indexing bug inperceptual.py(incorrect computation), and broken output formatting inprofiling.py(missing string concatenation). Additionally, incorrect type hints insure_loss.pywill mislead type checkers and several f-string replacements introduce minor spacing issues in warning messages. - Pay close attention to
monai/losses/dice.py(syntax error on line497),monai/losses/perceptual.py(indexing bug on line 260 and copy-paste error on line 98),tests/profile_subclass/profiling.py(split f-string on lines 66-67), andmonai/losses/sure_loss.py(incorrect type hints forepsandcomplex_input).
Additional Comments (1)
-
monai/losses/perceptual.py, line 260 (link)logic: off-by-one slicing error: should be
l_idx:r_idxnotl_idx:i+r_idx. This will cause incorrect channel-wise feature indexing.
16 files reviewed, 5 comments
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Greptile Overview
Greptile Summary
This review covers only the changes made since the last review, not the entire PR. The developer has corrected a critical syntax error in monai/losses/dice.py that was identified in the previous review. The error was a missing closing quote in an error message string within the GeneralizedWassersteinDiceLoss class constructor. This fix addresses a SyntaxError that would have prevented the entire monai.losses.dice module from being imported. The correction changes the malformed string 'GDL to the properly quoted 'GDL', ensuring the error message displays correctly when invalid weighting_mode values are provided. This change is part of the broader PR goal to migrate linting from pyupgrade to Ruff's UP rule, which caught this pre-existing syntax error during the linting process.
Important Files Changed
| Filename | Score | Overview |
|---|---|---|
| monai/losses/dice.py | 5/5 | Fixed missing closing quote in error message string on line 497 |
Confidence score: 5/5
- This change is a straightforward syntax error fix with zero risk of unintended side effects
- The fix correctly addresses the exact issue identified in the previous review by properly closing the quoted string
- No files require special attention as the single-line fix is trivial and clearly correct
1 file reviewed, no comments
|
Hi @Borda thanks for the contribution. There's a lot of changes related to typing and f-strings rather than the PyUpgrade change, these are fine but it obscures what is being done here. What is the purpose of changing the |
Good call, but f-string is to be upgraded, and if original pyupgrade mised it, it is rather its issue than Ruff's doing its job, right?
removing
Yes, will do |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
monai/networks/nets/vista3d.py (1)
882-882: Fix torch.torch.Tensor typo throughout PositionEmbeddingRandom.
torch.torch.Tensoris invalid - should betorch.Tensor. This typo appears in:
_pe_encodingsignature (line 882)forwardreturn type (line 894)forward_with_coordssignature and return type (lines 910-911)- def _pe_encoding(self, coords: torch.torch.Tensor) -> torch.torch.Tensor: + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: - def forward(self, size: tuple[int, int, int]) -> torch.torch.Tensor: + def forward(self, size: tuple[int, int, int]) -> torch.Tensor: def forward_with_coords( - self, coords_input: torch.torch.Tensor, image_size: tuple[int, int, int] - ) -> torch.torch.Tensor: + self, coords_input: torch.Tensor, image_size: tuple[int, int, int] + ) -> torch.Tensor:Also applies to: 894-894, 910-911
🧹 Nitpick comments (4)
monai/networks/nets/spade_network.py (2)
159-159: F-string conversion looks good.The error message is clearer with f-string formatting. Static analysis suggests extracting long messages to the exception class, but this is a minor style preference that can be deferred.
258-258: F-string conversion looks good.Same improvement as line 159. The TRY003 hint (extract long messages to exception class) applies here too but is optional.
monai/networks/blocks/pos_embed_utils.py (2)
45-48: Docstrings use capitalizedListinstead oflist.Lines 45 and 48 reference
List[int]andList[float]but the signature uses lowercaselist. Update for consistency.- grid_size (int | List[int]): The size of the grid in each spatial dimension. + grid_size (int | list[int]): The size of the grid in each spatial dimension. embed_dim (int): The dimension of the embedding. spatial_dims (int): The number of spatial dimensions (2 for 2D, 3 for 3D). - scales (float | List[float]): The scale for every spatial dimension. If a single float is provided, + scales (float | list[float]): The scale for every spatial dimension. If a single float is provided,
95-95: Docstring uses capitalizedListinstead oflist.Line 95 references
List[int]but the signature uses lowercaselist. Update for consistency.- grid_size (List[int]): The size of the grid in each spatial dimension. + grid_size (int | list[int]): The size of the grid in each spatial dimension.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (32)
.pre-commit-config.yaml(1 hunks)monai/apps/detection/utils/anchor_utils.py(3 hunks)monai/networks/blocks/attention_utils.py(1 hunks)monai/networks/blocks/crossattention.py(2 hunks)monai/networks/blocks/denseblock.py(1 hunks)monai/networks/blocks/mlp.py(1 hunks)monai/networks/blocks/patchembedding.py(1 hunks)monai/networks/blocks/pos_embed_utils.py(2 hunks)monai/networks/blocks/rel_pos_embedding.py(2 hunks)monai/networks/blocks/selfattention.py(3 hunks)monai/networks/blocks/spatialattention.py(1 hunks)monai/networks/blocks/transformerblock.py(1 hunks)monai/networks/layers/simplelayers.py(1 hunks)monai/networks/layers/utils.py(1 hunks)monai/networks/layers/vector_quantizer.py(4 hunks)monai/networks/nets/ahnet.py(1 hunks)monai/networks/nets/autoencoderkl.py(2 hunks)monai/networks/nets/basic_unet.py(1 hunks)monai/networks/nets/dints.py(4 hunks)monai/networks/nets/dynunet.py(5 hunks)monai/networks/nets/netadapter.py(2 hunks)monai/networks/nets/quicknat.py(3 hunks)monai/networks/nets/resnet.py(1 hunks)monai/networks/nets/segresnet_ds.py(3 hunks)monai/networks/nets/senet.py(1 hunks)monai/networks/nets/spade_network.py(3 hunks)monai/networks/nets/swin_unetr.py(1 hunks)monai/networks/nets/vista3d.py(6 hunks)monai/networks/nets/vqvae.py(3 hunks)monai/networks/schedulers/rectified_flow.py(1 hunks)monai/networks/trt_compiler.py(6 hunks)monai/networks/utils.py(1 hunks)
✅ Files skipped from review due to trivial changes (3)
- monai/networks/utils.py
- monai/networks/nets/swin_unetr.py
- monai/networks/blocks/attention_utils.py
🚧 Files skipped from review as they are similar to previous changes (1)
- .pre-commit-config.yaml
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py
⚙️ CodeRabbit configuration file
Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.
Files:
monai/networks/blocks/crossattention.pymonai/networks/nets/senet.pymonai/networks/blocks/mlp.pymonai/networks/schedulers/rectified_flow.pymonai/networks/blocks/patchembedding.pymonai/networks/nets/spade_network.pymonai/networks/nets/vista3d.pymonai/networks/blocks/spatialattention.pymonai/networks/layers/utils.pymonai/networks/blocks/transformerblock.pymonai/networks/layers/simplelayers.pymonai/networks/blocks/denseblock.pymonai/networks/nets/vqvae.pymonai/networks/nets/netadapter.pymonai/networks/nets/autoencoderkl.pymonai/apps/detection/utils/anchor_utils.pymonai/networks/nets/dints.pymonai/networks/nets/ahnet.pymonai/networks/nets/resnet.pymonai/networks/blocks/selfattention.pymonai/networks/trt_compiler.pymonai/networks/nets/dynunet.pymonai/networks/blocks/pos_embed_utils.pymonai/networks/nets/quicknat.pymonai/networks/layers/vector_quantizer.pymonai/networks/nets/segresnet_ds.pymonai/networks/blocks/rel_pos_embedding.pymonai/networks/nets/basic_unet.py
🪛 Ruff (0.14.3)
monai/networks/nets/spade_network.py
159-159: Avoid specifying long messages outside the exception class
(TRY003)
258-258: Avoid specifying long messages outside the exception class
(TRY003)
monai/networks/nets/resnet.py
243-243: Avoid specifying long messages outside the exception class
(TRY003)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-py3 (3.11)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: packaging
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: build-docs
🔇 Additional comments (58)
monai/networks/blocks/spatialattention.py (1)
48-48: Type annotation modernization looks good.PEP 604 union syntax applied correctly. Semantically equivalent to
Optional[torch.dtype].monai/networks/blocks/denseblock.py (1)
14-14: PEP 585 modernization applied correctly.Import updated to use
collections.abc.Sequenceinstead oftyping.Sequence. This is the recommended practice for Python 3.9+ and aligns with Ruff's UP rule.monai/networks/nets/spade_network.py (1)
14-14: LGTM: Import modernization.Switching from
typing.Sequencetocollections.abc.Sequencealigns with PEP 585 and Ruff's UP rules.monai/networks/layers/vector_quantizer.py (2)
14-14: LGTM: Import modernization correct.The shift from
typing.Tupleto built-intupleandtyping.Sequencetocollections.abc.Sequencealigns with Python 3.9+ best practices.
90-90: LGTM: Type hint modernization consistent.All
Tuple[...]annotations correctly updated to built-intuple[...]syntax. Non-functional changes only.Also applies to: 167-167, 214-214
monai/networks/blocks/pos_embed_utils.py (2)
35-35: Type hints modernized correctly.PEP 604 union syntax and built-in generics applied properly.
88-88: Type hint modernized correctly.PEP 604 union syntax applied properly.
monai/networks/blocks/patchembedding.py (1)
56-56: Type hint modernized correctly.
Optional[dict]→dict | Noneis semantically equivalent and follows PEP 604.monai/apps/detection/utils/anchor_utils.py (3)
42-42: Import modernization correct.The shift to
collections.abc.Sequenceand removal oftyping.Listaligns with built-in generics usage throughout the file.
109-109: Type annotation correctly applied.Explicit
__annotations__declaration avoids unintended class attribute creation innn.Modulewhile providing type information. Matches actual usage at line 139.
367-367: Type annotation correctly applied.Consistent with parent class pattern. Matches actual usage at line 389.
monai/networks/layers/simplelayers.py (1)
16-16: LGTM—Standard library import modernization.The move from
typing.Sequencetocollections.abc.Sequencealigns with Python 3.9+ best practices.monai/networks/nets/senet.py (1)
122-122: LGTM—F-string modernization.The error message is now clearer and follows modern Python conventions.
monai/networks/nets/autoencoderkl.py (2)
190-190: LGTM—Built-in generic type.Using
list[nn.Module]instead ofList[nn.Module]is the modern approach for Python 3.9+.
340-340: LGTM—Built-in generic type.Consistent with the modernization in Encoder (line 190).
monai/networks/nets/resnet.py (1)
243-243: LGTM—F-string modernization.The error message formatting is now consistent with modern Python practices.
monai/networks/nets/ahnet.py (3)
141-141: LGTM—Modern union syntax.The
bool | Nonesyntax is cleaner and aligns with Python 3.10+ conventions.
177-177: LGTM—Modern union syntax.Consistent with the change in UpTransition (line 141).
288-288: LGTM—Modern union syntax.Consistent type hint modernization throughout the file.
monai/networks/blocks/crossattention.py (2)
43-45: LGTM—Type hint modernization.The constructor parameters now use the modern
X | Nonesyntax, consistent with Python 3.10+.
136-136: LGTM—Type hint modernization.The forward method signature is now consistent with the constructor's type hint style.
monai/networks/nets/basic_unet.py (1)
152-152: LGTM—Type hint modernization.The forward signature now uses modern union syntax. The docstring correctly reflects that
x_eis optional.monai/networks/blocks/transformerblock.py (1)
93-93: LGTM—Type hint modernization.Both optional parameters now use the modern
X | Nonesyntax.monai/networks/layers/utils.py (1)
130-130: Type annotation modernization looks good.The change from
Optional[tuple]totuple | Noneis semantically equivalent and aligns with PEP 604.monai/networks/blocks/rel_pos_embedding.py (2)
12-12: Import modernization is correct.Moving
Iterablefromtypingtocollections.abcfollows current best practices.
22-22: Type annotation update is correct.Built-in
tuplegeneric with union syntax is semantically equivalent to the previous annotation.monai/networks/trt_compiler.py (4)
21-21: Import cleanup is appropriate.Removing unused typing imports after modernization keeps the module clean.
244-246: Function signature modernization is correct.Parameter and return type annotations properly use built-in generics and union syntax.
604-605: Parameter type updates look good.Using
dict[str, Any] | Noneandstr | list[str] | Nonealigns with modern typing conventions.
628-628: Variable annotation is correctly updated.
dict[str, Any]is the modern equivalent ofDict[str, Any].monai/networks/nets/vqvae.py (3)
109-109: Type annotation properly modernized.Using built-in
tuplewithSequenceis the correct approach.
200-200: Type annotation update is correct.Consistent use of built-in
tuplegeneric across the codebase.
314-319: Parameter type annotations properly updated.Both
downsample_parametersandupsample_parametersuse consistent modern typing.monai/networks/nets/dints.py (4)
43-43: Interface signature modernization is correct.The union syntax maintains the same semantics for optional parameters.
177-177: Forward signature properly updated.Consistent with the interface definition.
305-305: Type annotation matches interface.Consistent use of union syntax across all forward method signatures.
576-577: F-string conversion improves readability.The f-string syntax is clearer than string concatenation for formatted output.
monai/networks/blocks/selfattention.py (3)
43-43: Parameter type annotation properly updated.Using
tuple | Noneis consistent with modern Python typing.
103-112: Attribute type annotations correctly modernized.All attribute annotations use union syntax consistently across
out_proj,qkv,to_q,to_k, andto_v.
155-155: Forward method signature properly updated.The optional
attn_maskparameter type is correctly expressed with union syntax.monai/networks/nets/segresnet_ds.py (3)
390-390: Return type annotation properly modernized.Using
None | torch.Tensor | list[torch.Tensor]correctly expresses the possible return types.
426-426: Forward method return type is consistent.Matches the
_forwardimplementation signature.
487-487: Complex return type properly expressed.The tuple of unions correctly represents the dual-branch output structure.
monai/networks/nets/dynunet.py (5)
14-15: Import updates are correct.Moving
Sequencetocollections.abcand removingList,Tuplefromtypingaligns with modern practices.
36-36: Attribute type annotation properly updated.Using
Optional[list[torch.Tensor]]is correct.
140-142: Parameter type annotations modernized.Using built-in
tuplefordropout,norm_name, andact_nameis correct.
173-173: Initialization annotation correctly updated.
list[torch.Tensor]properly replacesList[torch.Tensor].
327-328: Method signature parameters properly typed.Using
list[int]for channel parameters is the modern equivalent.monai/networks/nets/quicknat.py (3)
14-14: LGTM: Import modernization is correct.Switching to
collections.abc.Sequenceand removing unusedtypingimports after type hint updates is appropriate.
126-127: LGTM: Type hints correctly modernized.
Optional[X]→X | Noneis a correct PEP 604 modernization with no behavioral change.
363-364: LGTM: Type hints correctly modernized.
Union[Tuple, str]→tuple | strmodernizes to PEP 604 syntax and replaces deprecated unparameterizedTuplewith builtintuple.monai/networks/nets/vista3d.py (6)
15-16: LGTM. Import modernization aligns with PEP 604.The removal of
TupleandOptionalfrom typing and addition ofSequencefrom collections.abc correctly supports the built-in generic type hints used throughout the file.
695-695: LGTM. Return type modernized correctly.
772-772: LGTM. Return type modernized correctly.
876-876: LGTM. Parameter type modernized correctly.
894-894: Inconsistency: AI summary claims torch.torch.Tensor was fixed.The summary states
coords_inputtype was updated fromtorch.torch.Tensortotorch.Tensor, but the code still containstorch.torch.Tensorat lines 882, 894, 910, 911.
910-910: LGTM. Parameter type modernized correctly.The
image_sizeparameter type change fromTuple[int, int, int]totuple[int, int, int]is correct (separate from the torch.torch.Tensor issue flagged above).monai/networks/nets/netadapter.py (1)
14-14: Import cleanup aligns with built-in generic usage.Removing
Dictis correct since line 112 now usesdict[str, torch.Tensor].
|
There's a few things coderabbit has mentioned that are worth looking at, but the failed checks are all related to versioneer files that should be ignored I think. I'm not sure why from your changes why these aren't being ignored now. All other changes looked fine to me however. |
sure, will do it shortly :) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This PR replaces the pyupgrade pre-commit hook with Ruff's built-in UP (pyupgrade) rule, simplifying the linting toolchain while maintaining all the same code modernization capabilities. The changes apply Python 3.9+ syntax improvements across the codebase.
Key changes:
- Removed
pyupgradefrom.pre-commit-config.yamland enabled Ruff's "UP" rule inpyproject.toml - Modernized type hints using PEP 604 syntax (Union[X, Y] → X | Y, Optional[X] → X | None)
- Converted imports from
typingtocollections.abcfor standard collection types - Updated string formatting from % and .format() to f-strings
- Simplified redundant function calls (
float()on literals,lru_cache(maxsize=None)→cache)
Reviewed changes
Copilot reviewed 47 out of 47 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| .pre-commit-config.yaml | Removed pyupgrade hook and simplified Ruff exclusions since typing rewrites are now allowed |
| pyproject.toml | Added "UP" (pyupgrade) rule to Ruff's select list |
| tests/profile_subclass/profiling.py | Converted .format() to f-strings for print statements |
| monai/transforms/utility/array.py | Removed Union import, modernized type hints to use pipe operator |
| monai/networks/utils.py | Moved Iterable import from typing to collections.abc |
| monai/networks/trt_compiler.py | Removed typing imports (Dict, List, Tuple, Union), converted all type hints to builtin generics |
| monai/networks/schedulers/rectified_flow.py | Removed Union import, converted Optional[X] to X | None |
| monai/networks/nets/vqvae.py | Removed Tuple import, converted Tuple to builtin tuple |
| monai/networks/nets/vista3d.py | Moved Sequence to collections.abc, removed Optional/Tuple, modernized type hints |
| monai/networks/nets/swin_unetr.py | Removed redundant float() calls on numeric literals |
| monai/networks/nets/spade_network.py | Moved Sequence to collections.abc, converted % formatting to f-strings |
| monai/networks/nets/senet.py | Converted % formatting to f-strings |
| monai/networks/nets/segresnet_ds.py | Removed Union import, converted Union[None, X, Y] to None | X | Y |
| monai/networks/nets/resnet.py | Converted % formatting to f-strings |
| monai/networks/nets/quicknat.py | Removed typing imports, modernized Optional and Union type hints |
| monai/networks/nets/netadapter.py | Removed Dict import, converted Dict to builtin dict |
| monai/networks/nets/dynunet.py | Added collections.abc import, converted List/Tuple to builtin generics |
| monai/networks/nets/dints.py | Removed Optional import, converted .format() to f-strings, modernized type hints |
| monai/networks/nets/basic_unet.py | Removed Optional import, modernized type hints |
| monai/networks/nets/autoencoderkl.py | Removed List import, converted List to builtin list |
| monai/networks/nets/ahnet.py | Removed Union import, converted Union type hints |
| monai/networks/layers/vector_quantizer.py | Moved Sequence to collections.abc, removed Tuple, converted return types |
| monai/networks/layers/utils.py | Removed Optional import, converted Optional to pipe syntax |
| monai/networks/layers/simplelayers.py | Moved Sequence import from typing to collections.abc |
| monai/networks/blocks/transformerblock.py | Removed Optional import, converted Optional parameters |
| monai/networks/blocks/spatialattention.py | Removed Optional import, modernized type hints |
| monai/networks/blocks/selfattention.py | Removed Optional/Tuple/Union imports, converted all type hints |
| monai/networks/blocks/rel_pos_embedding.py | Moved Iterable to collections.abc, removed Tuple, modernized hints |
| monai/networks/blocks/pos_embed_utils.py | Removed List/Union imports, converted to builtin generics |
| monai/networks/blocks/patchembedding.py | Removed Optional import, converted Optional type hints |
| monai/networks/blocks/mlp.py | Removed Union import, converted Union type annotations |
| monai/networks/blocks/denseblock.py | Moved Sequence from typing to collections.abc |
| monai/networks/blocks/crossattention.py | Removed Optional/Tuple imports, modernized type hints |
| monai/networks/blocks/attention_utils.py | Removed Tuple import, converted Tuple to builtin tuple |
| monai/metrics/utils.py | Changed lru_cache(maxsize=None) to cache decorator |
| monai/losses/sure_loss.py | Removed Optional import, converted Optional type hints |
| monai/losses/spatial_mask.py | Removed Optional import, modernized type hints |
| monai/losses/perceptual.py | Converted % formatting to .format() (inconsistent with other changes) |
| monai/losses/focal_loss.py | Removed Optional import, converted Optional type hints |
| monai/losses/ds_loss.py | Removed Union import, converted Union type hints |
| monai/losses/dice.py | Converted % formatting to f-strings, fixed typo (missing quote) |
| monai/losses/adversarial_loss.py | Converted % formatting to f-strings |
| monai/handlers/tensorboard_handlers.py | Converted .format() to f-strings |
| monai/handlers/stats_handler.py | Converted .format() to f-strings |
| monai/apps/nnunet/nnunet_bundle.py | Removed typing imports, modernized all type hints |
| monai/apps/detection/utils/anchor_utils.py | Removed List import, converted List to builtin list |
| monai/apps/deepgrow/dataset.py | Converted multi-line .format() calls to multi-line f-strings |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (2)
monai/networks/nets/netadapter.py (1)
14-14: TorchScript incompatible with PEP 585 syntax.Line 112 uses
dict[str, torch.Tensor]intorch.jit.isinstance, which TorchScript doesn't support. Revert totyping.Dict[str, torch.Tensor]and restore theDictimport at line 14.Based on past review: PyTorch 2.4 TorchScript requires
typing.Dict, not built-in generics.🔎 Proposed fix
-from typing import Any +from typing import Any, Dict- elif torch.jit.isinstance(x, dict[str, torch.Tensor]): + elif torch.jit.isinstance(x, Dict[str, torch.Tensor]):Also applies to: 112-112
monai/networks/schedulers/rectified_flow.py (1)
283-297: Docstring still uses old Union syntax.Line 293 documents
Union[int, None]while the signature now usesint | None. Update to match.Fix
- next_timestep (Union[int, None]): Optional next timestep. + next_timestep (int | None): Optional next timestep.
🧹 Nitpick comments (3)
monai/networks/blocks/pos_embed_utils.py (2)
45-48: Update docstrings to match lowercaselistin type hints.Lines 45 and 48 use capital
Listbut the actual type hints use lowercaselist.Suggested fix
- grid_size (int | List[int]): The size of the grid in each spatial dimension. + grid_size (int | list[int]): The size of the grid in each spatial dimension. embed_dim (int): The dimension of the embedding. spatial_dims (int): The number of spatial dimensions (2 for 2D, 3 for 3D). - scales (float | List[float]): The scale for every spatial dimension. If a single float is provided, + scales (float | list[float]): The scale for every spatial dimension. If a single float is provided, the same scale is used for all dimensions.
95-95: Update docstring to match type hint.Docstring should be
int | list[int]to match the actual type hint at line 88.Suggested fix
- grid_size (List[int]): The size of the grid in each spatial dimension. + grid_size (int | list[int]): The size of the grid in each spatial dimension.monai/networks/nets/dints.py (1)
575-578: F-string conversion is correct, but could be consolidated.The split across two f-strings is valid but unnecessary. Consider using a single f-string for clarity.
🔎 Optional consolidation
print( - f"{datetime.datetime.now()}" - f" - Length of input patch is recommended to be a multiple of {2 ** (num_depths + int(use_downsample)):d}." + f"{datetime.datetime.now()} - Length of input patch is recommended to be a multiple of {2 ** (num_depths + int(use_downsample)):d}." )
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (35)
.pre-commit-config.yamlmonai/apps/detection/utils/anchor_utils.pymonai/losses/ds_loss.pymonai/losses/perceptual.pymonai/metrics/utils.pymonai/networks/blocks/attention_utils.pymonai/networks/blocks/crossattention.pymonai/networks/blocks/denseblock.pymonai/networks/blocks/mlp.pymonai/networks/blocks/patchembedding.pymonai/networks/blocks/pos_embed_utils.pymonai/networks/blocks/rel_pos_embedding.pymonai/networks/blocks/selfattention.pymonai/networks/blocks/spatialattention.pymonai/networks/blocks/transformerblock.pymonai/networks/layers/simplelayers.pymonai/networks/layers/utils.pymonai/networks/layers/vector_quantizer.pymonai/networks/nets/ahnet.pymonai/networks/nets/autoencoderkl.pymonai/networks/nets/basic_unet.pymonai/networks/nets/dints.pymonai/networks/nets/dynunet.pymonai/networks/nets/netadapter.pymonai/networks/nets/quicknat.pymonai/networks/nets/resnet.pymonai/networks/nets/segresnet_ds.pymonai/networks/nets/senet.pymonai/networks/nets/spade_network.pymonai/networks/nets/swin_unetr.pymonai/networks/nets/vista3d.pymonai/networks/nets/vqvae.pymonai/networks/schedulers/rectified_flow.pymonai/networks/trt_compiler.pymonai/networks/utils.py
🚧 Files skipped from review as they are similar to previous changes (18)
- monai/networks/nets/autoencoderkl.py
- monai/losses/perceptual.py
- monai/networks/blocks/mlp.py
- monai/networks/nets/swin_unetr.py
- monai/networks/nets/vqvae.py
- monai/networks/layers/simplelayers.py
- monai/metrics/utils.py
- monai/networks/blocks/denseblock.py
- monai/networks/utils.py
- monai/networks/nets/basic_unet.py
- monai/networks/nets/vista3d.py
- monai/networks/blocks/selfattention.py
- monai/networks/blocks/patchembedding.py
- monai/apps/detection/utils/anchor_utils.py
- monai/networks/trt_compiler.py
- monai/networks/blocks/attention_utils.py
- monai/networks/nets/segresnet_ds.py
- monai/networks/nets/quicknat.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py
⚙️ CodeRabbit configuration file
Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.
Files:
monai/networks/layers/vector_quantizer.pymonai/losses/ds_loss.pymonai/networks/nets/resnet.pymonai/networks/blocks/spatialattention.pymonai/networks/nets/spade_network.pymonai/networks/layers/utils.pymonai/networks/blocks/transformerblock.pymonai/networks/blocks/pos_embed_utils.pymonai/networks/blocks/crossattention.pymonai/networks/nets/dynunet.pymonai/networks/nets/netadapter.pymonai/networks/nets/senet.pymonai/networks/nets/dints.pymonai/networks/schedulers/rectified_flow.pymonai/networks/nets/ahnet.pymonai/networks/blocks/rel_pos_embedding.py
🧬 Code graph analysis (1)
monai/networks/layers/vector_quantizer.py (1)
monai/networks/nets/vqvae.py (1)
quantize(438-440)
🪛 Ruff (0.14.10)
monai/networks/nets/resnet.py
243-243: Avoid specifying long messages outside the exception class
(TRY003)
monai/networks/nets/spade_network.py
159-159: Avoid specifying long messages outside the exception class
(TRY003)
258-258: Avoid specifying long messages outside the exception class
(TRY003)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (21)
- GitHub Check: CodeQL analysis (python)
- GitHub Check: Agent
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: packaging
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: build-docs
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-py3 (3.11)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-os (ubuntu-latest)
🔇 Additional comments (26)
monai/networks/nets/senet.py (1)
122-122: LGTM - f-string modernization.Error message formatting updated correctly as part of the broader pyupgrade → Ruff migration.
monai/networks/nets/resnet.py (1)
243-243: LGTM - f-string modernization.Error message formatting updated correctly as part of the broader pyupgrade → Ruff migration. The Ruff TRY003 hint can be ignored; the message is specific and clear.
monai/networks/nets/spade_network.py (3)
14-14: LGTM: Import modernizationCorrect migration from
typing.Sequencetocollections.abc.Sequenceper PEP 585.
159-159: f-string conversion correct; Ruff TRY003 is pedantic hereThe f-string improves readability. Ruff's TRY003 hint suggests moving the message to a custom exception class, but that's overkill for a simple validation error.
258-258: f-string conversion correct; Ruff TRY003 is pedantic hereSame as line 159: f-string improves readability, and the Ruff TRY003 hint is overly pedantic for this simple validation.
monai/networks/blocks/pos_embed_utils.py (2)
35-35: LGTM - type hints modernized correctly.PEP 604 union syntax with built-in generics is appropriate. The
__future__import at line 12 ensures compatibility.
88-88: LGTM - type hint modernized correctly.Consistent with the changes in
build_fourier_position_embedding.monai/networks/nets/ahnet.py (1)
141-141: LGTM - type hint modernization applied consistently.The three instances correctly update
Union[bool, None]tobool | Nonesyntax. No behavioral changes.Also applies to: 177-177, 288-288
monai/networks/nets/dints.py (3)
43-43: Type annotation modernized correctly.PEP 604 union syntax is appropriate here.
177-177: Type annotation modernized correctly.The implementation properly handles the None case.
305-305: Type annotation modernized correctly.Signature properly matches the interface definition.
monai/networks/blocks/crossattention.py (2)
42-44: Type annotations modernized correctly.The parameter type hints now use Python 3.10+ union syntax (
X | Noneinstead ofOptional[X],tupleinstead ofTuple). No behavioral changes.
135-135: Forward signature updated consistently.The
contextparameter type annotation follows the same modernization pattern.monai/networks/blocks/spatialattention.py (1)
47-47: Type annotation modernized.Consistent with Python 3.10+ style.
monai/losses/ds_loss.py (1)
71-71: Union syntax modernized.Changed to PEP 604 style (
|operator). No runtime impact.monai/networks/nets/dynunet.py (2)
14-15: Import modernization.Added
collections.abc.Sequence, updated typing imports to support builtin generics.
36-36: Type annotations use builtin generics.Changed
List→list,Tuple→tuplethroughout. Consistent with Python 3.10+ style.Also applies to: 140-142, 173-173, 327-328
monai/networks/layers/utils.py (1)
129-129: Signature updated with modern union syntax.Changed
Optional[tuple]totuple | None.monai/networks/blocks/transformerblock.py (1)
92-92: Forward parameters modernized.Both
contextandattn_maskuseX | Nonesyntax.monai/networks/blocks/rel_pos_embedding.py (2)
12-12: Import moved to collections.abc.Preferred source for
Iterablein modern Python.
22-22: Builtin tuple type used.Changed
Tuple→tuplein union type annotation.monai/networks/layers/vector_quantizer.py (4)
14-14: Import modernization is correct.Moved
Sequencetocollections.abcper Python 3.9+ conventions. Removed unusedTupleimport.
90-90: Return type annotation modernized correctly.Changed to built-in
tuple[...]syntax. Matches docstring and actual return statement.
167-167: Return type annotation updated correctly.Built-in
tuple[...]matches the three-tensor return at line 194.
214-214: Return type annotation modernized correctly.Changed to built-in
tuple[...]. Consistent with return at line 225 and related code in vqvae.py..pre-commit-config.yaml (1)
34-38: Versioneer files are already properly excluded. The exclude pattern correctly matches bothversioneer.pyandmonai/_version.py. Ruff UP rules are properly configured inpyproject.toml. No changes needed to the exclude pattern.Likely an incorrect or invalid review comment.
|
trying to unblock CI in #8673 |
|
Hi @Borda we're working on the CICD issue, let's see if we've sorted things here. |
Yeah, seems my PR with fix was merged 😏 |
|
FYI, some linting issues were reported in #8683 |
There was a problem hiding this 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
Fix all issues with AI Agents 🤖
In @runtests.sh:
- Around line 609-611: The --exclude glob for ruff in the ruff check invocations
is using a regex-style caret ("^monai/_version.py") which won't match as
intended; update both ruff check --exclude entries to use a glob pattern (e.g.,
"monai/_version.py" or "**/monai/_version.py") so the monai/_version.py file is
correctly excluded when running the ruff check commands.
🧹 Nitpick comments (1)
monai/apps/detection/utils/detector_utils.py (1)
94-94: Inconsistent spacing in similar expressions.Line 94 now has
{2 * spatial_dims}(with space), but line 98 still has{2* spatial_dims}(no space). Apply the same spacing for consistency.🔎 Proposed fix
- f"Expected target boxes to be a tensor of shape [N, {2* spatial_dims}], got {boxes.shape}.)." + f"Expected target boxes to be a tensor of shape [N, {2 * spatial_dims}], got {boxes.shape}.)."Also applies to: 98-98
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (11)
monai/apps/auto3dseg/bundle_gen.pymonai/apps/detection/networks/retinanet_detector.pymonai/apps/detection/utils/detector_utils.pyruntests.shtests/data/test_video_datasets.pytests/transforms/test_load_image.pytests/transforms/test_load_imaged.pytests/transforms/test_resample_to_match.pytests/transforms/test_resample_to_matchd.pytests/transforms/test_transform.pytests/utils/misc/test_monai_env_vars.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py
⚙️ CodeRabbit configuration file
Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.
Files:
tests/transforms/test_resample_to_matchd.pytests/transforms/test_transform.pytests/utils/misc/test_monai_env_vars.pytests/transforms/test_load_image.pytests/data/test_video_datasets.pymonai/apps/detection/utils/detector_utils.pymonai/apps/auto3dseg/bundle_gen.pymonai/apps/detection/networks/retinanet_detector.pytests/transforms/test_resample_to_match.pytests/transforms/test_load_imaged.py
🧬 Code graph analysis (6)
tests/transforms/test_transform.py (1)
tests/utils/misc/test_monai_env_vars.py (2)
setUpClass(23-25)tearDownClass(28-34)
tests/utils/misc/test_monai_env_vars.py (6)
tests/data/test_video_datasets.py (1)
setUpClass(101-126)tests/transforms/test_load_image.py (4)
setUpClass(190-201)setUpClass(473-478)tearDownClass(204-206)tearDownClass(481-483)tests/transforms/test_load_imaged.py (2)
setUpClass(159-166)tearDownClass(169-171)tests/transforms/test_resample_to_match.py (2)
setUpClass(50-60)tearDownClass(63-65)tests/transforms/test_resample_to_matchd.py (2)
setUpClass(40-50)tearDownClass(53-55)tests/transforms/test_transform.py (2)
setUpClass(35-37)tearDownClass(40-45)
tests/data/test_video_datasets.py (6)
tests/transforms/test_load_image.py (2)
setUpClass(190-201)setUpClass(473-478)tests/transforms/test_load_imaged.py (1)
setUpClass(159-166)tests/transforms/test_resample_to_match.py (1)
setUpClass(50-60)tests/transforms/test_resample_to_matchd.py (1)
setUpClass(40-50)tests/transforms/test_transform.py (1)
setUpClass(35-37)tests/utils/misc/test_monai_env_vars.py (1)
setUpClass(23-25)
monai/apps/detection/networks/retinanet_detector.py (1)
monai/transforms/utils_pytorch_numpy_unification.py (1)
max(461-481)
tests/transforms/test_resample_to_match.py (4)
tests/transforms/test_load_imaged.py (2)
setUpClass(159-166)tearDownClass(169-171)tests/transforms/test_resample_to_matchd.py (2)
setUpClass(40-50)tearDownClass(53-55)tests/transforms/test_transform.py (2)
setUpClass(35-37)tearDownClass(40-45)tests/utils/misc/test_monai_env_vars.py (2)
setUpClass(23-25)tearDownClass(28-34)
tests/transforms/test_load_imaged.py (2)
tests/transforms/test_resample_to_match.py (2)
setUpClass(50-60)tearDownClass(63-65)tests/utils/misc/test_monai_env_vars.py (2)
setUpClass(23-25)tearDownClass(28-34)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: min-dep-py3 (3.11)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: build-docs
- GitHub Check: packaging
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: quick-py3 (macOS-latest)
🔇 Additional comments (10)
monai/apps/auto3dseg/bundle_gen.py (1)
399-399: LGTM! Formatting consistency improved.Spacing around the
+operator aligns with PEP 8. No functional impact.monai/apps/detection/networks/retinanet_detector.py (1)
790-790: LGTM — formatting improvement.Proper spacing after comma aligns with PEP 8.
tests/transforms/test_load_imaged.py (1)
160-160: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
Also applies to: 171-171
tests/transforms/test_resample_to_match.py (1)
51-51: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
Also applies to: 65-65
tests/transforms/test_resample_to_matchd.py (1)
41-41: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
Also applies to: 55-55
tests/data/test_video_datasets.py (1)
102-102: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
tests/utils/misc/test_monai_env_vars.py (1)
24-24: LGTM - Modern super() syntax.Correct Python 3 modernization. No behavioral change.
Also applies to: 34-34
tests/transforms/test_load_image.py (1)
191-191: LGTM: Modern super() syntax.The simplified
super()form is correct and preferred for Python 3+.Also applies to: 206-206, 474-474, 483-483
tests/transforms/test_transform.py (1)
36-36: LGTM: Modern super() syntax.Consistent with Python 3+ best practices and other test files in the codebase.
Also applies to: 45-45
runtests.sh (1)
609-609: Confirm understanding of risks from--unsafe-fixes.The
--unsafe-fixesflag applies fixes that may alter runtime behavior or remove comments. Ensure the team has reviewed what changes this enables for the UP rule migration and explicitly accepts the risk.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Fix all issues with AI Agents 🤖
In @monai/networks/nets/spade_network.py:
- Around line 260-264: The error message in the divisibility check inside
spade_network.py is misleading: when the condition in the block that raises
ValueError (the check using s_ / (2 ** len(channels)) != s_ // (2 **
len(channels))) fails, update the ValueError text to state the correct divisor
"2 ** {len(channels)}" instead of "{len(channels)}"; adjust the f-string in that
raise in the same style as the encoder fix so it reads that the shape at
position {s_ind}, {s_} is not divisible by 2 ** {len(channels)} and retains the
surrounding context text.
- Around line 162-165: The ValueError message in spade_network.py inside the
check that raises for input-size divisibility is misleading; update the raise in
the block (the raise ValueError in the input-shape/divisibility check inside the
SPADE network construction) to state that each dimension must be divisible by 2
** len(channels) (or include the computed divisor variable like divisor = 2 **
len(channels) and use it in the message) instead of saying "divisible by
{len(channels)}", and keep the rest of the context (shape position and values)
in the message.
🧹 Nitpick comments (2)
monai/utils/profiling.py (1)
340-340: Remove unusednoqadirective.Ruff reports that
N805is not enabled, making thenoqadirective unnecessary. Clean up by removing it.🔎 Proposed fix
- def __iter__(_self): # noqa: N805 pylint: disable=E0213 + def __iter__(_self): # pylint: disable=E0213monai/networks/nets/spade_network.py (1)
158-165: Consider extracting shared validation logic.The input shape validation (length check + divisibility check) is duplicated between
SPADEEncoderandSPADEDecoder. Extracting to a shared helper would reduce duplication.Also applies to: 257-264
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (11)
monai/networks/nets/ahnet.pymonai/networks/nets/autoencoder.pymonai/networks/nets/densenet.pymonai/networks/nets/fullyconnectednet.pymonai/networks/nets/generator.pymonai/networks/nets/hovernet.pymonai/networks/nets/patchgan_discriminator.pymonai/networks/nets/regressor.pymonai/networks/nets/spade_network.pymonai/utils/profiling.pyruntests.sh
✅ Files skipped from review due to trivial changes (1)
- monai/networks/nets/densenet.py
🚧 Files skipped from review as they are similar to previous changes (1)
- monai/networks/nets/ahnet.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py
⚙️ CodeRabbit configuration file
Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.
Files:
monai/networks/nets/fullyconnectednet.pymonai/networks/nets/regressor.pymonai/networks/nets/autoencoder.pymonai/networks/nets/generator.pymonai/networks/nets/hovernet.pymonai/networks/nets/patchgan_discriminator.pymonai/utils/profiling.pymonai/networks/nets/spade_network.py
🪛 Ruff (0.14.10)
monai/utils/profiling.py
340-340: Unused noqa directive (non-enabled: N805)
Remove unused noqa directive
(RUF100)
monai/networks/nets/spade_network.py
159-159: Avoid specifying long messages outside the exception class
(TRY003)
258-258: Avoid specifying long messages outside the exception class
(TRY003)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: packaging
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: build-docs
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-py3 (3.11)
🔇 Additional comments (9)
monai/networks/nets/hovernet.py (1)
156-156: LGTM - f-string modernization.Correct conversion from printf-style to f-string formatting. Output identical, style improved.
monai/networks/nets/regressor.py (1)
99-99: LGTM - f-string modernization.Correct conversion. Functionally equivalent.
monai/networks/nets/fullyconnectednet.py (1)
79-79: LGTM - f-string modernization.All three module name conversions correct and functionally equivalent.
Also applies to: 139-139, 147-147
monai/networks/nets/generator.py (1)
100-100: LGTM - f-string modernization.Correct conversion.
monai/networks/nets/autoencoder.py (1)
151-151: LGTM - f-string modernization.All three module name conversions correct and functionally equivalent.
Also applies to: 202-202, 218-218
monai/networks/nets/patchgan_discriminator.py (2)
94-94: LGTM: f-string modernization for module naming.Conversion from
%formatting to f-string is correct and improves readability.
195-195: LGTM: f-string modernization for layer naming.Conversion from
%formatting to f-string is correct and improves readability.runtests.sh (1)
609-611: Exclusion patterns corrected.The glob patterns now correctly exclude versioneer files without regex syntax. The
--unsafe-fixesflag is appropriately applied only when fixing.monai/networks/nets/spade_network.py (1)
14-14: LGTM: Import modernization.Correctly moves from
typing.Sequencetocollections.abc.Sequence.
Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
Signed-off-by: Jirka Borovec <[email protected]> Signed-off-by: jirka <[email protected]>
### Description This consolidates the version bumps from Project-MONAI#8675, Project-MONAI#8676, Project-MONAI#8677, Project-MONAI#8678, and Project-MONAI#8679 into one PR for faster CICD and review. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [ ] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [ ] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: Eric Kerfoot <[email protected]> Signed-off-by: Yun Liu <[email protected]> Co-authored-by: Yun Liu <[email protected]> Signed-off-by: jirka <[email protected]>
Co-authored-by: Copilot <[email protected]> Signed-off-by: Jirka Borovec <[email protected]> Signed-off-by: jirka <[email protected]>
…NAI#8682) Replaced the unsafe `zipfile.extractall()` in `_download_from_ngc_private` with MONAI's safe extraction utility. Prevents path traversal via crafted zip member paths (CWE-22). ### Description This changes _download_from_ngc_private() to use the same safe zip extraction path as the other bundle download sources. The previous code used ZipFile.extractall() directly, which could allow Zip Slip path traversal if a malicious archive is downloaded. Now extraction validates member paths and keeps writes within the target directory. --------- Signed-off-by: Yue (Knox) Liu <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: YunLiu <[email protected]> Signed-off-by: jirka <[email protected]>
Signed-off-by: Jirka Borovec <[email protected]> Signed-off-by: jirka <[email protected]>
for more information, see https://pre-commit.ci Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
…indices=True) Project-MONAI#8656 (Project-MONAI#8657) Fixes Project-MONAI#8656 Distance_transform_edt indices preallocation to use channel-first (C, spatial_dims, ...) layout for both torch/cuCIM and NumPy/SciPy paths, resolving “indices array has wrong shape” errors when return_indices=True. ### Description ``` import torch from monai.transforms.utils import distance_transform_edt img = torch.tensor([[[0, 0, 1], [0, 1, 1], [1, 1, 1]]], dtype=torch.float32) # shape (1, 3, 3) # Previously raised: RuntimeError: indices array has wrong shape indices = distance_transform_edt(img, return_distances=False, return_indices=True) print(indices.shape) # now: (1, 2, 3, 3) ``` ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [ ] New tests added to cover the changes. - [x] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [x] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: alexanderjaus <[email protected]> Co-authored-by: Eric Kerfoot <[email protected]> Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
This reverts commit 0b4c686. Signed-off-by: jirka <[email protected]>
…tools.lru_cache(maxsize=None). Functionally they are the same when lru_cache is used with maxsize=None. Signed-off-by: jirka <[email protected]>
pyupgrade with builtin Ruff's UP rule + (yesqa with RUF100)pyupgrade with builtin Ruff's UP rule
Signed-off-by: jirka <[email protected]>
Signed-off-by: jirka <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 7
🤖 Fix all issues with AI Agents
In @monai/apps/nnunet/nnunet_bundle.py:
- Line 44: Remove the unused parameter use_compressed_data from the function
signature in nnunet_bundle.py (delete the parameter name from the function
definition), remove any mention of use_compressed_data from the function
docstring/comments, and update any call sites or tests that pass
use_compressed_data to this function (or, if API compatibility must be
preserved, accept **kwargs and ignore it while issuing a deprecation warning).
Ensure no references to use_compressed_data remain in the file or internal
calls.
In @monai/data/wsi_reader.py:
- Line 213: The ValueError message in wsi_reader.py (the raise ValueError(...)
line) contains a stray closing parenthesis before the exclamation mark; update
the f-string in that raise (the raise ValueError(...) in the WSI reader code) to
remove the extra ")" so the message becomes: f"The maximum level of this image
is {n_levels - 1} while level={level} is requested!".
In @monai/losses/sure_loss.py:
- Line 48: The type hint for the parameter complex_input should be changed from
"bool | None" to just "bool" in the function/class signature where it is
declared (the complex_input parameter in sure_loss.py), making it consistent
with other uses (e.g., the later annotation bool = False at line 153) and
removing the unnecessary None union; update the signature and any corresponding
type annotations/comments to use bool only so the default False and boolean
checks work correctly.
In @monai/networks/blocks/mlp.py:
- Around line 56-58: The comment above the dropout type annotations is
outdated—update or remove it so it matches the current pipe-style annotations
used for self.drop1 and self.drop2 (e.g., change "Use Union[nn.Dropout,
nn.Identity] for type annotations" to "Use nn.Dropout | nn.Identity for type
annotations" or simply delete the comment since self.drop1 and self.drop2 are
self-explanatory).
In @monai/networks/nets/netadapter.py:
- Line 14: The code uses PEP 585 generics which TorchScript doesn't support;
restore the import of Dict from typing (add Dict to the imports where Any is
imported) and replace the runtime type check torch.jit.isinstance(x, dict[str,
torch.Tensor]) with torch.jit.isinstance(x, Dict[str, torch.Tensor]) so the
isinstance call uses typing.Dict; locate the import line that currently reads
"from typing import Any" and add Dict, and update the isinstance usage (around
the torch.jit.isinstance call referencing x) to use Dict[str, torch.Tensor].
In @monai/networks/nets/spade_network.py:
- Around line 162-165: The ValueError message in spade_network.py incorrectly
states divisibility by len(channels) though the check uses 2 ** len(channels);
update the f-string in the raise ValueError to reference 2 ** len(channels) (or
compute divisor = 2 ** len(channels) and insert that) and keep the context
showing position variables s_ind and s_ so the message reads that the shape at
position {s_ind}, {s_} is not divisible by {2 ** len(channels)} (or {divisor} if
you compute it).
- Around line 260-264: The decoder error message in spade_network.py (inside the
block that raises ValueError when input spatial size s_ is not divisible by 2 **
len(channels)) incorrectly reports "{len(channels)}" instead of "2 **
{len(channels)}"; update the f-string in that ValueError (same pattern used in
the encoder) to interpolate the actual divisor expression (2 ** len(channels))
so the message reads e.g. "... is not divisible by 2 ** {len(channels)}." and
ensure the surrounding text is clear and grammatically separated.
🧹 Nitpick comments (2)
monai/transforms/regularization/array.py (1)
44-44: LGTM - formatting improvement.The f-string debug syntax now uses
{alpha=}without spaces, which is the standard convention. The message is clear and concise.The static analysis TRY003 hint suggests extracting the message to a constant, but given its brevity this is purely optional.
monai/networks/layers/utils.py (1)
129-137: Consider adding docstring and__all__entry.This function lacks a docstring (unlike
get_norm_layer,get_act_layer, etc.) and isn't listed in__all__(line 19). Per coding guidelines, docstrings should describe parameters, return values, and exceptions.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (77)
.pre-commit-config.yamlmonai/apps/auto3dseg/bundle_gen.pymonai/apps/deepgrow/dataset.pymonai/apps/detection/networks/retinanet_detector.pymonai/apps/detection/utils/anchor_utils.pymonai/apps/detection/utils/detector_utils.pymonai/apps/nnunet/nnunet_bundle.pymonai/auto3dseg/analyzer.pymonai/data/wsi_reader.pymonai/handlers/stats_handler.pymonai/handlers/tensorboard_handlers.pymonai/losses/adversarial_loss.pymonai/losses/dice.pymonai/losses/ds_loss.pymonai/losses/focal_loss.pymonai/losses/perceptual.pymonai/losses/spatial_mask.pymonai/losses/sure_loss.pymonai/losses/unified_focal_loss.pymonai/metrics/meandice.pymonai/metrics/utils.pymonai/networks/blocks/attention_utils.pymonai/networks/blocks/crossattention.pymonai/networks/blocks/denseblock.pymonai/networks/blocks/mlp.pymonai/networks/blocks/patchembedding.pymonai/networks/blocks/pos_embed_utils.pymonai/networks/blocks/rel_pos_embedding.pymonai/networks/blocks/selfattention.pymonai/networks/blocks/spatialattention.pymonai/networks/blocks/transformerblock.pymonai/networks/layers/factories.pymonai/networks/layers/simplelayers.pymonai/networks/layers/utils.pymonai/networks/layers/vector_quantizer.pymonai/networks/nets/ahnet.pymonai/networks/nets/autoencoder.pymonai/networks/nets/autoencoderkl.pymonai/networks/nets/basic_unet.pymonai/networks/nets/densenet.pymonai/networks/nets/dints.pymonai/networks/nets/dynunet.pymonai/networks/nets/fullyconnectednet.pymonai/networks/nets/generator.pymonai/networks/nets/hovernet.pymonai/networks/nets/netadapter.pymonai/networks/nets/patchgan_discriminator.pymonai/networks/nets/quicknat.pymonai/networks/nets/regressor.pymonai/networks/nets/resnet.pymonai/networks/nets/segresnet_ds.pymonai/networks/nets/senet.pymonai/networks/nets/spade_network.pymonai/networks/nets/swin_unetr.pymonai/networks/nets/vista3d.pymonai/networks/nets/vqvae.pymonai/networks/schedulers/rectified_flow.pymonai/networks/trt_compiler.pymonai/networks/utils.pymonai/transforms/compose.pymonai/transforms/croppad/array.pymonai/transforms/regularization/array.pymonai/transforms/utility/array.pypyproject.tomlruntests.shtests/data/test_video_datasets.pytests/integration/test_integration_lazy_samples.pytests/integration/test_loader_semaphore.pytests/profile_subclass/profiling.pytests/profile_subclass/pyspy_profiling.pytests/transforms/compose/test_compose.pytests/transforms/test_load_image.pytests/transforms/test_load_imaged.pytests/transforms/test_resample_to_match.pytests/transforms/test_resample_to_matchd.pytests/transforms/test_transform.pytests/utils/misc/test_monai_env_vars.py
💤 Files with no reviewable changes (2)
- tests/profile_subclass/pyspy_profiling.py
- tests/integration/test_loader_semaphore.py
✅ Files skipped from review due to trivial changes (1)
- monai/networks/layers/factories.py
🚧 Files skipped from review as they are similar to previous changes (33)
- tests/profile_subclass/profiling.py
- monai/handlers/stats_handler.py
- monai/networks/utils.py
- monai/apps/auto3dseg/bundle_gen.py
- monai/apps/detection/networks/retinanet_detector.py
- monai/networks/nets/patchgan_discriminator.py
- monai/apps/detection/utils/detector_utils.py
- monai/losses/spatial_mask.py
- monai/networks/nets/ahnet.py
- monai/networks/nets/autoencoderkl.py
- tests/transforms/compose/test_compose.py
- pyproject.toml
- monai/networks/blocks/pos_embed_utils.py
- monai/networks/nets/fullyconnectednet.py
- tests/integration/test_integration_lazy_samples.py
- monai/networks/blocks/denseblock.py
- tests/transforms/test_load_imaged.py
- monai/networks/blocks/transformerblock.py
- monai/metrics/meandice.py
- monai/transforms/croppad/array.py
- monai/apps/detection/utils/anchor_utils.py
- monai/networks/nets/vqvae.py
- monai/transforms/utility/array.py
- monai/networks/nets/swin_unetr.py
- monai/transforms/compose.py
- tests/transforms/test_transform.py
- monai/networks/schedulers/rectified_flow.py
- monai/metrics/utils.py
- monai/networks/nets/segresnet_ds.py
- tests/data/test_video_datasets.py
- monai/apps/deepgrow/dataset.py
- monai/networks/nets/densenet.py
- monai/networks/nets/generator.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py
⚙️ CodeRabbit configuration file
Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.
Files:
monai/networks/layers/simplelayers.pytests/transforms/test_resample_to_match.pymonai/losses/adversarial_loss.pytests/transforms/test_load_image.pymonai/handlers/tensorboard_handlers.pymonai/losses/perceptual.pytests/transforms/test_resample_to_matchd.pymonai/networks/nets/hovernet.pymonai/networks/blocks/spatialattention.pymonai/networks/nets/resnet.pymonai/networks/nets/dints.pymonai/networks/nets/netadapter.pymonai/networks/layers/utils.pymonai/networks/nets/autoencoder.pymonai/networks/nets/vista3d.pymonai/networks/nets/regressor.pymonai/networks/blocks/patchembedding.pymonai/networks/blocks/selfattention.pymonai/networks/blocks/attention_utils.pymonai/networks/blocks/mlp.pymonai/losses/sure_loss.pymonai/networks/nets/senet.pymonai/networks/layers/vector_quantizer.pymonai/apps/nnunet/nnunet_bundle.pymonai/networks/nets/dynunet.pymonai/networks/trt_compiler.pymonai/losses/focal_loss.pymonai/networks/nets/basic_unet.pymonai/losses/ds_loss.pymonai/networks/blocks/crossattention.pymonai/networks/nets/quicknat.pymonai/networks/blocks/rel_pos_embedding.pytests/utils/misc/test_monai_env_vars.pymonai/auto3dseg/analyzer.pymonai/data/wsi_reader.pymonai/losses/dice.pymonai/losses/unified_focal_loss.pymonai/networks/nets/spade_network.pymonai/transforms/regularization/array.py
🧬 Code graph analysis (8)
tests/transforms/test_resample_to_matchd.py (5)
tests/data/test_video_datasets.py (1)
setUpClass(101-126)tests/transforms/test_load_imaged.py (2)
setUpClass(159-166)tearDownClass(169-171)tests/transforms/test_resample_to_match.py (2)
setUpClass(50-60)tearDownClass(63-65)tests/transforms/test_transform.py (2)
setUpClass(35-37)tearDownClass(40-45)tests/utils/misc/test_monai_env_vars.py (2)
setUpClass(23-25)tearDownClass(28-34)
monai/networks/nets/vista3d.py (2)
monai/networks/blocks/selfattention.py (1)
forward(154-216)monai/networks/blocks/transformerblock.py (1)
forward(91-98)
monai/networks/blocks/selfattention.py (2)
monai/networks/blocks/crossattention.py (1)
forward(135-183)monai/networks/blocks/transformerblock.py (1)
forward(91-98)
monai/networks/blocks/mlp.py (1)
monai/transforms/utility/array.py (1)
Identity(117-130)
monai/networks/layers/vector_quantizer.py (1)
monai/networks/nets/vqvae.py (1)
quantize(438-440)
monai/networks/nets/basic_unet.py (1)
monai/networks/nets/dints.py (9)
forward(43-44)forward(51-52)forward(62-63)forward(177-190)forward(305-313)forward(484-514)forward(628-630)forward(670-686)forward(1021-1043)
monai/networks/blocks/crossattention.py (2)
monai/networks/blocks/transformerblock.py (1)
forward(91-98)monai/networks/nets/diffusion_model_unet.py (13)
forward(117-126)forward(214-242)forward(308-316)forward(324-327)forward(418-442)forward(518-532)forward(631-646)forward(759-773)forward(835-843)forward(916-923)forward(1013-1032)forward(1146-1166)forward(1293-1312)
tests/utils/misc/test_monai_env_vars.py (1)
tests/transforms/test_transform.py (2)
setUpClass(35-37)tearDownClass(40-45)
🪛 Ruff (0.14.10)
monai/networks/nets/resnet.py
243-243: Avoid specifying long messages outside the exception class
(TRY003)
monai/apps/nnunet/nnunet_bundle.py
44-44: Unused function argument: use_compressed_data
(ARG001)
monai/auto3dseg/analyzer.py
916-916: Avoid specifying long messages outside the exception class
(TRY003)
918-918: Avoid specifying long messages outside the exception class
(TRY003)
monai/data/wsi_reader.py
213-213: Avoid specifying long messages outside the exception class
(TRY003)
monai/losses/dice.py
497-497: Avoid specifying long messages outside the exception class
(TRY003)
monai/losses/unified_focal_loss.py
220-220: Avoid specifying long messages outside the exception class
(TRY003)
monai/networks/nets/spade_network.py
159-159: Avoid specifying long messages outside the exception class
(TRY003)
258-258: Avoid specifying long messages outside the exception class
(TRY003)
monai/transforms/regularization/array.py
44-44: Avoid specifying long messages outside the exception class
(TRY003)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: packaging
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: build-docs
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-pytorch (2.7.1)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-py3 (3.11)
- GitHub Check: min-dep-pytorch (2.5.1)
🔇 Additional comments (54)
monai/networks/nets/regressor.py (1)
99-99: LGTM - Clean f-string modernization.Functionally equivalent to the previous % formatting. Produces identical layer names.
monai/networks/nets/senet.py (1)
121-123: LGTM: f-string conversion is correct.The error message now uses f-string formatting, improving readability with no functional change.
monai/networks/layers/simplelayers.py (1)
15-15: LGTM—correct PEP 585 modernization.Moving
Sequencefromtypingtocollections.abcis the right approach for Python 3.9+. All usages remain valid.tests/transforms/test_resample_to_match.py (1)
51-51: LGTM - Modern super() syntax.Correct Python 3+ idiom. No functional changes.
Also applies to: 65-65
tests/transforms/test_resample_to_matchd.py (1)
41-41: LGTM - Modern super() syntax.Correct Python 3+ idiom. No functional changes.
Also applies to: 55-55
tests/transforms/test_load_image.py (1)
191-191: LGTM - Modern super() syntax.Correct Python 3+ idiom applied consistently to both test classes. No functional changes.
Also applies to: 206-206, 474-474, 483-483
tests/utils/misc/test_monai_env_vars.py (1)
24-24: LGTM - Modern super() syntax.Correct Python 3+ idiom. No functional changes.
Also applies to: 34-34
monai/networks/nets/dynunet.py (5)
14-15: LGTM: Import modernization is correct.Sequence correctly moved to
collections.abc, and unusedList/Tupleremoved.
36-36: LGTM: Type annotation correctly modernized.
140-142: LGTM: Parameter type annotations correctly modernized.
173-173: LGTM: Instance variable annotation correctly modernized.
327-328: LGTM: Method parameter annotations correctly modernized.monai/networks/nets/hovernet.py (1)
156-156: LGTM — f-string modernization.Conversion from
%dformatting to f-string produces identical module names with improved readability.monai/networks/nets/autoencoder.py (1)
151-151: LGTM — f-string modernization across encode/intermediate/decode module naming.All three conversions (
%i→{i}) produce identical module names with cleaner syntax.Also applies to: 202-202, 218-218
monai/networks/nets/dints.py (2)
43-43: Type hint modernization is correct.The conversion from
Optional[torch.Tensor]totorch.Tensor | Nonefollows PEP 604 union syntax. Interface and implementation signatures are consistent.Also applies to: 177-177, 305-305
576-577: F-string concatenation is correct.The second f-string begins with a space (
-), so adjacent string concatenation produces proper spacing:"2025-01-06... - Length...". The prior comment's concern does not apply.monai/networks/layers/utils.py (1)
129-129: Type annotation modernization looks correct.The change from
Optional[tuple]totuple | Noneis semantically equivalent and consistent with the PEP 604 syntax already used elsewhere in this file (lines 22, 76, 105).monai/networks/layers/vector_quantizer.py (2)
14-14: Import modernization is correct.Moving
Sequencetocollections.abcaligns with PEP 585. Built-intuplereplacestyping.Tuple.
90-90: Python 3.9+ requirement confirmed;tuple[...]syntax is valid.Project requires Python 3.9+ per setup.cfg, making the built-in generic syntax appropriate. Changes are consistent across the file.
Also applies to: 167-167, 214-214
monai/networks/nets/spade_network.py (1)
14-14: LGTM: Import modernization correct.Moving
Sequencefromtypingtocollections.abcaligns with Python 3.9+ best practices.runtests.sh (1)
609-611: LGTM - exclusion patterns corrected.The glob patterns now correctly exclude versioneer files without the regex anchor that was flagged in previous review.
.pre-commit-config.yaml (2)
33-33: LGTM - simplified ruff args.The streamlined
["--fix"]aligns with the PR's goal to consolidate tooling.
34-38: LGTM - narrowed exclusions align with PR goals.The reduced exclude pattern to only versioneer files is consistent with applying type modernization across the codebase. The
^regex anchor is correct for pre-commit's exclude syntax.monai/networks/nets/resnet.py (1)
243-243: LGTM - f-string conversion is correct.The error message formatting modernization preserves the original behavior and improves code consistency.
monai/networks/blocks/patchembedding.py (1)
56-56: LGTM - type annotation modernized to PEP 604 syntax.The change from
Optional[dict]todict | Noneis semantically equivalent and aligns with modern Python typing conventions.monai/handlers/tensorboard_handlers.py (1)
283-283: LGTM - f-string conversion is correct.monai/auto3dseg/analyzer.py (2)
288-288: LGTM - debug log formatting modernized.F-string conversions for debug logs are consistent with the PR's modernization goals.
Also applies to: 369-369, 538-538
916-918: LGTM - error messages improved.The f-string conversion and operator spacing (
i + 1instead ofi+1) enhance readability while preserving the error message semantics.monai/networks/blocks/rel_pos_embedding.py (1)
12-12: LGTM - type annotations modernized to built-in generics.The migration from
typing.Tupleto built-intupleand movingIterabletocollections.abcfollows PEP 585 conventions for Python 3.9+.Also applies to: 22-22
monai/networks/blocks/attention_utils.py (1)
50-52: LGTM!Type hint modernization is correct. The bare
tupleannotation is consistent with the previous bareTupleusage.monai/networks/nets/basic_unet.py (1)
152-152: LGTM!Union syntax correctly represents the optional parameter. Matches docstring and runtime checks.
monai/networks/blocks/crossattention.py (2)
42-44: LGTM!Type hint updates to union syntax are correct and match the docstrings.
135-135: LGTM!Union syntax correctly represents the optional context parameter. Consistent with usage at line 148.
monai/networks/blocks/spatialattention.py (1)
47-47: LGTM!Type hint modernization is correct and consistent with similar parameters in related attention blocks.
monai/networks/trt_compiler.py (6)
21-21: LGTM!Import cleanup is correct. Removed unused typing imports while retaining
Any.
244-246: LGTM!Built-in generics and union syntax correctly represent the complex return type. Matches docstring at lines 250-262.
264-264: LGTM!Type annotation consistent with return type at line 246.
276-276: LGTM!Type annotation consistent with groups variable and function return type.
604-605: LGTM!Public API signature updates use correct built-in generics and union syntax. Changes are non-breaking (syntactic only).
628-628: LGTM!Built-in generic correctly replaces
Dict[str, Any].monai/losses/focal_loss.py (1)
155-155: LGTM! Type hint modernization is correct.The updates from
Optional[...]to... | Nonesyntax are accurate and follow Python 3.10+ conventions. No functional changes.Also applies to: 205-205, 227-227
monai/networks/blocks/selfattention.py (1)
42-42: LGTM! Type annotations properly modernized.All changes from
Union/Optional/Tupleto built-in generics with|syntax are correct. Class attribute annotations and parameter types are properly updated.Also applies to: 102-111, 154-154
monai/losses/ds_loss.py (1)
71-71: LGTM! Union type correctly modernized.The conversion from
Union[None, torch.Tensor, list[torch.Tensor]]toNone | torch.Tensor | list[torch.Tensor]is semantically equivalent and follows modern Python conventions.monai/networks/nets/quicknat.py (1)
14-14: LGTM! Type hints and imports correctly updated.The import of
Sequencefromcollections.abcand the modernization of type hints (Optional→|,Union→|,Tuple→tuple) are all correct for Python 3.9+.Also applies to: 126-127, 363-364
monai/networks/nets/vista3d.py (1)
15-16: LGTM! Comprehensive type hint modernization.All updates are correct:
Sequenceproperly imported fromcollections.abc- Return types updated to
tuple[...]- Parameters updated to
| Noneandtuple[int, int, int]No functional changes.
Also applies to: 695-695, 772-772, 876-876, 894-894, 910-910
monai/apps/nnunet/nnunet_bundle.py (3)
169-169: Type annotation modernization looks good.Consistent with PEP 604 syntax.
297-297: Type annotation update is correct.
425-431: Type annotation modernizations are correct.Return type and parameter annotations properly updated to PEP 604 syntax and built-in generics.
Also applies to: 520-522
monai/losses/unified_focal_loss.py (1)
220-220: Formatting change is trivial.No functional impact.
monai/losses/sure_loss.py (5)
14-14: Import cleanup is correct.Removing
Optionalin favor of PEP 604 union syntax is the intended change.
45-47: Type hints correctly modernized.The changes align with the sentinel pattern (
-1.0notNone) and intended usage.
134-134: Class-levelepstype hint is correct.Allowing
Nonehere is appropriate since resolution happens inforward(line 198).
152-153: Forward signature correctly updated.Line 153 properly uses
bool = Falsewithout| None, demonstrating the correct pattern.
198-199: eps resolution logic is correct.Properly converts
Noneto-1.0before callingsure_loss_function, which now expects onlyfloat.
Signed-off-by: jirka <[email protected]>
There was a problem hiding this 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
🤖 Fix all issues with AI Agents
In @monai/data/wsi_reader.py:
- Around line 213-215: The ValueError message in the raise ValueError f-string
contains a stray closing parenthesis at the end; edit the raise ValueError (the
f-string referencing n_levels and level) to remove the extra ')' so the message
reads "... while level={level} is requested!" without the unmatched parenthesis.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting
📒 Files selected for processing (3)
monai/auto3dseg/analyzer.pymonai/data/wsi_reader.pymonai/metrics/utils.py
🚧 Files skipped from review as they are similar to previous changes (1)
- monai/metrics/utils.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py
⚙️ CodeRabbit configuration file
Review the Python code for quality and correctness. Ensure variable names adhere to PEP8 style guides, are sensible and informative in regards to their function, though permitting simple names for loop and comprehension variables. Ensure routine names are meaningful in regards to their function and use verbs, adjectives, and nouns in a semantically appropriate way. Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings. Examine code for logical error or inconsistencies, and suggest what may be changed to addressed these. Suggest any enhancements for code improving efficiency, maintainability, comprehensibility, and correctness. Ensure new or modified definitions will be covered by existing or new unit tests.
Files:
monai/auto3dseg/analyzer.pymonai/data/wsi_reader.py
🪛 Ruff (0.14.10)
monai/auto3dseg/analyzer.py
916-916: Avoid specifying long messages outside the exception class
(TRY003)
918-920: Avoid specifying long messages outside the exception class
(TRY003)
monai/data/wsi_reader.py
213-215: Avoid specifying long messages outside the exception class
(TRY003)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: flake8-py3 (mypy)
- GitHub Check: quick-py3 (macOS-latest)
- GitHub Check: quick-py3 (ubuntu-latest)
- GitHub Check: flake8-py3 (codeformat)
- GitHub Check: quick-py3 (windows-latest)
- GitHub Check: flake8-py3 (pytype)
- GitHub Check: packaging
- GitHub Check: build-docs
- GitHub Check: min-dep-py3 (3.11)
- GitHub Check: min-dep-py3 (3.10)
- GitHub Check: min-dep-py3 (3.9)
- GitHub Check: min-dep-py3 (3.12)
- GitHub Check: min-dep-os (windows-latest)
- GitHub Check: min-dep-os (macOS-latest)
- GitHub Check: min-dep-pytorch (2.5.1)
- GitHub Check: min-dep-pytorch (2.6.0)
- GitHub Check: min-dep-pytorch (2.8.0)
- GitHub Check: min-dep-os (ubuntu-latest)
- GitHub Check: min-dep-pytorch (2.7.1)
🔇 Additional comments (2)
monai/auto3dseg/analyzer.py (2)
288-288: LGTM - formatting improvements.Spaces around operators improve PEP8 compliance.
Also applies to: 369-369, 538-538
916-916: LGTM - formatting improvements.Spaces around operators and multi-line formatting improve readability. The TRY003 hints are not applicable here since these are dynamic f-string messages with variable interpolation.
Also applies to: 918-920
ericspod
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good to me!
|
/build |
simplify the lintong and reduce the number of used tools to increase consistency without any formatting loss
Description
A few sentences describing the changes proposed in this pull request.
Types of changes
./runtests.sh -f -u --net --coverage../runtests.sh --quick --unittests --disttests.make htmlcommand in thedocs/folder.