import logging import pathlib import httpx import pydantic logger = logging.getLogger(__name__) async def get_image_content(target: pathlib.Path | bytes | str) -> bytes: if isinstance(target, pathlib.Path): return target.read_bytes() elif isinstance(target, str): pydantic.parse_obj_as(pydantic.HttpUrl, target) async with httpx.AsyncClient() as client: response = await client.get(target) response.raise_for_status() return response.content elif isinstance(target, bytes): return target raise TypeError("Not supported `target` type.") async def get_image_content_or_none(target: pathlib.Path | bytes | str) -> bytes | None: try: return await get_image_content(target) except Exception as exc: if isinstance(target, bytes): message = "Failed to read image content." else: message = f"Failed to read `{target}` image content." logger.error(message, exc_info=exc) return None