rstallman lekkalar commited on
Commit
88da1f3
0 Parent(s):

Duplicate from lekkalar/chatgpt-for-pdfs-without-chat-history

Browse files

Co-authored-by: radhika lekkala <lekkalar@users.noreply.huggingface.co>

Files changed (4) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +192 -0
  4. requirements.txt +6 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ChatGPT For PDFs
3
+ emoji: 👁
4
+ colorFrom: indigo
5
+ colorTo: gray
6
+ sdk: gradio
7
+ sdk_version: 3.33.1
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: lekkalar/chatgpt-for-pdfs-without-chat-history
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import time
4
+ import pandas as pd
5
+
6
+
7
+ from langchain.document_loaders import OnlinePDFLoader #for laoding the pdf
8
+ from langchain.embeddings import OpenAIEmbeddings # for creating embeddings
9
+ from langchain.vectorstores import Chroma # for the vectorization part
10
+ from langchain.chains import RetrievalQA # for conversing with chatGPT
11
+ from langchain.chat_models import ChatOpenAI # the LLM model we'll use (ChatGPT)
12
+ from langchain import PromptTemplate
13
+
14
+ def load_pdf_and_generate_embeddings(pdf_doc, open_ai_key, relevant_pages):
15
+ if openai_key is not None:
16
+ os.environ['OPENAI_API_KEY'] = open_ai_key
17
+ #Load the pdf file
18
+ loader = OnlinePDFLoader(pdf_doc.name)
19
+ pages = loader.load_and_split()
20
+
21
+ #Create an instance of OpenAIEmbeddings, which is responsible for generating embeddings for text
22
+ embeddings = OpenAIEmbeddings()
23
+
24
+ pages_to_be_loaded =[]
25
+
26
+ if relevant_pages:
27
+ page_numbers = relevant_pages.split(",")
28
+ if len(page_numbers) != 0:
29
+ for page_number in page_numbers:
30
+ if page_number.isdigit():
31
+ pageIndex = int(page_number)-1
32
+ if pageIndex >=0 and pageIndex <len(pages):
33
+ pages_to_be_loaded.append(pages[pageIndex])
34
+ #In the scenario where none of the page numbers supplied exist in the PDF, we will revert to using the entire PDF.
35
+ if len(pages_to_be_loaded) ==0:
36
+ pages_to_be_loaded = pages.copy()
37
+
38
+
39
+ #To create a vector store, we use the Chroma class, which takes the documents (pages in our case) and the embeddings instance
40
+ vectordb = Chroma.from_documents(pages_to_be_loaded, embedding=embeddings)
41
+
42
+ #Finally, we create the bot using the RetrievalQA class
43
+ global pdf_qa
44
+
45
+ prompt_template = """Use the following pieces of context to answer the question at the end. If you do not know the answer, just return N/A. If you encounter a date, return it in mm/dd/yyyy format.
46
+
47
+ {context}
48
+
49
+ Question: {question}
50
+ Return just the answer :"""
51
+ PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
52
+ chain_type_kwargs = {"prompt": PROMPT}
53
+ pdf_qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(temperature=0, model_name="gpt-4"),chain_type="stuff", retriever=vectordb.as_retriever(search_kwargs={"k": 5}), chain_type_kwargs=chain_type_kwargs, return_source_documents=False)
54
+
55
+ return "Ready"
56
+ else:
57
+ return "Please provide an OpenAI gpt-4 API key"
58
+
59
+
60
+ def answer_predefined_questions(document_type):
61
+
62
+ if document_type == "Deed of Trust":
63
+ #Create a list of questions around the relevant fields of a Deed of Trust(DOT) document
64
+ query1 = "what is the Loan Number?"
65
+ field1 = "Loan Number"
66
+ query2 = "Who is the Borrower?"
67
+ field2 = "Borrower"
68
+ query3 = "what is the Case Number?"
69
+ field3 = "Case Number"
70
+ query4 = "what is the Mortgage Identification number?"
71
+ field4 = "MIN Number"
72
+ query5 = "DOT signed date?"
73
+ field5 = "Signed Date"
74
+ query6 = "Who is the Lender?"
75
+ field6 = "Lender"
76
+ query7 = "what is the VA/FHA Number?"
77
+ field7 = "VA/FHA Number"
78
+ query8 = "Who is the Co-Borrower?"
79
+ field8 = "Co-Borrower"
80
+ query9 = "What is the property type - single family, multi family?"
81
+ field9 = "Property Type"
82
+ query10 = "what is the Property Address?"
83
+ field10 = "Property Address"
84
+ query11 = "In what County is the property located?"
85
+ field11 = "Property County"
86
+ query12 = "what is the Electronically recorded date"
87
+ field12 = "Electronic Recording Date"
88
+
89
+
90
+
91
+ elif document_type == "Transmittal Summary":
92
+ #Create a list of questions around the relevant fields of a TRANSMITTAL SUMMARY document
93
+ query1 = "Who is the Borrower?"
94
+ field1 = "Borrower"
95
+ query2 = "what is the Property Address?"
96
+ field2 = "Property Address"
97
+ query3 = "what is the Loan Term?"
98
+ field3 = "Loan Term"
99
+ query4 = "What is the Base Income?"
100
+ field4 = "Base Income"
101
+ query5 = "what is the Borrower's SSN?"
102
+ field5 = "Borrower's SSN"
103
+ query6 = "Who is the Co-Borrower?"
104
+ field6 = "Co-Borrower"
105
+ query7 = "What is the Original Loan Amount?"
106
+ field7 = "Original Loan Amount"
107
+ query8 = "What is the Initial P&I payment?"
108
+ field8 = "Initial P&I payment"
109
+ query9 = "What is the Co-Borrower's SSN?"
110
+ field9 = "Co-Borrower’s SSN"
111
+ query10 = "Number of units?"
112
+ field10 = "Units#"
113
+ query11 = "Who is the Seller?"
114
+ field11 = "Seller"
115
+ query12 = "Document signed date?"
116
+ field12 = "Signed Date"
117
+
118
+
119
+
120
+ else:
121
+ return "Please choose your Document Type"
122
+
123
+ queryList = [query1, query2, query3, query4, query5, query6, query7, query8, query9, query10, query11,query12]
124
+ fieldList = [field1, field2, field3, field4, field5, field6, field7, field8, field9, field10, field11,field12]
125
+ responseList =[]
126
+
127
+ i = 0
128
+ while i < len(queryList):
129
+ question = queryList[i]
130
+ responseList.append(pdf_qa.run(question))
131
+ i = i+1
132
+
133
+ return pd.DataFrame({"Field": [fieldList[0],fieldList[1],fieldList[2],fieldList[3],fieldList[4],fieldList[5],fieldList[6],fieldList[7],fieldList[8],fieldList[9],fieldList[10],fieldList[11]],
134
+ "Question to gpt-4": [queryList[0],queryList[1],queryList[2],queryList[3],queryList[4],queryList[5],queryList[6],queryList[7],queryList[8],queryList[9],queryList[10],queryList[11]],
135
+ "Response from gpt-4": [responseList[0],responseList[1],responseList[2],responseList[3],responseList[4],responseList[5],responseList[6],responseList[7],responseList[8],responseList[9],responseList[10],responseList[11]]})
136
+
137
+
138
+
139
+ def answer_query(query):
140
+ question = query
141
+ return pdf_qa.run(question)
142
+
143
+
144
+ css="""
145
+ #col-container {max-width: 700px; margin-left: auto; margin-right: auto;}
146
+ """
147
+
148
+ title = """
149
+ <div style="text-align: center;max-width: 700px;">
150
+ <h1>Chatbot for PDFs - GPT-4</h1>
151
+ <p style="text-align: center;">Upload a .PDF, click the "Upload PDF and generate embeddings" button, <br />
152
+ Wait for the Status to show Ready. You can chose to get answers to the pre-defined question set OR ask your own question <br />
153
+ The app is built on GPT-4 and leverages PromptTemplate</p>
154
+ </div>
155
+ """
156
+
157
+ with gr.Blocks(css=css,theme=gr.themes.Monochrome()) as demo:
158
+ with gr.Column(elem_id="col-container"):
159
+ gr.HTML(title)
160
+
161
+ with gr.Column():
162
+ openai_key = gr.Textbox(label="Your GPT-4 OpenAI API key", type="password")
163
+ pdf_doc = gr.File(label="Load a pdf",file_types=['.pdf'],type='file')
164
+ relevant_pages = gr.Textbox(label="*Optional - List comma separated page numbers to load or leave this field blank to use the entire PDF")
165
+
166
+ with gr.Row():
167
+ status = gr.Textbox(label="Status", placeholder="", interactive=False)
168
+ load_pdf = gr.Button("Upload PDF and generate embeddings").style(full_width=False)
169
+
170
+ with gr.Row():
171
+ document_type = gr.Radio(['Deed of Trust', 'Transmittal Summary'], label="Select the Document Type")
172
+ answers = gr.Dataframe(label="Answers to Predefined Question set")
173
+ answers_for_predefined_question_set = gr.Button("Get gpt-4 answers to pre-defined question set").style(full_width=False)
174
+
175
+ with gr.Row():
176
+ input = gr.Textbox(label="Type in your question")
177
+ output = gr.Textbox(label="Answer")
178
+ submit_query = gr.Button("Submit your own question to gpt-4").style(full_width=False)
179
+
180
+
181
+ load_pdf.click(load_pdf_and_generate_embeddings, inputs=[pdf_doc, openai_key, relevant_pages], outputs=status)
182
+
183
+ answers_for_predefined_question_set.click(answer_predefined_questions, document_type, answers)
184
+
185
+ submit_query.click(answer_query,input,output)
186
+
187
+
188
+ demo.launch()
189
+
190
+
191
+
192
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openai
2
+ tiktoken
3
+ chromadb
4
+ langchain
5
+ unstructured
6
+ unstructured[local-inference]