Files
2026-10-20 00:37:43 +03:00

77 lines
2.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
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__(
self,
dictionary: ProfanityDictionary,
lemmatizer: Lemmatizer
):
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]:
result = []
for token in TOKEN_RE.findall(normalize_word(text)):
if any(self._is_profane(variant) for variant in self._variants(token)):
result.append(token)
return result