Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
def demo():
|
| 2 |
custom_css = """
|
| 3 |
.horizontal-container {
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
api_token = os.getenv("HF_TOKEN")
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from langchain_community.vectorstores import FAISS
|
| 7 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 8 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 9 |
+
from langchain_community.vectorstores import Chroma
|
| 10 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 11 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 12 |
+
from langchain_community.llms import HuggingFacePipeline
|
| 13 |
+
from langchain.chains import ConversationChain
|
| 14 |
+
from langchain.memory import ConversationBufferMemory
|
| 15 |
+
from langchain_community.llms import HuggingFaceEndpoint
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
list_llm = ["meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.2"]
|
| 19 |
+
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
| 20 |
+
|
| 21 |
+
# Load and split PDF document
|
| 22 |
+
def load_doc(list_file_path):
|
| 23 |
+
# Processing for one document only
|
| 24 |
+
# loader = PyPDFLoader(file_path)
|
| 25 |
+
# pages = loader.load()
|
| 26 |
+
loaders = [PyPDFLoader(x) for x in list_file_path]
|
| 27 |
+
pages = []
|
| 28 |
+
for loader in loaders:
|
| 29 |
+
pages.extend(loader.load())
|
| 30 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 31 |
+
chunk_size = 1024,
|
| 32 |
+
chunk_overlap = 64
|
| 33 |
+
)
|
| 34 |
+
doc_splits = text_splitter.split_documents(pages)
|
| 35 |
+
return doc_splits
|
| 36 |
+
|
| 37 |
+
# Create vector database
|
| 38 |
+
def create_db(splits):
|
| 39 |
+
embeddings = HuggingFaceEmbeddings()
|
| 40 |
+
vectordb = FAISS.from_documents(splits, embeddings)
|
| 41 |
+
return vectordb
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Initialize langchain LLM chain
|
| 45 |
+
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
| 46 |
+
if llm_model == "meta-llama/Meta-Llama-3-8B-Instruct":
|
| 47 |
+
llm = HuggingFaceEndpoint(
|
| 48 |
+
repo_id=llm_model,
|
| 49 |
+
huggingfacehub_api_token = api_token,
|
| 50 |
+
temperature = temperature,
|
| 51 |
+
max_new_tokens = max_tokens,
|
| 52 |
+
top_k = top_k,
|
| 53 |
+
)
|
| 54 |
+
else:
|
| 55 |
+
llm = HuggingFaceEndpoint(
|
| 56 |
+
huggingfacehub_api_token = api_token,
|
| 57 |
+
repo_id=llm_model,
|
| 58 |
+
temperature = temperature,
|
| 59 |
+
max_new_tokens = max_tokens,
|
| 60 |
+
top_k = top_k,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
memory = ConversationBufferMemory(
|
| 64 |
+
memory_key="chat_history",
|
| 65 |
+
output_key='answer',
|
| 66 |
+
return_messages=True
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
retriever=vector_db.as_retriever()
|
| 70 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
| 71 |
+
llm,
|
| 72 |
+
retriever=retriever,
|
| 73 |
+
chain_type="stuff",
|
| 74 |
+
memory=memory,
|
| 75 |
+
return_source_documents=True,
|
| 76 |
+
verbose=False,
|
| 77 |
+
)
|
| 78 |
+
return qa_chain
|
| 79 |
+
|
| 80 |
+
# Initialize database
|
| 81 |
+
def initialize_database(list_file_obj, progress=gr.Progress()):
|
| 82 |
+
# Create a list of documents (when valid)
|
| 83 |
+
list_file_path = [x.name for x in list_file_obj if x is not None]
|
| 84 |
+
# Load document and create splits
|
| 85 |
+
doc_splits = load_doc(list_file_path)
|
| 86 |
+
# Create or load vector database
|
| 87 |
+
vector_db = create_db(doc_splits)
|
| 88 |
+
return vector_db, "Database created!"
|
| 89 |
+
|
| 90 |
+
# Initialize LLM
|
| 91 |
+
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
| 92 |
+
# print("llm_option",llm_option)
|
| 93 |
+
llm_name = list_llm[llm_option]
|
| 94 |
+
print("llm_name: ",llm_name)
|
| 95 |
+
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
| 96 |
+
return qa_chain, "QA chain initialized. Chatbot is ready!"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def format_chat_history(message, chat_history):
|
| 100 |
+
formatted_chat_history = []
|
| 101 |
+
for user_message, bot_message in chat_history:
|
| 102 |
+
formatted_chat_history.append(f"User: {user_message}")
|
| 103 |
+
formatted_chat_history.append(f"Assistant: {bot_message}")
|
| 104 |
+
return formatted_chat_history
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def conversation(qa_chain, message, history):
|
| 108 |
+
formatted_chat_history = format_chat_history(message, history)
|
| 109 |
+
# Generate response using QA chain
|
| 110 |
+
response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history})
|
| 111 |
+
response_answer = response["answer"]
|
| 112 |
+
if response_answer.find("Helpful Answer:") != -1:
|
| 113 |
+
response_answer = response_answer.split("Helpful Answer:")[-1]
|
| 114 |
+
response_sources = response["source_documents"]
|
| 115 |
+
response_source1 = response_sources[0].page_content.strip()
|
| 116 |
+
response_source2 = response_sources[1].page_content.strip()
|
| 117 |
+
response_source3 = response_sources[2].page_content.strip()
|
| 118 |
+
# Langchain sources are zero-based
|
| 119 |
+
response_source1_page = response_sources[0].metadata["page"] + 1
|
| 120 |
+
response_source2_page = response_sources[1].metadata["page"] + 1
|
| 121 |
+
response_source3_page = response_sources[2].metadata["page"] + 1
|
| 122 |
+
# Append user message and response to chat history
|
| 123 |
+
new_history = history + [(message, response_answer)]
|
| 124 |
+
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def upload_file(file_obj):
|
| 128 |
+
list_file_path = []
|
| 129 |
+
for idx, file in enumerate(file_obj):
|
| 130 |
+
file_path = file_obj.name
|
| 131 |
+
list_file_path.append(file_path)
|
| 132 |
+
return list_file_path
|
| 133 |
+
|
| 134 |
def demo():
|
| 135 |
custom_css = """
|
| 136 |
.horizontal-container {
|