fix problem from claude

This commit is contained in:
SlimusMinus
2026-10-20 00:37:43 +03:00
parent f01f776d32
commit 28d91ce6d4
31 changed files with 994 additions and 284 deletions

View 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

View File

@@ -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}"
)

View File

@@ -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

View File

@@ -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

View File

@@ -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)