EagleOfEmpire commited on
Commit
3df8d53
·
verified ·
1 Parent(s): 20f7681

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -70
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)#меняет всё, что начинается с hhtp, www, https на ''. S+ - один или более непробельных символов, | - или
38
- text = re.sub(r'@\w+|#\w+', '', text)#удалили упоминания и хэштеги. \w+ - одна или более цифра/буква/нижнее подчёркивание.
39
- text = text.translate(str.maketrans('', '', string.punctuation))#удалили пунктуацию. str.maketrans(, , <символы для полного удаления>), text.translate - применение maketrans.
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 = [word for word in tokens if (word.isalpha() or (word.startswith(':') and word.endswith(':'))) and word not in stop_words and len(word) > 2]
56
- #использование isalpha - удаление всего, что имеет в составе цифры, знаки препинания, удаление стоп слова и очень коротких слов
57
- #но оставить метки смайликов
 
 
 
 
58
  try:
59
- lemmatizer = pymorphy2.MorphAnalyzer()# лемматизация, используя pymorphy
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)