Spaces:
Build error
Build error
Gabriele Arcangelo Scalici commited on
feat: refactoring and optimizations (#1)
Browse files- .streamlit/config.toml +1 -2
- main.py +71 -197
- modules/chatbot.py +25 -0
- modules/embedder.py +51 -0
- modules/history.py +44 -0
- modules/layout.py +20 -0
- modules/sidebar.py +51 -0
.streamlit/config.toml
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
[theme]
|
| 2 |
base="light"
|
| 3 |
-
|
| 4 |
-
secondaryBackgroundColor="#FFDCF1"
|
|
|
|
| 1 |
[theme]
|
| 2 |
base="light"
|
| 3 |
+
primaryColor="#0098ff"
|
|
|
main.py
CHANGED
|
@@ -1,249 +1,123 @@
|
|
| 1 |
import os
|
| 2 |
-
import pickle
|
| 3 |
import streamlit as st
|
| 4 |
-
import tempfile
|
| 5 |
import asyncio
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
|
| 8 |
-
# Import modules needed for building the chatbot application
|
| 9 |
from streamlit_chat import message
|
| 10 |
-
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 11 |
-
from langchain.chat_models import ChatOpenAI
|
| 12 |
-
from langchain.chains import ConversationalRetrievalChain
|
| 13 |
-
from langchain.document_loaders import PyPDFLoader
|
| 14 |
-
from langchain.vectorstores import FAISS
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
# Set the Streamlit page configuration, including the layout and page title/icon
|
| 20 |
-
st.set_page_config(layout="wide", page_icon="π¬", page_title="ChatBot-PDF")
|
| 21 |
|
| 22 |
-
|
| 23 |
-
st.markdown("<h1 style='text-align: center;'>ChatBot-PDF, Talk with your documents ! π¬</h1>", unsafe_allow_html=True)
|
| 24 |
|
| 25 |
-
|
| 26 |
-
user_api_key = os.getenv("OPENAI_API_KEY")
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
-
user_api_key =
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
st.
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
)
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
else:
|
| 47 |
-
# Set the OpenAI API key as an environment variable
|
| 48 |
-
os.environ["OPENAI_API_KEY"] = user_api_key
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
# If the user has uploaded a file, display it in an expander
|
| 54 |
-
if uploaded_file is not None:
|
| 55 |
|
| 56 |
-
|
| 57 |
-
file_container = st.expander("Your PDF file :")
|
| 58 |
-
file_container.write(uploaded_file)
|
| 59 |
|
| 60 |
-
|
|
|
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
st.sidebar.info(
|
| 65 |
-
"π Upload your PDF file to get started, "
|
| 66 |
-
"sample for try : [file.pdf](https://github.com/gabacode/chatPDF/blob/main/file.pdf)"
|
| 67 |
-
)
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
with tempfile.NamedTemporaryFile(mode="wb", delete=False) as tmp_file:
|
| 75 |
-
tmp_file.write(file)
|
| 76 |
-
tmp_file_path = tmp_file.name
|
| 77 |
-
|
| 78 |
-
# Load the data from the file using Langchain
|
| 79 |
-
loader = PyPDFLoader(file_path=tmp_file_path)
|
| 80 |
-
data = loader.load_and_split()
|
| 81 |
-
|
| 82 |
-
# Create an embeddings object using Langchain
|
| 83 |
-
embeddings = OpenAIEmbeddings()
|
| 84 |
-
|
| 85 |
-
# Store the embeddings vectors using FAISS
|
| 86 |
-
vectors = FAISS.from_documents(data, embeddings)
|
| 87 |
-
os.remove(tmp_file_path)
|
| 88 |
-
|
| 89 |
-
# Save the vectors to a pickle file
|
| 90 |
-
with open(filename + ".pkl", "wb") as f:
|
| 91 |
-
pickle.dump(vectors, f)
|
| 92 |
-
|
| 93 |
-
# Define an asynchronous function for retrieving document embeddings
|
| 94 |
-
async def getDocEmbeds(file, filename):
|
| 95 |
-
# Check if embeddings vectors have already been stored in a pickle file
|
| 96 |
-
if not os.path.isfile(filename + ".pkl"):
|
| 97 |
-
# If not, store the vectors using the storeDocEmbeds function
|
| 98 |
-
await storeDocEmbeds(file, filename)
|
| 99 |
-
|
| 100 |
-
# Load the vectors from the pickle file
|
| 101 |
-
with open(filename + ".pkl", "rb") as f:
|
| 102 |
-
global vectors
|
| 103 |
-
vectors = pickle.load(f)
|
| 104 |
-
|
| 105 |
-
return vectors
|
| 106 |
-
|
| 107 |
-
# Define an asynchronous function for conducting conversational chat using Langchain
|
| 108 |
-
async def conversational_chat(query):
|
| 109 |
-
# Use the Langchain ConversationalRetrievalChain to generate a response to the user's query
|
| 110 |
-
result = chain({"question": query, "chat_history": st.session_state["history"]})
|
| 111 |
-
|
| 112 |
-
# Add the user's query and the chatbot's response to the chat history
|
| 113 |
-
st.session_state["history"].append((query, result["answer"]))
|
| 114 |
-
|
| 115 |
-
# Print the chat history for debugging purposes
|
| 116 |
-
print("Log: ")
|
| 117 |
-
print(st.session_state["history"])
|
| 118 |
-
|
| 119 |
-
return result["answer"]
|
| 120 |
-
|
| 121 |
-
# Set up sidebar with various options
|
| 122 |
-
with st.sidebar.expander("π οΈ Settings", expanded=False):
|
| 123 |
-
# Add a button to reset the chat history
|
| 124 |
-
if st.button("Reset Chat"):
|
| 125 |
-
st.session_state["reset_chat"] = True
|
| 126 |
-
|
| 127 |
-
# Allow the user to select a chatbot model to use
|
| 128 |
-
MODEL = st.selectbox(label="Model", options=["gpt-3.5-turbo"])
|
| 129 |
-
|
| 130 |
-
# Allow the user to change the model temperature
|
| 131 |
-
TEMPERATURE = st.slider(label="Temperature", min_value=0.0, max_value=1.0, value=0.618, step=0.01)
|
| 132 |
-
|
| 133 |
-
# If the chat history has not yet been initialized, do so now
|
| 134 |
-
if "history" not in st.session_state:
|
| 135 |
-
st.session_state["history"] = []
|
| 136 |
-
|
| 137 |
-
# If the chatbot is not yet ready to chat, set the "ready" flag to False
|
| 138 |
-
if "ready" not in st.session_state:
|
| 139 |
-
st.session_state["ready"] = False
|
| 140 |
-
|
| 141 |
-
# If the "reset_chat" flag has not been set, set it to False
|
| 142 |
-
if "reset_chat" not in st.session_state:
|
| 143 |
-
st.session_state["reset_chat"] = False
|
| 144 |
-
|
| 145 |
-
# If a PDF file has been uploaded
|
| 146 |
-
if uploaded_file is not None:
|
| 147 |
-
# Display a spinner while processing the file
|
| 148 |
-
with st.spinner("Processing..."):
|
| 149 |
-
# Read the uploaded PDF file
|
| 150 |
-
uploaded_file.seek(0)
|
| 151 |
-
file = uploaded_file.read()
|
| 152 |
-
|
| 153 |
-
# Generate embeddings vectors for the file
|
| 154 |
-
vectors = await getDocEmbeds(file, uploaded_file.name)
|
| 155 |
-
|
| 156 |
-
# Use the Langchain ConversationalRetrievalChain to set up the chatbot
|
| 157 |
-
chain = ConversationalRetrievalChain.from_llm(
|
| 158 |
-
llm=ChatOpenAI(temperature=TEMPERATURE, model_name=MODEL), retriever=vectors.as_retriever()
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
# Set the "ready" flag to True now that the chatbot is ready to chat
|
| 162 |
-
st.session_state["ready"] = True
|
| 163 |
-
|
| 164 |
-
# If the chatbot is ready to chat
|
| 165 |
-
if st.session_state["ready"]:
|
| 166 |
-
# If the chat history has not yet been initialized, initialize it now
|
| 167 |
-
if "generated" not in st.session_state:
|
| 168 |
-
st.session_state["generated"] = [
|
| 169 |
-
"Hello ! Ask me anything about the document " + uploaded_file.name + " π€"
|
| 170 |
-
]
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
|
|
|
|
| 176 |
response_container = st.container()
|
| 177 |
-
|
| 178 |
-
# Create a container for the user's text input
|
| 179 |
container = st.container()
|
| 180 |
|
| 181 |
with container:
|
| 182 |
-
# Create a form for the user to enter their query
|
| 183 |
with st.form(key="my_form", clear_on_submit=True):
|
| 184 |
user_input = st.text_area(
|
| 185 |
"Query:",
|
| 186 |
-
placeholder="
|
| 187 |
key="input",
|
| 188 |
label_visibility="collapsed",
|
| 189 |
)
|
| 190 |
submit_button = st.form_submit_button(label="Send")
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
st.session_state["generated"] = [
|
| 197 |
-
"Hello ! Ask me anything about the document " + uploaded_file.name + " π€"
|
| 198 |
-
]
|
| 199 |
-
response_container.empty()
|
| 200 |
-
st.session_state["reset_chat"] = False
|
| 201 |
|
| 202 |
# If the user has submitted a query
|
| 203 |
if submit_button and user_input:
|
| 204 |
-
|
| 205 |
-
st.session_state["
|
| 206 |
-
|
| 207 |
-
# Generate a response using the Langchain ConversationalRetrievalChain
|
| 208 |
-
output = await conversational_chat(user_input)
|
| 209 |
-
|
| 210 |
-
# Add the user's chatbot's output to the chat history
|
| 211 |
-
st.session_state["generated"].append(output)
|
| 212 |
|
| 213 |
# If there are generated messages to display
|
| 214 |
-
if st.session_state["
|
| 215 |
-
# Display the chat history
|
| 216 |
with response_container:
|
| 217 |
-
for i in range(len(st.session_state["
|
| 218 |
message(
|
| 219 |
-
st.session_state["
|
| 220 |
is_user=True,
|
| 221 |
-
key=
|
| 222 |
avatar_style="big-smile",
|
| 223 |
)
|
| 224 |
-
message(st.session_state["
|
| 225 |
-
# st.write(chain)
|
| 226 |
|
| 227 |
except Exception as e:
|
| 228 |
st.error(f"Error: {str(e)}")
|
| 229 |
|
| 230 |
-
|
| 231 |
-
about = st.sidebar.expander("About π€")
|
| 232 |
-
|
| 233 |
-
# Write information about the chatbot in the "About" section
|
| 234 |
-
about.write(
|
| 235 |
-
"#### ChatBot-PDF is an AI chatbot featuring conversational memory, designed to enable users to discuss their PDF data in a more intuitive manner. π"
|
| 236 |
-
)
|
| 237 |
-
about.write(
|
| 238 |
-
"#### This is a fork of [ChatBot-CSV](https://github.com/yvann-hub/ChatBot-CSV) by [yvann-hub](https://github.com/yvann-hub), many thanks to him for his work. π€"
|
| 239 |
-
)
|
| 240 |
-
about.write(
|
| 241 |
-
"#### He employs large language models to provide users with seamless, context-aware natural language interactions for a better understanding of their data. π"
|
| 242 |
-
)
|
| 243 |
-
about.write(
|
| 244 |
-
"#### Powered by [Langchain](https://github.com/hwchase17/langchain), [OpenAI](https://platform.openai.com/docs/models/gpt-3-5) and [Streamlit](https://github.com/streamlit/streamlit) β‘"
|
| 245 |
-
)
|
| 246 |
-
about.write("#### Source code : [gabacode/ChatBot-PDF](https://github.com/gabacode/ChatBot-PDF)")
|
| 247 |
|
| 248 |
|
| 249 |
# Run the main function using asyncio
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import streamlit as st
|
|
|
|
| 3 |
import asyncio
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
|
|
|
|
| 6 |
from streamlit_chat import message
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
from modules.chatbot import Chatbot
|
| 9 |
+
from modules.embedder import Embedder
|
| 10 |
+
from modules.history import ChatHistory
|
| 11 |
+
from modules.layout import Layout
|
| 12 |
+
from modules.sidebar import Sidebar
|
| 13 |
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
load_dotenv()
|
|
|
|
| 16 |
|
| 17 |
+
st.set_page_config(layout="wide", page_icon="π¬", page_title="ChatBot-PDF")
|
|
|
|
| 18 |
|
| 19 |
+
# Load the OpenAI API key from the .env file or from the user's input
|
| 20 |
+
def load_api_key():
|
| 21 |
+
user_api_key = os.getenv("OPENAI_API_KEY")
|
| 22 |
+
if not user_api_key:
|
| 23 |
+
user_api_key = st.sidebar.text_input(
|
| 24 |
+
label="#### Your OpenAI API key π", placeholder="Paste your openAI API key, sk-", type="password"
|
| 25 |
+
)
|
| 26 |
+
else:
|
| 27 |
+
st.sidebar.success("API key loaded from .env", icon="π")
|
| 28 |
+
return user_api_key
|
| 29 |
|
| 30 |
|
| 31 |
+
# Handle the file upload and display the uploaded file
|
| 32 |
+
def handle_upload():
|
| 33 |
+
uploaded_file = st.sidebar.file_uploader("upload", type="pdf", label_visibility="collapsed")
|
| 34 |
+
if uploaded_file is not None:
|
| 35 |
+
file_container = st.expander("Your PDF file :")
|
| 36 |
+
file_container.write(uploaded_file)
|
| 37 |
+
else:
|
| 38 |
+
st.sidebar.info(
|
| 39 |
+
"π Upload your PDF file to get started, "
|
| 40 |
+
"sample for try : [file.pdf](https://github.com/gabacode/chatPDF/blob/main/file.pdf)"
|
| 41 |
)
|
| 42 |
+
st.session_state["reset_chat"] = True
|
| 43 |
+
return uploaded_file
|
| 44 |
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
# Set up the chatbot with the uploaded file, model, and temperature
|
| 47 |
+
async def setup_chatbot(uploaded_file, model, temperature):
|
| 48 |
+
embeds = Embedder()
|
| 49 |
+
with st.spinner("Processing..."):
|
| 50 |
+
uploaded_file.seek(0)
|
| 51 |
+
file = uploaded_file.read()
|
| 52 |
+
vectors = await embeds.getDocEmbeds(file, uploaded_file.name)
|
| 53 |
+
chatbot = Chatbot(model, temperature, vectors)
|
| 54 |
+
st.session_state["ready"] = True
|
| 55 |
+
return chatbot
|
| 56 |
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
async def main():
|
|
|
|
|
|
|
| 59 |
|
| 60 |
+
layout = Layout()
|
| 61 |
+
sidebar = Sidebar()
|
| 62 |
|
| 63 |
+
layout.display_header()
|
| 64 |
+
user_api_key = load_api_key()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
if user_api_key == "":
|
| 67 |
+
layout.show_api_key_error()
|
| 68 |
+
else:
|
| 69 |
+
os.environ["OPENAI_API_KEY"] = user_api_key
|
| 70 |
+
uploaded_file = handle_upload()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
if uploaded_file is not None:
|
| 73 |
+
history = ChatHistory()
|
| 74 |
+
sidebar.options()
|
| 75 |
+
try:
|
| 76 |
+
chatbot = await setup_chatbot(uploaded_file, st.session_state["model"], st.session_state["temperature"])
|
| 77 |
+
st.session_state["chatbot"] = chatbot
|
| 78 |
|
| 79 |
+
if st.session_state["ready"]:
|
| 80 |
+
# Create a containers for displaying the chat history
|
| 81 |
response_container = st.container()
|
|
|
|
|
|
|
| 82 |
container = st.container()
|
| 83 |
|
| 84 |
with container:
|
|
|
|
| 85 |
with st.form(key="my_form", clear_on_submit=True):
|
| 86 |
user_input = st.text_area(
|
| 87 |
"Query:",
|
| 88 |
+
placeholder="Ask me anything about the document...",
|
| 89 |
key="input",
|
| 90 |
label_visibility="collapsed",
|
| 91 |
)
|
| 92 |
submit_button = st.form_submit_button(label="Send")
|
| 93 |
|
| 94 |
+
if st.session_state["reset_chat"]:
|
| 95 |
+
history.reset(uploaded_file)
|
| 96 |
+
|
| 97 |
+
history.initialize(uploaded_file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
# If the user has submitted a query
|
| 100 |
if submit_button and user_input:
|
| 101 |
+
history.append("user", user_input)
|
| 102 |
+
output = await st.session_state["chatbot"].conversational_chat(user_input)
|
| 103 |
+
history.append("assistant", output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
# If there are generated messages to display
|
| 106 |
+
if st.session_state["assistant"]:
|
|
|
|
| 107 |
with response_container:
|
| 108 |
+
for i in range(len(st.session_state["assistant"])):
|
| 109 |
message(
|
| 110 |
+
st.session_state["user"][i],
|
| 111 |
is_user=True,
|
| 112 |
+
key=f"{i}_user",
|
| 113 |
avatar_style="big-smile",
|
| 114 |
)
|
| 115 |
+
message(st.session_state["assistant"][i], key=str(i), avatar_style="thumbs")
|
|
|
|
| 116 |
|
| 117 |
except Exception as e:
|
| 118 |
st.error(f"Error: {str(e)}")
|
| 119 |
|
| 120 |
+
sidebar.about()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
|
| 123 |
# Run the main function using asyncio
|
modules/chatbot.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from langchain.chat_models import ChatOpenAI
|
| 3 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Chatbot:
|
| 7 |
+
def __init__(self, model_name, temperature, vectors):
|
| 8 |
+
self.model_name = model_name
|
| 9 |
+
self.temperature = temperature
|
| 10 |
+
self.vectors = vectors
|
| 11 |
+
|
| 12 |
+
async def conversational_chat(self, query):
|
| 13 |
+
"""
|
| 14 |
+
Starts a conversational chat with a model via Langchain
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
chain = ConversationalRetrievalChain.from_llm(
|
| 18 |
+
llm=ChatOpenAI(model_name=self.model_name, temperature=self.temperature),
|
| 19 |
+
retriever=self.vectors.as_retriever(),
|
| 20 |
+
)
|
| 21 |
+
result = chain({"question": query, "chat_history": st.session_state["history"]})
|
| 22 |
+
|
| 23 |
+
st.session_state["history"].append((query, result["answer"]))
|
| 24 |
+
|
| 25 |
+
return result["answer"]
|
modules/embedder.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
import tempfile
|
| 4 |
+
from langchain.document_loaders import PyPDFLoader
|
| 5 |
+
from langchain.vectorstores import FAISS
|
| 6 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Embedder:
|
| 10 |
+
def __init__(self):
|
| 11 |
+
pass
|
| 12 |
+
|
| 13 |
+
async def storeDocEmbeds(self, file, filename):
|
| 14 |
+
"""
|
| 15 |
+
Stores document embeddings using Langchain and FAISS
|
| 16 |
+
"""
|
| 17 |
+
# Write the uploaded file to a temporary file
|
| 18 |
+
with tempfile.NamedTemporaryFile(mode="wb", delete=False) as tmp_file:
|
| 19 |
+
tmp_file.write(file)
|
| 20 |
+
tmp_file_path = tmp_file.name
|
| 21 |
+
|
| 22 |
+
# Load the data from the file using Langchain
|
| 23 |
+
loader = PyPDFLoader(file_path=tmp_file_path)
|
| 24 |
+
data = loader.load_and_split()
|
| 25 |
+
|
| 26 |
+
# Create an embeddings object using Langchain
|
| 27 |
+
embeddings = OpenAIEmbeddings()
|
| 28 |
+
|
| 29 |
+
# Store the embeddings vectors using FAISS
|
| 30 |
+
vectors = FAISS.from_documents(data, embeddings)
|
| 31 |
+
os.remove(tmp_file_path)
|
| 32 |
+
|
| 33 |
+
# Save the vectors to a pickle file
|
| 34 |
+
with open(filename + ".pkl", "wb") as f:
|
| 35 |
+
pickle.dump(vectors, f)
|
| 36 |
+
|
| 37 |
+
async def getDocEmbeds(self, file, filename):
|
| 38 |
+
"""
|
| 39 |
+
Retrieves document embeddings
|
| 40 |
+
"""
|
| 41 |
+
# Check if embeddings vectors have already been stored in a pickle file
|
| 42 |
+
if not os.path.isfile(filename + ".pkl"):
|
| 43 |
+
# If not, store the vectors using the storeDocEmbeds function
|
| 44 |
+
await self.storeDocEmbeds(file, filename)
|
| 45 |
+
|
| 46 |
+
# Load the vectors from the pickle file
|
| 47 |
+
with open(filename + ".pkl", "rb") as f:
|
| 48 |
+
global vectors
|
| 49 |
+
vectors = pickle.load(f)
|
| 50 |
+
|
| 51 |
+
return vectors
|
modules/history.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import streamlit as st
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ChatHistory:
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.history = st.session_state.get("history", [])
|
| 8 |
+
st.session_state["history"] = self.history
|
| 9 |
+
|
| 10 |
+
def default_greeting(self):
|
| 11 |
+
return "Hey ! π"
|
| 12 |
+
|
| 13 |
+
def default_prompt(self, thingy, topic):
|
| 14 |
+
return f'Hello! Ask me anything about the {thingy} "{topic}" π€'
|
| 15 |
+
|
| 16 |
+
def initialize_user_history(self):
|
| 17 |
+
st.session_state["user"] = [self.default_greeting()]
|
| 18 |
+
|
| 19 |
+
def initialize_assistant_history(self, uploaded_file):
|
| 20 |
+
st.session_state["assistant"] = [self.default_prompt("document", uploaded_file.name)]
|
| 21 |
+
|
| 22 |
+
def initialize(self, uploaded_file):
|
| 23 |
+
if "assistant" not in st.session_state:
|
| 24 |
+
self.initialize_assistant_history(uploaded_file)
|
| 25 |
+
if "user" not in st.session_state:
|
| 26 |
+
self.initialize_user_history()
|
| 27 |
+
|
| 28 |
+
def reset(self, uploaded_file):
|
| 29 |
+
st.session_state["history"] = []
|
| 30 |
+
self.initialize_user_history()
|
| 31 |
+
self.initialize_assistant_history(uploaded_file)
|
| 32 |
+
st.session_state["reset_chat"] = False
|
| 33 |
+
|
| 34 |
+
def append(self, mode, message):
|
| 35 |
+
st.session_state[mode].append(message)
|
| 36 |
+
|
| 37 |
+
def load(self):
|
| 38 |
+
if os.path.exists(self.history_file):
|
| 39 |
+
with open(self.history_file, "r") as f:
|
| 40 |
+
self.history = f.read().splitlines()
|
| 41 |
+
|
| 42 |
+
def save(self):
|
| 43 |
+
with open(self.history_file, "w") as f:
|
| 44 |
+
f.write("\n".join(self.history))
|
modules/layout.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Layout:
|
| 5 |
+
def display_header(self):
|
| 6 |
+
"""
|
| 7 |
+
Displays the header of the app
|
| 8 |
+
"""
|
| 9 |
+
st.markdown(
|
| 10 |
+
"<h1 style='text-align: center;'>ChatBot-PDF, Talk with your documents ! π¬</h1>", unsafe_allow_html=True
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
def show_api_key_error(self):
|
| 14 |
+
"""
|
| 15 |
+
Displays an error message if the user has not entered an API key
|
| 16 |
+
"""
|
| 17 |
+
st.markdown(
|
| 18 |
+
"<div style='text-align: center;'><h4>Enter your OpenAI API key to start chatting π</h4></div>",
|
| 19 |
+
unsafe_allow_html=True,
|
| 20 |
+
)
|
modules/sidebar.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Sidebar:
|
| 5 |
+
MODEL_OPTIONS = ["gpt-3.5-turbo"]
|
| 6 |
+
TEMPERATURE_MIN_VALUE = 0.0
|
| 7 |
+
TEMPERATURE_MAX_VALUE = 1.0
|
| 8 |
+
TEMPERATURE_DEFAULT_VALUE = 0.618
|
| 9 |
+
TEMPERATURE_STEP = 0.01
|
| 10 |
+
|
| 11 |
+
def __init__(self):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
def about(self):
|
| 15 |
+
about = st.sidebar.expander("About π€")
|
| 16 |
+
sections = [
|
| 17 |
+
"#### ChatBot-PDF is an AI chatbot featuring conversational memory, designed to enable users to discuss their PDF data in a more intuitive manner. π",
|
| 18 |
+
"#### This is a fork of [ChatBot-CSV](https://github.com/yvann-hub/ChatBot-CSV) by [yvann-hub](https://github.com/yvann-hub), many thanks to him for his work. π€",
|
| 19 |
+
"#### It employs large language models to provide users with seamless, context-aware natural language interactions for a better understanding of their data. π",
|
| 20 |
+
"#### Powered by [Langchain](https://github.com/hwchase17/langchain), [OpenAI](https://platform.openai.com/docs/models/gpt-3-5) and [Streamlit](https://github.com/streamlit/streamlit) β‘",
|
| 21 |
+
"#### Source code : [gabacode/ChatBot-PDF](https://github.com/gabacode/ChatBot-PDF)",
|
| 22 |
+
]
|
| 23 |
+
for section in sections:
|
| 24 |
+
about.write(section)
|
| 25 |
+
|
| 26 |
+
def reset_chat_button(self):
|
| 27 |
+
if st.button("Reset chat"):
|
| 28 |
+
st.session_state["reset_chat"] = True
|
| 29 |
+
st.session_state.setdefault("reset_chat", False)
|
| 30 |
+
|
| 31 |
+
def model_selector(self):
|
| 32 |
+
model = st.selectbox(label="Model", options=self.MODEL_OPTIONS)
|
| 33 |
+
st.session_state["model"] = model
|
| 34 |
+
|
| 35 |
+
def temperature_slider(self):
|
| 36 |
+
temperature = st.slider(
|
| 37 |
+
label="Temperature",
|
| 38 |
+
min_value=self.TEMPERATURE_MIN_VALUE,
|
| 39 |
+
max_value=self.TEMPERATURE_MAX_VALUE,
|
| 40 |
+
value=self.TEMPERATURE_DEFAULT_VALUE,
|
| 41 |
+
step=self.TEMPERATURE_STEP,
|
| 42 |
+
)
|
| 43 |
+
st.session_state["temperature"] = temperature
|
| 44 |
+
|
| 45 |
+
def options(self):
|
| 46 |
+
with st.sidebar.expander("π οΈ Settings", expanded=False):
|
| 47 |
+
self.reset_chat_button()
|
| 48 |
+
self.model_selector()
|
| 49 |
+
self.temperature_slider()
|
| 50 |
+
st.session_state.setdefault("model", self.MODEL_OPTIONS[0])
|
| 51 |
+
st.session_state.setdefault("temperature", self.TEMPERATURE_DEFAULT_VALUE)
|