Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,58 +1,82 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
from langchain_community.document_loaders import TextLoader
|
| 3 |
-
from langchain.text_splitter import
|
| 4 |
from langchain_community.vectorstores import FAISS
|
| 5 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
|
|
|
| 6 |
from langchain.chains import RetrievalQA
|
| 7 |
-
from
|
| 8 |
import gradio as gr
|
| 9 |
-
import re
|
| 10 |
|
| 11 |
-
# 1. Загрузка
|
| 12 |
-
def
|
| 13 |
-
|
| 14 |
-
for
|
| 15 |
-
if
|
| 16 |
-
loader = TextLoader(os.path.join(
|
| 17 |
-
docs
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
return
|
| 23 |
-
|
| 24 |
-
#
|
| 25 |
-
def split_documents(documents):
|
| 26 |
-
splitter = RecursiveCharacterTextSplitter(chunk_size=700, chunk_overlap=100)
|
| 27 |
-
return splitter.split_documents(documents)
|
| 28 |
-
|
| 29 |
-
# 3. Создание эмбеддингов
|
| 30 |
def create_embeddings():
|
| 31 |
return HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
|
| 32 |
|
| 33 |
-
# 4.
|
| 34 |
-
def
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
def
|
| 42 |
-
|
| 43 |
-
docs = split_documents(raw_docs)
|
| 44 |
embeddings = create_embeddings()
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
#
|
| 51 |
-
qa_chain =
|
| 52 |
|
| 53 |
-
def
|
| 54 |
-
|
| 55 |
-
return result
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
from langchain_community.document_loaders import TextLoader
|
| 4 |
+
from langchain.text_splitter import CharacterTextSplitter
|
| 5 |
from langchain_community.vectorstores import FAISS
|
| 6 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 7 |
+
from langchain_core.prompts import PromptTemplate
|
| 8 |
from langchain.chains import RetrievalQA
|
| 9 |
+
from transformers import pipeline
|
| 10 |
import gradio as gr
|
|
|
|
| 11 |
|
| 12 |
+
# 1. Загрузка всех файлов из папки lore/
|
| 13 |
+
def load_all_lore_files():
|
| 14 |
+
docs = []
|
| 15 |
+
for filename in os.listdir("lore"):
|
| 16 |
+
if filename.endswith(".txt"):
|
| 17 |
+
loader = TextLoader(os.path.join("lore", filename), encoding="utf-8")
|
| 18 |
+
docs.extend(loader.load())
|
| 19 |
+
return docs
|
| 20 |
+
|
| 21 |
+
# 2. Очистка от спецсимволов вроде [=/ и т.п.
|
| 22 |
+
def clean_text(text):
|
| 23 |
+
return re.sub(r"\[=.*?\/?]", "", text)
|
| 24 |
+
|
| 25 |
+
# 3. Настройка эмбеддингов
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def create_embeddings():
|
| 27 |
return HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
|
| 28 |
|
| 29 |
+
# 4. Создание векторной базы
|
| 30 |
+
def create_vectorstore(docs, embeddings):
|
| 31 |
+
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
| 32 |
+
split_docs = text_splitter.split_documents(docs)
|
| 33 |
+
for doc in split_docs:
|
| 34 |
+
doc.page_content = clean_text(doc.page_content)
|
| 35 |
+
return FAISS.from_documents(split_docs, embeddings)
|
| 36 |
+
|
| 37 |
+
# 5. Загрузка модели ответа (без HuggingFace API Token)
|
| 38 |
+
def create_llm_pipeline():
|
| 39 |
+
return pipeline("text-generation", model="IlyaGusev/saiga2_7b_lora", device=0 if torch.cuda.is_available() else -1)
|
| 40 |
|
| 41 |
+
# 6. Объединение в цепочку
|
| 42 |
+
def build_chain():
|
| 43 |
+
docs = load_all_lore_files()
|
|
|
|
| 44 |
embeddings = create_embeddings()
|
| 45 |
+
vectorstore = create_vectorstore(docs, embeddings)
|
| 46 |
+
|
| 47 |
+
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 3})
|
| 48 |
+
|
| 49 |
+
prompt = PromptTemplate(
|
| 50 |
+
template="""
|
| 51 |
+
Ты — помощник, который отвечает на вопросы по вымышленному лору. Отвечай кратко, точно и на русском языке.
|
| 52 |
+
Если в лоре нет нужной информации, честно скажи, что не знаешь.
|
| 53 |
+
|
| 54 |
+
Контекст:
|
| 55 |
+
{context}
|
| 56 |
+
|
| 57 |
+
Вопрос:
|
| 58 |
+
{question}
|
| 59 |
+
|
| 60 |
+
Ответ:
|
| 61 |
+
""",
|
| 62 |
+
input_variables=["context", "question"]
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
return RetrievalQA.from_chain_type(
|
| 66 |
+
llm=create_llm_pipeline(),
|
| 67 |
+
retriever=retriever,
|
| 68 |
+
chain_type_kwargs={"prompt": prompt}
|
| 69 |
+
)
|
| 70 |
|
| 71 |
+
# 7. Интерфейс
|
| 72 |
+
qa_chain = build_chain()
|
| 73 |
|
| 74 |
+
def ask_question(question):
|
| 75 |
+
return qa_chain.run(question)
|
|
|
|
| 76 |
|
| 77 |
+
gr.Interface(
|
| 78 |
+
fn=ask_question,
|
| 79 |
+
inputs=gr.Textbox(label="Спроси что-нибудь по лору"),
|
| 80 |
+
outputs=gr.Textbox(label="Ответ"),
|
| 81 |
+
title="Лор-бот"
|
| 82 |
+
).launch()
|