88 lines
2.7 KiB
Python
88 lines
2.7 KiB
Python
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(
|
||
prefix="/api/v1/moderation",
|
||
tags=["Moderation"]
|
||
)
|
||
|
||
ALLOWED_CONTENT_TYPES = (
|
||
"image/jpeg",
|
||
"image/png",
|
||
"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(
|
||
file: UploadFile = File(...),
|
||
service: ImageModerationService = Depends(get_image_moderation_service)
|
||
):
|
||
# 1. Проверка content-type — самая дешёвая, делаем её первой
|
||
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. Проверка размера — читаем не больше лимита + 1 байт
|
||
contents = file.file.read(settings.MAX_IMAGE_BYTES + 1)
|
||
|
||
if len(contents) > settings.MAX_IMAGE_BYTES:
|
||
raise HTTPException(
|
||
status_code=413,
|
||
detail="Image too large"
|
||
)
|
||
|
||
if not contents:
|
||
raise HTTPException(
|
||
status_code=400,
|
||
detail="Invalid 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,
|
||
score=prediction.score,
|
||
reason=prediction.reason,
|
||
label=prediction.label,
|
||
detected_labels=prediction.detected_labels
|
||
)
|