Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,15 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from sentence_transformers import SentenceTransformer
|
| 3 |
-
import chromadb
|
| 4 |
-
from chromadb.utils import embedding_functions
|
| 5 |
import os
|
| 6 |
from langdetect import detect
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 9 |
def load_text_files():
|
| 10 |
files = {
|
| 11 |
-
"vampires": "vampires.txt"
|
|
|
|
|
|
|
| 12 |
}
|
| 13 |
|
| 14 |
loaded_data = {}
|
|
@@ -22,138 +23,90 @@ def load_text_files():
|
|
| 22 |
|
| 23 |
return loaded_data
|
| 24 |
|
| 25 |
-
# Инициализация модели для
|
| 26 |
-
def
|
| 27 |
-
return
|
| 28 |
-
model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
| 29 |
-
)
|
| 30 |
|
| 31 |
-
#
|
| 32 |
-
def
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
except:
|
| 38 |
-
collection = client.create_collection(
|
| 39 |
-
name="knowledge_base",
|
| 40 |
-
embedding_function=embed_fn
|
| 41 |
-
)
|
| 42 |
|
| 43 |
-
#
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
ids = []
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
if documents:
|
| 59 |
-
collection.add(
|
| 60 |
-
documents=documents,
|
| 61 |
-
metadatas=metadatas,
|
| 62 |
-
ids=ids
|
| 63 |
-
)
|
| 64 |
-
|
| 65 |
-
return collection
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
def
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
model="IlyaGusev/saiga_llama3_8b",
|
| 75 |
-
device_map="auto"
|
| 76 |
-
)
|
| 77 |
|
| 78 |
-
|
| 79 |
-
def find_relevant_info(question, collection, embed_fn, n_results=3):
|
| 80 |
-
results = collection.query(
|
| 81 |
-
query_texts=[question],
|
| 82 |
-
n_results=n_results
|
| 83 |
-
)
|
| 84 |
-
|
| 85 |
-
context = "\n\n".join(results['documents'][0])
|
| 86 |
-
return context
|
| 87 |
|
| 88 |
-
|
| 89 |
-
def generate_response(question, context, llm_pipe):
|
| 90 |
-
system_prompt = """Ты - помощник, который отвечает на вопросы пользователя, используя предоставленную информацию.
|
| 91 |
-
Отвечай только на основе предоставленного контекста. Если ответа нет в контексте, скажи, что не знаешь.
|
| 92 |
-
Отвечай на русском языке."""
|
| 93 |
-
|
| 94 |
-
prompt = f"""<s>{system_prompt}
|
| 95 |
-
Контекст: {context}
|
| 96 |
-
Вопрос: {question}
|
| 97 |
-
Ответ:"""
|
| 98 |
-
|
| 99 |
-
output = llm_pipe(
|
| 100 |
-
prompt,
|
| 101 |
-
max_new_tokens=256,
|
| 102 |
-
do_sample=True,
|
| 103 |
-
temperature=0.7,
|
| 104 |
-
top_p=0.9,
|
| 105 |
-
repetition_penalty=1.2
|
| 106 |
-
)
|
| 107 |
-
|
| 108 |
-
return output[0]["generated_text"][len(prompt):].strip()
|
| 109 |
|
| 110 |
-
# Основная функция
|
| 111 |
-
def
|
| 112 |
-
#
|
| 113 |
try:
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
return "Пожалуйста, задавайте вопросы на русском языке."
|
| 117 |
except:
|
| 118 |
pass
|
| 119 |
|
| 120 |
-
#
|
| 121 |
-
if not hasattr(
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
# Инициализируем модели (если еще не инициализированы)
|
| 125 |
-
if not hasattr(answer_question, 'embed_fn'):
|
| 126 |
-
answer_question.embed_fn = initialize_embedding_model()
|
| 127 |
|
| 128 |
-
if not hasattr(
|
| 129 |
-
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
|
| 134 |
-
#
|
| 135 |
-
|
| 136 |
|
| 137 |
-
#
|
| 138 |
-
|
| 139 |
|
| 140 |
-
return
|
| 141 |
|
| 142 |
-
#
|
| 143 |
with gr.Blocks() as demo:
|
| 144 |
-
gr.Markdown("## Чат-бот с доступом к текстовым файлам")
|
| 145 |
-
gr.Markdown("Задавайте вопросы о вампирах, оборотнях или людях
|
| 146 |
-
|
| 147 |
-
chatbot = gr.Chatbot(label="Диалог")
|
| 148 |
-
msg = gr.Textbox(label="Ваш вопрос")
|
| 149 |
-
clear = gr.Button("Очистить")
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
return "", chat_history
|
| 155 |
|
| 156 |
-
msg.submit(
|
| 157 |
clear.click(lambda: None, None, chatbot, queue=False)
|
| 158 |
|
| 159 |
-
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 2 |
import os
|
| 3 |
from langdetect import detect
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
import numpy as np
|
| 6 |
|
| 7 |
+
# Загрузка текстовых файлов
|
| 8 |
def load_text_files():
|
| 9 |
files = {
|
| 10 |
+
"vampires": "vampires.txt",
|
| 11 |
+
"werewolves": "werewolves.txt",
|
| 12 |
+
"humans": "humans.txt"
|
| 13 |
}
|
| 14 |
|
| 15 |
loaded_data = {}
|
|
|
|
| 23 |
|
| 24 |
return loaded_data
|
| 25 |
|
| 26 |
+
# Инициализация модели для поиска (легковесная)
|
| 27 |
+
def initialize_search_model():
|
| 28 |
+
return SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
# Поиск наиболее релевантных фрагментов
|
| 31 |
+
def find_relevant_text(question, text_data, model, top_k=3):
|
| 32 |
+
# Разбиваем тексты на предложения
|
| 33 |
+
sentences = []
|
| 34 |
+
sources = []
|
| 35 |
+
for category, text in text_data.items():
|
| 36 |
+
if text:
|
| 37 |
+
for sentence in text.split('\n'):
|
| 38 |
+
if sentence.strip():
|
| 39 |
+
sentences.append(sentence.strip())
|
| 40 |
+
sources.append(category)
|
| 41 |
|
| 42 |
+
if not sentences:
|
| 43 |
+
return "Нет данных для анализа"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
# Эмбеддинги для предложений и вопроса
|
| 46 |
+
sentence_embeddings = model.encode(sentences)
|
| 47 |
+
question_embedding = model.encode([question])
|
|
|
|
| 48 |
|
| 49 |
+
# Поиск наиболее похожих предложений
|
| 50 |
+
similarities = np.dot(sentence_embeddings, question_embedding.T).flatten()
|
| 51 |
+
top_indices = similarities.argsort()[-top_k:][::-1]
|
| 52 |
+
|
| 53 |
+
# Формируем контекст
|
| 54 |
+
context = "Контекст:\n"
|
| 55 |
+
for idx in top_indices:
|
| 56 |
+
context += f"[Из {sources[idx]}]: {sentences[idx]}\n"
|
| 57 |
+
|
| 58 |
+
return context
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
+
# Генерация ответа (упрощенная)
|
| 61 |
+
def generate_answer(question, context):
|
| 62 |
+
# Простейшая логика ответа без LLM
|
| 63 |
+
if not context.strip():
|
| 64 |
+
return "Извините, не могу найти информацию по вашему вопросу."
|
| 65 |
+
|
| 66 |
+
return f"""На основе имеющейся информации:
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
{context}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
Это все, что я могу сказать по данному вопросу. Если вам нужны более подробные сведения, уточните вопрос."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
# Основная функция обработки
|
| 73 |
+
def process_question(question, history):
|
| 74 |
+
# Проверка языка
|
| 75 |
try:
|
| 76 |
+
if detect(question) != 'ru':
|
| 77 |
+
return "Пожалуйста, задавайте вопросы на русском языке.", history
|
|
|
|
| 78 |
except:
|
| 79 |
pass
|
| 80 |
|
| 81 |
+
# Ленивая загрузка данных и модели
|
| 82 |
+
if not hasattr(process_question, 'text_data'):
|
| 83 |
+
process_question.text_data = load_text_files()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
if not hasattr(process_question, 'search_model'):
|
| 86 |
+
process_question.search_model = initialize_search_model()
|
| 87 |
|
| 88 |
+
# Поиск релевантной информации
|
| 89 |
+
context = find_relevant_text(question, process_question.text_data, process_question.search_model)
|
| 90 |
|
| 91 |
+
# Формирование ответа
|
| 92 |
+
answer = generate_answer(question, context)
|
| 93 |
|
| 94 |
+
# Обновление истории
|
| 95 |
+
history.append((question, answer))
|
| 96 |
|
| 97 |
+
return "", history
|
| 98 |
|
| 99 |
+
# Создание интерфейса
|
| 100 |
with gr.Blocks() as demo:
|
| 101 |
+
gr.Markdown("## 📚 Чат-бот с доступом к текстовым файлам")
|
| 102 |
+
gr.Markdown("Задавайте вопросы о вампирах, оборотнях или людях")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
chatbot = gr.Chatbot(label="Диалог", height=400)
|
| 105 |
+
msg = gr.Textbox(label="Ваш вопрос", placeholder="Введите вопрос на русском языке...")
|
| 106 |
+
clear = gr.Button("Очистить чат")
|
|
|
|
| 107 |
|
| 108 |
+
msg.submit(process_question, [msg, chatbot], [msg, chatbot])
|
| 109 |
clear.click(lambda: None, None, chatbot, queue=False)
|
| 110 |
|
| 111 |
+
# Запуск приложения с ограничением ресурсов
|
| 112 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)
|