feat: support image inputs in assistant tests
This commit is contained in:
@@ -8,12 +8,10 @@ import hmac
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from io import BytesIO
|
||||
from uuid import uuid4
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
import settings
|
||||
from services.image_processing import normalize_image
|
||||
from services.object_storage import delete_object, get_object, put_object
|
||||
|
||||
|
||||
@@ -46,38 +44,8 @@ def _signature(payload: str) -> str:
|
||||
return _b64encode(digest)
|
||||
|
||||
|
||||
def _normalize_image(data: bytes) -> tuple[bytes, int, int]:
|
||||
try:
|
||||
source = Image.open(BytesIO(data))
|
||||
width, height = source.size
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError("图片尺寸无效")
|
||||
if width * height > settings.INPUT_IMAGE_MAX_PIXELS:
|
||||
raise ValueError("图片像素尺寸过大")
|
||||
source.load()
|
||||
except (UnidentifiedImageError, OSError) as exc:
|
||||
raise ValueError("文件不是可识别的图片") from exc
|
||||
|
||||
image = ImageOps.exif_transpose(source)
|
||||
image.thumbnail(
|
||||
(settings.INPUT_IMAGE_MAX_EDGE, settings.INPUT_IMAGE_MAX_EDGE),
|
||||
Image.Resampling.LANCZOS,
|
||||
)
|
||||
if image.mode in {"RGBA", "LA"} or "transparency" in image.info:
|
||||
rgba = image.convert("RGBA")
|
||||
background = Image.new("RGB", rgba.size, "white")
|
||||
background.paste(rgba, mask=rgba.getchannel("A"))
|
||||
image = background
|
||||
else:
|
||||
image = image.convert("RGB")
|
||||
|
||||
buffer = BytesIO()
|
||||
image.save(buffer, format="JPEG", quality=85, optimize=True)
|
||||
return buffer.getvalue(), image.width, image.height
|
||||
|
||||
|
||||
def store_input_image(data: bytes) -> StoredInputImage:
|
||||
normalized, width, height = _normalize_image(data)
|
||||
normalized, width, height = normalize_image(data)
|
||||
key = f"{INPUT_ASSET_PREFIX}{uuid4().hex}.jpg"
|
||||
put_object(key, normalized, "image/jpeg")
|
||||
expires_at = int(time.time()) + settings.INPUT_IMAGE_TOKEN_TTL_SECONDS
|
||||
|
||||
Reference in New Issue
Block a user