Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,116 +3,106 @@ import requests
|
|
3 |
import os
|
4 |
import json
|
5 |
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
load_dotenv()
|
8 |
|
9 |
-
# Initialize
|
10 |
-
|
|
|
|
|
|
|
11 |
|
12 |
def reset_conversation():
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
}
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
if decoded_line == "data: [DONE]":
|
63 |
-
return entire_assistant_response
|
64 |
-
|
65 |
-
try:
|
66 |
-
if decoded_line.startswith("data: "):
|
67 |
-
decoded_line = decoded_line.replace("data: ", "")
|
68 |
-
chunk_data = json.loads(decoded_line)
|
69 |
-
content = chunk_data['choices'][0]['delta']['content']
|
70 |
-
entire_assistant_response += content
|
71 |
-
yield content
|
72 |
-
|
73 |
-
except json.JSONDecodeError:
|
74 |
-
print(f"Invalid JSON received: {decoded_line}")
|
75 |
-
continue
|
76 |
-
except KeyError as e:
|
77 |
-
print(f"KeyError encountered: {e}")
|
78 |
-
continue
|
79 |
-
|
80 |
-
except requests.exceptions.RequestException as e:
|
81 |
-
print(f"Error occurred: {e}")
|
82 |
-
yield "Sorry, I couldn't connect to the server. Please try again later."
|
83 |
|
84 |
# Streamlit application
|
85 |
-
st.
|
86 |
-
|
87 |
-
st.
|
88 |
-
|
89 |
-
#
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
st.
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
3 |
import os
|
4 |
import json
|
5 |
from dotenv import load_dotenv
|
6 |
+
import PyPDF2
|
7 |
+
import io
|
8 |
+
from langchain.text_splitter import CharacterTextSplitter
|
9 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
10 |
+
from langchain.vectorstores import FAISS
|
11 |
+
from langchain.memory import ConversationBufferMemory
|
12 |
+
from langchain.chains import ConversationalRetrievalChain
|
13 |
+
from langchain.llms import HuggingFaceHub
|
14 |
|
15 |
load_dotenv()
|
16 |
|
17 |
+
# Initialize session state variables
|
18 |
+
if "conversation" not in st.session_state:
|
19 |
+
st.session_state.conversation = None
|
20 |
+
if "chat_history" not in st.session_state:
|
21 |
+
st.session_state.chat_history = []
|
22 |
|
23 |
def reset_conversation():
|
24 |
+
st.session_state.conversation = None
|
25 |
+
st.session_state.chat_history = []
|
26 |
+
|
27 |
+
def get_pdf_text(pdf_docs):
|
28 |
+
text = ""
|
29 |
+
for pdf in pdf_docs:
|
30 |
+
pdf_reader = PyPDF2.PdfReader(pdf)
|
31 |
+
for page in pdf_reader.pages:
|
32 |
+
text += page.extract_text()
|
33 |
+
return text
|
34 |
+
|
35 |
+
def get_text_chunks(text):
|
36 |
+
text_splitter = CharacterTextSplitter(
|
37 |
+
separator="\n",
|
38 |
+
chunk_size=1000,
|
39 |
+
chunk_overlap=200,
|
40 |
+
length_function=len
|
41 |
+
)
|
42 |
+
chunks = text_splitter.split_text(text)
|
43 |
+
return chunks
|
44 |
+
|
45 |
+
def get_vectorstore(text_chunks):
|
46 |
+
embeddings = HuggingFaceEmbeddings()
|
47 |
+
vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
|
48 |
+
return vectorstore
|
49 |
+
|
50 |
+
def get_conversation_chain(vectorstore):
|
51 |
+
llm = HuggingFaceHub(repo_id="google/flan-t5-xxl", model_kwargs={"temperature":0.5, "max_length":512})
|
52 |
+
|
53 |
+
memory = ConversationBufferMemory(
|
54 |
+
memory_key='chat_history', return_messages=True)
|
55 |
+
conversation_chain = ConversationalRetrievalChain.from_llm(
|
56 |
+
llm=llm,
|
57 |
+
retriever=vectorstore.as_retriever(),
|
58 |
+
memory=memory
|
59 |
+
)
|
60 |
+
return conversation_chain
|
61 |
+
|
62 |
+
def handle_userinput(user_question):
|
63 |
+
response = st.session_state.conversation({'question': user_question})
|
64 |
+
st.session_state.chat_history = response['chat_history']
|
65 |
+
|
66 |
+
for i, message in enumerate(st.session_state.chat_history):
|
67 |
+
if i % 2 == 0:
|
68 |
+
st.write(user_template.replace(
|
69 |
+
"{{MSG}}", message.content), unsafe_allow_html=True)
|
70 |
+
else:
|
71 |
+
st.write(bot_template.replace(
|
72 |
+
"{{MSG}}", message.content), unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
# Streamlit application
|
75 |
+
st.set_page_config(page_title="Chat with your PDFs", page_icon=":books:")
|
76 |
+
|
77 |
+
st.header("Chat with your PDFs :books:")
|
78 |
+
|
79 |
+
user_template = '<div style="background-color: #e6f3ff; padding: 10px; border-radius: 5px; margin-bottom: 10px;"><strong>Human:</strong> {{MSG}}</div>'
|
80 |
+
bot_template = '<div style="background-color: #f0f0f0; padding: 10px; border-radius: 5px; margin-bottom: 10px;"><strong>AI:</strong> {{MSG}}</div>'
|
81 |
+
|
82 |
+
# Sidebar
|
83 |
+
with st.sidebar:
|
84 |
+
st.subheader("Your documents")
|
85 |
+
pdf_docs = st.file_uploader("Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
|
86 |
+
if st.button("Process"):
|
87 |
+
with st.spinner("Processing"):
|
88 |
+
# Get PDF text
|
89 |
+
raw_text = get_pdf_text(pdf_docs)
|
90 |
+
|
91 |
+
# Get the text chunks
|
92 |
+
text_chunks = get_text_chunks(raw_text)
|
93 |
+
|
94 |
+
# Create vector store
|
95 |
+
vectorstore = get_vectorstore(text_chunks)
|
96 |
+
|
97 |
+
# Create conversation chain
|
98 |
+
st.session_state.conversation = get_conversation_chain(vectorstore)
|
99 |
+
|
100 |
+
st.button('Reset Chat', on_click=reset_conversation)
|
101 |
+
|
102 |
+
# Main chat interface
|
103 |
+
if st.session_state.conversation is None:
|
104 |
+
st.write("Please upload PDF documents and click 'Process' to start chatting.")
|
105 |
+
else:
|
106 |
+
user_question = st.text_input("Ask a question about your documents:")
|
107 |
+
if user_question:
|
108 |
+
handle_userinput(user_question)
|