fix problem from claude
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
from pydantic import SecretStr, field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
class Settings(BaseSettings):
|
||||
@@ -9,9 +10,12 @@ class Settings(BaseSettings):
|
||||
|
||||
PORT: int = 8000
|
||||
|
||||
DEBUG: bool = True
|
||||
DEBUG: bool = False
|
||||
|
||||
TEXT_TOXIC_THRESHOLD: float = 0.90
|
||||
# Максимальная длина текста в символах. Длинный текст режется на окна по
|
||||
# 512 токенов, и решение принимается по самому токсичному окну.
|
||||
TEXT_MAX_LENGTH: int = 5000
|
||||
|
||||
# ===== AI =====
|
||||
|
||||
@@ -26,16 +30,45 @@ class Settings(BaseSettings):
|
||||
WEAPON_MIN_AREA_FRACTION: float = 0.005
|
||||
MODEL_CACHE_DIR: str = "./models"
|
||||
|
||||
# Токен Hugging Face нужен только для приватных/gated моделей.
|
||||
# Никогда не вписывайте реальный токен сюда — только через окружение/.env.
|
||||
HF_TOKEN: SecretStr | None = None
|
||||
|
||||
# Максимальный размер файла картинки. Должен быть не меньше лимита бэкенда
|
||||
# (10 МБ) — иначе бэкенд принимает фото, а модерация отвечает 413.
|
||||
MAX_IMAGE_BYTES: int = 15 * 1024 * 1024
|
||||
# Максимум пикселей в исходной картинке. Проверяется по заголовку ДО
|
||||
# декодирования: маленький PNG 10000×10000 распаковывается в ~300 МБ.
|
||||
MAX_IMAGE_PIXELS: int = 50_000_000
|
||||
# Перед прогоном через модели картинка уменьшается до этой стороны: сами
|
||||
# модели работают на 224–960px, а 12-Мп фото с телефона лишь замедляют
|
||||
# предобработку и съедают память.
|
||||
MODERATION_MAX_SIDE: int = 1280
|
||||
# Лимит тела остальных запросов (JSON с текстом и т.п.).
|
||||
MAX_REQUEST_BYTES: int = 1024 * 1024
|
||||
|
||||
# Сколько запросов одновременно гоняют модели. Остальные ждут в очереди
|
||||
# не дольше INFERENCE_QUEUE_TIMEOUT секунд, затем получают 503 — бэкенд
|
||||
# повторит запрос. Без лимита до 40 потоков пула одновременно грузят CPU
|
||||
# и память, и под нагрузкой сервис падает по OOM.
|
||||
IMAGE_MAX_CONCURRENCY: int = 2
|
||||
TEXT_MAX_CONCURRENCY: int = 4
|
||||
INFERENCE_QUEUE_TIMEOUT: float = 20.0
|
||||
|
||||
# Если задан — все /api/* требуют заголовок X-API-Key с этим значением.
|
||||
# По умолчанию выключено, чтобы не ломать текущий бэкенд.
|
||||
API_KEY: SecretStr | None = None
|
||||
|
||||
DEVICE: str = "auto"
|
||||
|
||||
@field_validator("HF_TOKEN", "API_KEY", mode="before")
|
||||
@classmethod
|
||||
def _empty_secret_is_none(cls, value):
|
||||
# «API_KEY=» в .env — это «не задан», а не «ключ — пустая строка»
|
||||
if isinstance(value, str) and not value.strip():
|
||||
return None
|
||||
return value
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
extra="ignore"
|
||||
|
||||
88
ai-moderation/app/core/body_limit.py
Normal file
88
ai-moderation/app/core/body_limit.py
Normal file
@@ -0,0 +1,88 @@
|
||||
import json
|
||||
from typing import Callable
|
||||
|
||||
# Запас под заголовки multipart (boundary, Content-Disposition и т.п.)
|
||||
MULTIPART_OVERHEAD = 64 * 1024
|
||||
|
||||
|
||||
class _BodyTooLarge(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BodySizeLimitMiddleware:
|
||||
"""
|
||||
Отклоняет слишком большие тела запросов с 413, не дочитывая их.
|
||||
|
||||
Без этого Starlette сначала целиком принимает multipart (с диска), и только
|
||||
потом роутер видит размер — гигабайтный аплоад забивает диск и канал.
|
||||
Content-Length проверяется сразу; для chunked-запросов байты считаются
|
||||
на лету.
|
||||
"""
|
||||
|
||||
def __init__(self, app, limit_for_path: Callable[[str], int]):
|
||||
self.app = app
|
||||
self.limit_for_path = limit_for_path
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
limit = self.limit_for_path(scope.get("path", ""))
|
||||
|
||||
content_length = None
|
||||
for name, value in scope.get("headers", []):
|
||||
if name == b"content-length":
|
||||
content_length = value
|
||||
break
|
||||
|
||||
if content_length is not None:
|
||||
try:
|
||||
declared = int(content_length)
|
||||
except ValueError:
|
||||
await self._reject(send, 400, "INVALID_REQUEST", "Invalid Content-Length")
|
||||
return
|
||||
if declared > limit:
|
||||
await self._reject(send, 413, "PAYLOAD_TOO_LARGE", "Request body too large")
|
||||
return
|
||||
|
||||
received = 0
|
||||
rejected = False
|
||||
|
||||
async def limited_receive():
|
||||
nonlocal received, rejected
|
||||
message = await receive()
|
||||
if message["type"] == "http.request":
|
||||
received += len(message.get("body", b""))
|
||||
if received > limit:
|
||||
rejected = True
|
||||
raise _BodyTooLarge()
|
||||
return message
|
||||
|
||||
async def guarded_send(message):
|
||||
# После превышения лимита ответ приложения (обычно 400 «ошибка
|
||||
# разбора тела») подменяем на 413
|
||||
if not rejected:
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, limited_receive, guarded_send)
|
||||
except _BodyTooLarge:
|
||||
pass
|
||||
|
||||
if rejected:
|
||||
await self._reject(send, 413, "PAYLOAD_TOO_LARGE", "Request body too large")
|
||||
|
||||
@staticmethod
|
||||
async def _reject(send, status: int, code: str, message: str):
|
||||
body = json.dumps({"code": code, "message": message}).encode()
|
||||
await send({
|
||||
"type": "http.response.start",
|
||||
"status": status,
|
||||
"headers": [
|
||||
(b"content-type", b"application/json"),
|
||||
(b"content-length", str(len(body)).encode()),
|
||||
(b"connection", b"close"),
|
||||
],
|
||||
})
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
29
ai-moderation/app/core/concurrency.py
Normal file
29
ai-moderation/app/core/concurrency.py
Normal file
@@ -0,0 +1,29 @@
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
|
||||
from app.config.settings import settings
|
||||
from app.exceptions.service_busy_exception import ServiceBusyException
|
||||
|
||||
|
||||
class InferenceLimiter:
|
||||
"""Ограничивает число одновременных прогонов моделей (синхронные эндпоинты)."""
|
||||
|
||||
def __init__(self, name: str, max_concurrency: int):
|
||||
self.name = name
|
||||
self._semaphore = threading.BoundedSemaphore(max(1, max_concurrency))
|
||||
|
||||
@contextmanager
|
||||
def slot(self, timeout: float | None = None):
|
||||
timeout = settings.INFERENCE_QUEUE_TIMEOUT if timeout is None else timeout
|
||||
if not self._semaphore.acquire(timeout=timeout):
|
||||
raise ServiceBusyException(
|
||||
f"{self.name} moderation is busy, retry later"
|
||||
)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._semaphore.release()
|
||||
|
||||
|
||||
image_limiter = InferenceLimiter("Image", settings.IMAGE_MAX_CONCURRENCY)
|
||||
text_limiter = InferenceLimiter("Text", settings.TEXT_MAX_CONCURRENCY)
|
||||
@@ -1,4 +1,5 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from app.ml.image.clip_classifier import ClipClassifier
|
||||
from app.ml.image.image_classifier import ImageClassifier
|
||||
@@ -11,6 +12,12 @@ from app.moderation.profanity.lemmatizer import Lemmatizer
|
||||
from app.services.image_moderation_service import ImageModerationService
|
||||
from app.services.text_moderation_service import TextModerationService
|
||||
|
||||
# Путь от пакета, а не от текущей директории: иначе запуск не из
|
||||
# ai-moderation/ (тесты, IDE) падает с FileNotFoundError
|
||||
PROFANITY_WORDS_PATH = (
|
||||
Path(__file__).resolve().parent.parent / "resources" / "profanity_words.txt"
|
||||
)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_clip_classifier() -> ClipClassifier:
|
||||
@@ -26,7 +33,7 @@ def get_text_classifier() -> TextClassifier:
|
||||
def get_profanity_detector() -> ProfanityDetector:
|
||||
return ProfanityDetector(
|
||||
dictionary=ProfanityDictionary(
|
||||
file_path="app/resources/profanity_words.txt"
|
||||
file_path=PROFANITY_WORDS_PATH
|
||||
),
|
||||
lemmatizer=Lemmatizer()
|
||||
)
|
||||
@@ -62,4 +69,4 @@ def get_image_moderation_service() -> ImageModerationService:
|
||||
validator=get_image_validator(),
|
||||
clip_classifier=get_clip_classifier(),
|
||||
weapon_detector=get_weapon_detector()
|
||||
)
|
||||
)
|
||||
|
||||
18
ai-moderation/app/core/security.py
Normal file
18
ai-moderation/app/core/security.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import hmac
|
||||
|
||||
from fastapi import HTTPException, Security
|
||||
from fastapi.security import APIKeyHeader
|
||||
|
||||
from app.config.settings import settings
|
||||
|
||||
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
||||
|
||||
|
||||
def verify_api_key(api_key: str | None = Security(api_key_header)) -> None:
|
||||
"""Проверка общего секрета с бэкендом. Выключена, пока API_KEY не задан."""
|
||||
if settings.API_KEY is None:
|
||||
return
|
||||
|
||||
expected = settings.API_KEY.get_secret_value().encode()
|
||||
if api_key is None or not hmac.compare_digest(api_key.encode(), expected):
|
||||
raise HTTPException(status_code=401, detail="Invalid API key")
|
||||
@@ -1,8 +1,10 @@
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.config.logging import logger
|
||||
from app.exceptions.invalid_image_exception import InvalidImageException
|
||||
from app.exceptions.invalid_text_exception import InvalidTextException
|
||||
from app.exceptions.service_busy_exception import ServiceBusyException
|
||||
from app.models.response.error_response import ErrorResponse
|
||||
|
||||
|
||||
@@ -25,4 +27,34 @@ async def invalid_image_exception_handler(
|
||||
code="INVALID_IMAGE",
|
||||
message=exc.message
|
||||
)
|
||||
return JSONResponse(status_code=400, content=response.model_dump())
|
||||
return JSONResponse(status_code=400, content=response.model_dump())
|
||||
|
||||
|
||||
async def service_busy_exception_handler(
|
||||
request: Request,
|
||||
exc: ServiceBusyException
|
||||
):
|
||||
response = ErrorResponse(
|
||||
code="SERVICE_BUSY",
|
||||
message=exc.message
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content=response.model_dump(),
|
||||
headers={"Retry-After": "2"}
|
||||
)
|
||||
|
||||
|
||||
async def unhandled_exception_handler(
|
||||
request: Request,
|
||||
exc: Exception
|
||||
):
|
||||
# Трейс — только в лог; клиенту не отдаём внутренности
|
||||
logger.exception(
|
||||
"Unhandled error on %s %s", request.method, request.url.path
|
||||
)
|
||||
response = ErrorResponse(
|
||||
code="INTERNAL_ERROR",
|
||||
message="Internal server error"
|
||||
)
|
||||
return JSONResponse(status_code=500, content=response.model_dump())
|
||||
|
||||
5
ai-moderation/app/exceptions/service_busy_exception.py
Normal file
5
ai-moderation/app/exceptions/service_busy_exception.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from app.exceptions.moderation_exception import ModerationException
|
||||
|
||||
|
||||
class ServiceBusyException(ModerationException):
|
||||
pass
|
||||
@@ -3,6 +3,10 @@ from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.config.logging import logger
|
||||
from app.core.dependencies import (
|
||||
get_image_moderation_service,
|
||||
get_text_moderation_service
|
||||
)
|
||||
from app.ml.model_manager import model_manager
|
||||
|
||||
|
||||
@@ -11,6 +15,12 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
logger.info("Loading AI models...")
|
||||
model_manager.initialize()
|
||||
# CLIP, OWLv2 и словарь тоже грузим на старте: иначе первый запрос
|
||||
# картинки ждёт загрузки моделей дольше таймаута бэкенда, а параллельные
|
||||
# первые запросы могут загрузить одну модель дважды.
|
||||
get_text_moderation_service()
|
||||
get_image_moderation_service()
|
||||
model_manager.mark_ready()
|
||||
logger.info("AI models loaded.")
|
||||
yield
|
||||
logger.info("Stopping AI Service...")
|
||||
|
||||
@@ -1,24 +1,44 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi import Depends, FastAPI
|
||||
|
||||
from app.config.settings import settings
|
||||
from app.core.body_limit import BodySizeLimitMiddleware, MULTIPART_OVERHEAD
|
||||
from app.core.security import verify_api_key
|
||||
from app.exceptions.handlers import (
|
||||
invalid_text_exception_handler,
|
||||
invalid_image_exception_handler
|
||||
invalid_image_exception_handler,
|
||||
service_busy_exception_handler,
|
||||
unhandled_exception_handler
|
||||
)
|
||||
from app.exceptions.invalid_text_exception import InvalidTextException
|
||||
from app.exceptions.invalid_image_exception import InvalidImageException
|
||||
from app.exceptions.service_busy_exception import ServiceBusyException
|
||||
from app.lifespan import lifespan
|
||||
from app.routers.health_router import router as health_router
|
||||
from app.routers.image_moderation_router import router as image_router
|
||||
from app.routers.text_moderation_router import router as moderation_router
|
||||
|
||||
IMAGE_UPLOAD_PATH = "/api/v1/moderation/image"
|
||||
|
||||
|
||||
def request_body_limit(path: str) -> int:
|
||||
if path.rstrip("/") == IMAGE_UPLOAD_PATH:
|
||||
return settings.MAX_IMAGE_BYTES + MULTIPART_OVERHEAD
|
||||
return settings.MAX_REQUEST_BYTES
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title=settings.APP_NAME,
|
||||
version=settings.APP_VERSION,
|
||||
lifespan=lifespan
|
||||
)
|
||||
|
||||
app.include_router(moderation_router)
|
||||
app.include_router(image_router)
|
||||
app.include_router(health_router)
|
||||
app.include_router(moderation_router, dependencies=[Depends(verify_api_key)])
|
||||
app.include_router(image_router, dependencies=[Depends(verify_api_key)])
|
||||
|
||||
app.add_exception_handler(InvalidTextException, invalid_text_exception_handler)
|
||||
app.add_exception_handler(InvalidImageException, invalid_image_exception_handler)
|
||||
app.add_exception_handler(InvalidImageException, invalid_image_exception_handler)
|
||||
app.add_exception_handler(ServiceBusyException, service_busy_exception_handler)
|
||||
app.add_exception_handler(Exception, unhandled_exception_handler)
|
||||
|
||||
app.add_middleware(BodySizeLimitMiddleware, limit_for_path=request_body_limit)
|
||||
|
||||
@@ -2,21 +2,25 @@ import torch
|
||||
from PIL import Image
|
||||
from transformers import CLIPProcessor, CLIPModel
|
||||
|
||||
from app.config.logging import logger
|
||||
from app.config.settings import settings
|
||||
from app.ml.image.clip_prediction_result import ClipPredictionResult
|
||||
from app.ml.model_manager import model_manager
|
||||
|
||||
|
||||
class ClipClassifier:
|
||||
NORMAL_LABEL = "a normal photo"
|
||||
|
||||
LABELS = [
|
||||
"a normal photo",
|
||||
NORMAL_LABEL,
|
||||
"a photo containing marijuana",
|
||||
"a photo containing drugs",
|
||||
"a photo containing violence"
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
print(f"Loading CLIP on {self.device}")
|
||||
self.device = model_manager.get_device()
|
||||
logger.info("Loading CLIP on %s", self.device)
|
||||
|
||||
self.model = CLIPModel.from_pretrained(settings.IMAGE_CLIP_MODEL)
|
||||
self.processor = CLIPProcessor.from_pretrained(settings.IMAGE_CLIP_MODEL)
|
||||
@@ -24,19 +28,26 @@ class ClipClassifier:
|
||||
self.model.to(self.device)
|
||||
self.model.eval()
|
||||
|
||||
def predict(self, image: Image.Image) -> ClipPredictionResult:
|
||||
inputs = self.processor(
|
||||
text=self.LABELS,
|
||||
images=image,
|
||||
return_tensors="pt",
|
||||
padding=True
|
||||
)
|
||||
inputs = {k: v.to(self.device) for k, v in inputs.items()}
|
||||
# Метки постоянные — токенизируем один раз. Заодно запросы не трогают
|
||||
# общий токенизатор, который не потокобезопасен.
|
||||
self.text_inputs = {
|
||||
key: value.to(self.device)
|
||||
for key, value in self.processor(
|
||||
text=self.LABELS,
|
||||
padding=True,
|
||||
return_tensors="pt"
|
||||
).items()
|
||||
}
|
||||
|
||||
with torch.no_grad():
|
||||
outputs = self.model(**inputs)
|
||||
logits = outputs.logits_per_image
|
||||
probs = logits.softmax(dim=1)[0]
|
||||
def predict(self, image: Image.Image) -> ClipPredictionResult:
|
||||
pixel_values = self.processor(
|
||||
images=image,
|
||||
return_tensors="pt"
|
||||
)["pixel_values"].to(self.device)
|
||||
|
||||
with torch.inference_mode():
|
||||
outputs = self.model(pixel_values=pixel_values, **self.text_inputs)
|
||||
probs = outputs.logits_per_image.softmax(dim=1)[0]
|
||||
|
||||
scores = {}
|
||||
detected_labels = []
|
||||
@@ -46,14 +57,16 @@ class ClipClassifier:
|
||||
score = float(probability)
|
||||
scores[label] = score
|
||||
|
||||
if label != "a normal photo" and score >= settings.CLIP_THRESHOLD:
|
||||
if label != self.NORMAL_LABEL and score >= settings.CLIP_THRESHOLD:
|
||||
detected_labels.append(label)
|
||||
|
||||
max_index = torch.argmax(probs).item()
|
||||
max_index = int(torch.argmax(probs).item())
|
||||
|
||||
logger.debug("CLIP scores: %s", scores)
|
||||
|
||||
return ClipPredictionResult(
|
||||
label=self.LABELS[max_index],
|
||||
score=float(probs[max_index]),
|
||||
detected_labels=detected_labels,
|
||||
scores=scores
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import torch
|
||||
from PIL import Image
|
||||
|
||||
from app.config.logging import logger
|
||||
from app.ml.image.image_prediction_result import ImagePredictionResult
|
||||
from app.ml.model_manager import model_manager
|
||||
|
||||
@@ -11,11 +12,9 @@ class ImageClassifier:
|
||||
self,
|
||||
image: Image.Image
|
||||
) -> ImagePredictionResult:
|
||||
inputs = (
|
||||
model_manager.image_processor(
|
||||
image,
|
||||
return_tensors="pt"
|
||||
)
|
||||
inputs = model_manager.image_processor(
|
||||
image,
|
||||
return_tensors="pt"
|
||||
)
|
||||
|
||||
inputs = {
|
||||
@@ -23,10 +22,8 @@ class ImageClassifier:
|
||||
for key, value in inputs.items()
|
||||
}
|
||||
|
||||
with torch.no_grad():
|
||||
outputs = (
|
||||
model_manager.image_model(**inputs)
|
||||
)
|
||||
with torch.inference_mode():
|
||||
outputs = model_manager.image_model(**inputs)
|
||||
|
||||
probabilities = torch.softmax(
|
||||
outputs.logits,
|
||||
@@ -35,35 +32,20 @@ class ImageClassifier:
|
||||
|
||||
raw_scores = probabilities[0].tolist()
|
||||
|
||||
predicted_index = (
|
||||
torch.argmax(probabilities, dim=1)
|
||||
.item()
|
||||
)
|
||||
predicted_index = int(torch.argmax(probabilities, dim=1).item())
|
||||
|
||||
labels = (
|
||||
model_manager.image_model
|
||||
.config
|
||||
.id2label
|
||||
)
|
||||
|
||||
label = labels[predicted_index]
|
||||
label = model_manager.image_model.config.id2label[predicted_index]
|
||||
|
||||
score = raw_scores[predicted_index]
|
||||
|
||||
print("====================")
|
||||
print("IMAGE RESULT")
|
||||
print("Labels:", labels)
|
||||
print("Label:", label)
|
||||
print("Score:", score)
|
||||
print("Scores:", raw_scores)
|
||||
logger.debug(
|
||||
"NSFW model: label=%s, score=%.4f, scores=%s",
|
||||
label, score, raw_scores
|
||||
)
|
||||
|
||||
return ImagePredictionResult(
|
||||
|
||||
label=label,
|
||||
|
||||
score=score,
|
||||
|
||||
approved=False,
|
||||
|
||||
raw_scores=raw_scores
|
||||
)
|
||||
|
||||
@@ -2,8 +2,23 @@ import torch
|
||||
from PIL import Image
|
||||
from transformers import Owlv2ForObjectDetection, Owlv2Processor
|
||||
|
||||
from app.config.logging import logger
|
||||
from app.config.settings import settings
|
||||
from app.ml.image.weapon_prediction_result import WeaponPredictionResult
|
||||
from app.ml.model_manager import model_manager
|
||||
|
||||
|
||||
def owlv2_target_size(width: int, height: int) -> tuple[int, int]:
|
||||
"""
|
||||
Размер для пересчёта боксов OWLv2 в пиксели.
|
||||
|
||||
OWLv2 дополняет картинку до квадрата, и координаты боксов относительны
|
||||
этого квадрата. Масштабирование на (height, width) сжимает боксы по
|
||||
короткой стороне — площадь занижается, и реальное оружие на вытянутом фото
|
||||
отсекается фильтром WEAPON_MIN_AREA_FRACTION.
|
||||
"""
|
||||
side = max(width, height)
|
||||
return side, side
|
||||
|
||||
|
||||
class WeaponDetector:
|
||||
@@ -27,42 +42,42 @@ class WeaponDetector:
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
print(f"Loading OWLv2 weapon detector on {self.device}")
|
||||
self.device = model_manager.get_device()
|
||||
logger.info("Loading OWLv2 weapon detector on %s", self.device)
|
||||
|
||||
self.model = Owlv2ForObjectDetection.from_pretrained(
|
||||
settings.WEAPON_MODEL
|
||||
)
|
||||
self.processor = Owlv2Processor.from_pretrained(
|
||||
settings.WEAPON_MODEL
|
||||
)
|
||||
self.model = Owlv2ForObjectDetection.from_pretrained(settings.WEAPON_MODEL)
|
||||
self.processor = Owlv2Processor.from_pretrained(settings.WEAPON_MODEL)
|
||||
|
||||
self.model.to(self.device)
|
||||
self.model.eval()
|
||||
|
||||
# Запросы постоянные — токенизируем один раз (и не трогаем
|
||||
# непотокобезопасный токенизатор из параллельных запросов).
|
||||
self.text_inputs = {
|
||||
key: value.to(self.device)
|
||||
for key, value in self.processor(
|
||||
text=self.QUERIES,
|
||||
return_tensors="pt"
|
||||
).items()
|
||||
}
|
||||
|
||||
def predict(
|
||||
self,
|
||||
image: Image.Image
|
||||
) -> WeaponPredictionResult:
|
||||
inputs = self.processor(
|
||||
text=self.QUERIES,
|
||||
pixel_values = self.processor(
|
||||
images=image,
|
||||
return_tensors="pt"
|
||||
)
|
||||
)["pixel_values"].to(self.device)
|
||||
|
||||
inputs = {
|
||||
key: value.to(self.device)
|
||||
for key, value in inputs.items()
|
||||
}
|
||||
with torch.inference_mode():
|
||||
outputs = self.model(pixel_values=pixel_values, **self.text_inputs)
|
||||
|
||||
with torch.no_grad():
|
||||
outputs = self.model(**inputs)
|
||||
|
||||
target_sizes = torch.tensor([image.size[::-1]])
|
||||
target_sizes = torch.tensor([owlv2_target_size(image.width, image.height)])
|
||||
|
||||
results = self.processor.post_process_grounded_object_detection(
|
||||
outputs,
|
||||
threshold=0.0,
|
||||
threshold=settings.WEAPON_THRESHOLD,
|
||||
target_sizes=target_sizes
|
||||
)[0]
|
||||
|
||||
@@ -74,7 +89,10 @@ class WeaponDetector:
|
||||
label_scores = {}
|
||||
|
||||
for score, label_index, box in zip(scores, labels, boxes):
|
||||
box_area = (box[2] - box[0]) * (box[3] - box[1])
|
||||
# Бокс может частично лежать в паддинге — обрезаем по самой картинке
|
||||
x0, y0 = max(box[0], 0.0), max(box[1], 0.0)
|
||||
x1, y1 = min(box[2], image.width), min(box[3], image.height)
|
||||
box_area = max(x1 - x0, 0.0) * max(y1 - y0, 0.0)
|
||||
|
||||
if box_area < image_area * settings.WEAPON_MIN_AREA_FRACTION:
|
||||
continue
|
||||
@@ -97,13 +115,11 @@ class WeaponDetector:
|
||||
key=label_scores.get
|
||||
)
|
||||
|
||||
print("====================")
|
||||
print("WEAPON RESULT")
|
||||
print("Scores:", label_scores)
|
||||
logger.debug("Weapon detector scores: %s", label_scores)
|
||||
|
||||
return WeaponPredictionResult(
|
||||
label=best_label,
|
||||
score=label_scores[best_label],
|
||||
detected_labels=sorted(label_scores.keys()),
|
||||
box_count=len(label_scores)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -11,65 +11,78 @@ from app.config.settings import settings
|
||||
|
||||
class ModelManager:
|
||||
|
||||
def __init__(self):
|
||||
self.device = None
|
||||
self.text_model = None
|
||||
self.text_tokenizer = None
|
||||
self.image_model = None
|
||||
self.image_processor = None
|
||||
def __init__(self):
|
||||
self.device = None
|
||||
self.text_model = None
|
||||
self.text_tokenizer = None
|
||||
self.image_model = None
|
||||
self.image_processor = None
|
||||
self.ready = False
|
||||
|
||||
def _setup_hf_token(self):
|
||||
if settings.HF_TOKEN:
|
||||
os.environ["HF_TOKEN"] = settings.HF_TOKEN
|
||||
os.environ["HUGGING_FACE_HUB_TOKEN"] = settings.HF_TOKEN
|
||||
def mark_ready(self):
|
||||
self.ready = True
|
||||
|
||||
def load_device(self):
|
||||
if settings.DEVICE == "auto":
|
||||
self.device = torch.device(
|
||||
"cuda" if torch.cuda.is_available() else "cpu"
|
||||
)
|
||||
else:
|
||||
self.device = torch.device(settings.DEVICE)
|
||||
def _setup_hf_token(self):
|
||||
# huggingface_hub читает токен из окружения, а .env pydantic-settings
|
||||
# в os.environ сам не выгружает
|
||||
if settings.HF_TOKEN:
|
||||
token = settings.HF_TOKEN.get_secret_value()
|
||||
os.environ.setdefault("HF_TOKEN", token)
|
||||
os.environ.setdefault("HUGGING_FACE_HUB_TOKEN", token)
|
||||
|
||||
def load_tokenizer(self):
|
||||
logger.info("Loading tokenizer...")
|
||||
self.text_tokenizer = AutoTokenizer.from_pretrained(
|
||||
settings.TEXT_MODEL,
|
||||
cache_dir=settings.MODEL_CACHE_DIR
|
||||
)
|
||||
logger.info("Tokenizer loaded.")
|
||||
def load_device(self):
|
||||
if settings.DEVICE == "auto":
|
||||
self.device = torch.device(
|
||||
"cuda" if torch.cuda.is_available() else "cpu"
|
||||
)
|
||||
else:
|
||||
self.device = torch.device(settings.DEVICE)
|
||||
|
||||
def load_model(self):
|
||||
logger.info("Loading model...")
|
||||
self.text_model = AutoModelForSequenceClassification.from_pretrained(
|
||||
settings.TEXT_MODEL,
|
||||
cache_dir=settings.MODEL_CACHE_DIR
|
||||
)
|
||||
self.text_model.to(self.device)
|
||||
self.text_model.eval()
|
||||
logger.debug("id2label: %s", self.text_model.config.id2label)
|
||||
logger.info("Text model loaded.")
|
||||
def get_device(self) -> torch.device:
|
||||
if self.device is None:
|
||||
self.load_device()
|
||||
return self.device
|
||||
|
||||
def load_image_model(self):
|
||||
logger.info("Loading image model...")
|
||||
self.image_processor = AutoImageProcessor.from_pretrained(
|
||||
settings.IMAGE_MODEL,
|
||||
cache_dir=settings.MODEL_CACHE_DIR
|
||||
)
|
||||
self.image_model = AutoModelForImageClassification.from_pretrained(
|
||||
settings.IMAGE_MODEL,
|
||||
cache_dir=settings.MODEL_CACHE_DIR
|
||||
)
|
||||
self.image_model.to(self.device)
|
||||
self.image_model.eval()
|
||||
logger.info("Image model loaded.")
|
||||
def load_tokenizer(self):
|
||||
logger.info("Loading tokenizer...")
|
||||
self.text_tokenizer = AutoTokenizer.from_pretrained(
|
||||
settings.TEXT_MODEL,
|
||||
cache_dir=settings.MODEL_CACHE_DIR
|
||||
)
|
||||
logger.info("Tokenizer loaded.")
|
||||
|
||||
def initialize(self):
|
||||
self.load_device()
|
||||
logger.info(f"Using device: {self.device}")
|
||||
self.load_tokenizer()
|
||||
self.load_model()
|
||||
self.load_image_model()
|
||||
def load_model(self):
|
||||
logger.info("Loading model...")
|
||||
self.text_model = AutoModelForSequenceClassification.from_pretrained(
|
||||
settings.TEXT_MODEL,
|
||||
cache_dir=settings.MODEL_CACHE_DIR
|
||||
)
|
||||
self.text_model.to(self.device)
|
||||
self.text_model.eval()
|
||||
logger.debug("id2label: %s", self.text_model.config.id2label)
|
||||
logger.info("Text model loaded.")
|
||||
|
||||
def load_image_model(self):
|
||||
logger.info("Loading image model...")
|
||||
self.image_processor = AutoImageProcessor.from_pretrained(
|
||||
settings.IMAGE_MODEL,
|
||||
cache_dir=settings.MODEL_CACHE_DIR
|
||||
)
|
||||
self.image_model = AutoModelForImageClassification.from_pretrained(
|
||||
settings.IMAGE_MODEL,
|
||||
cache_dir=settings.MODEL_CACHE_DIR
|
||||
)
|
||||
self.image_model.to(self.device)
|
||||
self.image_model.eval()
|
||||
logger.info("Image model loaded.")
|
||||
|
||||
def initialize(self):
|
||||
self._setup_hf_token()
|
||||
self.load_device()
|
||||
logger.info("Using device: %s", self.device)
|
||||
self.load_tokenizer()
|
||||
self.load_model()
|
||||
self.load_image_model()
|
||||
|
||||
|
||||
model_manager = ModelManager()
|
||||
|
||||
@@ -1,46 +1,100 @@
|
||||
import threading
|
||||
|
||||
import torch
|
||||
|
||||
from app.config.logging import logger
|
||||
from app.ml.model_manager import model_manager
|
||||
from app.ml.prediction_result import PredictionResult
|
||||
|
||||
# Длинный текст режем на перекрывающиеся окна: раньше всё после первых
|
||||
# 512 токенов модель не видела. Окно 128, а не 512: в длинном окне одна
|
||||
# токсичная фраза «тонет» в нейтральном тексте (проверено на textdetox:
|
||||
# фраза в конце ~1000 токенов — 0.06 при окне 512 и 0.99 при 128).
|
||||
# Короткие тексты (до ~126 токенов) идут в модель как раньше.
|
||||
MAX_TOKENS = 128
|
||||
WINDOW_STRIDE = 32
|
||||
|
||||
|
||||
def split_windows(ids: list[int], size: int, overlap: int) -> list[list[int]]:
|
||||
"""Перекрывающиеся окна по size токенов; последнее окно всегда до конца текста."""
|
||||
if len(ids) <= size:
|
||||
return [ids]
|
||||
step = max(size - overlap, 1)
|
||||
starts = list(range(0, len(ids) - size + 1, step))
|
||||
if starts[-1] + size < len(ids):
|
||||
starts.append(len(ids) - size)
|
||||
return [ids[start:start + size] for start in starts]
|
||||
|
||||
|
||||
def toxic_label_index(id2label: dict) -> int:
|
||||
"""Индекс класса «токсично»: по имени метки, иначе класс 1 (так у textdetox)."""
|
||||
for index, label in id2label.items():
|
||||
name = str(label).lower()
|
||||
if "toxic" in name and not name.startswith(("non", "not")):
|
||||
return int(index)
|
||||
return 1
|
||||
|
||||
|
||||
class TextClassifier:
|
||||
def predict(self, text: str):
|
||||
inputs = model_manager.text_tokenizer(
|
||||
text,
|
||||
return_tensors="pt",
|
||||
truncation=True,
|
||||
max_length=512,
|
||||
padding=True
|
||||
|
||||
def __init__(self):
|
||||
# Быстрый токенизатор HF не потокобезопасен при truncation/padding:
|
||||
# параллельные вызовы падают с «RuntimeError: Already borrowed».
|
||||
self._tokenizer_lock = threading.Lock()
|
||||
|
||||
def predict(self, text: str) -> PredictionResult:
|
||||
tokenizer = model_manager.text_tokenizer
|
||||
# Окна режем сами: return_overflowing_tokens у токенизаторов transformers 5
|
||||
# отдаёт не все куски, и конец текста модель не видела
|
||||
with self._tokenizer_lock:
|
||||
ids = tokenizer(
|
||||
text,
|
||||
add_special_tokens=False,
|
||||
truncation=False,
|
||||
verbose=False
|
||||
)["input_ids"]
|
||||
# Шаблон спецтокенов одиночной последовательности: [CLS] … [SEP]
|
||||
special = tokenizer("")["input_ids"]
|
||||
|
||||
prefix, suffix = special[:1], special[1:]
|
||||
windows = [
|
||||
prefix + window + suffix
|
||||
for window in split_windows(ids, MAX_TOKENS - len(special), WINDOW_STRIDE)
|
||||
]
|
||||
|
||||
width = max(len(window) for window in windows)
|
||||
pad_id = tokenizer.pad_token_id or 0
|
||||
input_ids = torch.tensor(
|
||||
[window + [pad_id] * (width - len(window)) for window in windows]
|
||||
)
|
||||
attention_mask = torch.tensor(
|
||||
[[1] * len(window) + [0] * (width - len(window)) for window in windows]
|
||||
)
|
||||
|
||||
inputs = {
|
||||
key: value.to(model_manager.device)
|
||||
for key, value in inputs.items()
|
||||
"input_ids": input_ids.to(model_manager.device),
|
||||
"attention_mask": attention_mask.to(model_manager.device),
|
||||
}
|
||||
|
||||
print(inputs)
|
||||
|
||||
with torch.no_grad():
|
||||
with torch.inference_mode():
|
||||
outputs = model_manager.text_model(**inputs)
|
||||
|
||||
print(outputs)
|
||||
|
||||
# [окна × классы]; итог — самое токсичное окно
|
||||
probabilities = torch.softmax(outputs.logits, dim=1)
|
||||
print("Labels:", model_manager.text_model.config.id2label)
|
||||
print("Logits:", outputs.logits)
|
||||
print("Probabilities:", probabilities)
|
||||
id2label = model_manager.text_model.config.id2label
|
||||
toxic_index = toxic_label_index(id2label)
|
||||
|
||||
print(probabilities)
|
||||
raw_scores = probabilities[0].tolist()
|
||||
score = raw_scores[1]
|
||||
window = int(torch.argmax(probabilities[:, toxic_index]).item())
|
||||
raw_scores = probabilities[window].tolist()
|
||||
score = raw_scores[toxic_index]
|
||||
|
||||
label = (
|
||||
model_manager.text_model.config.id2label.get(1, "LABEL_1")
|
||||
logger.debug(
|
||||
"Text toxicity: windows=%d, score=%.4f",
|
||||
probabilities.shape[0], score
|
||||
)
|
||||
|
||||
return PredictionResult(
|
||||
label=label,
|
||||
label=id2label.get(toxic_index, f"LABEL_{toxic_index}"),
|
||||
score=score,
|
||||
approved=False,
|
||||
raw_scores=raw_scores
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
|
||||
from app.config.settings import settings
|
||||
|
||||
|
||||
class TextRequest(BaseModel):
|
||||
text: str = Field(
|
||||
min_length=1,
|
||||
max_length=5000
|
||||
max_length=settings.TEXT_MAX_LENGTH
|
||||
)
|
||||
|
||||
69
ai-moderation/app/moderation/image/loader.py
Normal file
69
ai-moderation/app/moderation/image/loader.py
Normal file
@@ -0,0 +1,69 @@
|
||||
import io
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from app.config.settings import settings
|
||||
from app.exceptions.invalid_image_exception import InvalidImageException
|
||||
from app.moderation.image.validator import ImageValidator
|
||||
|
||||
# Разбираем только эти форматы: остальные плагины Pillow (EPS, PSD, TIFF…) —
|
||||
# лишняя поверхность атаки, а бэкенд шлёт JPEG.
|
||||
ALLOWED_FORMATS = ("JPEG", "PNG", "WEBP")
|
||||
|
||||
# Встроенная защита Pillow от «бомб»: предупреждение выше лимита, ошибка
|
||||
# выше двойного. Свой лимит проверяем раньше, в валидаторе.
|
||||
Image.MAX_IMAGE_PIXELS = settings.MAX_IMAGE_PIXELS
|
||||
|
||||
|
||||
class CorruptImageError(Exception):
|
||||
"""Файл не удалось разобрать как картинку разрешённого формата."""
|
||||
|
||||
|
||||
def _flatten_alpha(image: Image.Image) -> Image.Image:
|
||||
# convert("RGB") просто отбрасывает альфу и показывает модели пиксели,
|
||||
# которые пользователь не видит. Кладём на белый фон — как в браузере.
|
||||
if image.mode in ("RGBA", "LA", "PA") or (
|
||||
image.mode == "P" and "transparency" in image.info
|
||||
):
|
||||
rgba = image.convert("RGBA")
|
||||
background = Image.new("RGB", rgba.size, (255, 255, 255))
|
||||
background.paste(rgba, mask=rgba.getchannel("A"))
|
||||
return background
|
||||
return image.convert("RGB")
|
||||
|
||||
|
||||
def load_image(
|
||||
data: bytes,
|
||||
validator: ImageValidator,
|
||||
max_side: int | None = None
|
||||
) -> Image.Image:
|
||||
"""
|
||||
Безопасно декодирует картинку для модерации.
|
||||
|
||||
Размеры проверяются по заголовку до декодирования, JPEG сразу
|
||||
декодируется в уменьшенном масштабе, результат — RGB не больше max_side.
|
||||
"""
|
||||
max_side = max_side or settings.MODERATION_MAX_SIDE
|
||||
|
||||
try:
|
||||
image = Image.open(io.BytesIO(data), formats=ALLOWED_FORMATS)
|
||||
except (UnidentifiedImageError, Image.DecompressionBombError, OSError) as ex:
|
||||
raise CorruptImageError(str(ex)) from ex
|
||||
|
||||
validator.validate(image)
|
||||
|
||||
try:
|
||||
# JPEG: декодер сразу уменьшает в 2/4/8 раз — в разы меньше памяти и CPU
|
||||
image.draft("RGB", (max_side, max_side))
|
||||
image.load()
|
||||
# Фото с телефона хранят поворот в EXIF — без этого модели видят его боком
|
||||
image = ImageOps.exif_transpose(image)
|
||||
image.thumbnail((max_side, max_side), Image.Resampling.LANCZOS)
|
||||
return _flatten_alpha(image)
|
||||
except InvalidImageException:
|
||||
raise
|
||||
except Exception as ex:
|
||||
# Битые/обрезанные файлы падают в Pillow самыми разными исключениями
|
||||
# (OSError, ValueError, SyntaxError, struct.error…). Это ошибка клиента,
|
||||
# а не сервера: 500 заставил бы бэкенд бесконечно повторять запрос.
|
||||
raise CorruptImageError(str(ex)) from ex
|
||||
@@ -1,5 +1,6 @@
|
||||
from PIL import Image
|
||||
|
||||
from app.config.settings import settings
|
||||
from app.exceptions.invalid_image_exception import InvalidImageException
|
||||
|
||||
|
||||
@@ -10,11 +11,16 @@ class ImageValidator:
|
||||
MAX_WIDTH = 10000
|
||||
MAX_HEIGHT = 10000
|
||||
|
||||
# Полоски 50×10000 после уменьшения превращаются в 6×1280, а препроцессоры
|
||||
# моделей растягивают короткую сторону до 224 — модели видят мусор.
|
||||
MAX_ASPECT_RATIO = 20
|
||||
|
||||
def validate(
|
||||
self,
|
||||
image: Image.Image
|
||||
) -> None:
|
||||
|
||||
# image.size берётся из заголовка — проверка не декодирует пиксели и
|
||||
# годится для ещё не загруженной картинки
|
||||
width, height = image.size
|
||||
|
||||
if width < self.MIN_WIDTH:
|
||||
@@ -36,3 +42,13 @@ class ImageValidator:
|
||||
raise InvalidImageException(
|
||||
f"Image height is too large: {height}"
|
||||
)
|
||||
|
||||
if width * height > settings.MAX_IMAGE_PIXELS:
|
||||
raise InvalidImageException(
|
||||
f"Image has too many pixels: {width}x{height}"
|
||||
)
|
||||
|
||||
if max(width, height) > self.MAX_ASPECT_RATIO * min(width, height):
|
||||
raise InvalidImageException(
|
||||
f"Image aspect ratio is too extreme: {width}x{height}"
|
||||
)
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
import re
|
||||
|
||||
from app.moderation.profanity.dictionary import ProfanityDictionary
|
||||
from app.moderation.profanity.dictionary import ProfanityDictionary, normalize_word
|
||||
from app.moderation.profanity.lemmatizer import Lemmatizer
|
||||
|
||||
# Слова из кириллицы, латиницы и цифр (в словаре есть транслит и «6ля»),
|
||||
# в том числе через дефис («бляха-муха»)
|
||||
TOKEN_RE = re.compile(r"[0-9a-zа-яё]+(?:-[0-9a-zа-яё]+)*")
|
||||
LETTERS_RE = re.compile(r"[a-zа-яё]+")
|
||||
CYRILLIC_RE = re.compile(r"[а-яё]")
|
||||
LATIN_RE = re.compile(r"[a-z]")
|
||||
DIGIT_RE = re.compile(r"[0-9]")
|
||||
|
||||
# Обход фильтра заменой букв на похожие из другого алфавита («xуй» с
|
||||
# латинской x) или цифры («п0рн»)
|
||||
LATIN_TO_CYRILLIC = str.maketrans("aceopxykmt036", "асеорхукмтозб")
|
||||
CYRILLIC_TO_LATIN = str.maketrans("асеорхукмт", "aceopxykmt")
|
||||
|
||||
|
||||
class ProfanityDetector:
|
||||
|
||||
def __init__(
|
||||
@@ -14,30 +28,49 @@ class ProfanityDetector:
|
||||
self.dictionary = dictionary
|
||||
self.lemmatizer = lemmatizer
|
||||
|
||||
@staticmethod
|
||||
def _variants(token: str) -> set[str]:
|
||||
variants = {token}
|
||||
has_cyrillic = bool(CYRILLIC_RE.search(token))
|
||||
has_latin = bool(LATIN_RE.search(token))
|
||||
|
||||
if has_cyrillic and (has_latin or DIGIT_RE.search(token)):
|
||||
variants.add(token.translate(LATIN_TO_CYRILLIC))
|
||||
if has_latin and has_cyrillic:
|
||||
variants.add(token.translate(CYRILLIC_TO_LATIN))
|
||||
|
||||
# «бля123», «ах-ху» → проверяем и отдельные части
|
||||
for variant in list(variants):
|
||||
variants.update(LETTERS_RE.findall(variant))
|
||||
|
||||
return variants
|
||||
|
||||
def _is_profane(self, word: str) -> bool:
|
||||
words = self.dictionary.words
|
||||
is_russian = bool(CYRILLIC_RE.search(word)) and not LATIN_RE.search(word)
|
||||
|
||||
if not is_russian:
|
||||
# транслит и «6ля» — только точное совпадение
|
||||
return word in words
|
||||
|
||||
# Обычные слова сверяем по лемме: прямое совпадение формы дало бы ложные
|
||||
# срабатывания («буфера», «опущенный» — формы из словаря). Сленг и
|
||||
# опечатки pymorphy не знает и лемматизирует плохо — их сверяем как есть.
|
||||
if word in words and not self.lemmatizer.is_known(word):
|
||||
return True
|
||||
|
||||
lemma = normalize_word(self.lemmatizer.normalize(word))
|
||||
return lemma in words
|
||||
|
||||
def detect(
|
||||
self,
|
||||
text: str
|
||||
) -> list[str]:
|
||||
|
||||
words = re.findall(
|
||||
r"[а-яА-ЯёЁ]+",
|
||||
text.lower()
|
||||
)
|
||||
|
||||
result = []
|
||||
|
||||
for word in words:
|
||||
for token in TOKEN_RE.findall(normalize_word(text)):
|
||||
if any(self._is_profane(variant) for variant in self._variants(token)):
|
||||
result.append(token)
|
||||
|
||||
lemma = self.lemmatizer.normalize(word)
|
||||
|
||||
|
||||
for bad_word in self.dictionary.words:
|
||||
|
||||
if lemma == bad_word or lemma.startswith(bad_word + "-"):
|
||||
|
||||
result.append(word)
|
||||
|
||||
break
|
||||
|
||||
|
||||
return result
|
||||
return result
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def normalize_word(word: str) -> str:
|
||||
return word.strip().lower().replace("", "").replace("ё", "е")
|
||||
|
||||
|
||||
class ProfanityDictionary:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
file_path: str
|
||||
file_path: str | Path
|
||||
):
|
||||
|
||||
self.words = self.load(file_path)
|
||||
|
||||
|
||||
|
||||
def load(
|
||||
self,
|
||||
file_path: str
|
||||
) -> set[str]:
|
||||
file_path: str | Path
|
||||
) -> frozenset[str]:
|
||||
|
||||
path = Path(file_path)
|
||||
|
||||
@@ -23,22 +26,21 @@ class ProfanityDictionary:
|
||||
f"Profanity dictionary not found: {file_path}"
|
||||
)
|
||||
|
||||
|
||||
with open(
|
||||
path,
|
||||
"r",
|
||||
encoding="utf-8"
|
||||
) as file:
|
||||
|
||||
return {
|
||||
line.strip().lower().replace("\ufeff", "")
|
||||
return frozenset(
|
||||
normalize_word(line)
|
||||
for line in file
|
||||
if line.strip()
|
||||
}
|
||||
if normalize_word(line)
|
||||
)
|
||||
|
||||
def contains(
|
||||
self,
|
||||
word: str
|
||||
) -> bool:
|
||||
|
||||
return word in self.words
|
||||
return word in self.words
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from functools import lru_cache
|
||||
|
||||
import pymorphy3
|
||||
|
||||
|
||||
@@ -5,11 +7,21 @@ class Lemmatizer:
|
||||
|
||||
def __init__(self):
|
||||
self.morph = pymorphy3.MorphAnalyzer()
|
||||
# Разбор pymorphy — самое дорогое в детекторе, а слова повторяются
|
||||
self._normalize_cached = lru_cache(maxsize=50_000)(self._normalize)
|
||||
self._is_known_cached = lru_cache(maxsize=50_000)(self.morph.word_is_known)
|
||||
|
||||
def is_known(self, word: str) -> bool:
|
||||
"""Есть ли слово в словаре pymorphy (обычное слово, а не сленг/опечатка)."""
|
||||
return self._is_known_cached(word)
|
||||
|
||||
def _normalize(self, word: str) -> str:
|
||||
result = self.morph.parse(word)
|
||||
|
||||
return result[0].normal_form
|
||||
|
||||
def normalize(
|
||||
self,
|
||||
word: str
|
||||
) -> str:
|
||||
result = self.morph.parse(word)
|
||||
|
||||
return result[0].normal_form
|
||||
return self._normalize_cached(word)
|
||||
|
||||
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