Fecalisboa commited on
Commit
510c455
1 Parent(s): 217ade3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +326 -0
app.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from pathlib import Path
4
+ import re
5
+ from unidecode import unidecode
6
+ import chromadb
7
+ from langchain_community.vectorstores import FAISS, ScaNN, Milvus
8
+ from langchain_community.document_loaders import PyPDFLoader
9
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
10
+ from langchain_community.vectorstores import Chroma
11
+ from langchain.chains import ConversationalRetrievalChain
12
+ from langchain_community.embeddings import HuggingFaceEmbeddings
13
+ from langchain_community.llms import HuggingFacePipeline
14
+ from langchain.chains import ConversationChain
15
+ from langchain.memory import ConversationBufferMemory
16
+ from langchain_community.llms import HuggingFaceEndpoint
17
+ import torch
18
+
19
+ api_token = os.getenv("HF_TOKEN")
20
+
21
+ list_llm = ["meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.3"]
22
+ list_llm_simple = [os.path.basename(llm) for llm in list_llm]
23
+
24
+ # Load PDF document and create doc splits
25
+ def load_doc(list_file_path, chunk_size, chunk_overlap):
26
+ loaders = [PyPDFLoader(x) for x in list_file_path]
27
+ pages = []
28
+ for loader in loaders:
29
+ pages.extend(loader.load())
30
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
31
+ doc_splits = text_splitter.split_documents(pages)
32
+ return doc_splits
33
+
34
+ # Create vector database
35
+ def create_db(splits, collection_name, db_type):
36
+ embedding = HuggingFaceEmbeddings()
37
+
38
+ if db_type == "ChromaDB":
39
+ new_client = chromadb.EphemeralClient()
40
+ vectordb = Chroma.from_documents(
41
+ documents=splits,
42
+ embedding=embedding,
43
+ client=new_client,
44
+ collection_name=collection_name,
45
+ )
46
+ elif db_type == "FAISS":
47
+ vectordb = FAISS.from_documents(
48
+ documents=splits,
49
+ embedding=embedding
50
+ )
51
+ elif db_type == "ScaNN":
52
+ vectordb = ScaNN.from_documents(
53
+ documents=splits,
54
+ embedding=embedding
55
+ )
56
+ elif db_type == "Milvus":
57
+ vectordb = Milvus.from_documents(
58
+ documents=splits,
59
+ embedding=embedding,
60
+ collection_name=collection_name,
61
+ )
62
+ else:
63
+ raise ValueError(f"Unsupported vector database type: {db_type}")
64
+
65
+ return vectordb
66
+
67
+ # Initialize langchain LLM chain
68
+ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, initial_prompt, progress=gr.Progress()):
69
+ progress(0.1, desc="Initializing HF tokenizer...")
70
+
71
+ progress(0.5, desc="Initializing HF Hub...")
72
+
73
+ llm = HuggingFaceEndpoint(
74
+ repo_id=llm_model,
75
+ huggingfacehub_api_token=api_token,
76
+ temperature=temperature,
77
+ max_new_tokens=max_tokens,
78
+ top_k=top_k,
79
+ )
80
+
81
+ progress(0.75, desc="Defining buffer memory...")
82
+ memory = ConversationBufferMemory(
83
+ memory_key="chat_history",
84
+ output_key='answer',
85
+ return_messages=True
86
+ )
87
+ retriever = vector_db.as_retriever()
88
+ progress(0.8, desc="Defining retrieval chain...")
89
+ qa_chain = ConversationalRetrievalChain.from_llm(
90
+ llm,
91
+ retriever=retriever,
92
+ chain_type="stuff",
93
+ memory=memory,
94
+ return_source_documents=True,
95
+ verbose=False,
96
+ )
97
+ qa_chain({"question": initial_prompt}) # Initialize with the initial prompt
98
+ progress(0.9, desc="Done!")
99
+ return qa_chain
100
+
101
+ def initialize_llm_no_doc(llm_model, temperature, max_tokens, top_k, initial_prompt, progress=gr.Progress()):
102
+ progress(0.1, desc="Initializing HF tokenizer...")
103
+ progress(0.5, desc="Initializing HF Hub...")
104
+ llm = HuggingFaceEndpoint(
105
+ repo_id=llm_model,
106
+ huggingfacehub_api_token=api_token,
107
+ temperature=temperature,
108
+ max_new_tokens=max_tokens,
109
+ top_k=top_k,
110
+ )
111
+ progress(0.75, desc="Defining buffer memory...")
112
+ memory = ConversationBufferMemory(
113
+ memory_key="chat_history",
114
+ output_key='answer',
115
+ return_messages=True
116
+ )
117
+ conversation_chain = ConversationChain(llm=llm, memory=memory, verbose=False)
118
+ conversation_chain({"question": initial_prompt})
119
+ progress(0.9, desc="Done!")
120
+ return conversation_chain
121
+
122
+ def format_chat_history(message, chat_history):
123
+ formatted_chat_history = []
124
+ for user_message, bot_message in chat_history:
125
+ formatted_chat_history.append(f"User: {user_message}")
126
+ formatted_chat_history.append(f"Assistant: {bot_message}")
127
+ return formatted_chat_history
128
+
129
+ def conversation(qa_chain, message, history):
130
+ formatted_chat_history = format_chat_history(message, history)
131
+ response = qa_chain({"question": message, "chat_history": formatted_chat_history})
132
+ response_answer = response["answer"]
133
+ if "Helpful Answer:" in response_answer:
134
+ response_answer = response_answer.split("Helpful Answer:")[-1]
135
+ response_sources = response["source_documents"]
136
+ response_source1 = response_sources[0].page_content.strip()
137
+ response_source2 = response_sources[1].page_content.strip()
138
+ response_source3 = response_sources[2].page_content.strip()
139
+ response_source1_page = response_sources[0].metadata["page"] + 1
140
+ response_source2_page = response_sources[1].metadata["page"] + 1
141
+ response_source3_page = response_sources[2].metadata["page"] + 1
142
+
143
+ new_history = history + [(message, response_answer)]
144
+ return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
145
+
146
+ def conversation_no_doc(llm, message, history):
147
+ formatted_chat_history = format_chat_history(message, history)
148
+ response = llm({"question": message, "chat_history": formatted_chat_history})
149
+ response_answer = response["answer"]
150
+ new_history = history + [(message, response_answer)]
151
+ return llm, gr.update(value=""), new_history
152
+
153
+ def upload_file(file_obj):
154
+ list_file_path = []
155
+ for file in file_obj:
156
+ list_file_path.append(file.name)
157
+ return list_file_path
158
+
159
+ def initialize_database(list_file_obj, chunk_size, chunk_overlap, db_type, progress=gr.Progress()):
160
+ list_file_path = [x.name for x in list_file_obj if x is not None]
161
+ progress(0.1, desc="Creating collection name...")
162
+ collection_name = create_collection_name(list_file_path[0])
163
+ progress(0.25, desc="Loading document...")
164
+ doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
165
+ progress(0.5, desc="Generating vector database...")
166
+ vector_db = create_db(doc_splits, collection_name, db_type)
167
+ progress(0.9, desc="Done!")
168
+ return vector_db, collection_name, "Complete!"
169
+
170
+ def create_collection_name(filepath):
171
+ collection_name = Path(filepath).stem
172
+ collection_name = collection_name.replace(" ", "-")
173
+ collection_name = unidecode(collection_name)
174
+ collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
175
+ collection_name = collection_name[:50]
176
+ if len(collection_name) < 3:
177
+ collection_name = collection_name + 'xyz'
178
+ if not collection_name[0].isalnum():
179
+ collection_name = 'A' + collection_name[1:]
180
+ if not collection_name[-1].isalnum():
181
+ collection_name = collection_name[:-1] + 'Z'
182
+ print('Filepath: ', filepath)
183
+ print('Collection name: ', collection_name)
184
+ return collection_name
185
+
186
+ def demo():
187
+ with gr.Blocks(theme="base") as demo:
188
+ vector_db = gr.State()
189
+ qa_chain = gr.State()
190
+ collection_name = gr.State()
191
+ initial_prompt = gr.State("")
192
+ llm_no_doc = gr.State()
193
+
194
+ gr.Markdown(
195
+ """<center><h2>lucIAna</center></h2>
196
+ <h3>Olá, sou a 2. versão</h3>""")
197
+ gr.Markdown(
198
+ """<b>Note:</b> Esta é a lucIAna, primeira Versão da IA para seus PDF documentos.
199
+ Este chatbot leva em consideração perguntas anteriores ao gerar respostas (por meio de memória conversacional) e inclui referências a documentos para fins de clareza.
200
+ """)
201
+
202
+ with gr.Tab("Step 1 - Upload PDF"):
203
+ with gr.Row():
204
+ document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
205
+
206
+ with gr.Tab("Step 2 - Process document"):
207
+ with gr.Row():
208
+ db_type_radio = gr.Radio(["ChromaDB", "FAISS", "ScaNN", "Milvus"], label="Vector database type", value="ChromaDB", type="value", info="Choose your vector database")
209
+ with gr.Accordion("Advanced options - Document text splitter", open=False):
210
+ with gr.Row():
211
+ slider_chunk_size = gr.Slider(minimum=100, maximum=1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
212
+ with gr.Row():
213
+ slider_chunk_overlap = gr.Slider(minimum=10, maximum=200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
214
+ with gr.Row():
215
+ db_progress = gr.Textbox(label="Vector database initialization", value="None")
216
+ with gr.Row():
217
+ db_btn = gr.Button("Generate vector database")
218
+
219
+ with gr.Tab("Step 3 - Set Initial Prompt"):
220
+ with gr.Row():
221
+ prompt_input = gr.Textbox(label="Initial Prompt", lines=5, value="Você é um advogado sênior, onde seu papel é analisar e trazer as informações sem inventar, dando a sua melhor opinião sempre trazendo contexto e referência. Aprenda o que é jurisprudência.")
222
+ with gr.Row():
223
+ set_prompt_btn = gr.Button("Set Prompt")
224
+
225
+ with gr.Tab("Step 4 - Initialize QA chain"):
226
+ with gr.Row():
227
+ llm_btn = gr.Radio(list_llm_simple,
228
+ label="LLM models", value=list_llm_simple[0], type="index", info="Choose your LLM model")
229
+ with gr.Accordion("Advanced options - LLM model", open=False):
230
+ with gr.Row():
231
+ slider_temperature = gr.Slider(minimum=0.01, maximum=1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
232
+ with gr.Row():
233
+ slider_maxtokens = gr.Slider(minimum=224, maximum=4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
234
+ with gr.Row():
235
+ slider_topk = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
236
+ with gr.Row():
237
+ llm_progress = gr.Textbox(value="None", label="QA chain initialization")
238
+ with gr.Row():
239
+ qachain_btn = gr.Button("Initialize Question Answering chain")
240
+
241
+ with gr.Tab("Step 5 - Chatbot with document"):
242
+ chatbot = gr.Chatbot(height=300)
243
+ with gr.Accordion("Advanced - Document references", open=False):
244
+ with gr.Row():
245
+ doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
246
+ source1_page = gr.Number(label="Page", scale=1)
247
+ with gr.Row():
248
+ doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
249
+ source2_page = gr.Number(label="Page", scale=1)
250
+ with gr.Row():
251
+ doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
252
+ source3_page = gr.Number(label="Page", scale=1)
253
+ with gr.Row():
254
+ msg = gr.Textbox(placeholder="Type message (e.g. 'What is this document about?')", container=True)
255
+ with gr.Row():
256
+ submit_btn = gr.Button("Submit message")
257
+ clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
258
+
259
+ with gr.Tab("Step 6 - Chatbot without document"):
260
+ with gr.Row():
261
+ llm_no_doc_btn = gr.Radio(list_llm_simple,
262
+ label="LLM models", value=list_llm_simple[0], type="index", info="Choose your LLM model for chatbot without document")
263
+ with gr.Accordion("Advanced options - LLM model", open=False):
264
+ with gr.Row():
265
+ slider_temperature_no_doc = gr.Slider(minimum=0.01, maximum=1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
266
+ with gr.Row():
267
+ slider_maxtokens_no_doc = gr.Slider(minimum=224, maximum=4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
268
+ with gr.Row():
269
+ slider_topk_no_doc = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
270
+ with gr.Row():
271
+ llm_no_doc_progress = gr.Textbox(value="None", label="LLM initialization for chatbot without document")
272
+ with gr.Row():
273
+ llm_no_doc_init_btn = gr.Button("Initialize LLM for Chatbot without document")
274
+ chatbot_no_doc = gr.Chatbot(height=300)
275
+ with gr.Row():
276
+ msg_no_doc = gr.Textbox(placeholder="Type message to chat with lucIAna", container=True)
277
+ with gr.Row():
278
+ submit_btn_no_doc = gr.Button("Submit message")
279
+ clear_btn_no_doc = gr.ClearButton([msg_no_doc, chatbot_no_doc], value="Clear conversation")
280
+
281
+ # Preprocessing events
282
+ db_btn.click(initialize_database,
283
+ inputs=[document, slider_chunk_size, slider_chunk_overlap, db_type_radio],
284
+ outputs=[vector_db, collection_name, db_progress])
285
+ set_prompt_btn.click(lambda prompt: gr.update(value=prompt),
286
+ inputs=prompt_input,
287
+ outputs=initial_prompt)
288
+ qachain_btn.click(initialize_llmchain,
289
+ inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db, initial_prompt],
290
+ outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0],
291
+ inputs=None,
292
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
293
+ queue=False)
294
+
295
+ # Chatbot events with document
296
+ msg.submit(conversation,
297
+ inputs=[qa_chain, msg, chatbot],
298
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
299
+ queue=False)
300
+ submit_btn.click(conversation,
301
+ inputs=[qa_chain, msg, chatbot],
302
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
303
+ queue=False)
304
+ clear_btn.click(lambda:[None,"",0,"",0,"",0],
305
+ inputs=None,
306
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
307
+ queue=False)
308
+
309
+ # Initialize LLM without document for conversation
310
+ llm_no_doc_init_btn.click(initialize_llm_no_doc,
311
+ inputs=[llm_no_doc_btn, slider_temperature_no_doc, slider_maxtokens_no_doc, slider_topk_no_doc, initial_prompt],
312
+ outputs=[llm_no_doc, llm_no_doc_progress])
313
+
314
+ submit_btn_no_doc.click(conversation_no_doc,
315
+ inputs=[llm_no_doc, msg_no_doc, chatbot_no_doc],
316
+ outputs=[llm_no_doc, msg_no_doc, chatbot_no_doc],
317
+ queue=False)
318
+ clear_btn_no_doc.click(lambda:[None,""],
319
+ inputs=None,
320
+ outputs=[chatbot_no_doc, msg_no_doc],
321
+ queue=False)
322
+
323
+ demo.queue().launch(debug=True, share=True)
324
+
325
+ if __name__ == "__main__":
326
+ demo()