Spaces:
Paused
Paused
Update func_ai.py
Browse files- func_ai.py +10 -44
func_ai.py
CHANGED
@@ -3,11 +3,11 @@ import torch
|
|
3 |
from transformers import pipeline
|
4 |
from deep_translator import GoogleTranslator
|
5 |
import time
|
6 |
-
import os
|
7 |
|
8 |
VECTOR_API_URL = os.getenv('API_URL')
|
9 |
|
10 |
-
#
|
11 |
sentiment_model = pipeline(
|
12 |
'sentiment-analysis',
|
13 |
model='distilbert-base-uncased-finetuned-sst-2-english',
|
@@ -15,37 +15,6 @@ sentiment_model = pipeline(
|
|
15 |
device=0 if torch.cuda.is_available() else -1
|
16 |
)
|
17 |
|
18 |
-
classifier = pipeline(
|
19 |
-
"zero-shot-classification",
|
20 |
-
model="valhalla/distilbart-mnli-12-6",
|
21 |
-
device=0 if torch.cuda.is_available() else -1
|
22 |
-
)
|
23 |
-
|
24 |
-
def classify_comment(text):
|
25 |
-
if not text:
|
26 |
-
print("Received empty text for classification.")
|
27 |
-
return "non-interrogative"
|
28 |
-
print(f"Classifying comment: {text}")
|
29 |
-
try:
|
30 |
-
translated_text = GoogleTranslator(source='auto', target="en").translate(text)
|
31 |
-
print(f"Translated text: {translated_text}")
|
32 |
-
except Exception as e:
|
33 |
-
print(f"Translation failed: {e}")
|
34 |
-
return "non-interrogative"
|
35 |
-
if not translated_text:
|
36 |
-
print("Translation returned empty text.")
|
37 |
-
return "non-interrogative"
|
38 |
-
|
39 |
-
try:
|
40 |
-
result = classifier(translated_text, ["interrogative", "non-interrogative"], clean_up_tokenization_spaces=True)
|
41 |
-
print(f"Classification result: {result}")
|
42 |
-
except Exception as e:
|
43 |
-
print(f"Classification failed: {e}")
|
44 |
-
return "non-interrogative"
|
45 |
-
|
46 |
-
top_class = result['labels'][0]
|
47 |
-
print(f"Top class: {top_class}")
|
48 |
-
return top_class
|
49 |
|
50 |
def retrieve_from_vdb(query):
|
51 |
print(f"Отправка запроса к FastAPI сервису: {query}")
|
@@ -58,20 +27,18 @@ def retrieve_from_vdb(query):
|
|
58 |
print(f"Ошибка при поиске: {response.text}")
|
59 |
return []
|
60 |
|
61 |
-
from deep_translator import GoogleTranslator
|
62 |
-
import time
|
63 |
|
64 |
def analyze_sentiment(comments):
|
65 |
print("Начинаем анализ настроений.")
|
66 |
results = []
|
67 |
-
|
68 |
for i in range(0, len(comments), 50):
|
69 |
batch = comments[i:i + 50]
|
70 |
print(f"Анализируем батч с {i} по {i + len(batch)} комментарий: {batch}")
|
71 |
-
|
72 |
translated_batch = []
|
73 |
valid_comments = [] # Список комментариев с успешным переводом
|
74 |
-
|
75 |
for comment in batch:
|
76 |
try:
|
77 |
translated = GoogleTranslator(source='auto', target="en").translate(comment)
|
@@ -82,13 +49,13 @@ def analyze_sentiment(comments):
|
|
82 |
print(f"Перевод комментария не удался или вернул пустую строку: {comment}")
|
83 |
except Exception as e:
|
84 |
print(f"Ошибка при переводе комментария '{comment}': {e}")
|
85 |
-
|
86 |
if not translated_batch:
|
87 |
print("Все переводы в этом батче не удались. Пропускаем этот батч.")
|
88 |
continue # Переходим к следующему батчу, если перевод не удался
|
89 |
-
|
90 |
print(f"Переведённый батч: {translated_batch}")
|
91 |
-
|
92 |
try:
|
93 |
batch_results = sentiment_model(translated_batch)
|
94 |
print(f"Результаты батча: {batch_results}")
|
@@ -98,9 +65,8 @@ def analyze_sentiment(comments):
|
|
98 |
# Добавляем результат с неопределенным настроением для каждого переведенного комментария
|
99 |
for _ in translated_batch:
|
100 |
results.append({'label': 'UNKNOWN', 'score': 0.0})
|
101 |
-
|
102 |
time.sleep(1) # Задержка для предотвращения перегрузки API
|
103 |
-
|
104 |
print(f"Анализ настроений завершен. Общие результаты: {results}")
|
105 |
return results
|
106 |
-
|
|
|
3 |
from transformers import pipeline
|
4 |
from deep_translator import GoogleTranslator
|
5 |
import time
|
6 |
+
import os
|
7 |
|
8 |
VECTOR_API_URL = os.getenv('API_URL')
|
9 |
|
10 |
+
# Модель для анализа настроений
|
11 |
sentiment_model = pipeline(
|
12 |
'sentiment-analysis',
|
13 |
model='distilbert-base-uncased-finetuned-sst-2-english',
|
|
|
15 |
device=0 if torch.cuda.is_available() else -1
|
16 |
)
|
17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
def retrieve_from_vdb(query):
|
20 |
print(f"Отправка запроса к FastAPI сервису: {query}")
|
|
|
27 |
print(f"Ошибка при поиске: {response.text}")
|
28 |
return []
|
29 |
|
|
|
|
|
30 |
|
31 |
def analyze_sentiment(comments):
|
32 |
print("Начинаем анализ настроений.")
|
33 |
results = []
|
34 |
+
|
35 |
for i in range(0, len(comments), 50):
|
36 |
batch = comments[i:i + 50]
|
37 |
print(f"Анализируем батч с {i} по {i + len(batch)} комментарий: {batch}")
|
38 |
+
|
39 |
translated_batch = []
|
40 |
valid_comments = [] # Список комментариев с успешным переводом
|
41 |
+
|
42 |
for comment in batch:
|
43 |
try:
|
44 |
translated = GoogleTranslator(source='auto', target="en").translate(comment)
|
|
|
49 |
print(f"Перевод комментария не удался или вернул пустую строку: {comment}")
|
50 |
except Exception as e:
|
51 |
print(f"Ошибка при переводе комментария '{comment}': {e}")
|
52 |
+
|
53 |
if not translated_batch:
|
54 |
print("Все переводы в этом батче не удались. Пропускаем этот батч.")
|
55 |
continue # Переходим к следующему батчу, если перевод не удался
|
56 |
+
|
57 |
print(f"Переведённый батч: {translated_batch}")
|
58 |
+
|
59 |
try:
|
60 |
batch_results = sentiment_model(translated_batch)
|
61 |
print(f"Результаты батча: {batch_results}")
|
|
|
65 |
# Добавляем результат с неопределенным настроением для каждого переведенного комментария
|
66 |
for _ in translated_batch:
|
67 |
results.append({'label': 'UNKNOWN', 'score': 0.0})
|
68 |
+
|
69 |
time.sleep(1) # Задержка для предотвращения перегрузки API
|
70 |
+
|
71 |
print(f"Анализ настроений завершен. Общие результаты: {results}")
|
72 |
return results
|
|