from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, Literal
from pydantic import GetCoreSchemaHandler, ValidationInfo
from pydantic_core import core_schema
[docs]
class Image:
"""
abstract base class, defines the interface of image object.
all image implementations must implement this protocol to ensure compatibility with the message system.
"""
[docs]
@classmethod
def from_uri(cls, uri: str) -> Image:
"""
create image object from image uri.
Args:
uri (str): image uri, usually in data uri format
Returns:
BaseImage: image object
Raises:
ValueError: if the uri format is invalid
"""
...
[docs]
@classmethod
def from_base64(cls, base64_str: str) -> Image:
"""
create image object from base64 encoded string.
Args:
base64_str (str): base64 encoded string of image
Returns:
BaseImage: image object
"""
...
[docs]
@classmethod
def from_file(cls, file_path: Path) -> Image:
"""
create image object from file path.
Args:
file_path (Path): path of image file
Returns:
BaseImage: image object
"""
...
[docs]
def to_base64(self) -> str:
"""
convert image to base64 encoded string.
Returns:
str: base64 encoded string of image
"""
...
@property
def data_uri(self) -> str:
"""
get data uri of image.
Returns:
str: data uri of image
"""
...
def _repr_html_(self) -> str:
"""
display image in jupyter notebook.
Returns:
str: html representation of image
"""
...
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
# Custom validation
def validate(value: Any, validation_info: ValidationInfo) -> Image:
if isinstance(value, dict):
base_64 = cast(str | None, value.get("data")) # type: ignore
if base_64 is None:
raise ValueError("Expected 'data' key in the dictionary")
return cls.from_base64(base_64)
elif isinstance(value, cls):
return value
else:
raise TypeError(f"Expected dict or {cls.__name__} instance, got {type(value)}")
# Custom serialization
def serialize(value: Image) -> dict[str, Any]:
return {"data": value.to_base64()}
return core_schema.with_info_after_validator_function(
validate,
core_schema.any_schema(), # Accept any type; adjust if needed
serialization=core_schema.plain_serializer_function_ser_schema(serialize),
)