Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,40 +1,57 @@
|
|
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
|
|
|
9 |
from langchain.memory import ConversationBufferMemory
|
|
|
|
|
10 |
from pathlib import Path
|
11 |
import chromadb
|
12 |
from unidecode import unidecode
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
import re
|
|
|
|
|
14 |
|
15 |
-
#
|
16 |
-
list_llm = [
|
17 |
-
"
|
18 |
-
"
|
19 |
-
"
|
20 |
-
"
|
21 |
-
"
|
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()
|
@@ -42,18 +59,102 @@ def create_db(splits, collection_name):
|
|
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 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
progress(0.75, desc="Defining buffer memory...")
|
59 |
memory = ConversationBufferMemory(
|
@@ -61,50 +162,77 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
61 |
output_key='answer',
|
62 |
return_messages=True
|
63 |
)
|
64 |
-
retriever
|
|
|
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 |
-
|
|
|
|
|
|
|
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 |
-
|
|
|
|
|
94 |
collection_name = create_collection_name(list_file_path[0])
|
95 |
-
progress(0.25, desc="
|
|
|
96 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
97 |
|
98 |
-
|
|
|
99 |
vector_db = create_db(doc_splits, collection_name)
|
100 |
-
progress(0.9, desc="
|
101 |
|
102 |
-
return vector_db, collection_name, "
|
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 |
-
|
|
|
108 |
|
109 |
def format_chat_history(message, chat_history):
|
110 |
formatted_chat_history = []
|
@@ -112,28 +240,34 @@ def format_chat_history(message, 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 |
-
|
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
|
|
|
|
|
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):
|
@@ -196,6 +330,7 @@ def demo():
|
|
196 |
with gr.Row():
|
197 |
qachain_btn = gr.Button("Inizializza Question Answering chain")
|
198 |
|
|
|
199 |
with gr.Tab("Passo 4 - Chatbot"):
|
200 |
chatbot = gr.Chatbot(height=300)
|
201 |
with gr.Accordion("Opzioni avanzate - Riferimenti ai documenti", open=False):
|
@@ -208,12 +343,6 @@ def demo():
|
|
208 |
with gr.Row():
|
209 |
doc_source3 = gr.Textbox(label="Riferimento 3", lines=2, container=True, scale=20)
|
210 |
source3_page = gr.Number(label="Pagina", scale=1)
|
211 |
-
with gr.Row():
|
212 |
-
doc_source4 = gr.Textbox(label="Riferimento 4", lines=2, container=True, scale=20)
|
213 |
-
source4_page = gr.Number(label="Pagina", scale=1)
|
214 |
-
with gr.Row():
|
215 |
-
doc_source5 = gr.Textbox(label="Riferimento 5", lines=2, container=True, scale=20)
|
216 |
-
source5_page = gr.Number(label="Pagina", scale=1)
|
217 |
with gr.Row():
|
218 |
msg = gr.Textbox(placeholder="Inserisci messaggio (es. 'Di cosa tratta questo documento?')", container=True)
|
219 |
with gr.Row():
|
@@ -225,49 +354,28 @@ def demo():
|
|
225 |
db_btn.click(initialize_database, \
|
226 |
inputs=[document, slider_chunk_size, slider_chunk_overlap], \
|
227 |
outputs=[vector_db, collection_name, db_progress])
|
228 |
-
|
229 |
qachain_btn.click(initialize_LLM, \
|
230 |
inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
|
231 |
-
outputs=[qa_chain, llm_progress]).then(lambda:[None,
|
232 |
inputs=None, \
|
233 |
-
outputs=[chatbot,
|
234 |
-
|
235 |
-
doc_source2, source2_page,
|
236 |
-
doc_source3, source3_page,
|
237 |
-
doc_source4, source4_page,
|
238 |
-
doc_source5, source5_page], queue=False)
|
239 |
|
240 |
# Chatbot events
|
241 |
msg.submit(conversation, \
|
242 |
inputs=[qa_chain, msg, chatbot], \
|
243 |
-
outputs=[qa_chain, msg, chatbot, \
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
inputs=
|
251 |
-
outputs=[
|
252 |
-
|
253 |
-
doc_source2, source2_page,
|
254 |
-
doc_source3, source3_page,
|
255 |
-
doc_source4, source4_page,
|
256 |
-
doc_source5, source5_page], queue=False)
|
257 |
-
clear_btn.click(
|
258 |
-
lambda: [None, "", 0, "", 0, "", 0, "", 0, "", 0],
|
259 |
-
inputs=None,
|
260 |
-
outputs=[
|
261 |
-
chatbot,
|
262 |
-
doc_source1, source1_page,
|
263 |
-
doc_source2, source2_page,
|
264 |
-
doc_source3, source3_page,
|
265 |
-
doc_source4, source4_page,
|
266 |
-
doc_source5, source5_page
|
267 |
-
],
|
268 |
-
queue=False
|
269 |
-
)
|
270 |
demo.queue().launch(debug=True)
|
271 |
|
|
|
272 |
if __name__ == "__main__":
|
273 |
-
demo()
|
|
|
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 |
+
# default_persist_directory = './chroma_HF/'
|
28 |
+
list_llm = ["mistralai/Mistral-7B-Instruct-v0.2", "mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1", \
|
29 |
+
"google/gemma-7b-it","google/gemma-2b-it", \
|
30 |
+
"HuggingFaceH4/zephyr-7b-beta", "HuggingFaceH4/zephyr-7b-gemma-v0.1", \
|
31 |
+
"meta-llama/Llama-2-7b-chat-hf", "microsoft/phi-2", \
|
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 |
+
# text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
|
47 |
text_splitter = RecursiveCharacterTextSplitter(
|
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()
|
|
|
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 |
+
# Use of trust_remote_code as model_kwargs
|
102 |
+
# Warning: langchain issue
|
103 |
+
# URL: https://github.com/langchain-ai/langchain/issues/6080
|
104 |
+
if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
|
105 |
+
llm = HuggingFaceEndpoint(
|
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(
|
|
|
162 |
output_key='answer',
|
163 |
return_messages=True
|
164 |
)
|
165 |
+
# retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
|
166 |
+
retriever=vector_db.as_retriever()
|
167 |
progress(0.8, desc="Defining retrieval chain...")
|
168 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
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 |
+
# Fix potential issues from naming convention
|
188 |
+
## Remove space
|
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 = collection_name + 'xyz'
|
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 |
+
progress(0.9, desc="Fatto!")
|
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 |
formatted_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 |
+
response_source1 = response_sources[0].page_content.strip()
|
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 |
+
# return gr.update(value=""), new_history, response_sources[0], response_sources[1]
|
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):
|
|
|
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("Opzioni avanzate - Riferimenti ai documenti", open=False):
|
|
|
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():
|
|
|
354 |
db_btn.click(initialize_database, \
|
355 |
inputs=[document, slider_chunk_size, slider_chunk_overlap], \
|
356 |
outputs=[vector_db, collection_name, db_progress])
|
|
|
357 |
qachain_btn.click(initialize_LLM, \
|
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()
|