Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,6 +5,14 @@ import pickle
|
|
| 5 |
import torch
|
| 6 |
from transformers import AutoTokenizer, AutoModel
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
# ---------------------------
|
| 9 |
# ЗАГРУЗКА BERT
|
| 10 |
# ---------------------------
|
|
@@ -22,98 +30,58 @@ keras_model = tf.keras.models.load_model("model.h5")
|
|
| 22 |
|
| 23 |
EMOTIONS = ["neutral", "joy", "sadness", "anger", "fear", "surprise"]
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
# ---------------------------
|
| 27 |
-
#
|
| 28 |
# ---------------------------
|
| 29 |
def preprocess_text(text):
|
| 30 |
-
def preprocess_text(text):
|
| 31 |
|
| 32 |
-
text = remove_duplicate_emojis(text)
|
| 33 |
if is_emoji_spam(text):
|
| 34 |
text = remove_all_emojis(text)
|
| 35 |
|
| 36 |
-
text = str(text).lower()
|
| 37 |
-
text = re.sub(r'http\S+|www\S+|https\S+', '', text)
|
| 38 |
-
text = re.sub(r'@\w+|#\w+', '', text)
|
| 39 |
-
text = text.translate(str.maketrans('', '', string.punctuation))
|
| 40 |
|
| 41 |
-
text = emoji.demojize(text)
|
| 42 |
|
| 43 |
-
text = re.sub(r'\d+', '', text)
|
| 44 |
|
| 45 |
try:
|
| 46 |
-
tokens = word_tokenize(text, language="russian")
|
| 47 |
except:
|
| 48 |
tokens = text.split()
|
| 49 |
|
| 50 |
try:
|
| 51 |
-
stop_words = set(stopwords.words('russian'))
|
| 52 |
except:
|
| 53 |
stop_words = set()
|
| 54 |
|
| 55 |
-
tokens = [
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
try:
|
| 59 |
-
lemmatizer = pymorphy2.MorphAnalyzer()
|
| 60 |
tokens = [lemmatizer.parse(word)[0].normal_form for word in tokens]
|
| 61 |
except:
|
| 62 |
pass
|
| 63 |
|
| 64 |
-
|
| 65 |
return ' '.join(tokens)
|
| 66 |
-
return text
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
# ---------------------------
|
| 70 |
-
# ВЕКТОРИЗАЦИЯ ЧЕРЕЗ BERT
|
| 71 |
-
# ---------------------------
|
| 72 |
-
def bert_vector(text):
|
| 73 |
-
inputs = tokenizer(
|
| 74 |
-
text,
|
| 75 |
-
return_tensors='pt',
|
| 76 |
-
truncation=True,
|
| 77 |
-
max_length=256,
|
| 78 |
-
padding='max_length'
|
| 79 |
-
)
|
| 80 |
-
with torch.no_grad():
|
| 81 |
-
output = bert_model(**inputs)
|
| 82 |
-
|
| 83 |
-
embeddings = output.last_hidden_state
|
| 84 |
-
mask = inputs['attention_mask'].unsqueeze(-1).expand(embeddings.size()).float()
|
| 85 |
-
|
| 86 |
-
masked_embeddings = embeddings * mask
|
| 87 |
-
summed = torch.sum(masked_embeddings, 1)
|
| 88 |
-
counted = torch.clamp(mask.sum(1), min=1e-9)
|
| 89 |
-
|
| 90 |
-
mean_pooled = summed / counted
|
| 91 |
-
return mean_pooled.squeeze().numpy()
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
# ---------------------------
|
| 95 |
-
# ПРЕДСКАЗАНИЕ
|
| 96 |
-
# ---------------------------
|
| 97 |
-
def predict(text):
|
| 98 |
-
text_clean = preprocess_text(text)
|
| 99 |
-
|
| 100 |
-
vec = bert_vector(text_clean)
|
| 101 |
-
vec_scaled = scaler.transform([vec])
|
| 102 |
-
|
| 103 |
-
preds = keras_model.predict(vec_scaled)[0]
|
| 104 |
-
|
| 105 |
-
return {EMOTIONS[i]: float(preds[i]) for i in range(len(EMOTIONS))}
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
# ---------------------------
|
| 109 |
-
# GRADIO UI
|
| 110 |
-
# ---------------------------
|
| 111 |
-
demo = gr.Interface(
|
| 112 |
-
fn=predict,
|
| 113 |
-
inputs=gr.Textbox(label="Введите текст"),
|
| 114 |
-
outputs=gr.Label(num_top_classes=len(EMOTIONS)),
|
| 115 |
-
title="Классификация эмоций (ruBERT + Keras)",
|
| 116 |
-
description="Подаём текст → очистка → BERT-вектор → нормализация → Keras нейросеть"
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
demo.launch()
|
|
|
|
| 5 |
import torch
|
| 6 |
from transformers import AutoTokenizer, AutoModel
|
| 7 |
|
| 8 |
+
# добавляем нужные импорты
|
| 9 |
+
import re
|
| 10 |
+
import string
|
| 11 |
+
import emoji
|
| 12 |
+
import pymorphy2
|
| 13 |
+
from nltk.tokenize import word_tokenize
|
| 14 |
+
from nltk.corpus import stopwords
|
| 15 |
+
|
| 16 |
# ---------------------------
|
| 17 |
# ЗАГРУЗКА BERT
|
| 18 |
# ---------------------------
|
|
|
|
| 30 |
|
| 31 |
EMOTIONS = ["neutral", "joy", "sadness", "anger", "fear", "surprise"]
|
| 32 |
|
| 33 |
+
# ---------------------------------------
|
| 34 |
+
# ФУНКЦИИ ДЛЯ ОБРАБОТКИ ЭМОДЗИ (добавь свои)
|
| 35 |
+
# ---------------------------------------
|
| 36 |
+
def remove_duplicate_emojis(text):
|
| 37 |
+
return text # заглушка — поставь свою реализацию
|
| 38 |
+
|
| 39 |
+
def is_emoji_spam(text):
|
| 40 |
+
return False # заглушка — поставь свою реализацию
|
| 41 |
+
|
| 42 |
+
def remove_all_emojis(text):
|
| 43 |
+
return text # заглушка — поставь свою реализацию
|
| 44 |
+
|
| 45 |
|
| 46 |
# ---------------------------
|
| 47 |
+
# ПРЕДОБРАБОТКА ТЕКСТА
|
| 48 |
# ---------------------------
|
| 49 |
def preprocess_text(text):
|
|
|
|
| 50 |
|
| 51 |
+
text = remove_duplicate_emojis(text)
|
| 52 |
if is_emoji_spam(text):
|
| 53 |
text = remove_all_emojis(text)
|
| 54 |
|
| 55 |
+
text = str(text).lower()
|
| 56 |
+
text = re.sub(r'http\S+|www\S+|https\S+', '', text)
|
| 57 |
+
text = re.sub(r'@\w+|#\w+', '', text)
|
| 58 |
+
text = text.translate(str.maketrans('', '', string.punctuation))
|
| 59 |
|
| 60 |
+
text = emoji.demojize(text)
|
| 61 |
|
| 62 |
+
text = re.sub(r'\d+', '', text)
|
| 63 |
|
| 64 |
try:
|
| 65 |
+
tokens = word_tokenize(text, language="russian")
|
| 66 |
except:
|
| 67 |
tokens = text.split()
|
| 68 |
|
| 69 |
try:
|
| 70 |
+
stop_words = set(stopwords.words('russian'))
|
| 71 |
except:
|
| 72 |
stop_words = set()
|
| 73 |
|
| 74 |
+
tokens = [
|
| 75 |
+
word for word in tokens
|
| 76 |
+
if (word.isalpha() or (word.startswith(':') and word.endswith(':')))
|
| 77 |
+
and word not in stop_words
|
| 78 |
+
and len(word) > 2
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
try:
|
| 82 |
+
lemmatizer = pymorphy2.MorphAnalyzer()
|
| 83 |
tokens = [lemmatizer.parse(word)[0].normal_form for word in tokens]
|
| 84 |
except:
|
| 85 |
pass
|
| 86 |
|
|
|
|
| 87 |
return ' '.join(tokens)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|