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: FilePath | 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.

storage_options class-attribute instance-attribute

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

Media's storage options.

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")

    return values

from_path classmethod

from_path(
    path: FilePath,
    *,
    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

FilePath

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: FilePath,
    *,
    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: FilePath | 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

FilePath | 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: FilePath | 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.
    """
    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.
    """
    return adapter.to_external(self)

to_string

to_string(**kwargs: Any) -> str

Returns the media as a string.

Source code in src/mosaico/media.py
def to_string(self, **kwargs: Any) -> 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:
        kwargs["mode"] = "r"
        with self.open(**kwargs) as f:
            return cast(str, f.read())
    raise ValueError("Data is not a string or bytes")

to_bytes

to_bytes(**kwargs: Any) -> bytes

Returns the media as bytes.

Source code in src/mosaico/media.py
def to_bytes(self, **kwargs: Any) -> 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:
        kwargs["mode"] = "rb"
        with self.open(**kwargs) as f:
            return cast(bytes, f.read())
    raise ValueError("Data is not a string or bytes")

to_bytes_io

to_bytes_io(
    **kwargs: Any,
) -> Generator[IO[bytes], None, None]

Read data as a byte stream.

Source code in src/mosaico/media.py
@contextlib.contextmanager
def to_bytes_io(self, **kwargs: Any) -> Generator[IO[bytes], None, None]:
    """
    Read data as a byte stream.
    """
    if isinstance(self.data, bytes):
        yield io.BytesIO(self.data)
    elif self.data is None and self.path:
        kwargs["mode"] = "rb"
        with self.open(**kwargs) as f:
            yield cast(IO[bytes], f)
    else:
        raise NotImplementedError(f"Unable to convert blob {self}")

open

open(
    **kwargs,
) -> Generator[IO[bytes] | IO[str], None, None]

Opens the media for read/write operations.

Source code in src/mosaico/media.py
@contextlib.contextmanager
def open(self, **kwargs) -> Generator[IO[bytes] | IO[str], None, None]:
    """
    Opens the media for read/write operations.
    """
    if self.path is None:
        raise ValueError("File-opening could only be done when 'path' is not missing.")
    fs, path_str = fsspec.core.url_to_fs(self.path, **self.storage_options)
    with fs.open(path_str, **kwargs) as f:
        yield f

add_metadata

add_metadata(metadata: dict[str, Any]) -> Self

Add metadata to the media object.

Source code in src/mosaico/media.py
def add_metadata(self, metadata: dict[str, Any]) -> Self:
    """
    Add metadata to the media object.
    """
    self.metadata.update(metadata)
    return self

with_metadata

with_metadata(metadata: dict[str, Any]) -> Self

Set media object metadata.

Source code in src/mosaico/media.py
def with_metadata(self, metadata: dict[str, Any]) -> Self:
    """
    Set media object metadata.
    """
    self.metadata = metadata
    return self

with_storage_options

with_storage_options(
    storage_options: dict[str, Any],
) -> Self

Add/replace storage options of the media object.

Source code in src/mosaico/media.py
def with_storage_options(self, storage_options: dict[str, Any]) -> Self:
    """
    Add/replace storage options of the media object.
    """
    self.storage_options = storage_options
    return self