fix desktop version

This commit is contained in:
SlimusMinus
2026-10-23 00:12:34 +03:00
parent 3983e9a2f8
commit ea3abd88d1
6 changed files with 467 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
from types import SimpleNamespace
import torch
from app.ml import text_classifier as module
from app.ml.text_classifier import TextClassifier, split_windows, toxic_label_index
CLS, SEP, TOXIC_TOKEN = 101, 102, 999
def test_toxic_label_index():
assert toxic_label_index({0: "LABEL_0", 1: "LABEL_1"}) == 1
assert toxic_label_index({0: "toxic", 1: "neutral"}) == 0
assert toxic_label_index({0: "non-toxic", 1: "toxic"}) == 1
def test_split_windows_cover_whole_text():
ids = list(range(300))
windows = split_windows(ids, size=126, overlap=32)
assert all(len(window) <= 126 for window in windows)
assert windows[0][0] == 0
assert windows[-1][-1] == 299
covered = {token for window in windows for token in window}
assert covered == set(ids)
def test_short_text_is_single_window():
assert split_windows([1, 2, 3], size=126, overlap=32) == [[1, 2, 3]]
class FakeTokenizer:
pad_token_id = 0
def __call__(self, text, **kwargs):
if not text:
return {"input_ids": [CLS, SEP]}
# 600 «нейтральных» токенов и один токсичный в самом конце
return {"input_ids": [5] * 600 + [TOXIC_TOKEN]}
class FakeModel:
config = SimpleNamespace(id2label={0: "LABEL_0", 1: "LABEL_1"})
def __init__(self):
self.batch = None
def __call__(self, input_ids, attention_mask):
self.batch = input_ids
toxic = (input_ids == TOXIC_TOKEN).any(dim=1).float() * 8 - 4
return SimpleNamespace(logits=torch.stack([-toxic, toxic], dim=1))
def test_toxic_tail_of_long_text_is_seen(monkeypatch):
model = FakeModel()
monkeypatch.setattr(module.model_manager, "text_tokenizer", FakeTokenizer())
monkeypatch.setattr(module.model_manager, "text_model", model)
monkeypatch.setattr(module.model_manager, "device", torch.device("cpu"))
result = TextClassifier().predict("длинный текст")
assert model.batch.shape[0] > 1
assert model.batch.shape[1] <= module.MAX_TOKENS
assert (model.batch[:, 0] == CLS).all()
assert result.score > 0.99
assert result.label == "LABEL_1"