Skip to content

deepecgkit.utils

Utility functions for CSV reading, pretrained weight management, and download locations.

read_csv

read_csv(
    csv_file: str,
    delimiter: str = ",",
    transpose: bool = False,
    skip_header: bool = True,
    dtype: type | None = None,
) -> tuple[np.ndarray, dict[str, int]]

Read CSV file and return data array and header mapping.

Parameters:

Name Type Description Default
csv_file str

Path to the CSV file

required
delimiter str

Column delimiter (default: ',')

','
transpose bool

Whether to transpose the data array

False
skip_header bool

Whether to skip the first row as header

True
dtype type | None

Data type for the numpy array

None

Returns:

Type Description
tuple[ndarray, dict[str, int]]

Tuple of (data_array, header_mapping)

Source code in deepecgkit/utils/__init__.py
def read_csv(
    csv_file: str,
    delimiter: str = ",",
    transpose: bool = False,
    skip_header: bool = True,
    dtype: type | None = None,
) -> tuple[np.ndarray, dict[str, int]]:
    """
    Read CSV file and return data array and header mapping.

    Args:
        csv_file: Path to the CSV file
        delimiter: Column delimiter (default: ',')
        transpose: Whether to transpose the data array
        skip_header: Whether to skip the first row as header
        dtype: Data type for the numpy array

    Returns:
        Tuple of (data_array, header_mapping)
    """
    if not os.path.exists(csv_file):
        raise FileNotFoundError(f"CSV file not found: {csv_file}")

    data: list[list[str]] = []
    header: dict[str, int] = {}

    try:
        with open(csv_file) as f:
            csv_data = csv.reader(f, delimiter=delimiter)

            if skip_header:
                try:
                    temp = next(csv_data)
                    header = {k: v for v, k in enumerate(temp)}
                except StopIteration as err:
                    raise ValueError("File is empty") from err

            for row in csv_data:
                data.append(row)

        if not data:
            raise ValueError("No data found in CSV file")

        data_array = np.array(data, dtype=dtype)

        if transpose:
            data_array = np.transpose(data_array)

        return data_array, header

    except Exception as err:
        raise ValueError(f"Error reading CSV file: {err!s}") from err

get_data_home

get_data_home() -> Path

Return the root directory for downloaded datasets.

Returns:

Type Description
Path

$DEEPECGKIT_HOME when that variable is set, otherwise

Path

~/.deepecgkit. Datasets live in its datasets/ subdirectory.

Source code in deepecgkit/utils/paths.py
def get_data_home() -> Path:
    """Return the root directory for downloaded datasets.

    Returns:
        ``$DEEPECGKIT_HOME`` when that variable is set, otherwise
        ``~/.deepecgkit``. Datasets live in its ``datasets/`` subdirectory.
    """
    override = os.environ.get(DATA_HOME_ENV)
    if override:
        return Path(override).expanduser()
    return Path.home() / ".deepecgkit"

list_pretrained_weights

list_pretrained_weights(
    include_unpublished: bool = False,
) -> dict[str, str]

List the pretrained weights that can be downloaded, with descriptions.

Parameters:

Name Type Description Default
include_unpublished bool

Also list registry entries that are reserved for a future release and have nothing to download yet

False
Source code in deepecgkit/utils/weights.py
def list_pretrained_weights(include_unpublished: bool = False) -> dict[str, str]:
    """List the pretrained weights that can be downloaded, with descriptions.

    Args:
        include_unpublished: Also list registry entries that are reserved for
            a future release and have nothing to download yet
    """
    return {
        name: info["description"]
        for name, info in WEIGHTS_REGISTRY.items()
        if include_unpublished or is_published(name)
    }

is_published

is_published(weight_name: str) -> bool

Report whether registered weights can actually be downloaded.

Parameters:

Name Type Description Default
weight_name str

Key into the pretrained weight registry

required

Returns:

Type Description
bool

False for unknown names and for entries whose URL is still a

bool

placeholder awaiting a published release.

Source code in deepecgkit/utils/weights.py
def is_published(weight_name: str) -> bool:
    """Report whether registered weights can actually be downloaded.

    Args:
        weight_name: Key into the pretrained weight registry

    Returns:
        False for unknown names and for entries whose URL is still a
        placeholder awaiting a published release.
    """
    info = WEIGHTS_REGISTRY.get(weight_name)
    if info is None:
        return False
    return not any(marker in info["url"] for marker in _PLACEHOLDER_URL_MARKERS)

load_pretrained_weights

load_pretrained_weights(
    weight_name: str,
    map_location: str | device | None = None,
    force_download: bool = False,
) -> dict

Load pretrained weights by name.

Parameters:

Name Type Description Default
weight_name str

Name of the pretrained weights

required
map_location str | device | None

Device to map weights to (e.g., "cpu", "cuda")

None
force_download bool

If True, re-download weights even if cached

False

Returns:

Type Description
dict

State dict containing model weights

Source code in deepecgkit/utils/weights.py
def load_pretrained_weights(
    weight_name: str,
    map_location: str | torch.device | None = None,
    force_download: bool = False,
) -> dict:
    """Load pretrained weights by name.

    Args:
        weight_name: Name of the pretrained weights
        map_location: Device to map weights to (e.g., "cpu", "cuda")
        force_download: If True, re-download weights even if cached

    Returns:
        State dict containing model weights
    """
    weight_path = download_weights(weight_name, force=force_download)
    return torch.load(weight_path, map_location=map_location, weights_only=True)

register_weights

register_weights(
    name: str,
    url: str,
    model_class: str,
    model_kwargs: dict,
    description: str = "",
) -> None

Register custom pretrained weights.

Parameters:

Name Type Description Default
name str

Unique name for the weights

required
url str

URL to download weights from

required
model_class str

Name of the model class these weights are for

required
model_kwargs dict

Keyword arguments to instantiate the model

required
description str

Human-readable description of the weights

''
Source code in deepecgkit/utils/weights.py
def register_weights(
    name: str,
    url: str,
    model_class: str,
    model_kwargs: dict,
    description: str = "",
) -> None:
    """Register custom pretrained weights.

    Args:
        name: Unique name for the weights
        url: URL to download weights from
        model_class: Name of the model class these weights are for
        model_kwargs: Keyword arguments to instantiate the model
        description: Human-readable description of the weights
    """
    WEIGHTS_REGISTRY[name] = {
        "url": url,
        "model_class": model_class,
        "model_kwargs": model_kwargs,
        "description": description,
    }