-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathapp.py
221 lines (173 loc) · 6.32 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
"""
ChatPDF
ChatPDF is a Streamlit application that allows users to upload PDF and DOCX files
and then ask questions related to the content of those documents.
The content of the documents is indexed and vectorized to allow for natural
language interactions. The application uses the OpenAI API to power the conversational
interface, FAISS for fast similarity search, and various other utilities to parse
and handle document content.
Functions:
----------
- parse_docx(data: bytes) -> str:
Parse a DOCX file and return its textual content.
- get_text(docs: list) -> str:
Extract and combine the textual content of a list of uploaded PDF and DOCX files.
- get_chunks(data: str) -> list:
Split the provided text into manageable chunks based on characters.
- get_vector(chunks: list) -> FAISS:
Convert a list of text chunks into vectors using OpenAI embeddings and store them using FAISS.
- get_llm_chain(vectors: FAISS) -> ConversationalRetrievalChain:
Create a conversational retrieval chain instance ready for processing user queries
using the provided set of vectors.
- main() -> None:
The main function initializes and runs the Streamlit application. It handles
the file uploads, user input, and displays bot responses.
If you run this module directly, it will start the Streamlit application where you can
upload PDFs and DOCX files, and then interact with their content using natural language queries.
"""
import os
import streamlit as st
from docx import Document
from langchain.chains import ConversationalRetrievalChain
from langchain.chat_models import ChatOpenAI
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.memory import ConversationBufferMemory
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import FAISS
from PyPDF2 import PdfReader
os.environ["OPENAI_API_KEY"] = "" # OPENAI_API_KEY
def parse_docx(data):
"""
Parse and extract text content from a DOCX file.
Parameters:
-----------
data : bytes
The binary content of the DOCX file.
Returns:
--------
str
The extracted text content from the DOCX file.
"""
document = Document(docx=data)
content = ""
for para in document.paragraphs:
data = para.text
content += data
return content
def get_text(docs):
"""
Extract textual content from a list of uploaded PDF files.
Parameters:
-----------
docs : list
List of uploaded PDF files.
Returns:
--------
str
The combined textual content of all the provided PDFs.
"""
doc_text = ""
for doc in docs:
if ".pdf" in doc.name:
pdf_reader = PdfReader(doc)
for each_page in pdf_reader.pages:
doc_text += each_page.extractText()
doc_text += "\n"
elif ".docx" in doc.name:
doc_text += parse_docx(data=doc)
return doc_text
def get_chunks(data):
"""
Splits the provided text data into manageable chunks.
Parameters:
-----------
data : str
Text data that needs to be split.
Returns:
--------
list
A list containing chunks of the provided text data.
"""
text_splitter = CharacterTextSplitter(
separator="\n", chunk_size=1000, chunk_overlap=250, length_function=len
)
text_chunks = text_splitter.split_text(data)
return text_chunks
def get_vector(chunks):
"""
Generate vectors from text chunks using FAISS vector store and OpenAI embeddings.
Parameters:
-----------
chunks : list
List of text chunks that need to be vectorized.
Returns:
--------
FAISS
FAISS vector store containing vectors of the provided text chunks.
"""
return FAISS.from_texts(texts=chunks, embedding=OpenAIEmbeddings())
def get_llm_chain(vectors):
"""
Create a conversational retrieval chain using the provided set of vectors.
Parameters:
-----------
vectors : FAISS
FAISS vector store containing vectors of text chunks.
Returns:
--------
ConversationalRetrievalChain
A conversational retrieval chain instance ready for processing user queries.
"""
llm_chain = ConversationalRetrievalChain.from_llm(
llm=ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.7),
retriever=vectors.as_retriever(),
memory=ConversationBufferMemory(
memory_key="chat_history", return_messages=True
),
)
return llm_chain
def main():
"""
Main function to initialize the Streamlit application.
Handles file uploads, user queries, and bot responses.
Returns:
--------
None
"""
st.set_page_config(page_title="ChatPDF")
st.title("ChatPDF - Chat with PDFs 📄")
if not "llm_chain" in st.session_state:
st.session_state.llm_chain = None
if not "chat_history" in st.session_state:
st.session_state.chat_history = []
if not "doc_len" in st.session_state:
st.session_state.doc_len = 0
user_input = st.text_input("Ask any question related to the pdf")
if user_input and st.session_state.llm_chain:
bot_response = st.session_state.llm_chain({"question": user_input})
st.session_state.memory = bot_response["chat_history"]
for idx, msg in enumerate(st.session_state.memory):
if idx % 2 == 0:
with st.chat_message("user"):
st.write(msg.content)
else:
with st.chat_message("assistant"):
st.write(msg.content)
elif user_input and not st.session_state.llm_chain:
st.error("Please upload files and click proceed before asking questions")
with st.sidebar:
st.subheader("About")
docs = st.file_uploader(
"Upload PDF and click proceed", accept_multiple_files=True
)
if len(docs) > st.session_state.doc_len:
st.session_state.doc_len = len(docs)
with st.spinner("Processing..."):
doc_text = get_text(docs)
doc_chunks = get_chunks(doc_text)
vectors = get_vector(doc_chunks)
st.session_state.llm_chain = get_llm_chain(vectors)
with st.chat_message("assistant"):
st.write("Hello, Please upload your files and click proceed to ask questions.")
if __name__ == "__main__":
main()