imgutils.sd.model

A utility module for reading and writing metadata from/to model files in the A41 WebUI format.

This module provides functions to read metadata from model files and save model files with custom metadata. It supports operations on SafeTensors files, which are a safe and efficient way to store tensors.

Note

torch and safetensors are required by this module. Please install them with the following command before using this module:

pip install dghs-imgutils[model]

Functions:

  • read_metadata: Reads metadata from a model file.

  • save_with_metadata: Saves a model file with custom metadata.

  • _check_env: Internal function to check if required dependencies are installed.

Dependencies:

  • torch

  • safetensors

read_metadata

imgutils.sd.model.read_metadata(model_file: str) Dict[str, str][source]

Read metadata from a model file and return it as a dictionary.

This function opens the specified model file using SafeTensors and extracts its metadata. The metadata is returned as a dictionary where both keys and values are strings.

Parameters:

model_file (str) – The path to the model file to read metadata from.

Returns:

A dictionary containing the metadata of the model file.

Return type:

Dict[str, str]

Raises:

EnvironmentError – If required dependencies are not installed.

Usage:
>>> metadata = read_metadata("path/to/model.safetensors")
>>> print(metadata)
{'key1': 'value1', 'key2': 'value2', ...}

save_with_metadata

imgutils.sd.model.save_with_metadata(src_model_file: str, dst_model_file: str, metadata: Dict[str, str], clear: bool = False)[source]

Save a model file with custom metadata.

This function reads the source model file, adds or updates its metadata, and saves it to a new destination file. It can optionally clear existing metadata before adding new metadata.

Parameters:
  • src_model_file (str) – The path to the source model file.

  • dst_model_file (str) – The path where the new model file will be saved.

  • metadata (Dict[str, str]) – A dictionary of metadata to add or update in the model file.

  • clear (bool) – If True, clear existing metadata before adding new metadata. Default is False.

Raises:

EnvironmentError – If required dependencies are not installed.

Usage:
>>> new_metadata = {"author": "John Doe", "version": "1.0"}
>>> save_with_metadata("input_model.safetensors", "output_model.safetensors", new_metadata)
# This will add or update the "author" and "version" metadata in the new file
>>> save_with_metadata("input_model.safetensors", "output_model.safetensors", new_metadata, clear=True)
# This will clear all existing metadata and only include the new metadata in the output file