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

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