Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -294,6 +294,34 @@ def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Pr
|
|
294 |
progress(0.9, desc="Done!")
|
295 |
return vector_db, collection_name, "Complete!"
|
296 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
297 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
298 |
llm_name = list_llm[llm_option]
|
299 |
print("llm_name: ",llm_name)
|
@@ -305,4 +333,133 @@ def format_chat_history(message, chat_history):
|
|
305 |
for user_message, bot_message in chat_history:
|
306 |
formatted_chat_history.append(f"User: {user_message}")
|
307 |
formatted_chat_history.append(f"Assistant: {bot_message}")
|
308 |
-
return formatted_chat_history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
294 |
progress(0.9, desc="Done!")
|
295 |
return vector_db, collection_name, "Complete!"
|
296 |
|
297 |
+
# Initialize LlamaIndex parsing
|
298 |
+
def initialize_llama_index(file_obj):
|
299 |
+
documents = LlamaParse(result_type="markdown", api_key=api_token).load_data(file_obj[0].name)
|
300 |
+
node_parser = MarkdownElementNodeParser(llm=None, num_workers=8)
|
301 |
+
nodes = node_parser.get_nodes_from_documents(documents)
|
302 |
+
base_nodes, objects = node_parser.get_nodes_and_objects(nodes)
|
303 |
+
|
304 |
+
# Usando SimpleVectorStore para criar um índice vetorial
|
305 |
+
vector_store = SimpleVectorStore()
|
306 |
+
for node in base_nodes + objects:
|
307 |
+
vector_store.add(node)
|
308 |
+
|
309 |
+
# Criando um recuperador a partir do índice vetorial
|
310 |
+
index_ret = VectorIndexRetriever(vector_store=vector_store, top_k=15)
|
311 |
+
|
312 |
+
# Configurando o motor de consulta
|
313 |
+
reranker = FlagEmbeddingReranker(
|
314 |
+
top_n=5,
|
315 |
+
model="BAAI/bge-reranker-large"
|
316 |
+
)
|
317 |
+
recursive_query_engine = RetrieverQueryEngine(
|
318 |
+
retriever=index_ret,
|
319 |
+
node_postprocessors=[reranker],
|
320 |
+
verbose=False
|
321 |
+
)
|
322 |
+
|
323 |
+
return recursive_query_engine, "LlamaIndex parsing complete"
|
324 |
+
|
325 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
326 |
llm_name = list_llm[llm_option]
|
327 |
print("llm_name: ",llm_name)
|
|
|
333 |
for user_message, bot_message in chat_history:
|
334 |
formatted_chat_history.append(f"User: {user_message}")
|
335 |
formatted_chat_history.append(f"Assistant: {bot_message}")
|
336 |
+
return formatted_chat_history
|
337 |
+
|
338 |
+
def conversation(qa_chain, message, history):
|
339 |
+
formatted_chat_history = format_chat_history(message, history)
|
340 |
+
|
341 |
+
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
342 |
+
response_answer = response["answer"]
|
343 |
+
if "Helpful Answer:" in response_answer:
|
344 |
+
response_answer = response_answer.split("Helpful Answer:")[-1]
|
345 |
+
response_sources = response["source_documents"]
|
346 |
+
response_source1 = response_sources[0].page_content.strip()
|
347 |
+
response_source2 = response_sources[1].page_content.strip()
|
348 |
+
response_source3 = response_sources[2].page_content.strip()
|
349 |
+
response_source1_page = response_sources[0].metadata["page"] + 1
|
350 |
+
response_source2_page = response_sources[1].metadata["page"] + 1
|
351 |
+
response_source3_page = response_sources[2].metadata["page"] + 1
|
352 |
+
|
353 |
+
new_history = history + [(message, response_answer)]
|
354 |
+
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
355 |
+
|
356 |
+
def upload_file(file_obj):
|
357 |
+
list_file_path = []
|
358 |
+
for file in file_obj:
|
359 |
+
list_file_path.append(file.name)
|
360 |
+
return list_file_path
|
361 |
+
|
362 |
+
def demo():
|
363 |
+
with gr.Blocks(theme="base") as demo:
|
364 |
+
vector_db = gr.State()
|
365 |
+
qa_chain = gr.State()
|
366 |
+
collection_name = gr.State()
|
367 |
+
llama_index_engine = gr.State()
|
368 |
+
|
369 |
+
gr.Markdown(
|
370 |
+
"""<center><h2>PDF-based chatbot</center></h2>
|
371 |
+
<h3>Ask any questions about your PDF documents</h3>""")
|
372 |
+
gr.Markdown(
|
373 |
+
"""<b>Note:</b> Esta é a lucIAna, primeira Versão da IA para seus PDF documentos.
|
374 |
+
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.
|
375 |
+
""")
|
376 |
+
|
377 |
+
with gr.Tab("Step 1 - Upload PDF"):
|
378 |
+
with gr.Row():
|
379 |
+
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
|
380 |
+
|
381 |
+
with gr.Tab("Step 2 - Process document"):
|
382 |
+
with gr.Row():
|
383 |
+
db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value="ChromaDB", type="index", info="Choose your vector database")
|
384 |
+
with gr.Accordion("Advanced options - Document text splitter", open=False):
|
385 |
+
with gr.Row():
|
386 |
+
slider_chunk_size = gr.Slider(minimum=100, maximum=1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
|
387 |
+
with gr.Row():
|
388 |
+
slider_chunk_overlap = gr.Slider(minimum=10, maximum=200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
|
389 |
+
with gr.Row():
|
390 |
+
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
391 |
+
with gr.Row():
|
392 |
+
db_btn = gr.Button("Generate vector database")
|
393 |
+
|
394 |
+
with gr.Tab("Step 3 - Initialize QA chain"):
|
395 |
+
with gr.Row():
|
396 |
+
llm_btn = gr.Radio(list_llm_simple,
|
397 |
+
label="LLM models", value=list_llm_simple[0], type="index", info="Choose your LLM model")
|
398 |
+
with gr.Accordion("Advanced options - LLM model", open=False):
|
399 |
+
with gr.Row():
|
400 |
+
slider_temperature = gr.Slider(minimum=0.01, maximum=1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
|
401 |
+
with gr.Row():
|
402 |
+
slider_maxtokens = gr.Slider(minimum=224, maximum=4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
|
403 |
+
with gr.Row():
|
404 |
+
slider_topk = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
|
405 |
+
with gr.Row():
|
406 |
+
llm_progress = gr.Textbox(value="None", label="QA chain initialization")
|
407 |
+
with gr.Row():
|
408 |
+
qachain_btn = gr.Button("Initialize Question Answering chain")
|
409 |
+
|
410 |
+
with gr.Tab("Step 4 - LlamaIndex parsing"):
|
411 |
+
with gr.Row():
|
412 |
+
llama_index_btn = gr.Button("Parse with LlamaIndex")
|
413 |
+
with gr.Row():
|
414 |
+
llama_index_progress = gr.Textbox(label="LlamaIndex parsing status", value="None")
|
415 |
+
|
416 |
+
with gr.Tab("Step 5 - Chatbot"):
|
417 |
+
chatbot = gr.Chatbot(height=300)
|
418 |
+
with gr.Accordion("Advanced - Document references", open=False):
|
419 |
+
with gr.Row():
|
420 |
+
doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
|
421 |
+
source1_page = gr.Number(label="Page", scale=1)
|
422 |
+
with gr.Row():
|
423 |
+
doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
|
424 |
+
source2_page = gr.Number(label="Page", scale=1)
|
425 |
+
with gr.Row():
|
426 |
+
doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
|
427 |
+
source3_page = gr.Number(label="Page", scale=1)
|
428 |
+
with gr.Row():
|
429 |
+
msg = gr.Textbox(placeholder="Type message (e.g. 'What is this document about?')", container=True)
|
430 |
+
with gr.Row():
|
431 |
+
submit_btn = gr.Button("Submit message")
|
432 |
+
clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
|
433 |
+
|
434 |
+
# Preprocessing events
|
435 |
+
db_btn.click(initialize_database,
|
436 |
+
inputs=[document, slider_chunk_size, slider_chunk_overlap],
|
437 |
+
outputs=[vector_db, collection_name, db_progress])
|
438 |
+
qachain_btn.click(initialize_LLM,
|
439 |
+
inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db],
|
440 |
+
outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0],
|
441 |
+
inputs=None,
|
442 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
443 |
+
queue=False)
|
444 |
+
llama_index_btn.click(initialize_llama_index,
|
445 |
+
inputs=[document],
|
446 |
+
outputs=[llama_index_engine, llama_index_progress])
|
447 |
+
|
448 |
+
# Chatbot events
|
449 |
+
msg.submit(conversation,
|
450 |
+
inputs=[qa_chain, msg, chatbot],
|
451 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
452 |
+
queue=False)
|
453 |
+
submit_btn.click(conversation,
|
454 |
+
inputs=[qa_chain, msg, chatbot],
|
455 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
456 |
+
queue=False)
|
457 |
+
clear_btn.click(lambda:[None,"",0,"",0,"",0],
|
458 |
+
inputs=None,
|
459 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
460 |
+
queue=False)
|
461 |
+
demo.queue().launch(debug=True)
|
462 |
+
|
463 |
+
|
464 |
+
if __name__ == "__main__":
|
465 |
+
demo()
|