farmax commited on
Commit
ebc9208
1 Parent(s): 17239c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +269 -0
app.py CHANGED
@@ -1,5 +1,274 @@
1
  import gradio as gr
2
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  from langchain_community.document_loaders import PyPDFLoader
5
  from langchain.text_splitter import RecursiveCharacterTextSplitter
 
1
  import gradio as gr
2
  import os
3
+ from langchain_community.document_loaders import PyPDFLoader
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain_community.vectorstores import Chroma
6
+ from langchain.chains import ConversationalRetrievalChain
7
+ from langchain_community.embeddings import HuggingFaceEmbeddings
8
+ from langchain_community.llms import HuggingFaceEndpoint
9
+ from langchain.memory import ConversationBufferMemory
10
+ from pathlib import Path
11
+ import chromadb
12
+ from unidecode import unidecode
13
+ import re
14
+
15
+ # List of available LLM models
16
+ list_llm = [
17
+ "mistralai/Mistral-7B-Instruct-v0.2", "mistralai/Mixtral-8x7B-Instruct-v0.1",
18
+ "google/gemma-7b-it", "google/gemma-2b-it",
19
+ "HuggingFaceH4/zephyr-7b-beta", "HuggingFaceH4/zephyr-7b-gemma-v0.1",
20
+ "meta-llama/Llama-2-7b-chat-hf", "microsoft/phi-2",
21
+ "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "mosaicml/mpt-7b-instruct",
22
+ "tiiuae/falcon-7b-instruct", "google/flan-t5-xxl"
23
+ ]
24
+ list_llm_simple = [os.path.basename(llm) for llm in list_llm]
25
+
26
+ def load_doc(list_file_path, chunk_size, chunk_overlap):
27
+ loaders = [PyPDFLoader(x) for x in list_file_path]
28
+ pages = []
29
+ for loader in loaders:
30
+ pages.extend(loader.load())
31
+ text_splitter = RecursiveCharacterTextSplitter(
32
+ chunk_size=chunk_size,
33
+ chunk_overlap=chunk_overlap
34
+ )
35
+ doc_splits = text_splitter.split_documents(pages)
36
+ return doc_splits
37
+
38
+ def create_db(splits, collection_name):
39
+ embedding = HuggingFaceEmbeddings()
40
+ new_client = chromadb.EphemeralClient()
41
+ vectordb = Chroma.from_documents(
42
+ documents=splits,
43
+ embedding=embedding,
44
+ client=new_client,
45
+ collection_name=collection_name
46
+ )
47
+ return vectordb
48
+
49
+ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
50
+ progress(0.5, desc="Initializing HF Hub...")
51
+ llm = HuggingFaceEndpoint(
52
+ repo_id=llm_model,
53
+ temperature=temperature,
54
+ max_new_tokens=max_tokens,
55
+ top_k=top_k
56
+ )
57
+
58
+ progress(0.75, desc="Defining buffer memory...")
59
+ memory = ConversationBufferMemory(
60
+ memory_key="chat_history",
61
+ output_key='answer',
62
+ return_messages=True
63
+ )
64
+ retriever = vector_db.as_retriever(search_kwargs={'k': 5}) # Increased from 3 to 5
65
+ progress(0.8, desc="Defining retrieval chain...")
66
+ qa_chain = ConversationalRetrievalChain.from_llm(
67
+ llm,
68
+ retriever=retriever,
69
+ chain_type="stuff",
70
+ memory=memory,
71
+ return_source_documents=True,
72
+ verbose=False,
73
+ )
74
+ progress(0.9, desc="Done!")
75
+ return qa_chain
76
+
77
+ def create_collection_name(filepath):
78
+ collection_name = Path(filepath).stem
79
+ collection_name = collection_name.replace(" ", "-")
80
+ collection_name = unidecode(collection_name)
81
+ collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
82
+ collection_name = collection_name[:50]
83
+ if len(collection_name) < 3:
84
+ collection_name = collection_name + 'xyz'
85
+ if not collection_name[0].isalnum():
86
+ collection_name = 'A' + collection_name[1:]
87
+ if not collection_name[-1].isalnum():
88
+ collection_name = collection_name[:-1] + 'Z'
89
+ return collection_name
90
+
91
+ def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
92
+ list_file_path = [x.name for x in list_file_obj if x is not None]
93
+ progress(0.1, desc="Creating collection...")
94
+ collection_name = create_collection_name(list_file_path[0])
95
+ progress(0.25, desc="Loading documents...")
96
+ doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
97
+
98
+ progress(0.5, desc="Generating vector database...")
99
+ vector_db = create_db(doc_splits, collection_name)
100
+ progress(0.9, desc="Done!")
101
+
102
+ return vector_db, collection_name, "Completed!"
103
+
104
+ def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
105
+ llm_name = list_llm[llm_option]
106
+ qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
107
+ return qa_chain, "Completed!"
108
+
109
+ def format_chat_history(message, chat_history):
110
+ formatted_chat_history = []
111
+ for user_message, bot_message in chat_history:
112
+ formatted_chat_history.append(f"User: {user_message}")
113
+ formatted_chat_history.append(f"Assistant: {bot_message}")
114
+ return formatted_chat_history
115
+
116
+ def conversation(qa_chain, message, history):
117
+ formatted_chat_history = format_chat_history(message, history)
118
+ response = qa_chain({"question": message, "chat_history": formatted_chat_history})
119
+ response_answer = response["answer"]
120
+ if response_answer.find("Helpful Answer:") != -1:
121
+ response_answer = response_answer.split("Helpful Answer:")[-1]
122
+ response_sources = response["source_documents"]
123
+
124
+ source_info = []
125
+ for i in range(min(5, len(response_sources))): # Increased from 3 to 5
126
+ source = response_sources[i]
127
+ source_info.append({
128
+ 'content': source.page_content.strip(),
129
+ 'page': source.metadata["page"] + 1
130
+ })
131
+
132
+ new_history = history + [(message, response_answer)]
133
+ return qa_chain, gr.update(value=""), new_history, *[info['content'] for info in source_info], *[info['page'] for info in source_info]
134
+
135
+ # The rest of the code (demo function and UI setup) remains largely the same,
136
+ # but update the outputs of the conversation function to handle 5 sources instead of 3.
137
+ def upload_file(file_obj):
138
+ list_file_path = []
139
+ for idx, file in enumerate(file_obj):
140
+ file_path = file_obj.name
141
+ list_file_path.append(file_path)
142
+ print(file_path)
143
+ # initialize_database(file_path, progress)
144
+ return list_file_path
145
+
146
+ def demo():
147
+ with gr.Blocks(theme="base") as demo:
148
+ vector_db = gr.State()
149
+ qa_chain = gr.State()
150
+ collection_name = gr.State()
151
+
152
+ gr.Markdown(
153
+ """<center><h2>Creatore di chatbot basato su PDF</center></h2>
154
+ <h3>Potete fare domande su i vostri documenti PDF</h3>""")
155
+
156
+ gr.Markdown(
157
+ """<b>Nota:</b> Questo assistente IA, utilizzando Langchain e modelli LLM open source, esegue generazione aumentata da recupero (RAG) dai vostri documenti PDF. \
158
+ L'interfaccia utente esplicitamente mostra i passaggi multipli per aiutare a comprendere il flusso di lavoro RAG.
159
+ Questo chatbot tiene conto delle domande passate nel generare le risposte (tramite memoria conversazionale), e include riferimenti ai documenti per scopi di chiarezza.<br>
160
+ <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.
161
+ """)
162
+
163
+ with gr.Tab("Step 1 - Carica PDFs"):
164
+ with gr.Row():
165
+ document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
166
+ # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
167
+
168
+ with gr.Tab("Step 2 - Processa i documenti"):
169
+ with gr.Row():
170
+ db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
171
+ with gr.Accordion("Opzioni Avanzate - Document text splitter", open=False):
172
+ with gr.Row():
173
+ slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=1000, step=20, label="Chunk size", info="Chunk size", interactive=True)
174
+ with gr.Row():
175
+ slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=100, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
176
+ with gr.Row():
177
+ db_progress = gr.Textbox(label="Vector database initialization", value="None")
178
+ with gr.Row():
179
+ db_btn = gr.Button("Genera vector database")
180
+
181
+ with gr.Tab("Step 3 - Inizializza QA chain"):
182
+ with gr.Row():
183
+ llm_btn = gr.Radio(list_llm_simple, \
184
+ label="LLM models", value = list_llm_simple[5], type="index", info="Scegli il tuo modello LLM")
185
+ with gr.Accordion("Advanced options - LLM model", open=False):
186
+ with gr.Row():
187
+ slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.3, step=0.1, label="Temperature", info="Model temperature", interactive=True)
188
+ with gr.Row():
189
+ slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
190
+ with gr.Row():
191
+ slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
192
+ with gr.Row():
193
+ language_btn = gr.Radio(["Italian", "English"], label="Linua", value="Italian", type="index", info="Seleziona la lingua per il chatbot")
194
+ with gr.Row():
195
+ llm_progress = gr.Textbox(value="None",label="QA chain initialization")
196
+ with gr.Row():
197
+ qachain_btn = gr.Button("Inizializza Question Answering chain")
198
+
199
+
200
+ with gr.Tab("Passo 4 - Chatbot"):
201
+ chatbot = gr.Chatbot(height=300)
202
+ with gr.Accordion("Opzioni avanzate - Riferimenti ai documenti", open=False):
203
+ with gr.Row():
204
+ doc_source1 = gr.Textbox(label="Riferimento 1", lines=2, container=True, scale=20)
205
+ source1_page = gr.Number(label="Pagina", scale=1)
206
+ with gr.Row():
207
+ doc_source2 = gr.Textbox(label="Riferimento 2", lines=2, container=True, scale=20)
208
+ source2_page = gr.Number(label="Pagina", scale=1)
209
+ with gr.Row():
210
+ doc_source3 = gr.Textbox(label="Riferimento 3", lines=2, container=True, scale=20)
211
+ source3_page = gr.Number(label="Pagina", scale=1)
212
+ with gr.Row():
213
+ msg = gr.Textbox(placeholder="Inserisci messaggio (es. 'Di cosa tratta questo documento?')", container=True)
214
+ with gr.Row():
215
+ submit_btn = gr.Button("Invia messaggio")
216
+ clear_btn = gr.ClearButton([msg, chatbot], value="Cancella conversazione")
217
+
218
+ # Preprocessing events
219
+ #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
220
+ db_btn.click(initialize_database, \
221
+ inputs=[document, slider_chunk_size, slider_chunk_overlap], \
222
+ outputs=[vector_db, collection_name, db_progress])
223
+ qachain_btn.click(initialize_LLM, \
224
+ inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
225
+ outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
226
+ inputs=None, \
227
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
228
+ queue=False)
229
+
230
+
231
+ # Chatbot events
232
+ msg.submit(conversation, \
233
+ inputs=[qa_chain, msg, chatbot], \
234
+ outputs=[qa_chain, msg, chatbot, \
235
+ doc_source1, source1_page,
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,
244
+ doc_source1, source1_page,
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, \
253
+ doc_source1, source1_page,
254
+ doc_source2, source2_page,
255
+ doc_source3, source3_page,
256
+ doc_source4, source4_page,
257
+ doc_source5, source5_page], \
258
+ queue=False)
259
+ demo.queue().launch(debug=True)
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