wiwaaw commited on
Commit
12bcd45
β€’
1 Parent(s): 0fcc376

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from dotenv import load_dotenv
3
+ from PyPDF2 import PdfReader
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.embeddings import HuggingFaceBgeEmbeddings
6
+ from langchain.vectorstores import FAISS
7
+ from langchain.memory import ConversationBufferMemory
8
+ from langchain.chains import ConversationalRetrievalChain
9
+ from htmltemp import css, bot_template, user_template
10
+ from langchain.llms import HuggingFaceHub
11
+
12
+
13
+ def main():
14
+ load_dotenv()
15
+ st.set_page_config(page_title="PDF Chatbot", page_icon="πŸ“š")
16
+ custom_html = """
17
+ <div class="banner">
18
+ <img src="https://www.canva.com/design/DAFys-F940k/2s_2FuK_FCWlBKS8VEWLMA/view?utm_content=DAFys-F940k&utm_campaign=designshare&utm_medium=link&utm_source=editor" alt="Banner Image">
19
+ </div>
20
+ <style>
21
+ .banner {
22
+ width: 160%;
23
+ height: 200px;
24
+ overflow: hidden;
25
+ }
26
+ .banner img {
27
+ width: 100%;
28
+ object-fit: cover;
29
+ }
30
+ </style>
31
+ """
32
+ st.write(css, unsafe_allow_html=True)
33
+
34
+ if "conversation" not in st.session_state:
35
+ st.session_state.conversation = None
36
+ if "chat_history" not in st.session_state:
37
+ st.session_state.chat_history = None
38
+
39
+ st.header("Chat with your PDFs πŸ“š")
40
+ user_question = st.text_input("Ask a question about your documents:")
41
+ if user_question:
42
+ handle_userinput(user_question)
43
+
44
+ with st.sidebar:
45
+ st.sidebar.info("""Note: I haven't used any GPU for this project so It can take
46
+ long time to process large PDFs. Also this is POC project and can be easily upgraded
47
+ with better model and resources. """)
48
+
49
+ st.subheader("Your PDFs")
50
+ pdf_docs = st.file_uploader(
51
+ "Upload your PDFs here", accept_multiple_files=True
52
+ )
53
+ if st.button("Process"):
54
+ with st.spinner("Processing"):
55
+ # get pdf text
56
+ raw_text = get_pdf_text(pdf_docs)
57
+
58
+ # get the text chunks
59
+ text_chunks = get_text_chunks(raw_text)
60
+
61
+ # create vector store
62
+ vectorstore = get_vectorstore(text_chunks)
63
+
64
+ # create conversation chain
65
+ st.session_state.conversation = get_conversation_chain(vectorstore)
66
+ st.success("file uploaded")
67
+
68
+
69
+ def get_pdf_text(pdf_docs):
70
+ text = ""
71
+ for pdf in pdf_docs:
72
+ pdf_reader = PdfReader(pdf)
73
+ for page in pdf_reader.pages:
74
+ text += page.extract_text()
75
+ return text
76
+
77
+
78
+ def get_text_chunks(text):
79
+ text_splitter = RecursiveCharacterTextSplitter(
80
+ separators=["\n\n", "\n", "."], chunk_size=900, chunk_overlap=200, length_function=len
81
+ )
82
+ chunks = text_splitter.split_text(text)
83
+ return chunks
84
+
85
+
86
+ def get_vectorstore(text_chunks):
87
+ embeddings = HuggingFaceBgeEmbeddings(model_name="BAAI/bge-base-en-v1.5")
88
+ vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
89
+ return vectorstore
90
+
91
+
92
+ def get_conversation_chain(vectorstore):
93
+ llm = HuggingFaceHub(
94
+ repo_id="google/flan-t5-large",
95
+ model_kwargs={"temperature": 0.5, "max_length": 1024},
96
+
97
+ )
98
+
99
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
100
+ conversation_chain = ConversationalRetrievalChain.from_llm(
101
+ llm=llm, retriever=vectorstore.as_retriever(), memory=memory
102
+ )
103
+ return conversation_chain
104
+
105
+
106
+ def handle_userinput(user_question):
107
+ response = st.session_state.conversation({"question": user_question})
108
+ st.session_state.chat_history = response["chat_history"]
109
+
110
+ for i, message in enumerate(st.session_state.chat_history):
111
+ if i % 2 == 0:
112
+ st.write(
113
+ user_template.replace("{{MSG}}", message.content),
114
+ unsafe_allow_html=True,
115
+ )
116
+ else:
117
+ st.write(
118
+ bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True
119
+ )
120
+
121
+
122
+ if __name__ == "__main__":
123
+ main()