Ubai commited on
Commit
a233e6a
1 Parent(s): d20d8d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -0
app.py CHANGED
@@ -80,3 +80,181 @@ def initialize_llmchain(vector_db, progress=gr.Progress()):
80
 
81
 
82
  # ... (other functions remain the same)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
 
82
  # ... (other functions remain the same)
83
+
84
+
85
+ # Initialize database
86
+ def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
87
+ # Create list of documents (when valid)
88
+ list_file_path = [x.name for x in list_file_obj if x is not None]
89
+ # Create collection_name for vector database
90
+ progress(0.1, desc="Creating collection name...")
91
+ collection_name = Path(list_file_path[0]).stem
92
+ # Fix potential issues from naming convention
93
+ ## Remove space
94
+ collection_name = collection_name.replace(" ","-")
95
+ ## Limit lenght to 50 characters
96
+ collection_name = collection_name[:50]
97
+ ## Enforce start and end as alphanumeric character
98
+ if not collection_name[0].isalnum():
99
+ collection_name[0] = 'A'
100
+ if not collection_name[-1].isalnum():
101
+ collection_name[-1] = 'Z'
102
+ # print('list_file_path: ', list_file_path)
103
+ print('Collection name: ', collection_name)
104
+ progress(0.25, desc="Loading document...")
105
+ # Load document and create splits
106
+ doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
107
+ # Create or load vector database
108
+ progress(0.5, desc="Generating vector database...")
109
+ # global vector_db
110
+ vector_db = create_db(doc_splits, collection_name)
111
+ progress(0.9, desc="Done!")
112
+ return vector_db, collection_name, "Complete!"
113
+
114
+
115
+ def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
116
+ # print("llm_option",llm_option)
117
+ llm_name = list_llm[llm_option]
118
+ print("llm_name: ",llm_name)
119
+ qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
120
+ return qa_chain, "Complete!"
121
+
122
+
123
+ def format_chat_history(message, chat_history):
124
+ formatted_chat_history = []
125
+ for user_message, bot_message in chat_history:
126
+ formatted_chat_history.append(f"User: {user_message}")
127
+ formatted_chat_history.append(f"Assistant: {bot_message}")
128
+ return formatted_chat_history
129
+
130
+
131
+ def conversation(qa_chain, message, history):
132
+ formatted_chat_history = format_chat_history(message, history)
133
+ #print("formatted_chat_history",formatted_chat_history)
134
+
135
+ # Generate response using QA chain
136
+ response = qa_chain({"question": message, "chat_history": formatted_chat_history})
137
+ response_answer = response["answer"]
138
+ if response_answer.find("Helpful Answer:") != -1:
139
+ response_answer = response_answer.split("Helpful Answer:")[-1]
140
+ response_sources = response["source_documents"]
141
+ response_source1 = response_sources[0].page_content.strip()
142
+ response_source2 = response_sources[1].page_content.strip()
143
+ response_source3 = response_sources[2].page_content.strip()
144
+ # Langchain sources are zero-based
145
+ response_source1_page = response_sources[0].metadata["page"] + 1
146
+ response_source2_page = response_sources[1].metadata["page"] + 1
147
+ response_source3_page = response_sources[2].metadata["page"] + 1
148
+ # print ('chat response: ', response_answer)
149
+ # print('DB source', response_sources)
150
+
151
+ # Append user message and response to chat history
152
+ new_history = history + [(message, response_answer)]
153
+ # return gr.update(value=""), new_history, response_sources[0], response_sources[1]
154
+ return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
155
+
156
+
157
+ def upload_file(file_obj):
158
+ list_file_path = []
159
+ for idx, file in enumerate(file_obj):
160
+ file_path = file_obj.name
161
+ list_file_path.append(file_path)
162
+ # print(file_path)
163
+ # initialize_database(file_path, progress)
164
+ return list_file_path
165
+
166
+
167
+ def demo():
168
+ with gr.Blocks(theme="base") as demo:
169
+ vector_db = gr.State()
170
+ qa_chain = gr.State()
171
+ collection_name = gr.State()
172
+
173
+ gr.Markdown(
174
+ """<center><h2>PDF-based chatbot (powered by LangChain and open-source LLMs)</center></h2>
175
+ <h3>Ask any questions about your PDF documents, along with follow-ups</h3>
176
+ <b>Note:</b> This AI assistant performs retrieval-augmented generation from your PDF documents. \
177
+ When generating answers, it takes past questions into account (via conversational memory), and includes document references for clarity purposes.</i>
178
+ <br><b>Warning:</b> This space uses the free CPU Basic hardware from Hugging Face. Some steps and LLM models used below (free inference endpoints) can take some time to generate an output.<br>
179
+ """)
180
+ with gr.Tab("Step 1 - Document pre-processing"):
181
+ with gr.Row():
182
+ document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
183
+ # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
184
+ with gr.Row():
185
+ db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
186
+ with gr.Accordion("Advanced options - Document text splitter", open=False):
187
+ with gr.Row():
188
+ slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
189
+ with gr.Row():
190
+ slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
191
+ with gr.Row():
192
+ db_progress = gr.Textbox(label="Vector database initialization", value="None")
193
+ with gr.Row():
194
+ db_btn = gr.Button("Generate vector database...")
195
+
196
+ with gr.Tab("Step 2 - QA chain initialization"):
197
+ with gr.Row():
198
+ llm_btn = gr.Radio(list_llm_simple, \
199
+ label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")
200
+ with gr.Accordion("Advanced options - LLM model", open=False):
201
+ with gr.Row():
202
+ slider_temperature = gr.Slider(minimum = 0.0, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
203
+ with gr.Row():
204
+ slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
205
+ with gr.Row():
206
+ slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
207
+ with gr.Row():
208
+ llm_progress = gr.Textbox(value="None",label="QA chain initialization")
209
+ with gr.Row():
210
+ qachain_btn = gr.Button("Initialize question-answering chain...")
211
+
212
+ with gr.Tab("Step 3 - Conversation with chatbot"):
213
+ chatbot = gr.Chatbot(height=300)
214
+ with gr.Accordion("Advanced - Document references", open=False):
215
+ with gr.Row():
216
+ doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
217
+ source1_page = gr.Number(label="Page", scale=1)
218
+ with gr.Row():
219
+ doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
220
+ source2_page = gr.Number(label="Page", scale=1)
221
+ with gr.Row():
222
+ doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
223
+ source3_page = gr.Number(label="Page", scale=1)
224
+ with gr.Row():
225
+ msg = gr.Textbox(placeholder="Type message", container=True)
226
+ with gr.Row():
227
+ submit_btn = gr.Button("Submit")
228
+ clear_btn = gr.ClearButton([msg, chatbot])
229
+
230
+ # Preprocessing events
231
+ #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
232
+ db_btn.click(initialize_database, \
233
+ inputs=[document, slider_chunk_size, slider_chunk_overlap], \
234
+ outputs=[vector_db, collection_name, db_progress])
235
+ qachain_btn.click(initialize_LLM, \
236
+ inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
237
+ outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
238
+ inputs=None, \
239
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
240
+ queue=False)
241
+
242
+ # Chatbot events
243
+ msg.submit(conversation, \
244
+ inputs=[qa_chain, msg, chatbot], \
245
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
246
+ queue=False)
247
+ submit_btn.click(conversation, \
248
+ inputs=[qa_chain, msg, chatbot], \
249
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
250
+ queue=False)
251
+ clear_btn.click(lambda:[None,"",0,"",0,"",0], \
252
+ inputs=None, \
253
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
254
+ queue=False)
255
+ demo.queue().launch(debug=True)
256
+
257
+
258
+ if __name__ == "__main__":
259
+ demo()
260
+