Skip to content

Assets

BaseAsset

Bases: Media, Generic[T]

Represents an assets with various properties.

type instance-attribute

type: str

The type of the assets.

params instance-attribute

params: T

The parameters for the assets.

from_media classmethod

from_media(media: Media) -> Self

Creates an assets from a media object.

Parameters:

Name Type Description Default
media Media

The media object.

required

Returns:

Type Description
Self

The assets.

Source code in src/mosaico/assets/base.py
@classmethod
def from_media(cls, media: Media) -> Self:
    """
    Creates an assets from a media object.

    :param media: The media object.
    :return: The assets.
    """
    return cls(**media.model_dump())

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> Self

Creates an assets from a dictionary.

Parameters:

Name Type Description Default
data Mapping[str, Any]

The dictionary data.

required

Returns:

Type Description
Self

The assets.

Source code in src/mosaico/assets/base.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> Self:
    """
    Creates an assets from a dictionary.

    :param data: The dictionary data.
    :return: The assets.
    """
    return cls.model_validate(data)

validate_params classmethod

validate_params(params: Any) -> T

Validates the parameters for the assets.

Parameters:

Name Type Description Default
params Any

The parameters to validate.

required

Returns:

Type Description
T

The validated parameters.

Source code in src/mosaico/assets/base.py
@classmethod
def validate_params(cls, params: Any) -> T:
    """
    Validates the parameters for the assets.

    :param params: The parameters to validate.
    :return: The validated parameters.
    """
    params_cls = cls.model_fields["params"].annotation
    params_cls = cast(type[T], params_cls)
    return params_cls.model_validate(params)

with_params

with_params(params: T | dict[str, Any]) -> Self

Returns a new assets with the specified parameters.

Parameters:

Name Type Description Default
params T | dict[str, Any]

The parameters to update.

required

Returns:

Type Description
Self

A new assets with the specified parameters.

Source code in src/mosaico/assets/base.py
def with_params(self, params: T | dict[str, Any]) -> Self:
    """
    Returns a new assets with the specified parameters.

    :param params: The parameters to update.
    :return: A new assets with the specified parameters.
    """
    if isinstance(params, BaseModel):
        params = params.model_dump(exclude_unset=True)

    if not isinstance(params, dict):
        raise ValueError("params must be a dict or a Pydantic model")

    existing_params = self.params.model_dump(exclude_unset=True)
    existing_params.update(params)

    self.params = self.validate_params(existing_params)

    return self

AssetType module-attribute

AssetType = Literal[
    "video", "image", "audio", "text", "subtitle"
]

An enumeration of the different types of assets that can be held in an assets.

Asset module-attribute

Represents an assets with various properties.

AssetParams module-attribute

Represents the parameters of an assets.

create_asset

create_asset(
    asset_type: AssetType,
    id: str | None = None,
    data: str | bytes | None = None,
    path: PathLike | None = None,
    metadata: dict[str, Any] | None = None,
    params: AssetParams | dict[str, Any] | None = None,
    **kwargs: Any
) -> Asset

Create an asset from the given asset type.

Parameters:

Name Type Description Default
asset_type AssetType

The asset type.

required
id str | None

The asset ID.

None
data str | bytes | None

The asset data.

None
path PathLike | None

The asset path.

None
metadata dict[str, Any] | None

The asset metadata. ;param params: The asset parameters.

None
kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
Asset

The asset.

Source code in src/mosaico/assets/factory.py
def create_asset(
    asset_type: AssetType,
    id: str | None = None,
    data: str | bytes | None = None,
    path: PathLike | None = None,
    metadata: dict[str, Any] | None = None,
    params: AssetParams | dict[str, Any] | None = None,
    **kwargs: Any,
) -> Asset:
    """
    Create an asset from the given asset type.

    :param asset_type: The asset type.
    :param id: The asset ID.
    :param data: The asset data.
    :param path: The asset path.
    :param metadata: The asset metadata.
    ;param params: The asset parameters.
    :param kwargs: Additional keyword arguments.
    :return: The asset.
    """
    asset_mod_name = f"mosaico.assets.{asset_type}"

    if not importlib.util.find_spec(asset_mod_name):
        raise InvalidAssetTypeError(asset_type)

    asset_mod = importlib.import_module(f"mosaico.assets.{asset_type}")
    asset_class = getattr(asset_mod, asset_type.capitalize() + "Asset")

    def _get_asset_class_default_params(asset_class: type[Asset]) -> AssetParams:
        params_field = asset_class.model_fields["params"]
        params_factory = params_field.default_factory
        if params_factory is None:
            raise ValueError(f"Asset class '{asset_class.__name__}' does not have a default params factory.")
        return params_factory()

    def _merge_params_with_dict(params: AssetParams, params_dict: dict[str, Any]) -> AssetParams:
        new_params = params.__class__.model_validate(params_dict)
        for field_name in new_params.model_fields_set:
            setattr(params, field_name, getattr(new_params, field_name))
        return params

    if params is not None:
        if isinstance(params, dict):
            default_params = _get_asset_class_default_params(asset_class)
            params = _merge_params_with_dict(default_params, params)

        kwargs["params"] = params

    if data is not None:
        return asset_class.from_data(data, id=id, path=path, metadata=metadata, **kwargs)

    if path is None:
        msg = "Either 'data' or 'path' must be provided."
        raise ValueError(msg)

    return asset_class.from_path(path, id=id, metadata=metadata, **kwargs)

get_asset_params_class

get_asset_params_class(
    asset_type: AssetType,
) -> type[AssetParams]

Get the asset parameters class for the given asset type.

Parameters:

Name Type Description Default
asset_type AssetType

The asset type.

required

Returns:

Type Description
type[AssetParams]

The asset parameters class.

Source code in src/mosaico/assets/factory.py
def get_asset_params_class(asset_type: AssetType) -> type[AssetParams]:
    """
    Get the asset parameters class for the given asset type.

    :param asset_type: The asset type.
    :return: The asset parameters class.
    """
    if asset_type == "subtitle":
        asset_type = "text"

    asset_mod_name = f"mosaico.assets.{asset_type}"

    if not importlib.util.find_spec(asset_mod_name):
        raise InvalidAssetTypeError(asset_type)

    asset_mod = importlib.import_module(asset_mod_name)
    asset_params_class = getattr(asset_mod, f"{asset_type.capitalize()}AssetParams")

    return asset_params_class

convert_media_to_asset

convert_media_to_asset(media: Media) -> Asset

Convert a media object to an asset.

Parameters:

Name Type Description Default
media Media

The media object to convert.

required

Returns:

Type Description
Asset

The asset object.

Raises:

Type Description
ValueError

If the media object does not have a MIME type or the MIME type is unsupported.

Source code in src/mosaico/assets/utils.py
def convert_media_to_asset(media: Media) -> Asset:
    """
    Convert a media object to an asset.

    :param media: The media object to convert.
    :return: The asset object.
    :raises ValueError: If the media object does not have a MIME type or the MIME type is unsupported.
    """
    if media.mime_type is None:
        raise ValueError("Media object does not have a MIME type.")
    asset_type = guess_asset_type_from_mime_type(media.mime_type)
    return create_asset(asset_type, **media.model_dump())

guess_asset_type_from_mime_type

guess_asset_type_from_mime_type(
    mime_type: str,
) -> AssetType

Guess the asset type from a MIME type.

Parameters:

Name Type Description Default
mime_type str

The MIME type to guess the asset type from.

required

Returns:

Type Description
AssetType

The asset type.

Source code in src/mosaico/assets/utils.py
def guess_asset_type_from_mime_type(mime_type: str) -> AssetType:
    """
    Guess the asset type from a MIME type.

    :param mime_type: The MIME type to guess the asset type from.
    :return: The asset type.
    """
    if mime_type.startswith("audio/"):
        return "audio"
    if mime_type.startswith("image/"):
        return "image"
    if mime_type.startswith("text/"):
        return "text"
    raise ValueError(f"Unsupported MIME type: {mime_type}")

check_user_provided_required_keys

check_user_provided_required_keys(
    data: dict, required_keys: Sequence[str]
) -> bool

Check if the user provided all required keys.

Parameters:

Name Type Description Default
data dict

The data to check.

required
required_keys Sequence[str]

The required keys.

required

Returns:

Type Description
bool

Whether the user provided all required keys.

Source code in src/mosaico/assets/utils.py
def check_user_provided_required_keys(data: dict, required_keys: Sequence[str]) -> bool:
    """
    Check if the user provided all required keys.

    :param data: The data to check.
    :param required_keys: The required keys.
    :return: Whether the user provided all required keys.
    """
    return set(required_keys).issubset(data.keys())