Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,151 +1,68 @@
|
|
1 |
-
import gradio as gr
|
2 |
import os
|
3 |
-
|
4 |
-
|
5 |
import numpy as np
|
6 |
-
import
|
7 |
-
import
|
8 |
|
9 |
-
#
|
10 |
-
|
11 |
-
files = {
|
12 |
-
"vampires": "vampires.txt"
|
13 |
-
}
|
14 |
-
|
15 |
-
knowledge_base = {}
|
16 |
-
for category, filename in files.items():
|
17 |
-
try:
|
18 |
-
with open(filename, 'r', encoding='utf-8') as file:
|
19 |
-
content = file.read()
|
20 |
-
# Разбиваем на осмысленные блоки (абзацы)
|
21 |
-
paragraphs = [p.strip() for p in content.split('\n\n') if p.strip()]
|
22 |
-
knowledge_base[category] = paragraphs
|
23 |
-
except FileNotFoundError:
|
24 |
-
print(f"Файл {filename} не найден")
|
25 |
-
knowledge_base[category] = []
|
26 |
-
|
27 |
-
return knowledge_base
|
28 |
|
29 |
-
#
|
30 |
-
|
31 |
-
return SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
|
32 |
|
33 |
-
#
|
34 |
-
|
35 |
-
|
36 |
-
for category, paragraphs in knowledge_base.items():
|
37 |
-
for para in paragraphs:
|
38 |
-
all_fragments.append((para, category))
|
39 |
-
|
40 |
-
if not all_fragments:
|
41 |
-
return []
|
42 |
-
|
43 |
-
texts = [f[0] for f in all_fragments]
|
44 |
-
embeddings = model.encode(texts)
|
45 |
-
question_embedding = model.encode([question])
|
46 |
-
|
47 |
-
similarities = np.dot(embeddings, question_embedding.T).flatten()
|
48 |
-
top_indices = similarities.argsort()[-top_k:][::-1]
|
49 |
-
|
50 |
-
return [all_fragments[i] for i in top_indices]
|
51 |
|
52 |
-
#
|
53 |
-
def
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
endings = [
|
84 |
-
"Надеюсь, эта информация была полезной!",
|
85 |
-
"Если хотите узнать больше деталей, уточните вопрос.",
|
86 |
-
"Могу уточнить какие-то моменты, если нужно.",
|
87 |
-
"Это основные сведения, которые у меня есть."
|
88 |
-
]
|
89 |
-
|
90 |
-
response += random.choice(endings)
|
91 |
-
|
92 |
return response
|
93 |
|
94 |
-
#
|
95 |
-
|
96 |
-
|
97 |
-
if detect(question) != 'ru':
|
98 |
-
return "Пожалуйста, задавайте вопросы на русском языке.", history
|
99 |
-
except:
|
100 |
-
pass
|
101 |
-
|
102 |
-
if not hasattr(process_question, 'knowledge_base'):
|
103 |
-
process_question.knowledge_base = load_and_preprocess_files()
|
104 |
-
|
105 |
-
if not hasattr(process_question, 'search_model'):
|
106 |
-
process_question.search_model = initialize_search_model()
|
107 |
-
|
108 |
-
relevant_info = find_relevant_info(question, process_question.knowledge_base, process_question.search_model)
|
109 |
-
answer = generate_natural_response(question, relevant_info)
|
110 |
-
history.append((question, answer))
|
111 |
-
return "", history
|
112 |
|
113 |
-
|
114 |
-
|
115 |
-
gr.Markdown("""<h1 style='text-align: center'>🧛♂️ Мир сверхъестественного 🐺</h1>""")
|
116 |
-
gr.Markdown("""<div style='text-align: center'>Задавайте вопросы о вампирах, оборотнях и людях на русском языке</div>""")
|
117 |
-
|
118 |
-
# Сначала определяем элементы ввода
|
119 |
-
msg = gr.Textbox(
|
120 |
-
label="Ваш вопрос",
|
121 |
-
placeholder="Введите вопрос и нажмите Enter...",
|
122 |
-
container=False
|
123 |
-
)
|
124 |
-
|
125 |
-
# Затем определяем примеры, которые используют msg
|
126 |
-
examples = gr.Examples(
|
127 |
examples=[
|
128 |
-
"Какие
|
129 |
-
"
|
130 |
-
"
|
131 |
-
"Расскажи подробнее о вампирах"
|
132 |
],
|
133 |
-
|
134 |
-
|
135 |
-
)
|
136 |
-
|
137 |
-
# Затем определяем чат
|
138 |
-
chatbot = gr.Chatbot(
|
139 |
-
label="Диалог",
|
140 |
-
height=500
|
141 |
)
|
142 |
-
|
143 |
-
with gr.Row():
|
144 |
-
submit = gr.Button("Отправить", variant="primary")
|
145 |
-
clear = gr.Button("Очистить историю")
|
146 |
-
|
147 |
-
submit.click(process_question, [msg, chatbot], [msg, chatbot])
|
148 |
-
msg.submit(process_question, [msg, chatbot], [msg, chatbot])
|
149 |
-
clear.click(lambda: None, None, chatbot, queue=False)
|
150 |
|
151 |
-
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import glob
|
3 |
+
import gradio as gr
|
4 |
import numpy as np
|
5 |
+
from sentence_transformers import SentenceTransformer
|
6 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
7 |
|
8 |
+
# Загружаем модель эмбеддингов
|
9 |
+
model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
# Путь к папке с лором
|
12 |
+
LORE_DIR = "./lore"
|
|
|
13 |
|
14 |
+
# Параметры нарезки текста
|
15 |
+
CHUNK_SIZE = 500 # длина куска в символах
|
16 |
+
CHUNK_OVERLAP = 100 # перекрытие для плавности
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
+
# Загружаем и разбиваем текст на кусочки
|
19 |
+
def load_lore_chunks():
|
20 |
+
chunks = []
|
21 |
+
files = glob.glob(os.path.join(LORE_DIR, "*.txt"))
|
22 |
+
if not files:
|
23 |
+
print(f"В папке {LORE_DIR} нет файлов.")
|
24 |
+
for file_path in files:
|
25 |
+
with open(file_path, "r", encoding="utf-8") as file:
|
26 |
+
text = file.read()
|
27 |
+
text = ''.join(c if 0x20 <= ord(c) <= 0xFFFF else ' ' for c in text) # чистим мусор
|
28 |
+
for i in range(0, len(text), CHUNK_SIZE - CHUNK_OVERLAP):
|
29 |
+
chunk = text[i:i+CHUNK_SIZE].strip()
|
30 |
+
if chunk:
|
31 |
+
chunks.append(chunk)
|
32 |
+
return chunks
|
33 |
+
|
34 |
+
# Загружаем все куски и эмбеддим
|
35 |
+
print("🚀 Загружаем лор...")
|
36 |
+
lore_chunks = load_lore_chunks()
|
37 |
+
if not lore_chunks:
|
38 |
+
print("⚠️ Внимание: нет данных для поиска.")
|
39 |
+
lore_embeddings = model.encode(lore_chunks)
|
40 |
+
print(f"✅ Загружено {len(lore_chunks)} кусков текста.")
|
41 |
+
|
42 |
+
# Поиск лучшего ответа
|
43 |
+
def find_best_answer(question):
|
44 |
+
question_embedding = model.encode([question])[0]
|
45 |
+
similarities = cosine_similarity([question_embedding], lore_embeddings)[0]
|
46 |
+
best_indices = similarities.argsort()[-3:][::-1] # Топ-3 самых похожих
|
47 |
+
best_chunks = [lore_chunks[idx] for idx in best_indices]
|
48 |
+
response = "\n\n".join(best_chunks)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
return response
|
50 |
|
51 |
+
# Gradio интерфейс
|
52 |
+
with gr.Blocks() as demo:
|
53 |
+
gr.Markdown("## 🧛♂️ ЛОР-БОТ: задавай вопросы о мире!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
+
chat = gr.ChatInterface(
|
56 |
+
fn=lambda message, history: (find_best_answer(message), history),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
examples=[
|
58 |
+
["Какие кланы есть у вампиров?"],
|
59 |
+
["Чем оборотни отличаются от ликантропов?"],
|
60 |
+
["Где находится замок теней?"]
|
|
|
61 |
],
|
62 |
+
title="Лор-бот",
|
63 |
+
theme="soft"
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
+
# Для запуска локально:
|
67 |
+
if __name__ == "__main__":
|
68 |
+
demo.launch()
|