farmax commited on
Commit
d0c3ad5
·
verified ·
1 Parent(s): ebc9208

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -392
app.py CHANGED
@@ -236,8 +236,7 @@ def demo():
236
  doc_source2, source2_page,
237
  doc_source3, source3_page,
238
  doc_source4, source4_page,
239
- doc_source5, source5_page], \
240
- queue=False)
241
  submit_btn.click(conversation,
242
  inputs=[qa_chain, msg, chatbot],
243
  outputs=[qa_chain, msg, chatbot,
@@ -245,8 +244,7 @@ def demo():
245
  doc_source2, source2_page,
246
  doc_source3, source3_page,
247
  doc_source4, source4_page,
248
- doc_source5, source5_page], \
249
- queue=False)
250
  clear_btn.click(lambda:[None,"",0,"",0,"",0], \
251
  inputs=None, \
252
  outputs=[chatbot, \
@@ -260,391 +258,4 @@ def demo():
260
 
261
 
262
  if __name__ == "__main__":
263
- demo()
264
-
265
-
266
-
267
-
268
-
269
- #####################################################
270
- import gradio as gr
271
- import os
272
-
273
- from langchain_community.document_loaders import PyPDFLoader
274
- from langchain.text_splitter import RecursiveCharacterTextSplitter
275
- from langchain_community.vectorstores import Chroma
276
- from langchain.chains import ConversationalRetrievalChain
277
- from langchain_community.embeddings import HuggingFaceEmbeddings
278
- from langchain_community.llms import HuggingFacePipeline
279
- from langchain.chains import ConversationChain
280
- from langchain.memory import ConversationBufferMemory
281
- from langchain_community.llms import HuggingFaceEndpoint
282
-
283
- from pathlib import Path
284
- import chromadb
285
- from unidecode import unidecode
286
-
287
- from transformers import AutoTokenizer
288
- import transformers
289
- import torch
290
- import tqdm
291
- import accelerate
292
- import re
293
- # from chromadb.utils import get_default_config
294
- vector_db = ''
295
-
296
- # default_persist_directory = './chroma_HF/'
297
- list_llm = ["mistralai/Mistral-7B-Instruct-v0.2", "mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1", \
298
- "google/gemma-7b-it","google/gemma-2b-it", \
299
- "HuggingFaceH4/zephyr-7b-beta", "HuggingFaceH4/zephyr-7b-gemma-v0.1", \
300
- "meta-llama/Llama-2-7b-chat-hf", "microsoft/phi-2", \
301
- "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "mosaicml/mpt-7b-instruct", "tiiuae/falcon-7b-instruct", \
302
- "google/flan-t5-xxl"
303
- ]
304
- list_llm_simple = [os.path.basename(llm) for llm in list_llm]
305
-
306
- # Load PDF document and create doc splits
307
- def load_doc(list_file_path, chunk_size, chunk_overlap):
308
- # Processing for one document only
309
- # loader = PyPDFLoader(file_path)
310
- # pages = loader.load()
311
- loaders = [PyPDFLoader(x) for x in list_file_path]
312
- pages = []
313
- for loader in loaders:
314
- pages.extend(loader.load())
315
- # text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
316
- text_splitter = RecursiveCharacterTextSplitter(
317
- chunk_size = chunk_size,
318
- chunk_overlap = chunk_overlap)
319
- doc_splits = text_splitter.split_documents(pages)
320
- return doc_splits
321
-
322
-
323
- # Create vector database
324
- def create_db(splits, collection_name):
325
- embedding = HuggingFaceEmbeddings()
326
- new_client = chromadb.EphemeralClient()
327
- vectordb = Chroma.from_documents(
328
- documents=splits,
329
- embedding=embedding,
330
- client=new_client,
331
- collection_name=collection_name,
332
- # persist_directory=default_persist_directory
333
- )
334
- return vectordb
335
-
336
-
337
- # Load vector database
338
- def load_db():
339
- embedding = HuggingFaceEmbeddings()
340
- vectordb = Chroma(
341
- # persist_directory=default_persist_directory,
342
- embedding_function=embedding)
343
- return vectordb
344
-
345
- # Initialize langchain LLM chain
346
- def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
347
- progress(0.1, desc="Initializing HF tokenizer...")
348
- # HuggingFacePipeline uses local model
349
- # Note: it will download model locally...
350
- # tokenizer=AutoTokenizer.from_pretrained(llm_model)
351
- # progress(0.5, desc="Initializing HF pipeline...")
352
- # pipeline=transformers.pipeline(
353
- # "text-generation",
354
- # model=llm_model,
355
- # tokenizer=tokenizer,
356
- # torch_dtype=torch.bfloat16,
357
- # trust_remote_code=True,
358
- # device_map="auto",
359
- # # max_length=1024,
360
- # max_new_tokens=max_tokens,
361
- # do_sample=True,
362
- # top_k=top_k,
363
- # num_return_sequences=1,
364
- # eos_token_id=tokenizer.eos_token_id
365
- # )
366
- # llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
367
-
368
- # HuggingFaceHub uses HF inference endpoints
369
- progress(0.5, desc="Initializing HF Hub...")
370
- # Use of trust_remote_code as model_kwargs
371
- # Warning: langchain issue
372
- # URL: https://github.com/langchain-ai/langchain/issues/6080
373
- if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
374
- llm = HuggingFaceEndpoint(
375
- repo_id=llm_model,
376
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True}
377
- temperature = temperature,
378
- max_new_tokens = max_tokens,
379
- top_k = top_k,
380
- load_in_8bit = True,
381
- )
382
- elif llm_model in ["HuggingFaceH4/zephyr-7b-gemma-v0.1","mosaicml/mpt-7b-instruct"]:
383
- raise gr.Error("LLM model is too large to be loaded automatically on free inference endpoint")
384
- llm = HuggingFaceEndpoint(
385
- repo_id=llm_model,
386
- temperature = temperature,
387
- max_new_tokens = max_tokens,
388
- top_k = top_k,
389
- )
390
- elif llm_model == "microsoft/phi-2":
391
- # raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")
392
- llm = HuggingFaceEndpoint(
393
- repo_id=llm_model,
394
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
395
- temperature = temperature,
396
- max_new_tokens = max_tokens,
397
- top_k = top_k,
398
- trust_remote_code = True,
399
- torch_dtype = "auto",
400
- )
401
- elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
402
- llm = HuggingFaceEndpoint(
403
- repo_id=llm_model,
404
- # model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}
405
- temperature = temperature,
406
- max_new_tokens = 250,
407
- top_k = top_k,
408
- )
409
- elif llm_model == "meta-llama/Llama-2-7b-chat-hf":
410
- raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")
411
- llm = HuggingFaceEndpoint(
412
- repo_id=llm_model,
413
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
414
- temperature = temperature,
415
- max_new_tokens = max_tokens,
416
- top_k = top_k,
417
- )
418
- else:
419
- llm = HuggingFaceEndpoint(
420
- repo_id=llm_model,
421
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
422
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
423
- temperature = temperature,
424
- max_new_tokens = max_tokens,
425
- top_k = top_k,
426
- )
427
-
428
- progress(0.75, desc="Defining buffer memory...")
429
- memory = ConversationBufferMemory(
430
- memory_key="chat_history",
431
- output_key='answer',
432
- return_messages=True
433
- )
434
- # retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
435
- retriever=vector_db.as_retriever()
436
- progress(0.8, desc="Defining retrieval chain...")
437
- qa_chain = ConversationalRetrievalChain.from_llm(
438
- llm,
439
- retriever=retriever,
440
- chain_type="stuff",
441
- memory=memory,
442
- # combine_docs_chain_kwargs={"prompt": your_prompt})
443
- return_source_documents=True,
444
- #return_generated_question=False,
445
- verbose=False,
446
- )
447
- progress(0.9, desc="Done!")
448
- return qa_chain
449
-
450
-
451
- # Generate collection name for vector database
452
- # - Use filepath as input, ensuring unicode text
453
- def create_collection_name(filepath):
454
- # Extract filename without extension
455
- collection_name = Path(filepath).stem
456
- # Fix potential issues from naming convention
457
- ## Remove space
458
- collection_name = collection_name.replace(" ","-")
459
- ## ASCII transliterations of Unicode text
460
- collection_name = unidecode(collection_name)
461
- ## Remove special characters
462
- #collection_name = re.findall("[\dA-Za-z]*", collection_name)[0]
463
- collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
464
- ## Limit length to 50 characters
465
- collection_name = collection_name[:50]
466
- ## Minimum length of 3 characters
467
- if len(collection_name) < 3:
468
- collection_name = collection_name + 'xyz'
469
- ## Enforce start and end as alphanumeric character
470
- if not collection_name[0].isalnum():
471
- collection_name = 'A' + collection_name[1:]
472
- if not collection_name[-1].isalnum():
473
- collection_name = collection_name[:-1] + 'Z'
474
- print('Filepath: ', filepath)
475
- print('Collection name: ', collection_name)
476
- return collection_name
477
-
478
- # Initialize database
479
- def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
480
- # Create list of documents (when valid)
481
- list_file_path = [x.name for x in list_file_obj if x is not None]
482
- print(list_file_path)
483
- # Create collection_name for vector database
484
- progress(0.1, desc="Creazione collezione...")
485
- collection_name = create_collection_name(list_file_path[0])
486
- progress(0.25, desc="Caricamento documenti..")
487
- # Load document and create splits
488
- doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
489
-
490
- # Creare o caricare il nuovo database
491
- progress(0.5, desc="Generazione vector database...")
492
- vector_db = create_db(doc_splits, collection_name)
493
- progress(0.9, desc="Fatto!")
494
-
495
- return vector_db, collection_name, "Completato!"
496
-
497
- def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
498
- # print("llm_option",llm_option)
499
- llm_name = list_llm[llm_option]
500
- print(f"Nome del modello: {llm_name}")
501
-
502
- qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
503
-
504
- return qa_chain, "Completato!"
505
-
506
- def format_chat_history(message, chat_history):
507
- formatted_chat_history = []
508
- for user_message, bot_message in chat_history:
509
- formatted_chat_history.append(f"User: {user_message}")
510
- formatted_chat_history.append(f"Assistant: {bot_message}")
511
- return formatted_chat_history
512
-
513
-
514
- def conversation(qa_chain, message, history):
515
- formatted_chat_history = format_chat_history(message, history)
516
- print("formatted_chat_history",formatted_chat_history)
517
-
518
- # Generate response using QA chain
519
- response = qa_chain({"question": message, "chat_history": formatted_chat_history})
520
- response_answer = response["answer"]
521
- if response_answer.find("Helpful Answer:") != -1:
522
- response_answer = response_answer.split("Helpful Answer:")[-1]
523
- response_sources = response["source_documents"]
524
- response_source1 = response_sources[0].page_content.strip()
525
- response_source2 = response_sources[1].page_content.strip()
526
- response_source3 = response_sources[2].page_content.strip()
527
- # Langchain sources are zero-based
528
- response_source1_page = response_sources[0].metadata["page"] + 1
529
- response_source2_page = response_sources[1].metadata["page"] + 1
530
- response_source3_page = response_sources[2].metadata["page"] + 1
531
- #print('chat response: ', response_answer)
532
- #print('DB source', response_sources)
533
-
534
- # Append user message and response to chat history
535
- new_history = history + [(message, response_answer)]
536
- # return gr.update(value=""), new_history, response_sources[0], response_sources[1]
537
- return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
538
-
539
-
540
- def upload_file(file_obj):
541
- list_file_path = []
542
- for idx, file in enumerate(file_obj):
543
- file_path = file_obj.name
544
- list_file_path.append(file_path)
545
- print(file_path)
546
- # initialize_database(file_path, progress)
547
- return list_file_path
548
-
549
- def demo():
550
- with gr.Blocks(theme="base") as demo:
551
- vector_db = gr.State()
552
- qa_chain = gr.State()
553
- collection_name = gr.State()
554
-
555
- gr.Markdown(
556
- """<center><h2>Creatore di chatbot basato su PDF</center></h2>
557
- <h3>Potete fare domande su i vostri documenti PDF</h3>""")
558
-
559
- gr.Markdown(
560
- """<b>Nota:</b> Questo assistente IA, utilizzando Langchain e modelli LLM open source, esegue generazione aumentata da recupero (RAG) dai vostri documenti PDF. \
561
- L'interfaccia utente esplicitamente mostra i passaggi multipli per aiutare a comprendere il flusso di lavoro RAG.
562
- Questo chatbot tiene conto delle domande passate nel generare le risposte (tramite memoria conversazionale), e include riferimenti ai documenti per scopi di chiarezza.<br>
563
- <br><b>Avviso:</b> Questo spazio utilizza l'hardware di base CPU gratuito da Hugging Face. Alcuni passaggi e modelli LLM usati qui sotto (endpoint di inferenza gratuiti) possono richiedere del tempo per generare una risposta.
564
- """)
565
-
566
- with gr.Tab("Step 1 - Carica PDFs"):
567
- with gr.Row():
568
- document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
569
- # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
570
-
571
- with gr.Tab("Step 2 - Processa i documenti"):
572
- with gr.Row():
573
- db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
574
- with gr.Accordion("Opzioni Avanzate - Document text splitter", open=False):
575
- with gr.Row():
576
- slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=1000, step=20, label="Chunk size", info="Chunk size", interactive=True)
577
- with gr.Row():
578
- slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=100, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
579
- with gr.Row():
580
- db_progress = gr.Textbox(label="Vector database initialization", value="None")
581
- with gr.Row():
582
- db_btn = gr.Button("Genera vector database")
583
-
584
- with gr.Tab("Step 3 - Inizializza QA chain"):
585
- with gr.Row():
586
- llm_btn = gr.Radio(list_llm_simple, \
587
- label="LLM models", value = list_llm_simple[5], type="index", info="Scegli il tuo modello LLM")
588
- with gr.Accordion("Advanced options - LLM model", open=False):
589
- with gr.Row():
590
- slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.3, step=0.1, label="Temperature", info="Model temperature", interactive=True)
591
- with gr.Row():
592
- slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
593
- with gr.Row():
594
- slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
595
- with gr.Row():
596
- language_btn = gr.Radio(["Italian", "English"], label="Linua", value="Italian", type="index", info="Seleziona la lingua per il chatbot")
597
- with gr.Row():
598
- llm_progress = gr.Textbox(value="None",label="QA chain initialization")
599
- with gr.Row():
600
- qachain_btn = gr.Button("Inizializza Question Answering chain")
601
-
602
-
603
- with gr.Tab("Passo 4 - Chatbot"):
604
- chatbot = gr.Chatbot(height=300)
605
- with gr.Accordion("Opzioni avanzate - Riferimenti ai documenti", open=False):
606
- with gr.Row():
607
- doc_source1 = gr.Textbox(label="Riferimento 1", lines=2, container=True, scale=20)
608
- source1_page = gr.Number(label="Pagina", scale=1)
609
- with gr.Row():
610
- doc_source2 = gr.Textbox(label="Riferimento 2", lines=2, container=True, scale=20)
611
- source2_page = gr.Number(label="Pagina", scale=1)
612
- with gr.Row():
613
- doc_source3 = gr.Textbox(label="Riferimento 3", lines=2, container=True, scale=20)
614
- source3_page = gr.Number(label="Pagina", scale=1)
615
- with gr.Row():
616
- msg = gr.Textbox(placeholder="Inserisci messaggio (es. 'Di cosa tratta questo documento?')", container=True)
617
- with gr.Row():
618
- submit_btn = gr.Button("Invia messaggio")
619
- clear_btn = gr.ClearButton([msg, chatbot], value="Cancella conversazione")
620
-
621
- # Preprocessing events
622
- #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
623
- db_btn.click(initialize_database, \
624
- inputs=[document, slider_chunk_size, slider_chunk_overlap], \
625
- outputs=[vector_db, collection_name, db_progress])
626
- qachain_btn.click(initialize_LLM, \
627
- inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
628
- outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
629
- inputs=None, \
630
- outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
631
- queue=False)
632
-
633
- # Chatbot events
634
- msg.submit(conversation, \
635
- inputs=[qa_chain, msg, chatbot], \
636
- outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
637
- queue=False)
638
- submit_btn.click(conversation, \
639
- inputs=[qa_chain, msg, chatbot], \
640
- outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
641
- queue=False)
642
- clear_btn.click(lambda:[None,"",0,"",0,"",0], \
643
- inputs=None, \
644
- outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
645
- queue=False)
646
- demo.queue().launch(debug=True)
647
-
648
-
649
- if __name__ == "__main__":
650
- demo()
 
236
  doc_source2, source2_page,
237
  doc_source3, source3_page,
238
  doc_source4, source4_page,
239
+ doc_source5, source5_page], queue=False)
 
240
  submit_btn.click(conversation,
241
  inputs=[qa_chain, msg, chatbot],
242
  outputs=[qa_chain, msg, chatbot,
 
244
  doc_source2, source2_page,
245
  doc_source3, source3_page,
246
  doc_source4, source4_page,
247
+ doc_source5, source5_page], queue=False)
 
248
  clear_btn.click(lambda:[None,"",0,"",0,"",0], \
249
  inputs=None, \
250
  outputs=[chatbot, \
 
258
 
259
 
260
  if __name__ == "__main__":
261
+ demo()