Files
post-moderation/ai-moderation/app/routers/image_moderation_router.py
2026-10-15 01:27:20 +03:00

66 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from PIL import Image, ImageOps, UnidentifiedImageError
from fastapi import APIRouter, UploadFile, File, Depends, HTTPException
from app.config.settings import settings
from app.core.dependencies import get_image_moderation_service
from app.models.response.image_moderation_response import \
ImageModerationResponse
from app.services.image_moderation_service import ImageModerationService
router = APIRouter(
prefix="/api/v1/moderation",
tags=["Moderation"]
)
ALLOWED_CONTENT_TYPES = (
"image/jpeg",
"image/png",
"image/webp",
)
@router.post("/image", response_model=ImageModerationResponse)
def moderate_image(
file: UploadFile = File(...),
service: ImageModerationService = Depends(get_image_moderation_service)
):
# 1. Проверка content-type — самая дешёвая, делаем её первой
if file.content_type not in ALLOWED_CONTENT_TYPES:
raise HTTPException(
status_code=400,
detail="Unsupported image format"
)
# 2. Проверка размера — читаем файл целиком
contents = file.file.read()
if len(contents) > settings.MAX_IMAGE_BYTES:
raise HTTPException(
status_code=413,
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):
raise HTTPException(
status_code=400,
detail="Invalid image"
)
prediction = service.moderate(image)
return ImageModerationResponse(
approved=prediction.approved,
score=prediction.score,
reason=prediction.reason,
label=prediction.label,
detected_labels=prediction.detected_labels
)