[docs]classImage:"""Represents an image. Example: Loading an image from a URL: .. code-block:: python from autogen_core import Image from PIL import Image as PILImage import aiohttp import asyncio async def from_url(url: str) -> Image: async with aiohttp.ClientSession() as session: async with session.get(url) as response: content = await response.read() return Image.from_pil(PILImage.open(content)) image = asyncio.run(from_url("https://example.com/image")) """def__init__(self,image:PILImage.Image):self.image:PILImage.Image=image.convert("RGB")
[docs]@classmethoddeffrom_uri(cls,uri:str)->Image:ifnotre.match(r"data:image/(?:png|jpeg);base64,",uri):raiseValueError("Invalid URI format. It should be a base64 encoded image URI.")# A URI. Remove the prefix and decode the base64 string.base64_data=re.sub(r"data:image/(?:png|jpeg);base64,","",uri)returncls.from_base64(base64_data)
def_repr_html_(self)->str:# Show the image in Jupyter notebookreturnf'<img src="{self.data_uri}"/>'@propertydefdata_uri(self)->str:return_convert_base64_to_data_uri(self.to_base64())# Returns openai.types.chat.ChatCompletionContentPartImageParam, which is a TypedDict# We don't use the explicit type annotation so that we can avoid a dependency on the OpenAI Python SDK in this package.
@classmethoddef__get_pydantic_core_schema__(cls,source_type:Any,handler:GetCoreSchemaHandler)->core_schema.CoreSchema:# Custom validationdefvalidate(value:Any,validation_info:ValidationInfo)->Image:ifisinstance(value,dict):base_64=cast(str|None,value.get("data"))# type: ignoreifbase_64isNone:raiseValueError("Expected 'data' key in the dictionary")returncls.from_base64(base_64)elifisinstance(value,cls):returnvalueelse:raiseTypeError(f"Expected dict or {cls.__name__} instance, got {type(value)}")# Custom serializationdefserialize(value:Image)->dict[str,Any]:return{"data":value.to_base64()}returncore_schema.with_info_after_validator_function(validate,core_schema.any_schema(),# Accept any type; adjust if neededserialization=core_schema.plain_serializer_function_ser_schema(serialize),)
def_convert_base64_to_data_uri(base64_image:str)->str:def_get_mime_type_from_data_uri(base64_image:str)->str:# Decode the base64 stringimage_data=base64.b64decode(base64_image)# Check the first few bytes for known signaturesifimage_data.startswith(b"\xff\xd8\xff"):return"image/jpeg"elifimage_data.startswith(b"\x89PNG\r\n\x1a\n"):return"image/png"elifimage_data.startswith(b"GIF87a")orimage_data.startswith(b"GIF89a"):return"image/gif"elifimage_data.startswith(b"RIFF")andimage_data[8:12]==b"WEBP":return"image/webp"return"image/jpeg"# use jpeg for unknown formats, best guess.mime_type=_get_mime_type_from_data_uri(base64_image)data_uri=f"data:{mime_type};base64,{base64_image}"returndata_uri