fix problem from claude
This commit is contained in:
20
ai-moderation/app/routers/health_router.py
Normal file
20
ai-moderation/app/routers/health_router.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.ml.model_manager import model_manager
|
||||
|
||||
router = APIRouter(tags=["Health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health():
|
||||
"""Liveness: процесс жив и отвечает."""
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/ready")
|
||||
def ready():
|
||||
"""Readiness: модели загружены, можно слать запросы."""
|
||||
if not model_manager.ready:
|
||||
return JSONResponse(status_code=503, content={"status": "loading"})
|
||||
return {"status": "ready"}
|
||||
@@ -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,
|
||||
|
||||
@@ -2,6 +2,7 @@ from fastapi import APIRouter
|
||||
from typing import Annotated
|
||||
from fastapi import Depends
|
||||
|
||||
from app.core.concurrency import text_limiter
|
||||
from app.models.dto.text_request import TextRequest
|
||||
from app.models.response.moderation_response import ModerationResponse
|
||||
from app.services.text_moderation_service import TextModerationService
|
||||
@@ -27,7 +28,8 @@ def moderate_text(
|
||||
Depends(get_text_moderation_service)
|
||||
]
|
||||
):
|
||||
prediction = service.moderate(request.text)
|
||||
with text_limiter.slot():
|
||||
prediction = service.moderate(request.text)
|
||||
|
||||
return ModerationResponse(
|
||||
approved=prediction.approved,
|
||||
|
||||
Reference in New Issue
Block a user