Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,15 +4,11 @@ import nltk
|
|
| 4 |
from huggingface_hub import login
|
| 5 |
import gradio as gr
|
| 6 |
|
| 7 |
-
#
|
| 8 |
try:
|
| 9 |
-
print("Проверяем наличие NLTK компонента 'punkt'...")
|
| 10 |
nltk.data.find('tokenizers/punkt')
|
| 11 |
-
print("'punkt' уже на месте.")
|
| 12 |
except LookupError:
|
| 13 |
-
|
| 14 |
-
nltk.download('punkt', quiet=False)
|
| 15 |
-
print("Загрузка 'punkt' завершена.")
|
| 16 |
|
| 17 |
from langchain_community.document_loaders import UnstructuredWordDocumentLoader
|
| 18 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
@@ -21,90 +17,76 @@ from langchain_community.vectorstores import FAISS
|
|
| 21 |
from langchain.chains import RetrievalQA
|
| 22 |
from langchain_huggingface import HuggingFaceEndpoint
|
| 23 |
|
| 24 |
-
# --- Константы
|
| 25 |
-
DOCX_FILE_PATH = "" # Путь будет определен автоматически
|
| 26 |
FAISS_INDEX_PATH = "faiss_index"
|
| 27 |
MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
|
| 28 |
-
REPO_ID = "
|
|
|
|
| 29 |
|
| 30 |
-
# ---
|
| 31 |
-
def
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
docx_files = glob.glob("*.docx")
|
| 37 |
if docx_files:
|
| 38 |
DOCX_FILE_PATH = docx_files[0]
|
| 39 |
-
return
|
| 40 |
-
|
| 41 |
-
print("База знаний не найдена. Запускаю процесс создания...")
|
| 42 |
-
|
| 43 |
-
docx_files = glob.glob("*.docx")
|
| 44 |
-
if not docx_files:
|
| 45 |
-
raise FileNotFoundError("Ошибка: Не найден .docx файл в репозитории. Пожалуйста, загрузите ваш документ.")
|
| 46 |
-
|
| 47 |
-
DOCX_FILE_PATH = docx_files[0]
|
| 48 |
-
print(f"Найден документ для обработки: {DOCX_FILE_PATH}")
|
| 49 |
-
|
| 50 |
-
loader = UnstructuredWordDocumentLoader(DOCX_FILE_PATH)
|
| 51 |
-
documents = loader.load()
|
| 52 |
-
|
| 53 |
-
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
|
| 54 |
-
docs = text_splitter.split_documents(documents)
|
| 55 |
-
|
| 56 |
-
print(f"Документ разделен на {len(docs)} частей.")
|
| 57 |
-
|
| 58 |
-
embeddings = HuggingFaceEmbeddings(model_name=MODEL_NAME)
|
| 59 |
-
db = FAISS.from_documents(docs, embeddings)
|
| 60 |
-
db.save_local(FAISS_INDEX_PATH)
|
| 61 |
-
|
| 62 |
-
print(f"База знаний успешно создана и сохранена в '{FAISS_INDEX_PATH}'.")
|
| 63 |
|
| 64 |
-
# ---
|
| 65 |
def initialize_qa_chain():
|
| 66 |
HF_TOKEN = os.environ.get("HUGGINGFACEHUB_API_TOKEN")
|
| 67 |
if not HF_TOKEN:
|
| 68 |
-
raise ValueError("
|
| 69 |
|
| 70 |
login(token=HF_TOKEN)
|
| 71 |
-
|
| 72 |
-
|
| 73 |
embeddings = HuggingFaceEmbeddings(model_name=MODEL_NAME)
|
| 74 |
db = FAISS.load_local(FAISS_INDEX_PATH, embeddings, allow_dangerous_deserialization=True)
|
| 75 |
-
|
| 76 |
llm = HuggingFaceEndpoint(
|
| 77 |
repo_id=REPO_ID,
|
| 78 |
-
temperature=0.3,
|
| 79 |
max_new_tokens=512,
|
|
|
|
| 80 |
repetition_penalty=1.1,
|
| 81 |
huggingfacehub_api_token=HF_TOKEN
|
| 82 |
)
|
| 83 |
-
|
| 84 |
-
|
| 85 |
llm=llm,
|
| 86 |
chain_type="stuff",
|
| 87 |
-
retriever=db.as_retriever(search_kwargs={"k": 3})
|
| 88 |
-
return_source_documents=True
|
| 89 |
)
|
| 90 |
-
print("Цепочка QA успешно инициализирована.")
|
| 91 |
-
return qa_chain
|
| 92 |
|
| 93 |
# --- Основной код ---
|
| 94 |
-
|
| 95 |
qa_chain = initialize_qa_chain()
|
| 96 |
|
| 97 |
def chatbot_response(message, history):
|
| 98 |
-
response = qa_chain.invoke(
|
| 99 |
return response["result"]
|
| 100 |
|
| 101 |
-
# ---
|
| 102 |
with gr.Blocks(theme='gradio/soft', title="AI-Ассистент по ВКР") as demo:
|
| 103 |
gr.Markdown("# 🤖 AI-Ассистент по вопросам ВКР")
|
| 104 |
-
|
|
|
|
| 105 |
|
| 106 |
-
# В новой версии Gradio параметры кнопок встроены по умолчанию.
|
| 107 |
-
# Просто убираем лишние аргументы, и все заработает.
|
| 108 |
gr.ChatInterface(
|
| 109 |
fn=chatbot_response,
|
| 110 |
title=None,
|
|
@@ -117,5 +99,4 @@ with gr.Blocks(theme='gradio/soft', title="AI-Ассистент по ВКР") a
|
|
| 117 |
]
|
| 118 |
)
|
| 119 |
|
| 120 |
-
# Запуск приложения
|
| 121 |
demo.launch()
|
|
|
|
| 4 |
from huggingface_hub import login
|
| 5 |
import gradio as gr
|
| 6 |
|
| 7 |
+
# --- Загрузка NLTK ---
|
| 8 |
try:
|
|
|
|
| 9 |
nltk.data.find('tokenizers/punkt')
|
|
|
|
| 10 |
except LookupError:
|
| 11 |
+
nltk.download('punkt', quiet=True)
|
|
|
|
|
|
|
| 12 |
|
| 13 |
from langchain_community.document_loaders import UnstructuredWordDocumentLoader
|
| 14 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
|
| 17 |
from langchain.chains import RetrievalQA
|
| 18 |
from langchain_huggingface import HuggingFaceEndpoint
|
| 19 |
|
| 20 |
+
# --- Константы ---
|
|
|
|
| 21 |
FAISS_INDEX_PATH = "faiss_index"
|
| 22 |
MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
|
| 23 |
+
REPO_ID = "google/flan-t5-large"
|
| 24 |
+
DOCX_FILE_PATH = ""
|
| 25 |
|
| 26 |
+
# --- Создание базы знаний ---
|
| 27 |
+
def create_vector_db():
|
| 28 |
+
global DOCX_FILE_PATH
|
| 29 |
+
if not os.path.exists(FAISS_INDEX_PATH):
|
| 30 |
+
print("База знаний не найдена. Создаю новую...")
|
| 31 |
+
docx_files = glob.glob("*.docx")
|
| 32 |
+
if not docx_files:
|
| 33 |
+
raise FileNotFoundError("Ошибка: Не найден .docx файл.")
|
| 34 |
+
DOCX_FILE_PATH = docx_files[0]
|
| 35 |
+
|
| 36 |
+
loader = UnstructuredWordDocumentLoader(DOCX_FILE_PATH)
|
| 37 |
+
documents = loader.load()
|
| 38 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
|
| 39 |
+
docs = text_splitter.split_documents(documents)
|
| 40 |
+
|
| 41 |
+
embeddings = HuggingFaceEmbeddings(model_name=MODEL_NAME)
|
| 42 |
+
db = FAISS.from_documents(docs, embeddings)
|
| 43 |
+
db.save_local(FAISS_INDEX_PATH)
|
| 44 |
+
print("База знаний создана.")
|
| 45 |
+
else:
|
| 46 |
+
print("База знаний найдена.")
|
| 47 |
docx_files = glob.glob("*.docx")
|
| 48 |
if docx_files:
|
| 49 |
DOCX_FILE_PATH = docx_files[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
# --- Инициализация QA ---
|
| 52 |
def initialize_qa_chain():
|
| 53 |
HF_TOKEN = os.environ.get("HUGGINGFACEHUB_API_TOKEN")
|
| 54 |
if not HF_TOKEN:
|
| 55 |
+
raise ValueError("Не найден HUGGINGFACEHUB_API_TOKEN.")
|
| 56 |
|
| 57 |
login(token=HF_TOKEN)
|
| 58 |
+
|
|
|
|
| 59 |
embeddings = HuggingFaceEmbeddings(model_name=MODEL_NAME)
|
| 60 |
db = FAISS.load_local(FAISS_INDEX_PATH, embeddings, allow_dangerous_deserialization=True)
|
| 61 |
+
|
| 62 |
llm = HuggingFaceEndpoint(
|
| 63 |
repo_id=REPO_ID,
|
|
|
|
| 64 |
max_new_tokens=512,
|
| 65 |
+
temperature=0.3,
|
| 66 |
repetition_penalty=1.1,
|
| 67 |
huggingfacehub_api_token=HF_TOKEN
|
| 68 |
)
|
| 69 |
+
|
| 70 |
+
return RetrievalQA.from_chain_type(
|
| 71 |
llm=llm,
|
| 72 |
chain_type="stuff",
|
| 73 |
+
retriever=db.as_retriever(search_kwargs={"k": 3})
|
|
|
|
| 74 |
)
|
|
|
|
|
|
|
| 75 |
|
| 76 |
# --- Основной код ---
|
| 77 |
+
create_vector_db()
|
| 78 |
qa_chain = initialize_qa_chain()
|
| 79 |
|
| 80 |
def chatbot_response(message, history):
|
| 81 |
+
response = qa_chain.invoke(message)
|
| 82 |
return response["result"]
|
| 83 |
|
| 84 |
+
# --- Интерфейс ---
|
| 85 |
with gr.Blocks(theme='gradio/soft', title="AI-Ассистент по ВКР") as demo:
|
| 86 |
gr.Markdown("# 🤖 AI-Ассистент по вопросам ВКР")
|
| 87 |
+
if DOCX_FILE_PATH:
|
| 88 |
+
gr.Markdown(f"Бот отвечает на вопросы на основе документа: **{os.path.basename(DOCX_FILE_PATH)}**.")
|
| 89 |
|
|
|
|
|
|
|
| 90 |
gr.ChatInterface(
|
| 91 |
fn=chatbot_response,
|
| 92 |
title=None,
|
|
|
|
| 99 |
]
|
| 100 |
)
|
| 101 |
|
|
|
|
| 102 |
demo.launch()
|