fix problem from claude
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
from fastapi import APIRouter, UploadFile, File, Depends, HTTPException
|
||||
|
||||
from app.config.settings import settings
|
||||
from app.core.concurrency import image_limiter
|
||||
from app.core.dependencies import get_image_moderation_service
|
||||
from app.models.response.image_moderation_response import \
|
||||
ImageModerationResponse
|
||||
from app.moderation.image.loader import CorruptImageError, load_image
|
||||
from app.services.image_moderation_service import ImageModerationService
|
||||
|
||||
router = APIRouter(
|
||||
@@ -18,6 +19,18 @@ ALLOWED_CONTENT_TYPES = (
|
||||
"image/webp",
|
||||
)
|
||||
|
||||
# Клиент не всегда знает тип: Spring берёт его из расширения имени файла и
|
||||
# без расширения шлёт octet-stream. Настоящий формат всё равно определяется
|
||||
# по содержимому в load_image.
|
||||
GENERIC_CONTENT_TYPES = (
|
||||
"",
|
||||
"application/octet-stream",
|
||||
)
|
||||
|
||||
|
||||
def _media_type(content_type: str | None) -> str:
|
||||
return (content_type or "").split(";")[0].strip().lower()
|
||||
|
||||
|
||||
@router.post("/image", response_model=ImageModerationResponse)
|
||||
def moderate_image(
|
||||
@@ -25,14 +38,15 @@ def moderate_image(
|
||||
service: ImageModerationService = Depends(get_image_moderation_service)
|
||||
):
|
||||
# 1. Проверка content-type — самая дешёвая, делаем её первой
|
||||
if file.content_type not in ALLOWED_CONTENT_TYPES:
|
||||
media_type = _media_type(file.content_type)
|
||||
if media_type not in ALLOWED_CONTENT_TYPES + GENERIC_CONTENT_TYPES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Unsupported image format"
|
||||
)
|
||||
|
||||
# 2. Проверка размера — читаем файл целиком
|
||||
contents = file.file.read()
|
||||
# 2. Проверка размера — читаем не больше лимита + 1 байт
|
||||
contents = file.file.read(settings.MAX_IMAGE_BYTES + 1)
|
||||
|
||||
if len(contents) > settings.MAX_IMAGE_BYTES:
|
||||
raise HTTPException(
|
||||
@@ -40,21 +54,29 @@ def moderate_image(
|
||||
detail="Image too large"
|
||||
)
|
||||
|
||||
file.file.seek(0) # обязательно вернуть указатель в начало!
|
||||
|
||||
# 3. Только теперь пытаемся открыть изображение
|
||||
try:
|
||||
image = Image.open(file.file)
|
||||
# Фото с телефона хранят поворот в EXIF — без этого модели видят его боком
|
||||
image = ImageOps.exif_transpose(image)
|
||||
image = image.convert("RGB")
|
||||
except (UnidentifiedImageError, Image.DecompressionBombError):
|
||||
if not contents:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Invalid image"
|
||||
)
|
||||
|
||||
prediction = service.moderate(image)
|
||||
# 3. Декодирование и модели — под лимитом параллельности: и то и другое
|
||||
# ест память пропорционально числу одновременных запросов
|
||||
with image_limiter.slot():
|
||||
try:
|
||||
image = load_image(contents, service.validator)
|
||||
except CorruptImageError:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Invalid image"
|
||||
)
|
||||
finally:
|
||||
del contents
|
||||
|
||||
try:
|
||||
prediction = service.moderate(image)
|
||||
finally:
|
||||
image.close()
|
||||
|
||||
return ImageModerationResponse(
|
||||
approved=prediction.approved,
|
||||
|
||||
Reference in New Issue
Block a user