Passed
Push — master ( 066103...5d2729 )
by Fernando
01:22
created

torchio.cli.apply_transform()   B

Complexity

Conditions 3

Size

Total Lines 56
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 42
nop 6
dl 0
loc 56
rs 8.872
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
# pylint: disable=import-outside-toplevel
2
3
"""Console script for torchio."""
4
import sys
5
import click
6
7
8
@click.command()
9
@click.argument('input-path', type=click.Path(exists=True))
10
@click.argument('transform-name', type=str)
11
@click.argument('output-path', type=click.Path())
12
@click.option(
13
    '--kwargs', '-k',
14
    type=str,
15
    help='String of kwargs, e.g. "degrees=(-5,15) num_transforms=3".',
16
)
17
@click.option(
18
    '--seed', '-s',
19
    type=int,
20
    help='Seed for PyTorch random number generator.',
21
)
22
@click.option(
23
    '--verbose/--no-verbose', '-v',
24
    type=bool,
25
    default=False,
26
    help='Print random transform parameters.',
27
)
28
def apply_transform(
29
        input_path,
30
        transform_name,
31
        output_path,
32
        kwargs,
33
        seed,
34
        verbose,
35
        ):
36
    """Apply transform to an image.
37
38
    \b
39
    Example:
40
    $ torchio-transform -k "degrees=(-5,15) num_transforms=3" input.nrrd RandomMotion output.nii
41
    """
42
    # Imports are placed here so that the tool loads faster if not being run
43
    import torchio.transforms as transforms
44
    from torchio.transforms.augmentation import RandomTransform
45
    from torchio.utils import apply_transform_to_file
46
47
    try:
48
        transform_class = getattr(transforms, transform_name)
49
    except AttributeError as error:
50
        message = f'Transform "{transform_name}" not found in torchio'
51
        raise ValueError(message) from error
52
53
    params_dict = get_params_dict_from_kwargs(kwargs)
54
    if issubclass(transform_class, RandomTransform):
55
        params_dict['seed'] = seed
56
    transform = transform_class(**params_dict)
57
    apply_transform_to_file(
58
        input_path,
59
        transform,
60
        output_path,
61
        verbose=verbose,
62
    )
63
    return 0
64
65
66
def get_params_dict_from_kwargs(kwargs):
67
    from torchio.utils import guess_type
68
    params_dict = {}
69
    if kwargs is not None:
70
        for substring in kwargs.split():
71
            try:
72
                key, value_string = substring.split('=')
73
            except ValueError as error:
74
                message = f'Arguments string "{kwargs}" not valid'
75
                raise ValueError(message) from error
76
77
            value = guess_type(value_string)
78
            params_dict[key] = value
79
    return params_dict
80
81
82
if __name__ == "__main__":
83
    # pylint: disable=no-value-for-parameter
84
    sys.exit(apply_transform())  # pragma: no cover
85