Skip to content

deepecgkit.utils

Utility functions for CSV reading and pretrained weight management.

read_csv

read_csv(
    csv_file: str,
    delimiter: str = ",",
    transpose: bool = False,
    skip_header: bool = True,
    dtype: Optional[type] = 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 Optional[type]

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: Optional[type] = 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

list_pretrained_weights

list_pretrained_weights() -> Dict[str, str]

List all available pretrained weights with descriptions.

Source code in deepecgkit/utils/weights.py
def list_pretrained_weights() -> Dict[str, str]:
    """List all available pretrained weights with descriptions."""
    return {name: info["description"] for name, info in WEIGHTS_REGISTRY.items()}

load_pretrained_weights

load_pretrained_weights(
    weight_name: str,
    map_location: Optional[Union[str, device]] = 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 Optional[Union[str, device]]

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: Optional[Union[str, torch.device]] = 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,
    }