Skip to content

pixano.features.schemas.views.image

Image(created_at=None, updated_at=None, **data)

Bases: View

Image view.

Attributes:

Name Type Description
url str

The image URL. Can be relative or absolute or a data URL.

width int

The image width.

height int

The image height.

format str

The image format.

Source code in pixano/features/schemas/base_schema.py
def __init__(self, /, created_at: datetime | None = None, updated_at: datetime | None = None, **data: Any):
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.

    Args:
        created_at: The creation date of the object.
        updated_at: The last modification date of the object.
        data: The data of the object validated by Pydantic.
    """
    created_at, updated_at = validate_and_init_create_at_and_update_at(created_at, updated_at)
    data.update({"created_at": created_at, "updated_at": updated_at})
    super().__init__(**data)

open(media_dir=None, output_type='base64')

open(media_dir: Path | None, output_type: Literal['base64'] = 'base64') -> str
open(media_dir: Path | None, output_type: Literal['image']) -> PILImage

Open the image.

Note

If the output type is "base64", the image is returned as a base64 string formatted as "data:image/{image_format};base64,{base64}".

Parameters:

Name Type Description Default
media_dir Path | None

Path to the media directory. If the URL is relative, it is relative to this directory.

None
output_type Literal['base64', 'image']

The output type. Can be "base64" or "image" (PIL.Image).

'base64'

Returns:

Type Description
str | Image

opened image.

Source code in pixano/features/schemas/views/image.py
def open(
    self,
    media_dir: Path | None = None,
    output_type: Literal["base64", "image"] = "base64",
) -> str | PILImage:
    """Open the image.

    Note:
        If the output type is "base64", the image is returned as a base64 string formatted as
        "data:image/{image_format};base64,{base64}".

    Args:
        media_dir: Path to the media directory. If the URL is relative, it is relative to this directory.
        output_type: The output type. Can be "base64" or "image" (PIL.Image).

    Returns:
        opened image.
    """
    return Image.open_url(url=self.url, media_dir=media_dir, output_type=output_type)

open_url(url, media_dir=None, output_type='base64') staticmethod

open_url(url: str, media_dir: Path | None, output_type: Literal['base64'] = 'base64') -> str
open_url(url: str, media_dir: Path | None, output_type: Literal['image']) -> PILImage

Open an image from a URL.

Note

If the output type is "base64", the image is returned as a base64 string formatted as "data:image/{image_format};base64,{base64}".

Parameters:

Name Type Description Default
url str

image url relative to media_dir or absolute.

required
media_dir Path | None

path to the media directory if the URL is relative.

None
output_type Literal['base64', 'image']

output type. Can be "base64" or "image" (PIL.Image).

'base64'

Returns:

Type Description
str | Image

The opened image.

Source code in pixano/features/schemas/views/image.py
@staticmethod
def open_url(
    url: str,
    media_dir: Path | None = None,
    output_type: Literal["base64", "image"] = "base64",
) -> str | PILImage:
    """Open an image from a URL.

    Note:
        If the output type is "base64", the image is returned as a base64 string formatted as
        "data:image/{image_format};base64,{base64}".

    Args:
        url: image url relative to media_dir or absolute.
        media_dir: path to the media directory if the URL is relative.
        output_type: output type. Can be "base64" or "image" (PIL.Image).

    Returns:
        The opened image.
    """
    if output_type not in ["base64", "image"]:
        raise ValueError(f"Invalid output type: {output_type}")

    # URI is incomplete
    if urlparse(url).scheme == "":
        if media_dir is None:
            raise ValueError("URI is incomplete, need media directory")
        uri_prefix = media_dir.absolute().as_uri()
        # URI prefix exists
        if uri_prefix is not None:
            parsed_uri = urlparse(uri_prefix)
            # URI prefix is incomplete
            if parsed_uri.scheme == "":
                raise ValueError("URI prefix is incomplete, no scheme provided (http://, file://, ...)")
            if url.startswith("/"):
                url = url[1:]
            combined_path = Path(parsed_uri.path) / url
            parsed_uri = parsed_uri._replace(path=str(combined_path))
            api_url = parsed_uri.geturl()
        else:
            # No URI prefix
            raise ValueError("URI is incomplete, need URI prefix")
    # URI is already complete
    else:
        api_url = url

    try:
        with urlopen(api_url) as f:
            im_bytes = f.read()
    except URLError:
        raise ValueError(f"Error: image not found ({api_url})")

    pil_image = PIL.Image.open(io.BytesIO(im_bytes))

    # Handle output types
    if output_type == "base64":
        return image_to_base64(pil_image)

    return pil_image

create_image(url, id='', item_ref=ItemRef.none(), parent_ref=ViewRef.none(), width=None, height=None, format=None, url_relative_path=None)

Create an Image instance.

Parameters:

Name Type Description Default
url Path

The image URL. If not relative, the URL is converted to a relative path using other_path.

required
id str

Image ID.

''
item_ref ItemRef

Item reference.

none()
parent_ref ViewRef

Parent view reference.

none()
width int | None

The image width. If None, the width is extracted from the image file.

None
height int | None

The image height. If None, the height is extracted from the image file.

None
format str | None

The image format. If None, the format is extracted from the image file.

None
url_relative_path Path | None

The path to convert the URL to a relative path.

None

Returns:

Type Description
Image

The created Image instance.

Source code in pixano/features/schemas/views/image.py
def create_image(
    url: Path,
    id: str = "",
    item_ref: ItemRef = ItemRef.none(),
    parent_ref: ViewRef = ViewRef.none(),
    width: int | None = None,
    height: int | None = None,
    format: str | None = None,
    url_relative_path: Path | None = None,
) -> Image:
    """Create an `Image` instance.

    Args:
        url: The image URL. If not relative, the URL is converted to a relative path using `other_path`.
        id: Image ID.
        item_ref: Item reference.
        parent_ref: Parent view reference.
        width: The image width. If None, the width is extracted from the image file.
        height: The image height. If None, the height is extracted from the image file.
        format: The image format. If None, the format is extracted from the image file.
        url_relative_path: The path to convert the URL to a relative path.

    Returns:
        The created `Image` instance.
    """
    none_conditions = [width is None, height is None, format is None]
    not_none_conditions = [width is not None, height is not None, format is not None]
    if not all(none_conditions) and not all(not_none_conditions):
        raise ValueError("width, height and format must be all defined or all None")

    url = Path(url)

    if width is None:
        img = PIL.Image.open(url)
        width = img.width
        height = img.height
        format = img.format

    if url_relative_path is not None:
        url_relative_path = Path(url_relative_path)
        url = url.relative_to(url_relative_path)

    return Image(
        id=id, item_ref=item_ref, parent_ref=parent_ref, url=url.as_posix(), width=width, height=height, format=format
    )

is_image(cls, strict=False)

Check if the given class is Image or a subclass of Image.

Source code in pixano/features/schemas/views/image.py
def is_image(cls: type, strict: bool = False) -> bool:
    """Check if the given class is `Image` or a subclass of `Image`."""
    return issubclass_strict(cls, Image, strict)