Passed
Push — main ( 287682...fc78a5 )
by Fernando
01:27
created

torchio.external.imports.get_distinctipy()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
from __future__ import annotations
2
3
from importlib import import_module
4
from importlib.util import find_spec
5
from shutil import which
6
from types import ModuleType
7
8
9
def _check_module(*, module: str, extra: str, package: str | None = None) -> None:
10
    if find_spec(module) is None:
11
        name = module if package is None else package
12
        message = (
13
            f'The `{name}` package is required for this.'
14
            f' Install TorchIO with the `{extra}` extra:'
15
            f' `pip install torchio[{extra}]`.'
16
        )
17
        raise ImportError(message)
18
19
20
def _check_and_import(module: str, extra: str, **kwargs) -> ModuleType:
21
    _check_module(module=module, extra=extra, **kwargs)
22
    return import_module(module)
23
24
25
def get_pandas() -> ModuleType:
26
    return _check_and_import(module='pandas', extra='csv')
27
28
29
def get_distinctipy() -> ModuleType:
30
    return _check_and_import(module='distinctipy', extra='plot')
31
32
33
def get_ffmpeg() -> ModuleType:
34
    ffmpeg = _check_and_import(module='ffmpeg', extra='video', package='ffmpeg-python')
35
    _check_executable('ffmpeg')
36
    return ffmpeg
37
38
39
def _check_executable(executable: str) -> None:
40
    if which(executable) is None:
41
        message = (
42
            f'The `{executable}` executable is required for this. Install it from your'
43
            ' package manager or download it from the official website.'
44
        )
45
        raise FileNotFoundError(message)
46