Skip to content

Commit da3240f

Browse files
authored
fixes issue of typing with py3.6 (#1942)
* less warning msg; remove PILImage types Signed-off-by: Wenqi Li <[email protected]> * remove engine type Signed-off-by: Wenqi Li <[email protected]> * temp tests Signed-off-by: Wenqi Li <[email protected]> * add quick py36 37 tests Signed-off-by: Wenqi Li <[email protected]> * temp tests Signed-off-by: Wenqi Li <[email protected]> * Revert "temp tests" This reverts commit deaed40. Signed-off-by: Wenqi Li <[email protected]> * Revert "temp tests" This reverts commit 3e8d8f4. Signed-off-by: Wenqi Li <[email protected]> * min test exclude senet test Signed-off-by: Wenqi Li <[email protected]> * update Signed-off-by: Wenqi Li <[email protected]> * temp test Signed-off-by: Wenqi Li <[email protected]> * Revert "temp test" This reverts commit 31f40a0. Signed-off-by: Wenqi Li <[email protected]> * update get gpu id Signed-off-by: Wenqi Li <[email protected]> * update docsstrings Signed-off-by: Wenqi Li <[email protected]>
1 parent 348cbe8 commit da3240f

File tree

7 files changed

+69
-41
lines changed

7 files changed

+69
-41
lines changed

.github/workflows/pythonapp.yml

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ jobs:
4141
# Git hub actions have 2 cores, so parallize pytype
4242
$(pwd)/runtests.sh --codeformat -j 2
4343
44-
quick-py3: # full dependencies installed
44+
quick-py3: # full dependencies installed tests for different OS
4545
runs-on: ${{ matrix.os }}
4646
strategy:
4747
fail-fast: false
@@ -105,7 +105,7 @@ jobs:
105105
env:
106106
QUICKTEST: True
107107

108-
min-dep-py3: # min dependencies installed
108+
min-dep-os: # min dependencies installed tests for different OS
109109
runs-on: ${{ matrix.os }}
110110
strategy:
111111
fail-fast: false
@@ -154,6 +154,51 @@ jobs:
154154
env:
155155
QUICKTEST: True
156156

157+
min-dep-py3: # min dependencies installed tests for different python
158+
runs-on: ubuntu-latest
159+
strategy:
160+
fail-fast: false
161+
matrix:
162+
python-version: [3.6, 3.7]
163+
timeout-minutes: 40
164+
steps:
165+
- uses: actions/checkout@v2
166+
- name: Set up Python ${{ matrix.python-version }}
167+
uses: actions/setup-python@v2
168+
with:
169+
python-version: ${{ matrix.python-version }}
170+
- name: Prepare pip wheel
171+
run: |
172+
which python
173+
python -m pip install --user --upgrade pip setuptools wheel
174+
- name: cache weekly timestamp
175+
id: pip-cache
176+
run: |
177+
echo "::set-output name=datew::$(date '+%Y-%V')"
178+
echo "::set-output name=dir::$(pip cache dir)"
179+
shell: bash
180+
- name: cache for pip
181+
uses: actions/cache@v2
182+
id: cache
183+
with:
184+
path: ${{ steps.pip-cache.outputs.dir }}
185+
key: ubuntu-latest-latest-pip-${{ steps.pip-cache.outputs.datew }}
186+
- name: Install the dependencies
187+
run: |
188+
# min. requirements
189+
python -m pip install torch==1.8.1
190+
python -m pip install -r requirements-min.txt
191+
python -m pip list
192+
BUILD_MONAI=0 python setup.py develop # no compile of extensions
193+
shell: bash
194+
- name: Run quick tests (CPU ${{ runner.os }})
195+
run: |
196+
python -c 'import torch; print(torch.__version__); print(torch.rand(5,3))'
197+
python -c "import monai; monai.config.print_config()"
198+
python -m tests.min_tests
199+
env:
200+
QUICKTEST: True
201+
157202
GPU-quick-py3: # GPU with full dependencies
158203
if: github.repository == 'Project-MONAI/MONAI'
159204
strategy:

monai/handlers/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
import os
1313
from collections import OrderedDict
14-
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Union
14+
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Union
1515

1616
import numpy as np
1717
import torch
@@ -33,7 +33,7 @@
3333
]
3434

3535

36-
def stopping_fn_from_metric(metric_name: str) -> Callable[[Engine], Any]:
36+
def stopping_fn_from_metric(metric_name: str):
3737
"""
3838
Returns a stopping function for ignite.handlers.EarlyStopping using the given metric name.
3939
"""
@@ -44,7 +44,7 @@ def stopping_fn(engine: Engine):
4444
return stopping_fn
4545

4646

47-
def stopping_fn_from_loss() -> Callable[[Engine], Any]:
47+
def stopping_fn_from_loss():
4848
"""
4949
Returns a stopping function for ignite.handlers.EarlyStopping using the loss value.
5050
"""

monai/transforms/utility/array.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import logging
1717
import sys
1818
import time
19-
from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Sequence, Tuple, Union
19+
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
2020

2121
import numpy as np
2222
import torch
@@ -26,14 +26,8 @@
2626
from monai.transforms.utils import extreme_points_to_image, get_extreme_points, map_binary_to_indices
2727
from monai.utils import ensure_tuple, min_version, optional_import
2828

29-
if TYPE_CHECKING:
30-
from PIL.Image import Image as PILImageImage
31-
from PIL.Image import fromarray as pil_image_fromarray
32-
33-
has_pil = True
34-
else:
35-
PILImageImage, has_pil = optional_import("PIL.Image", name="Image")
36-
pil_image_fromarray, _ = optional_import("PIL.Image", name="fromarray")
29+
PILImageImage, has_pil = optional_import("PIL.Image", name="Image")
30+
pil_image_fromarray, _ = optional_import("PIL.Image", name="fromarray")
3731

3832
__all__ = [
3933
"Identity",
@@ -302,7 +296,7 @@ class ToTensor(Transform):
302296
Converts the input image to a tensor without applying any other transformations.
303297
"""
304298

305-
def __call__(self, img: Union[np.ndarray, torch.Tensor, PILImageImage]) -> torch.Tensor:
299+
def __call__(self, img) -> torch.Tensor:
306300
"""
307301
Apply the transform to `img` and make it contiguous.
308302
"""
@@ -316,7 +310,7 @@ class ToNumpy(Transform):
316310
Converts the input data to numpy array, can support list or tuple of numbers and PyTorch Tensor.
317311
"""
318312

319-
def __call__(self, img: Union[List, Tuple, np.ndarray, torch.Tensor, PILImageImage]) -> np.ndarray:
313+
def __call__(self, img) -> np.ndarray:
320314
"""
321315
Apply the transform to `img` and make it contiguous.
322316
"""
@@ -330,7 +324,7 @@ class ToPIL(Transform):
330324
Converts the input image (in the form of NumPy array or PyTorch Tensor) to PIL image
331325
"""
332326

333-
def __call__(self, img: Union[np.ndarray, torch.Tensor, PILImageImage]) -> PILImageImage:
327+
def __call__(self, img):
334328
"""
335329
Apply the transform to `img` and make it contiguous.
336330
"""

monai/transforms/utility/dictionary.py

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import copy
1919
import logging
20-
from typing import TYPE_CHECKING, Any, Callable, Dict, Hashable, List, Mapping, Optional, Sequence, Tuple, Union
20+
from typing import Any, Callable, Dict, Hashable, List, Mapping, Optional, Sequence, Tuple, Union
2121

2222
import numpy as np
2323
import torch
@@ -48,14 +48,7 @@
4848
ToTensor,
4949
)
5050
from monai.transforms.utils import extreme_points_to_image, get_extreme_points
51-
from monai.utils import ensure_tuple, ensure_tuple_rep, optional_import
52-
53-
if TYPE_CHECKING:
54-
from PIL.Image import Image as PILImageImage
55-
56-
has_pil = True
57-
else:
58-
PILImageImage, has_pil = optional_import("PIL.Image", name="Image")
51+
from monai.utils import ensure_tuple, ensure_tuple_rep
5952

6053
__all__ = [
6154
"Identityd",
@@ -401,9 +394,7 @@ def __init__(self, keys: KeysCollection, allow_missing_keys: bool = False) -> No
401394
super().__init__(keys, allow_missing_keys)
402395
self.converter = ToTensor()
403396

404-
def __call__(
405-
self, data: Mapping[Hashable, Union[np.ndarray, torch.Tensor, PILImageImage]]
406-
) -> Dict[Hashable, Union[np.ndarray, torch.Tensor, PILImageImage]]:
397+
def __call__(self, data: Mapping[Hashable, Any]) -> Dict[Hashable, Any]:
407398
d = dict(data)
408399
for key in self.key_iterator(d):
409400
d[key] = self.converter(d[key])
@@ -425,9 +416,7 @@ def __init__(self, keys: KeysCollection, allow_missing_keys: bool = False) -> No
425416
super().__init__(keys, allow_missing_keys)
426417
self.converter = ToNumpy()
427418

428-
def __call__(
429-
self, data: Mapping[Hashable, Union[np.ndarray, torch.Tensor, PILImageImage]]
430-
) -> Dict[Hashable, Union[np.ndarray, torch.Tensor, PILImageImage]]:
419+
def __call__(self, data: Mapping[Hashable, Any]) -> Dict[Hashable, Any]:
431420
d = dict(data)
432421
for key in self.key_iterator(d):
433422
d[key] = self.converter(d[key])
@@ -449,9 +438,7 @@ def __init__(self, keys: KeysCollection, allow_missing_keys: bool = False) -> No
449438
super().__init__(keys, allow_missing_keys)
450439
self.converter = ToPIL()
451440

452-
def __call__(
453-
self, data: Mapping[Hashable, Union[np.ndarray, torch.Tensor, PILImageImage]]
454-
) -> Dict[Hashable, Union[np.ndarray, torch.Tensor, PILImageImage]]:
441+
def __call__(self, data: Mapping[Hashable, Any]) -> Dict[Hashable, Any]:
455442
d = dict(data)
456443
for key in self.key_iterator(d):
457444
d[key] = self.converter(d[key])

monai/utils/module.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,14 +96,14 @@ def min_version(the_module, min_version_str: str = "") -> bool:
9696
Returns True if the module's version is greater or equal to the 'min_version'.
9797
When min_version_str is not provided, it always returns True.
9898
"""
99+
if not min_version_str:
100+
return True # always valid version
99101
if not hasattr(the_module, "__version__"):
100102
warnings.warn(f"{the_module} has no attribute __version__ in min_version check.")
101103
return True # min_version is the default, shouldn't be noisy
102-
if min_version_str:
103-
mod_version = tuple(int(x) for x in the_module.__version__.split(".")[:2])
104-
required = tuple(int(x) for x in min_version_str.split(".")[:2])
105-
return mod_version >= required
106-
return True # always valid version
104+
mod_version = tuple(int(x) for x in the_module.__version__.split(".")[:2])
105+
required = tuple(int(x) for x in min_version_str.split(".")[:2])
106+
return mod_version >= required
107107

108108

109109
def exact_version(the_module, version_str: str = "") -> bool:

tests/min_tests.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ def run_testsuit():
9494
"test_smartcachedataset",
9595
"test_spacing",
9696
"test_spacingd",
97+
"test_senet",
9798
"test_surface_distance",
9899
"test_zoom",
99100
"test_zoom_affine",

tests/utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -569,13 +569,14 @@ def query_memory(n=2):
569569
"""
570570
Find best n idle devices and return a string of device ids.
571571
"""
572-
bash_string = "nvidia-smi --query-gpu=utilization.gpu,power.draw,memory.used --format=csv,noheader,nounits"
572+
bash_string = "nvidia-smi --query-gpu=power.draw,temperature.gpu,memory.used --format=csv,noheader,nounits"
573573

574574
try:
575575
p1 = Popen(bash_string.split(), stdout=PIPE)
576576
output, error = p1.communicate()
577577
free_memory = [x.split(",") for x in output.decode("utf-8").split("\n")[:-1]]
578578
free_memory = np.asarray(free_memory, dtype=float).T
579+
free_memory[1] += free_memory[0] # combine 0/1 column measures
579580
ids = np.lexsort(free_memory)[:n]
580581
except (FileNotFoundError, TypeError, IndexError):
581582
ids = range(n) if isinstance(n, int) else []

0 commit comments

Comments
 (0)