Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
from langchain_community.vectorstores import FAISS
|
4 |
+
from langchain_community.document_loaders import PyPDFLoader
|
5 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
6 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
7 |
+
from langchain_community.llms import HuggingFaceEndpoint
|
8 |
+
from langchain.chains import ConversationalRetrievalChain
|
9 |
+
from langchain.memory import ConversationBufferMemory
|
10 |
+
import torch
|
11 |
+
|
12 |
+
api_token = os.getenv("HF_TOKEN")
|
13 |
+
list_llm = ["meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.2"]
|
14 |
+
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
15 |
+
|
16 |
+
def load_doc(list_file_path):
|
17 |
+
try:
|
18 |
+
loaders = [PyPDFLoader(x) for x in list_file_path]
|
19 |
+
pages = []
|
20 |
+
for loader in loaders:
|
21 |
+
pages.extend(loader.load())
|
22 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1024, chunk_overlap=64)
|
23 |
+
doc_splits = text_splitter.split_documents(pages)
|
24 |
+
return doc_splits
|
25 |
+
except Exception as e:
|
26 |
+
st.error(f"Error loading document: {e}")
|
27 |
+
return []
|
28 |
+
|
29 |
+
def create_db(splits):
|
30 |
+
try:
|
31 |
+
embeddings = HuggingFaceEmbeddings()
|
32 |
+
vectordb = FAISS.from_documents(splits, embeddings)
|
33 |
+
return vectordb
|
34 |
+
except Exception as e:
|
35 |
+
st.error(f"Error creating vector database: {e}")
|
36 |
+
return None
|
37 |
+
|
38 |
+
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db):
|
39 |
+
try:
|
40 |
+
llm = HuggingFaceEndpoint(
|
41 |
+
repo_id=llm_model,
|
42 |
+
huggingfacehub_api_token=api_token,
|
43 |
+
temperature=temperature,
|
44 |
+
max_new_tokens=max_tokens,
|
45 |
+
top_k=top_k,
|
46 |
+
)
|
47 |
+
memory = ConversationBufferMemory(
|
48 |
+
memory_key="chat_history",
|
49 |
+
output_key='answer',
|
50 |
+
return_messages=True
|
51 |
+
)
|
52 |
+
|
53 |
+
retriever = vector_db.as_retriever()
|
54 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
55 |
+
llm,
|
56 |
+
retriever=retriever,
|
57 |
+
chain_type="stuff",
|
58 |
+
memory=memory,
|
59 |
+
return_source_documents=True,
|
60 |
+
verbose=False,
|
61 |
+
)
|
62 |
+
return qa_chain
|
63 |
+
except Exception as e:
|
64 |
+
st.error(f"Error initializing LLM chain: {e}")
|
65 |
+
return None
|
66 |
+
|
67 |
+
def initialize_database(list_file_obj):
|
68 |
+
try:
|
69 |
+
list_file_path = [x.name for x in list_file_obj if x is not None]
|
70 |
+
doc_splits = load_doc(list_file_path)
|
71 |
+
if not doc_splits:
|
72 |
+
return None, "Failed to load documents."
|
73 |
+
vector_db = create_db(doc_splits)
|
74 |
+
if vector_db is None:
|
75 |
+
return None, "Failed to create vector database."
|
76 |
+
return vector_db, "Database created!"
|
77 |
+
except Exception as e:
|
78 |
+
st.error(f"Error initializing database: {e}")
|
79 |
+
return None, "Failed to initialize database."
|
80 |
+
|
81 |
+
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db):
|
82 |
+
try:
|
83 |
+
llm_name = list_llm[llm_option]
|
84 |
+
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db)
|
85 |
+
if qa_chain is None:
|
86 |
+
return None, "Failed to initialize QA chain."
|
87 |
+
return qa_chain, "QA chain initialized. Chatbot is ready!"
|
88 |
+
except Exception as e:
|
89 |
+
st.error(f"Error initializing LLM: {e}")
|
90 |
+
return None, "Failed to initialize LLM."
|
91 |
+
|
92 |
+
def format_chat_history(chat_history):
|
93 |
+
formatted_chat_history = []
|
94 |
+
for user_message, bot_message in chat_history:
|
95 |
+
formatted_chat_history.append(f"User: {user_message}")
|
96 |
+
formatted_chat_history.append(f"Assistant: {bot_message}")
|
97 |
+
return formatted_chat_history
|
98 |
+
|
99 |
+
def conversation(qa_chain, message, history):
|
100 |
+
try:
|
101 |
+
formatted_chat_history = format_chat_history(history)
|
102 |
+
response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history})
|
103 |
+
response_answer = response["answer"]
|
104 |
+
if "Helpful Answer:" in response_answer:
|
105 |
+
response_answer = response_answer.split("Helpful Answer:")[-1]
|
106 |
+
response_sources = response["source_documents"]
|
107 |
+
response_source1 = response_sources[0].page_content.strip()
|
108 |
+
response_source1_page = response_sources[0].metadata["page"] + 1
|
109 |
+
response_source2 = response_sources[1].page_content.strip()
|
110 |
+
response_source2_page = response_sources[1].metadata["page"] + 1
|
111 |
+
response_source3 = response_sources[2].page_content.strip()
|
112 |
+
response_source3_page = response_sources[2].metadata["page"] + 1
|
113 |
+
new_history = history + [(message, response_answer)]
|
114 |
+
return qa_chain, new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
115 |
+
except Exception as e:
|
116 |
+
st.error(f"Error in conversation: {e}")
|
117 |
+
return qa_chain, history, "", 0, "", 0, "", 0
|
118 |
+
|
119 |
+
def main():
|
120 |
+
st.title("PDF Chatbot")
|
121 |
+
|
122 |
+
st.markdown("### Step 1 - Upload PDF documents and Initialize RAG pipeline")
|
123 |
+
uploaded_files = st.file_uploader("Upload PDF documents", type="pdf", accept_multiple_files=True)
|
124 |
+
|
125 |
+
if uploaded_files:
|
126 |
+
if st.button("Create vector database"):
|
127 |
+
with st.spinner("Creating vector database..."):
|
128 |
+
vector_db, db_message = initialize_database(uploaded_files)
|
129 |
+
st.success(db_message)
|
130 |
+
|
131 |
+
if 'vector_db' not in st.session_state:
|
132 |
+
st.session_state['vector_db'] = None
|
133 |
+
|
134 |
+
if 'qa_chain' not in st.session_state:
|
135 |
+
st.session_state['qa_chain'] = None
|
136 |
+
|
137 |
+
st.markdown("### Select Large Language Model (LLM) and input parameters")
|
138 |
+
llm_option = st.radio("Available LLMs", list_llm_simple)
|
139 |
+
temperature = st.slider("Temperature", 0.01, 1.0, 0.5, 0.1)
|
140 |
+
max_tokens = st.slider("Max New Tokens", 128, 9192, 4096, 128)
|
141 |
+
top_k = st.slider("top-k", 1, 10, 3, 1)
|
142 |
+
|
143 |
+
if st.button("Initialize Question Answering Chatbot"):
|
144 |
+
with st.spinner("Initializing QA chatbot..."):
|
145 |
+
qa_chain, llm_message = initialize_LLM(list_llm_simple.index(llm_option), temperature, max_tokens, top_k, st.session_state['vector_db'])
|
146 |
+
st.session_state['qa_chain'] = qa_chain
|
147 |
+
st.success(llm_message)
|
148 |
+
|
149 |
+
st.markdown("### Step 2 - Chat with your Document")
|
150 |
+
if st.session_state['qa_chain']:
|
151 |
+
history = []
|
152 |
+
message = st.text_input("Ask a question")
|
153 |
+
|
154 |
+
if st.button("Submit"):
|
155 |
+
with st.spinner("Generating response..."):
|
156 |
+
qa_chain, history, response_source1, source1_page, response_source2, source2_page, response_source3, source3_page = conversation(st.session_state['qa_chain'], message, history)
|
157 |
+
st.session_state['qa_chain'] = qa_chain
|
158 |
+
|
159 |
+
st.markdown("### Chatbot Response")
|
160 |
+
st.text_area("Chatbot Response", value=response_source1, height=100)
|
161 |
+
st.text_area("Source 1", value=response_source1, height=100)
|
162 |
+
st.text(f"Page: {source1_page}")
|
163 |
+
st.text_area("Source 2", value=response_source2, height=100)
|
164 |
+
st.text(f"Page: {source2_page}")
|
165 |
+
st.text_area("Source 3", value=response_source3, height=100)
|
166 |
+
st.text(f"Page: {source3_page}")
|
167 |
+
|
168 |
+
if __name__ == "__main__":
|
169 |
+
main()
|