moksha1234 commited on
Commit
76ae9cb
·
verified ·
1 Parent(s): 27803fb

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +96 -0
  2. htmlTemplates.py +44 -0
  3. requirements.txt +8 -0
  4. test.py +110 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import streamlit as st
3
+ from PyPDF2 import PdfReader
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain_community.embeddings import HuggingFaceInstructEmbeddings
6
+ from langchain_community.vectorstores import FAISS
7
+ from langchain_community.chat_models import ChatOpenAI
8
+ from langchain_community.callbacks.manager import get_openai_callback
9
+ from langchain.memory import ConversationBufferMemory
10
+ from langchain.chains import ConversationalRetrievalChain
11
+ from htmlTemplates import css, user_template, bot_template
12
+
13
+
14
+ def get_pdf_text(pdf_docs):
15
+ """Extract text from multiple uploaded PDF files."""
16
+ text = ""
17
+ for pdf in pdf_docs:
18
+ pdf_reader = PdfReader(pdf)
19
+ for page in pdf_reader.pages:
20
+ extracted_text = page.extract_text()
21
+ if extracted_text:
22
+ text += extracted_text + "\n"
23
+ return text
24
+
25
+
26
+ def get_text_chunks(text):
27
+ """Split the extracted text into smaller chunks for vector storage."""
28
+ text_splitter = CharacterTextSplitter(
29
+ separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len
30
+ )
31
+ return text_splitter.split_text(text)
32
+
33
+
34
+ def get_vectorstore(text_chunks):
35
+ """Convert text chunks into vector embeddings and store them in FAISS."""
36
+ embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
37
+ vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
38
+ return vectorstore
39
+
40
+
41
+ def get_conversation_chain(vectorstore):
42
+ """Set up the conversational AI chain using a language model and vector storage."""
43
+ llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.8)
44
+
45
+ memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
46
+
47
+ conversation_chain = ConversationalRetrievalChain.from_llm(
48
+ llm=llm, retriever=vectorstore.as_retriever(), memory=memory
49
+ )
50
+ return conversation_chain
51
+
52
+
53
+ def handle_user_input(user_question):
54
+ """Process user input and generate a response."""
55
+ response = st.session_state.conversation({'question': user_question})
56
+ st.session_state.chat_history = response['chat_history']
57
+
58
+ for i, message in enumerate(st.session_state.chat_history):
59
+ if i % 2 == 0:
60
+ st.write(user_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
61
+ else:
62
+ st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
63
+
64
+
65
+ def main():
66
+ load_dotenv()
67
+ st.set_page_config(page_title="Chat with multiple PDFs", page_icon="📚")
68
+
69
+ st.write(css, unsafe_allow_html=True)
70
+
71
+ if "conversation" not in st.session_state:
72
+ st.session_state.conversation = None
73
+
74
+ if "chat_history" not in st.session_state:
75
+ st.session_state.chat_history = []
76
+
77
+ st.header("📚 Chat with Multiple PDFs")
78
+
79
+ user_question = st.text_input("Ask a question about your documents:")
80
+ if user_question:
81
+ handle_user_input(user_question)
82
+
83
+ with st.sidebar:
84
+ st.subheader("Upload Your PDFs")
85
+ pdf_docs = st.file_uploader("Upload PDFs and click Process", accept_multiple_files=True)
86
+
87
+ if st.button("Process"):
88
+ with st.spinner("Processing..."):
89
+ raw_text = get_pdf_text(pdf_docs)
90
+ text_chunks = get_text_chunks(raw_text)
91
+ vectorstore = get_vectorstore(text_chunks)
92
+ st.session_state.conversation = get_conversation_chain(vectorstore)
93
+
94
+
95
+ if __name__ == '__main__':
96
+ main()
htmlTemplates.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ css = '''
2
+ <style>
3
+ .chat-message {
4
+ padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex
5
+ }
6
+ .chat-message.user {
7
+ background-color: #2b313e
8
+ }
9
+ .chat-message.bot {
10
+ background-color: #475063
11
+ }
12
+ .chat-message .avatar {
13
+ width: 20%;
14
+ }
15
+ .chat-message .avatar img {
16
+ max-width: 78px;
17
+ max-height: 78px;
18
+ border-radius: 50%;
19
+ object-fit: cover;
20
+ }
21
+ .chat-message .message {
22
+ width: 80%;
23
+ padding: 0 1.5rem;
24
+ color: #fff;
25
+ }
26
+ '''
27
+
28
+ bot_template = '''
29
+ <div class="chat-message bot">
30
+ <div class="avatar">
31
+ <img src="https://i.ibb.co/cN0nmSj/Screenshot-2023-05-28-at-02-37-21.png" style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;">
32
+ </div>
33
+ <div class="message">{{MSG}}</div>
34
+ </div>
35
+ '''
36
+
37
+ user_template = '''
38
+ <div class="chat-message user">
39
+ <div class="avatar">
40
+ <img src="https://i.ibb.co/rdZC7LZ/Photo-logo-1.png">
41
+ </div>
42
+ <div class="message">{{MSG}}</div>
43
+ </div>
44
+ '''
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ streamlit==1.29.0
2
+ langchain==0.0.353
3
+ PyPDF2==3.0.1
4
+ python-dotenv==1.0.1
5
+ faiss-cpu==1.7.4
6
+ openai==0.28.1
7
+ huggingface_hub==0.20.2
8
+ numpy
test.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import streamlit as st
3
+ from PyPDF2 import PdfReader
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain.embeddings.openai import OpenAIEmbeddings
6
+ from langchain.embeddings.huggingface import HuggingFaceInstructEmbeddings
7
+ from langchain.memory import ConversationBufferMemory
8
+ from langchain.chains.conversational_retrieval.base import ConversationalRetrievalChain
9
+ from langchain.vectorstores import faiss
10
+ from langchain.chains.question_answering import load_qa_chain
11
+ from langchain.chat_models.openai import ChatOpenAI
12
+ from langchain.callbacks import get_openai_callback
13
+ from htmlTemplates import css, user_template, bot_template
14
+ from langchain.llms import huggingface_hub
15
+
16
+
17
+ def get_pdf_text(pdf_docs):
18
+ text = ""
19
+ for pdf in pdf_docs:
20
+ pdf_reader = PdfReader(pdf)
21
+ for page in pdf_reader.pages:
22
+ text += page.extract_text()
23
+ return text
24
+
25
+
26
+ def get_text_chunks(text):
27
+ text_splitter = CharacterTextSplitter(
28
+ separator="\n",
29
+ chunk_size=1000,
30
+ chunk_overlap=200,
31
+ length_function=len
32
+ )
33
+ chunks = text_splitter.split_text(text)
34
+ return chunks
35
+
36
+
37
+ def get_vectorstore(text_chunks):
38
+ # embeddings = OpenAIEmbeddings()
39
+ embeddings = HuggingFaceInstructEmbeddings(
40
+ model_name="hkunlp/instructor-xl")
41
+ vectorstore = faiss.FAISS.from_texts(
42
+ texts=text_chunks, embedding=embeddings)
43
+ return vectorstore
44
+
45
+
46
+ def get_conversation_chain(vectorstore):
47
+ llm = ChatOpenAI()
48
+ # llm = huggingface_hub.HuggingFaceHub(
49
+ # repo_id="google/flan-t5-xxl", model_kwargs={"temperature": 0.8, "max_length": 512})
50
+
51
+ memory = ConversationBufferMemory(
52
+ memory_key='chat_history', return_messages=True)
53
+ conversation_chain = ConversationalRetrievalChain.from_llm(
54
+ llm=llm,
55
+ retriever=vectorstore.as_retriever(),
56
+ memory=memory
57
+ )
58
+ return conversation_chain
59
+
60
+
61
+ def handle_userinput(user_question):
62
+ response = st.session_state.conversation({'question': user_question})
63
+ st.session_state.chat_history = response['chat_history']
64
+
65
+ for i, message in enumerate(st.session_state.chat_history):
66
+ if i % 2 == 0:
67
+ st.write(user_template.replace(
68
+ "{{MSG}}", message.content), unsafe_allow_html=True)
69
+ else:
70
+ st.write(bot_template.replace(
71
+ "{{MSG}}", message.content), unsafe_allow_html=True)
72
+
73
+
74
+ def main():
75
+ load_dotenv()
76
+ st.set_page_config(page_title="Chat with multiple PDFs",
77
+ page_icon=":books:")
78
+ st.write(css, unsafe_allow_html=True)
79
+
80
+ if "conversation" not in st.session_state:
81
+ st.session_state.conversation = []
82
+ if "chat_history" not in st.session_state:
83
+ st.session_state.chat_history = []
84
+ st.header("Chat with multiple PDFs :books:")
85
+ user_question = st.text_input("Ask a question about your documents:")
86
+ if user_question:
87
+ handle_userinput(user_question)
88
+
89
+ with st.sidebar:
90
+ st.subheader("Your documents")
91
+ pdf_docs = st.file_uploader(
92
+ "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
93
+ if st.button("Process"):
94
+ with st.spinner("Processing"):
95
+ # get pdf text
96
+ raw_text = get_pdf_text(pdf_docs)
97
+
98
+ # get the text chunks
99
+ text_chunks = get_text_chunks(raw_text)
100
+
101
+ # create vector store
102
+ vectorstore = get_vectorstore(text_chunks)
103
+
104
+ # create conversation chain
105
+ st.session_state.conversation = get_conversation_chain(
106
+ vectorstore)
107
+
108
+
109
+ if __name__ == '__main__':
110
+ main()