Skip to content

Media

Media

Bases: BaseModel

Represents a media object.

id class-attribute instance-attribute

id: str = Field(default_factory=lambda: str(uuid4()))

The unique identifier of the assets.

data class-attribute instance-attribute

data: str | bytes | None = None

The content of the media.

path class-attribute instance-attribute

path: PathLike | None = None

The path to the media.

mime_type class-attribute instance-attribute

mime_type: str | None = None

The MIME type of the media.

encoding class-attribute instance-attribute

encoding: str = 'utf-8'

The encoding of the media.

metadata class-attribute instance-attribute

metadata: dict[str, Any] = Field(default_factory=dict)

The metadata of the media.

description property

description: str

Returns a description of the media.

credit property

credit: str

Returns the credits of the media.

validate_media classmethod

validate_media(values: dict[str, Any]) -> Any

Validates the content of the media.

Source code in src/mosaico/media.py
@model_validator(mode="before")
@classmethod
def validate_media(cls, values: dict[str, Any]) -> Any:
    """
    Validates the content of the media.
    """
    if "data" not in values and "path" not in values:
        raise ValueError("Either data or path must be provided")

    if str(values.get("path", "")).startswith("http"):
        raise ValueError("HTTP paths are not supported")

    return values

from_path classmethod

from_path(
    path: PathLike,
    *,
    encoding: str = "utf-8",
    mime_type: str | None = None,
    guess_mime_type: bool = True,
    metadata: dict | None = None,
    **kwargs: Any
) -> Self

Creates a media from a path.

Parameters:

Name Type Description Default
path PathLike

The path to the media.

required
encoding str

The encoding of the media.

'utf-8'
mime_type str | None

The MIME type of the media.

None
guess_mime_type bool

Whether to guess the MIME type.

True
metadata dict | None

The metadata of the media.

None
kwargs Any

Additional keyword arguments to the constructor.

{}

Returns:

Type Description
Self

The media.

Source code in src/mosaico/media.py
@classmethod
def from_path(
    cls,
    path: PathLike,
    *,
    encoding: str = "utf-8",
    mime_type: str | None = None,
    guess_mime_type: bool = True,
    metadata: dict | None = None,
    **kwargs: Any,
) -> Self:
    """
    Creates a media from a path.

    :param path: The path to the media.
    :param encoding: The encoding of the media.
    :param mime_type: The MIME type of the media.
    :param guess_mime_type: Whether to guess the MIME type.
    :param metadata: The metadata of the media.
    :param kwargs: Additional keyword arguments to the constructor.
    :return: The media.
    """
    if not mime_type and guess_mime_type:
        mime_type = mimetypes.guess_type(str(path))[0]

    return cls(
        data=None,
        path=path,
        metadata=metadata if metadata is not None else {},
        encoding=encoding,
        mime_type=mime_type,
        **kwargs,
    )

from_data classmethod

from_data(
    data: str | bytes,
    *,
    path: PathLike | None = None,
    metadata: dict | None = None,
    mime_type: str | None = None,
    **kwargs: Any
) -> Self

Creates a media from data.

Parameters:

Name Type Description Default
data str | bytes

The data of the media.

required
path PathLike | None

The path to the media.

None
metadata dict | None

The metadata of the media.

None
mime_type str | None

The MIME type of the media.

None
kwargs Any

Additional keyword arguments to the constructor.

{}

Returns:

Type Description
Self

The media.

Source code in src/mosaico/media.py
@classmethod
def from_data(
    cls,
    data: str | bytes,
    *,
    path: PathLike | None = None,
    metadata: dict | None = None,
    mime_type: str | None = None,
    **kwargs: Any,
) -> Self:
    """
    Creates a media from data.

    :param data: The data of the media.
    :param path: The path to the media.
    :param metadata: The metadata of the media.
    :param mime_type: The MIME type of the media.
    :param kwargs: Additional keyword arguments to the constructor.
    :return: The media.
    """
    return cls(
        data=data,
        path=path,
        metadata=metadata if metadata is not None else {},
        mime_type=mime_type,
        **{k: v for k, v in kwargs.items() if v is not None},
    )

from_external classmethod

from_external(
    adapter: Adapter[Media, Any], external: Any
) -> Media

Converts an external representation to a media.

Source code in src/mosaico/media.py
@classmethod
def from_external(cls, adapter: Adapter[Media, Any], external: Any) -> Media:
    """
    Converts an external representation to a media.
    """
    if not isinstance(adapter, Adapter):
        raise TypeError("Adapter must be an instance of Adapter")
    return adapter.from_external(external)

to_external

to_external(adapter: Adapter[Media, Any]) -> Any

Converts the media to an external representation.

Source code in src/mosaico/media.py
def to_external(self, adapter: Adapter[Media, Any]) -> Any:
    """
    Converts the media to an external representation.
    """
    if not isinstance(adapter, Adapter):
        raise TypeError("Adapter must be an instance of Adapter")
    return adapter.to_external(self)

to_string

to_string(
    *, storage_options: dict[str, Any] | None = None
) -> str

Returns the media as a string.

Source code in src/mosaico/media.py
def to_string(self, *, storage_options: dict[str, Any] | None = None) -> str:
    """
    Returns the media as a string.
    """
    if isinstance(self.data, str):
        return self.data
    if isinstance(self.data, bytes):
        return self.data.decode(self.encoding)
    if self.data is None and self.path is not None:
        return _load_file(self.path, storage_options).decode(self.encoding)
    raise ValueError("Data is not a string or bytes")

to_bytes

to_bytes(
    *, storage_options: dict[str, Any] | None = None
) -> bytes

Returns the media as bytes.

Source code in src/mosaico/media.py
def to_bytes(self, *, storage_options: dict[str, Any] | None = None) -> bytes:
    """
    Returns the media as bytes.
    """
    if isinstance(self.data, bytes):
        return self.data
    if isinstance(self.data, str):
        return self.data.encode(self.encoding)
    if self.data is None and self.path is not None:
        return _load_file(self.path, storage_options)
    raise ValueError("Data is not a string or bytes")

to_bytes_io

to_bytes_io(
    *, storage_options: dict[str, Any] | None = None
) -> Generator[BytesIO | BufferedReader]

Read data as a byte stream.

Source code in src/mosaico/media.py
@contextlib.contextmanager
def to_bytes_io(
    self, *, storage_options: dict[str, Any] | None = None
) -> Generator[io.BytesIO | io.BufferedReader]:
    """
    Read data as a byte stream.
    """
    if isinstance(self.data, bytes):
        yield io.BytesIO(self.data)
    elif self.data is None and self.path:
        yield from _yield_file(self.path, storage_options)
    else:
        raise NotImplementedError(f"Unable to convert blob {self}")