Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,281 +1,94 @@
|
|
1 |
import gradio as gr
|
2 |
import os
|
3 |
-
|
4 |
from langchain_community.document_loaders import PyPDFLoader
|
5 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
6 |
from langchain_community.vectorstores import Chroma
|
7 |
from langchain.chains import ConversationalRetrievalChain
|
8 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
9 |
-
from langchain_community.llms import HuggingFacePipeline
|
10 |
-
from langchain.chains import ConversationChain
|
11 |
-
from langchain.memory import ConversationBufferMemory
|
12 |
from langchain_community.llms import HuggingFaceEndpoint
|
13 |
-
|
14 |
from pathlib import Path
|
15 |
import chromadb
|
16 |
from unidecode import unidecode
|
17 |
-
|
18 |
-
from transformers import AutoTokenizer
|
19 |
-
import transformers
|
20 |
-
import torch
|
21 |
-
import tqdm
|
22 |
-
import accelerate
|
23 |
import re
|
24 |
-
# from chromadb.utils import get_default_config
|
25 |
-
vector_db = ''
|
26 |
|
27 |
-
|
28 |
-
|
29 |
-
"google/gemma-7b-it","google/gemma-2b-it",
|
30 |
-
"HuggingFaceH4/zephyr-7b-beta", "HuggingFaceH4/zephyr-7b-gemma-v0.1",
|
31 |
-
"
|
32 |
-
"TinyLlama/TinyLlama-1.1B-Chat-v1.0", "mosaicml/mpt-7b-instruct", "tiiuae/falcon-7b-instruct", \
|
33 |
-
"google/flan-t5-xxl"
|
34 |
]
|
35 |
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
36 |
|
37 |
-
# Load PDF document and create doc splits
|
38 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
39 |
-
# Processing for one document only
|
40 |
-
# loader = PyPDFLoader(file_path)
|
41 |
-
# pages = loader.load()
|
42 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
43 |
pages = []
|
44 |
for loader in loaders:
|
45 |
pages.extend(loader.load())
|
46 |
-
|
47 |
-
text_splitter
|
48 |
-
chunk_size = chunk_size,
|
49 |
-
chunk_overlap = chunk_overlap)
|
50 |
-
doc_splits = text_splitter.split_documents(pages)
|
51 |
-
return doc_splits
|
52 |
-
|
53 |
|
54 |
-
# Create vector database
|
55 |
def create_db(splits, collection_name):
|
56 |
embedding = HuggingFaceEmbeddings()
|
57 |
new_client = chromadb.EphemeralClient()
|
58 |
-
|
59 |
-
documents=splits,
|
60 |
-
embedding=embedding,
|
61 |
-
client=new_client,
|
62 |
-
collection_name=collection_name,
|
63 |
-
# persist_directory=default_persist_directory
|
64 |
-
)
|
65 |
-
return vectordb
|
66 |
-
|
67 |
|
68 |
-
# Load vector database
|
69 |
-
def load_db():
|
70 |
-
embedding = HuggingFaceEmbeddings()
|
71 |
-
vectordb = Chroma(
|
72 |
-
# persist_directory=default_persist_directory,
|
73 |
-
embedding_function=embedding)
|
74 |
-
return vectordb
|
75 |
-
|
76 |
-
# Initialize langchain LLM chain
|
77 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
78 |
-
progress(0.1, desc="Initializing HF tokenizer...")
|
79 |
-
# HuggingFacePipeline uses local model
|
80 |
-
# Note: it will download model locally...
|
81 |
-
# tokenizer=AutoTokenizer.from_pretrained(llm_model)
|
82 |
-
# progress(0.5, desc="Initializing HF pipeline...")
|
83 |
-
# pipeline=transformers.pipeline(
|
84 |
-
# "text-generation",
|
85 |
-
# model=llm_model,
|
86 |
-
# tokenizer=tokenizer,
|
87 |
-
# torch_dtype=torch.bfloat16,
|
88 |
-
# trust_remote_code=True,
|
89 |
-
# device_map="auto",
|
90 |
-
# # max_length=1024,
|
91 |
-
# max_new_tokens=max_tokens,
|
92 |
-
# do_sample=True,
|
93 |
-
# top_k=top_k,
|
94 |
-
# num_return_sequences=1,
|
95 |
-
# eos_token_id=tokenizer.eos_token_id
|
96 |
-
# )
|
97 |
-
# llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
|
98 |
-
|
99 |
-
# HuggingFaceHub uses HF inference endpoints
|
100 |
progress(0.5, desc="Initializing HF Hub...")
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
repo_id=llm_model,
|
107 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True}
|
108 |
-
temperature = temperature,
|
109 |
-
max_new_tokens = max_tokens,
|
110 |
-
top_k = top_k,
|
111 |
-
load_in_8bit = True,
|
112 |
-
)
|
113 |
-
elif llm_model in ["HuggingFaceH4/zephyr-7b-gemma-v0.1","mosaicml/mpt-7b-instruct"]:
|
114 |
-
raise gr.Error("LLM model is too large to be loaded automatically on free inference endpoint")
|
115 |
-
llm = HuggingFaceEndpoint(
|
116 |
-
repo_id=llm_model,
|
117 |
-
temperature = temperature,
|
118 |
-
max_new_tokens = max_tokens,
|
119 |
-
top_k = top_k,
|
120 |
-
)
|
121 |
-
elif llm_model == "microsoft/phi-2":
|
122 |
-
# raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")
|
123 |
-
llm = HuggingFaceEndpoint(
|
124 |
-
repo_id=llm_model,
|
125 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
126 |
-
temperature = temperature,
|
127 |
-
max_new_tokens = max_tokens,
|
128 |
-
top_k = top_k,
|
129 |
-
trust_remote_code = True,
|
130 |
-
torch_dtype = "auto",
|
131 |
-
)
|
132 |
-
elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
|
133 |
-
llm = HuggingFaceEndpoint(
|
134 |
-
repo_id=llm_model,
|
135 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}
|
136 |
-
temperature = temperature,
|
137 |
-
max_new_tokens = 250,
|
138 |
-
top_k = top_k,
|
139 |
-
)
|
140 |
-
elif llm_model == "meta-llama/Llama-2-7b-chat-hf":
|
141 |
-
raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")
|
142 |
-
llm = HuggingFaceEndpoint(
|
143 |
-
repo_id=llm_model,
|
144 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
145 |
-
temperature = temperature,
|
146 |
-
max_new_tokens = max_tokens,
|
147 |
-
top_k = top_k,
|
148 |
-
)
|
149 |
-
else:
|
150 |
-
llm = HuggingFaceEndpoint(
|
151 |
-
repo_id=llm_model,
|
152 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
153 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
154 |
-
temperature = temperature,
|
155 |
-
max_new_tokens = max_tokens,
|
156 |
-
top_k = top_k,
|
157 |
-
)
|
158 |
-
|
159 |
-
progress(0.75, desc="Defining buffer memory...")
|
160 |
-
memory = ConversationBufferMemory(
|
161 |
-
memory_key="chat_history",
|
162 |
-
output_key='answer',
|
163 |
-
return_messages=True
|
164 |
)
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
|
|
169 |
llm,
|
170 |
retriever=retriever,
|
171 |
chain_type="stuff",
|
172 |
memory=memory,
|
173 |
-
# combine_docs_chain_kwargs={"prompt": your_prompt})
|
174 |
return_source_documents=True,
|
175 |
-
#return_generated_question=False,
|
176 |
verbose=False,
|
177 |
)
|
178 |
-
progress(0.9, desc="Done!")
|
179 |
-
return qa_chain
|
180 |
-
|
181 |
|
182 |
-
# Generate collection name for vector database
|
183 |
-
# - Use filepath as input, ensuring unicode text
|
184 |
def create_collection_name(filepath):
|
185 |
-
# Extract filename without extension
|
186 |
collection_name = Path(filepath).stem
|
187 |
-
|
188 |
-
|
189 |
-
collection_name = collection_name.replace(" ","-")
|
190 |
-
## ASCII transliterations of Unicode text
|
191 |
-
collection_name = unidecode(collection_name)
|
192 |
-
## Remove special characters
|
193 |
-
#collection_name = re.findall("[\dA-Za-z]*", collection_name)[0]
|
194 |
-
collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
|
195 |
-
## Limit length to 50 characters
|
196 |
-
collection_name = collection_name[:50]
|
197 |
-
## Minimum length of 3 characters
|
198 |
if len(collection_name) < 3:
|
199 |
-
collection_name
|
200 |
-
## Enforce start and end as alphanumeric character
|
201 |
if not collection_name[0].isalnum():
|
202 |
collection_name = 'A' + collection_name[1:]
|
203 |
if not collection_name[-1].isalnum():
|
204 |
collection_name = collection_name[:-1] + 'Z'
|
205 |
-
print('Filepath: ', filepath)
|
206 |
-
print('Collection name: ', collection_name)
|
207 |
return collection_name
|
208 |
|
209 |
-
# Initialize database
|
210 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
211 |
-
# Create list of documents (when valid)
|
212 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
213 |
-
print(list_file_path)
|
214 |
-
# Create collection_name for vector database
|
215 |
-
progress(0.1, desc="Creazione collezione...")
|
216 |
collection_name = create_collection_name(list_file_path[0])
|
217 |
-
progress(0.25, desc="Caricamento documenti..")
|
218 |
-
# Load document and create splits
|
219 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
220 |
-
|
221 |
-
# Creare o caricare il nuovo database
|
222 |
-
progress(0.5, desc="Generazione vector database...")
|
223 |
vector_db = create_db(doc_splits, collection_name)
|
224 |
-
|
225 |
-
|
226 |
-
return vector_db, collection_name, "Completato!"
|
227 |
|
228 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
229 |
-
# print("llm_option",llm_option)
|
230 |
llm_name = list_llm[llm_option]
|
231 |
-
print(f"Nome del modello: {llm_name}")
|
232 |
-
|
233 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
234 |
-
|
235 |
-
return qa_chain, "Completato!"
|
236 |
|
237 |
def format_chat_history(message, chat_history):
|
238 |
-
|
239 |
-
for user_message, bot_message in chat_history:
|
240 |
-
formatted_chat_history.append(f"User: {user_message}")
|
241 |
-
formatted_chat_history.append(f"Assistant: {bot_message}")
|
242 |
-
return formatted_chat_history
|
243 |
-
|
244 |
|
245 |
def conversation(qa_chain, message, history):
|
246 |
formatted_chat_history = format_chat_history(message, history)
|
247 |
-
print("formatted_chat_history",formatted_chat_history)
|
248 |
-
|
249 |
-
# Generate response using QA chain
|
250 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
251 |
-
response_answer = response["answer"]
|
252 |
-
if response_answer.find("Helpful Answer:") != -1:
|
253 |
-
response_answer = response_answer.split("Helpful Answer:")[-1]
|
254 |
response_sources = response["source_documents"]
|
255 |
-
|
256 |
-
response_source2 = response_sources[1].page_content.strip()
|
257 |
-
response_source3 = response_sources[2].page_content.strip()
|
258 |
-
# Langchain sources are zero-based
|
259 |
-
response_source1_page = response_sources[0].metadata["page"] + 1
|
260 |
-
response_source2_page = response_sources[1].metadata["page"] + 1
|
261 |
-
response_source3_page = response_sources[2].metadata["page"] + 1
|
262 |
-
#print('chat response: ', response_answer)
|
263 |
-
#print('DB source', response_sources)
|
264 |
-
|
265 |
-
# Append user message and response to chat history
|
266 |
new_history = history + [(message, response_answer)]
|
267 |
-
|
268 |
-
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
269 |
-
|
270 |
-
|
271 |
-
def upload_file(file_obj):
|
272 |
-
list_file_path = []
|
273 |
-
for idx, file in enumerate(file_obj):
|
274 |
-
file_path = file_obj.name
|
275 |
-
list_file_path.append(file_path)
|
276 |
-
print(file_path)
|
277 |
-
# initialize_database(file_path, progress)
|
278 |
-
return list_file_path
|
279 |
|
280 |
def demo():
|
281 |
with gr.Blocks(theme="base") as demo:
|
@@ -283,99 +96,45 @@ def demo():
|
|
283 |
qa_chain = gr.State()
|
284 |
collection_name = gr.State()
|
285 |
|
286 |
-
gr.Markdown(
|
287 |
-
"""<center><h2>Creatore di chatbot basato su PDF</center></h2>
|
288 |
-
<h3>Potete fare domande su i vostri documenti PDF</h3>""")
|
289 |
-
|
290 |
-
gr.Markdown(
|
291 |
-
"""<b>Nota:</b> Questo assistente IA, utilizzando Langchain e modelli LLM open source, esegue generazione aumentata da recupero (RAG) dai vostri documenti PDF. \
|
292 |
-
L'interfaccia utente esplicitamente mostra i passaggi multipli per aiutare a comprendere il flusso di lavoro RAG.
|
293 |
-
Questo chatbot tiene conto delle domande passate nel generare le risposte (tramite memoria conversazionale), e include riferimenti ai documenti per scopi di chiarezza.<br>
|
294 |
-
<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.
|
295 |
-
""")
|
296 |
|
297 |
-
with gr.Tab("Step 1 -
|
298 |
-
|
299 |
-
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
|
300 |
-
# upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
|
301 |
|
302 |
-
with gr.Tab("Step 2 -
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=100, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
|
310 |
-
with gr.Row():
|
311 |
-
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
312 |
-
with gr.Row():
|
313 |
-
db_btn = gr.Button("Genera vector database")
|
314 |
|
315 |
-
with gr.Tab("Step 3 -
|
316 |
-
|
317 |
-
llm_btn = gr.Radio(list_llm_simple, \
|
318 |
-
label="LLM models", value = list_llm_simple[5], type="index", info="Scegli il tuo modello LLM")
|
319 |
with gr.Accordion("Advanced options - LLM model", open=False):
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
with gr.Row():
|
327 |
-
language_btn = gr.Radio(["Italian", "English"], label="Linua", value="Italian", type="index", info="Seleziona la lingua per il chatbot")
|
328 |
-
with gr.Row():
|
329 |
-
llm_progress = gr.Textbox(value="None",label="QA chain initialization")
|
330 |
-
with gr.Row():
|
331 |
-
qachain_btn = gr.Button("Inizializza Question Answering chain")
|
332 |
|
333 |
-
|
334 |
-
with gr.Tab("Passo 4 - Chatbot"):
|
335 |
chatbot = gr.Chatbot(height=300)
|
336 |
-
with gr.Accordion("
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
source2_page = gr.Number(label="Pagina", scale=1)
|
343 |
-
with gr.Row():
|
344 |
-
doc_source3 = gr.Textbox(label="Riferimento 3", lines=2, container=True, scale=20)
|
345 |
-
source3_page = gr.Number(label="Pagina", scale=1)
|
346 |
-
with gr.Row():
|
347 |
-
msg = gr.Textbox(placeholder="Inserisci messaggio (es. 'Di cosa tratta questo documento?')", container=True)
|
348 |
-
with gr.Row():
|
349 |
-
submit_btn = gr.Button("Invia messaggio")
|
350 |
-
clear_btn = gr.ClearButton([msg, chatbot], value="Cancella conversazione")
|
351 |
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
|
359 |
-
outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
|
360 |
-
inputs=None, \
|
361 |
-
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
|
362 |
-
queue=False)
|
363 |
-
|
364 |
-
# Chatbot events
|
365 |
-
msg.submit(conversation, \
|
366 |
-
inputs=[qa_chain, msg, chatbot], \
|
367 |
-
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
|
368 |
-
queue=False)
|
369 |
-
submit_btn.click(conversation, \
|
370 |
-
inputs=[qa_chain, msg, chatbot], \
|
371 |
-
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
|
372 |
-
queue=False)
|
373 |
-
clear_btn.click(lambda:[None,"",0,"",0,"",0], \
|
374 |
-
inputs=None, \
|
375 |
-
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
|
376 |
-
queue=False)
|
377 |
demo.queue().launch(debug=True)
|
378 |
|
379 |
-
|
380 |
if __name__ == "__main__":
|
381 |
demo()
|
|
|
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_llm = [
|
16 |
+
"mistralai/Mistral-7B-Instruct-v0.2", "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
17 |
+
"google/gemma-7b-it", "google/gemma-2b-it",
|
18 |
+
"HuggingFaceH4/zephyr-7b-beta", "HuggingFaceH4/zephyr-7b-gemma-v0.1",
|
19 |
+
"TinyLlama/TinyLlama-1.1B-Chat-v1.0", "tiiuae/falcon-7b-instruct"
|
|
|
|
|
20 |
]
|
21 |
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
22 |
|
|
|
23 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
|
|
|
|
|
|
24 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
25 |
pages = []
|
26 |
for loader in loaders:
|
27 |
pages.extend(loader.load())
|
28 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
29 |
+
return text_splitter.split_documents(pages)
|
|
|
|
|
|
|
|
|
|
|
30 |
|
|
|
31 |
def create_db(splits, collection_name):
|
32 |
embedding = HuggingFaceEmbeddings()
|
33 |
new_client = chromadb.EphemeralClient()
|
34 |
+
return Chroma.from_documents(documents=splits, embedding=embedding, client=new_client, collection_name=collection_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
progress(0.5, desc="Initializing HF Hub...")
|
38 |
+
llm = HuggingFaceEndpoint(
|
39 |
+
repo_id=llm_model,
|
40 |
+
temperature=temperature,
|
41 |
+
max_new_tokens=max_tokens,
|
42 |
+
top_k=top_k,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
)
|
44 |
+
|
45 |
+
memory = ConversationBufferMemory(memory_key="chat_history", output_key='answer', return_messages=True)
|
46 |
+
retriever = vector_db.as_retriever()
|
47 |
+
|
48 |
+
return ConversationalRetrievalChain.from_llm(
|
49 |
llm,
|
50 |
retriever=retriever,
|
51 |
chain_type="stuff",
|
52 |
memory=memory,
|
|
|
53 |
return_source_documents=True,
|
|
|
54 |
verbose=False,
|
55 |
)
|
|
|
|
|
|
|
56 |
|
|
|
|
|
57 |
def create_collection_name(filepath):
|
|
|
58 |
collection_name = Path(filepath).stem
|
59 |
+
collection_name = unidecode(collection_name.replace(" ", "-"))
|
60 |
+
collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)[:50]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
if len(collection_name) < 3:
|
62 |
+
collection_name += 'xyz'
|
|
|
63 |
if not collection_name[0].isalnum():
|
64 |
collection_name = 'A' + collection_name[1:]
|
65 |
if not collection_name[-1].isalnum():
|
66 |
collection_name = collection_name[:-1] + 'Z'
|
|
|
|
|
67 |
return collection_name
|
68 |
|
|
|
69 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
|
|
70 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
|
|
|
|
|
|
71 |
collection_name = create_collection_name(list_file_path[0])
|
|
|
|
|
72 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
|
|
|
|
|
|
73 |
vector_db = create_db(doc_splits, collection_name)
|
74 |
+
return vector_db, collection_name, "Completed!"
|
|
|
|
|
75 |
|
76 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
|
|
77 |
llm_name = list_llm[llm_option]
|
|
|
|
|
78 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
79 |
+
return qa_chain, "Completed!"
|
|
|
80 |
|
81 |
def format_chat_history(message, chat_history):
|
82 |
+
return [f"User: {user_message}\nAssistant: {bot_message}" for user_message, bot_message in chat_history]
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
def conversation(qa_chain, message, history):
|
85 |
formatted_chat_history = format_chat_history(message, history)
|
|
|
|
|
|
|
86 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
87 |
+
response_answer = response["answer"].split("Helpful Answer:")[-1]
|
|
|
|
|
88 |
response_sources = response["source_documents"]
|
89 |
+
sources = [(source.page_content.strip(), source.metadata["page"] + 1) for source in response_sources[:3]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
new_history = history + [(message, response_answer)]
|
91 |
+
return qa_chain, gr.update(value=""), new_history, *[item for source in sources for item in source]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
def demo():
|
94 |
with gr.Blocks(theme="base") as demo:
|
|
|
96 |
qa_chain = gr.State()
|
97 |
collection_name = gr.State()
|
98 |
|
99 |
+
gr.Markdown("# PDF-based Chatbot Creator")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
|
101 |
+
with gr.Tab("Step 1 - Upload PDFs"):
|
102 |
+
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents")
|
|
|
|
|
103 |
|
104 |
+
with gr.Tab("Step 2 - Process Documents"):
|
105 |
+
db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value="ChromaDB", type="index")
|
106 |
+
with gr.Accordion("Advanced Options - Document text splitter", open=False):
|
107 |
+
slider_chunk_size = gr.Slider(100, 1000, 1000, step=20, label="Chunk size")
|
108 |
+
slider_chunk_overlap = gr.Slider(10, 200, 100, step=10, label="Chunk overlap")
|
109 |
+
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
110 |
+
db_btn = gr.Button("Generate vector database")
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
+
with gr.Tab("Step 3 - Initialize QA chain"):
|
113 |
+
llm_btn = gr.Radio(list_llm_simple, label="LLM models", value=list_llm_simple[5], type="index")
|
|
|
|
|
114 |
with gr.Accordion("Advanced options - LLM model", open=False):
|
115 |
+
slider_temperature = gr.Slider(0.01, 1.0, 0.3, step=0.1, label="Temperature")
|
116 |
+
slider_maxtokens = gr.Slider(224, 4096, 1024, step=32, label="Max Tokens")
|
117 |
+
slider_topk = gr.Slider(1, 10, 3, step=1, label="top-k samples")
|
118 |
+
language_btn = gr.Radio(["Italian", "English"], label="Language", value="Italian", type="index")
|
119 |
+
llm_progress = gr.Textbox(value="None", label="QA chain initialization")
|
120 |
+
qachain_btn = gr.Button("Initialize Question Answering chain")
|
|
|
|
|
|
|
|
|
|
|
|
|
121 |
|
122 |
+
with gr.Tab("Step 4 - Chatbot"):
|
|
|
123 |
chatbot = gr.Chatbot(height=300)
|
124 |
+
with gr.Accordion("Advanced options - Document references", open=False):
|
125 |
+
doc_sources = [gr.Textbox(label=f"Reference {i+1}", lines=2, container=True, scale=20) for i in range(3)]
|
126 |
+
source_pages = [gr.Number(label="Page", scale=1) for _ in range(3)]
|
127 |
+
msg = gr.Textbox(placeholder="Enter message (e.g., 'What is this document about?')", container=True)
|
128 |
+
submit_btn = gr.Button("Send message")
|
129 |
+
clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
|
131 |
+
db_btn.click(initialize_database, inputs=[document, slider_chunk_size, slider_chunk_overlap], outputs=[vector_db, collection_name, db_progress])
|
132 |
+
qachain_btn.click(initialize_LLM, inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], outputs=[qa_chain, llm_progress])
|
133 |
+
|
134 |
+
submit_btn.click(conversation, inputs=[qa_chain, msg, chatbot], outputs=[qa_chain, msg, chatbot] + doc_sources + source_pages)
|
135 |
+
msg.submit(conversation, inputs=[qa_chain, msg, chatbot], outputs=[qa_chain, msg, chatbot] + doc_sources + source_pages)
|
136 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
demo.queue().launch(debug=True)
|
138 |
|
|
|
139 |
if __name__ == "__main__":
|
140 |
demo()
|