Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,58 +1,24 @@
|
|
1 |
import gradio as gr
|
2 |
import os
|
3 |
-
|
4 |
from langchain.document_loaders import PyPDFLoader
|
5 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
6 |
from langchain.vectorstores import Chroma
|
7 |
from langchain.chains import ConversationalRetrievalChain
|
8 |
from langchain.embeddings import HuggingFaceEmbeddings
|
9 |
-
from langchain.llms import HuggingFacePipeline
|
10 |
-
from langchain.chains import ConversationChain
|
11 |
-
from langchain.memory import ConversationBufferMemory
|
12 |
from langchain.llms import HuggingFaceHub
|
13 |
-
|
14 |
from pathlib import Path
|
15 |
import chromadb
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
import torch
|
20 |
-
import tqdm
|
21 |
-
import accelerate
|
22 |
-
|
23 |
-
|
24 |
-
# default_persist_directory = './chroma_HF/'
|
25 |
-
|
26 |
-
llm_name0 = "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
27 |
-
llm_name1 = "mistralai/Mistral-7B-Instruct-v0.2"
|
28 |
-
llm_name2 = "mistralai/Mistral-7B-Instruct-v0.1"
|
29 |
-
llm_name3 = "meta-llama/Llama-2-7b-chat-hf"
|
30 |
-
llm_name4 = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
31 |
-
llm_name5 = "microsoft/phi-2"
|
32 |
-
llm_name6 = "mosaicml/mpt-7b-instruct"
|
33 |
-
llm_name7 = "tiiuae/falcon-7b-instruct"
|
34 |
-
llm_name8 = "google/flan-t5-xxl"
|
35 |
-
list_llm = [llm_name0, llm_name1, llm_name2, llm_name3, llm_name4, llm_name5, llm_name6, llm_name7, llm_name8]
|
36 |
-
list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
37 |
|
38 |
-
# Load PDF document and create doc splits
|
39 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
40 |
-
# Processing for one document only
|
41 |
-
# loader = PyPDFLoader(file_path)
|
42 |
-
# pages = loader.load()
|
43 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
44 |
-
pages = []
|
45 |
-
|
46 |
-
pages.extend(loader.load())
|
47 |
-
# text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
|
48 |
-
text_splitter = RecursiveCharacterTextSplitter(
|
49 |
-
chunk_size = chunk_size,
|
50 |
-
chunk_overlap = chunk_overlap)
|
51 |
doc_splits = text_splitter.split_documents(pages)
|
52 |
return doc_splits
|
53 |
|
54 |
-
|
55 |
-
# Create vector database
|
56 |
def create_db(splits, collection_name):
|
57 |
embedding = HuggingFaceEmbeddings()
|
58 |
new_client = chromadb.EphemeralClient()
|
@@ -61,254 +27,113 @@ def create_db(splits, collection_name):
|
|
61 |
embedding=embedding,
|
62 |
client=new_client,
|
63 |
collection_name=collection_name,
|
64 |
-
# persist_directory=default_persist_directory
|
65 |
)
|
66 |
return vectordb
|
67 |
|
68 |
-
|
69 |
-
# Load vector database
|
70 |
def load_db():
|
71 |
embedding = HuggingFaceEmbeddings()
|
72 |
-
vectordb = Chroma(
|
73 |
-
# persist_directory=default_persist_directory,
|
74 |
-
embedding_function=embedding)
|
75 |
return vectordb
|
76 |
|
77 |
-
|
78 |
-
# Initialize langchain LLM chain
|
79 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
80 |
progress(0.1, desc="Initializing HF tokenizer...")
|
81 |
-
# HuggingFacePipeline uses local model
|
82 |
-
# Note: it will download model locally...
|
83 |
-
# tokenizer=AutoTokenizer.from_pretrained(llm_model)
|
84 |
-
# progress(0.5, desc="Initializing HF pipeline...")
|
85 |
-
# pipeline=transformers.pipeline(
|
86 |
-
# "text-generation",
|
87 |
-
# model=llm_model,
|
88 |
-
# tokenizer=tokenizer,
|
89 |
-
# torch_dtype=torch.bfloat16,
|
90 |
-
# trust_remote_code=True,
|
91 |
-
# device_map="auto",
|
92 |
-
# # max_length=1024,
|
93 |
-
# max_new_tokens=max_tokens,
|
94 |
-
# do_sample=True,
|
95 |
-
# top_k=top_k,
|
96 |
-
# num_return_sequences=1,
|
97 |
-
# eos_token_id=tokenizer.eos_token_id
|
98 |
-
# )
|
99 |
-
# llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
|
100 |
-
|
101 |
-
# HuggingFaceHub uses HF inference endpoints
|
102 |
progress(0.5, desc="Initializing HF Hub...")
|
103 |
-
|
104 |
-
# Warning: langchain issue
|
105 |
-
# URL: https://github.com/langchain-ai/langchain/issues/6080
|
106 |
if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
|
107 |
-
|
108 |
-
|
109 |
-
model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True}
|
110 |
-
)
|
111 |
-
elif llm_model == "microsoft/phi-2":
|
112 |
-
raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")
|
113 |
-
llm = HuggingFaceHub(
|
114 |
-
repo_id=llm_model,
|
115 |
-
model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
116 |
-
)
|
117 |
-
elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
|
118 |
-
llm = HuggingFaceHub(
|
119 |
-
repo_id=llm_model,
|
120 |
-
model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}
|
121 |
-
)
|
122 |
-
elif llm_model == "meta-llama/Llama-2-7b-chat-hf":
|
123 |
-
raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")
|
124 |
-
llm = HuggingFaceHub(
|
125 |
-
repo_id=llm_model,
|
126 |
-
model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
127 |
-
)
|
128 |
-
else:
|
129 |
-
llm = HuggingFaceHub(
|
130 |
-
repo_id=llm_model,
|
131 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
132 |
-
model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
133 |
-
)
|
134 |
-
|
135 |
progress(0.75, desc="Defining buffer memory...")
|
136 |
-
memory = ConversationBufferMemory(
|
137 |
-
|
138 |
-
output_key='answer',
|
139 |
-
return_messages=True
|
140 |
-
)
|
141 |
-
# retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
|
142 |
-
retriever=vector_db.as_retriever()
|
143 |
progress(0.8, desc="Defining retrieval chain...")
|
144 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
145 |
llm,
|
146 |
retriever=retriever,
|
147 |
-
chain_type="stuff",
|
148 |
memory=memory,
|
149 |
-
# combine_docs_chain_kwargs={"prompt": your_prompt})
|
150 |
return_source_documents=True,
|
151 |
-
# return_generated_question=True,
|
152 |
-
# verbose=True,
|
153 |
)
|
154 |
progress(0.9, desc="Done!")
|
155 |
return qa_chain
|
156 |
|
157 |
-
|
158 |
-
# Initialize database
|
159 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
160 |
-
# Create list of documents (when valid)
|
161 |
-
#file_path = file_obj.name
|
162 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
163 |
collection_name = Path(list_file_path[0]).stem
|
164 |
-
# print('list_file_path: ', list_file_path)
|
165 |
-
# print('Collection name: ', collection_name)
|
166 |
progress(0.25, desc="Loading document...")
|
167 |
-
# Load document and create splits
|
168 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
169 |
-
# Create or load Vector database
|
170 |
progress(0.5, desc="Generating vector database...")
|
171 |
-
# global vector_db
|
172 |
vector_db = create_db(doc_splits, collection_name)
|
173 |
progress(0.9, desc="Done!")
|
174 |
return vector_db, collection_name, "Complete!"
|
175 |
|
176 |
-
|
177 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
178 |
-
|
179 |
-
llm_name = list_llm[llm_option]
|
180 |
-
print("llm_name: ",llm_name)
|
181 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
182 |
return qa_chain, "Complete!"
|
183 |
|
184 |
-
|
185 |
def format_chat_history(message, chat_history):
|
186 |
-
formatted_chat_history = []
|
187 |
-
for user_message, bot_message in chat_history:
|
188 |
-
formatted_chat_history.append(f"User: {user_message}")
|
189 |
-
formatted_chat_history.append(f"Assistant: {bot_message}")
|
190 |
return formatted_chat_history
|
191 |
-
|
192 |
|
193 |
def conversation(qa_chain, message, history):
|
194 |
formatted_chat_history = format_chat_history(message, history)
|
195 |
-
#print("formatted_chat_history",formatted_chat_history)
|
196 |
-
|
197 |
-
# Generate response using QA chain
|
198 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
199 |
response_answer = response["answer"]
|
200 |
response_sources = response["source_documents"]
|
201 |
response_source1 = response_sources[0].page_content.strip()
|
202 |
response_source2 = response_sources[1].page_content.strip()
|
203 |
-
# Langchain sources are zero-based
|
204 |
response_source1_page = response_sources[0].metadata["page"] + 1
|
205 |
response_source2_page = response_sources[1].metadata["page"] + 1
|
206 |
-
# print ('chat response: ', response_answer)
|
207 |
-
# print('DB source', response_sources)
|
208 |
-
|
209 |
-
# Append user message and response to chat history
|
210 |
new_history = history + [(message, response_answer)]
|
211 |
-
# return gr.update(value=""), new_history, response_sources[0], response_sources[1]
|
212 |
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page
|
213 |
-
|
214 |
|
215 |
def upload_file(file_obj):
|
216 |
-
list_file_path = []
|
217 |
-
for idx, file in enumerate(file_obj):
|
218 |
-
file_path = file_obj.name
|
219 |
-
list_file_path.append(file_path)
|
220 |
-
# print(file_path)
|
221 |
-
# initialize_database(file_path, progress)
|
222 |
return list_file_path
|
223 |
|
224 |
-
|
225 |
def demo():
|
226 |
with gr.Blocks(theme="base") as demo:
|
227 |
vector_db = gr.State()
|
228 |
qa_chain = gr.State()
|
229 |
collection_name = gr.State()
|
230 |
-
|
231 |
-
gr.Markdown(
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
<br><b>Warning:</b> This space uses the free CPU Basic hardware from Hugging Face. Some steps and LLM models used below (free inference endpoints) can take some time to generate an output.<br>
|
237 |
-
""")
|
238 |
-
with gr.Tab("Step 1 - Document pre-processing"):
|
239 |
-
with gr.Row():
|
240 |
-
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
|
241 |
-
# upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
|
242 |
-
with gr.Row():
|
243 |
-
db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
|
244 |
with gr.Accordion("Advanced options - Document text splitter", open=False):
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
with gr.Row():
|
250 |
-
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
251 |
-
with gr.Row():
|
252 |
-
db_btn = gr.Button("Generate vector database...")
|
253 |
-
|
254 |
-
with gr.Tab("Step 2 - QA chain initialization"):
|
255 |
-
with gr.Row():
|
256 |
-
llm_btn = gr.Radio(list_llm_simple, \
|
257 |
-
label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")
|
258 |
-
with gr.Accordion("Advanced options - LLM model", open=False):
|
259 |
-
with gr.Row():
|
260 |
-
slider_temperature = gr.Slider(minimum = 0.0, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
|
261 |
-
with gr.Row():
|
262 |
-
slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
|
263 |
-
with gr.Row():
|
264 |
-
slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
|
265 |
-
with gr.Row():
|
266 |
-
llm_progress = gr.Textbox(value="None",label="QA chain initialization")
|
267 |
-
with gr.Row():
|
268 |
-
qachain_btn = gr.Button("Initialize question-answering chain...")
|
269 |
|
270 |
-
with gr.Tab("Step
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
271 |
chatbot = gr.Chatbot(height=300)
|
272 |
-
with gr.Accordion("Advanced - Document references", open=
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
# Preprocessing events
|
286 |
-
#upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
|
287 |
-
db_btn.click(initialize_database, \
|
288 |
-
inputs=[document, slider_chunk_size, slider_chunk_overlap], \
|
289 |
-
outputs=[vector_db, collection_name, db_progress])
|
290 |
-
qachain_btn.click(initialize_LLM, \
|
291 |
-
inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
|
292 |
-
outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0], \
|
293 |
-
inputs=None, \
|
294 |
-
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], \
|
295 |
-
queue=False)
|
296 |
|
297 |
-
# Chatbot events
|
298 |
-
msg.submit(conversation, \
|
299 |
-
inputs=[qa_chain, msg, chatbot], \
|
300 |
-
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], \
|
301 |
-
queue=False)
|
302 |
-
submit_btn.click(conversation, \
|
303 |
-
inputs=[qa_chain, msg, chatbot], \
|
304 |
-
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], \
|
305 |
-
queue=False)
|
306 |
-
clear_btn.click(lambda:[None,"",0,"",0], \
|
307 |
-
inputs=None, \
|
308 |
-
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], \
|
309 |
-
queue=False)
|
310 |
demo.queue().launch(debug=True)
|
311 |
|
312 |
-
|
313 |
if __name__ == "__main__":
|
314 |
-
demo()
|
|
|
1 |
import gradio as gr
|
2 |
import os
|
|
|
3 |
from langchain.document_loaders import PyPDFLoader
|
4 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
from langchain.vectorstores import Chroma
|
6 |
from langchain.chains import ConversationalRetrievalChain
|
7 |
from langchain.embeddings import HuggingFaceEmbeddings
|
|
|
|
|
|
|
8 |
from langchain.llms import HuggingFaceHub
|
|
|
9 |
from pathlib import Path
|
10 |
import chromadb
|
11 |
|
12 |
+
llm_names = ["mistralai/Mixtral-8x7B-Instruct-v0.1"]
|
13 |
+
llm_names_simple = [os.path.basename(llm) for llm in llm_names]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
|
|
15 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
|
|
|
|
|
|
16 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
17 |
+
pages = [loader.load() for loader in loaders]
|
18 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
|
|
|
|
|
|
|
|
|
|
19 |
doc_splits = text_splitter.split_documents(pages)
|
20 |
return doc_splits
|
21 |
|
|
|
|
|
22 |
def create_db(splits, collection_name):
|
23 |
embedding = HuggingFaceEmbeddings()
|
24 |
new_client = chromadb.EphemeralClient()
|
|
|
27 |
embedding=embedding,
|
28 |
client=new_client,
|
29 |
collection_name=collection_name,
|
|
|
30 |
)
|
31 |
return vectordb
|
32 |
|
|
|
|
|
33 |
def load_db():
|
34 |
embedding = HuggingFaceEmbeddings()
|
35 |
+
vectordb = Chroma(embedding_function=embedding)
|
|
|
|
|
36 |
return vectordb
|
37 |
|
|
|
|
|
38 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
39 |
progress(0.1, desc="Initializing HF tokenizer...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
progress(0.5, desc="Initializing HF Hub...")
|
41 |
+
model_kwargs = {"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
|
|
|
|
42 |
if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
|
43 |
+
model_kwargs["load_in_8bit"] = True
|
44 |
+
llm = HuggingFaceHub(repo_id=llm_model, model_kwargs=model_kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
progress(0.75, desc="Defining buffer memory...")
|
46 |
+
memory = ConversationBufferMemory(memory_key="chat_history", output_key='answer', return_messages=True)
|
47 |
+
retriever = vector_db.as_retriever()
|
|
|
|
|
|
|
|
|
|
|
48 |
progress(0.8, desc="Defining retrieval chain...")
|
49 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
50 |
llm,
|
51 |
retriever=retriever,
|
52 |
+
chain_type="stuff",
|
53 |
memory=memory,
|
|
|
54 |
return_source_documents=True,
|
|
|
|
|
55 |
)
|
56 |
progress(0.9, desc="Done!")
|
57 |
return qa_chain
|
58 |
|
|
|
|
|
59 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
|
|
|
|
60 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
61 |
collection_name = Path(list_file_path[0]).stem
|
|
|
|
|
62 |
progress(0.25, desc="Loading document...")
|
|
|
63 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
|
|
64 |
progress(0.5, desc="Generating vector database...")
|
|
|
65 |
vector_db = create_db(doc_splits, collection_name)
|
66 |
progress(0.9, desc="Done!")
|
67 |
return vector_db, collection_name, "Complete!"
|
68 |
|
|
|
69 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
70 |
+
llm_name = llm_names[llm_option]
|
|
|
|
|
71 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
72 |
return qa_chain, "Complete!"
|
73 |
|
|
|
74 |
def format_chat_history(message, chat_history):
|
75 |
+
formatted_chat_history = [f"User: {user_message}\nAssistant: {bot_message}" for user_message, bot_message in chat_history]
|
|
|
|
|
|
|
76 |
return formatted_chat_history
|
|
|
77 |
|
78 |
def conversation(qa_chain, message, history):
|
79 |
formatted_chat_history = format_chat_history(message, history)
|
|
|
|
|
|
|
80 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
81 |
response_answer = response["answer"]
|
82 |
response_sources = response["source_documents"]
|
83 |
response_source1 = response_sources[0].page_content.strip()
|
84 |
response_source2 = response_sources[1].page_content.strip()
|
|
|
85 |
response_source1_page = response_sources[0].metadata["page"] + 1
|
86 |
response_source2_page = response_sources[1].metadata["page"] + 1
|
|
|
|
|
|
|
|
|
87 |
new_history = history + [(message, response_answer)]
|
|
|
88 |
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page
|
|
|
89 |
|
90 |
def upload_file(file_obj):
|
91 |
+
list_file_path = [file_obj.name for _ in file_obj]
|
|
|
|
|
|
|
|
|
|
|
92 |
return list_file_path
|
93 |
|
|
|
94 |
def demo():
|
95 |
with gr.Blocks(theme="base") as demo:
|
96 |
vector_db = gr.State()
|
97 |
qa_chain = gr.State()
|
98 |
collection_name = gr.State()
|
99 |
+
|
100 |
+
gr.Markdown("""<center><h2>ChatPDF</center></h2>""")
|
101 |
+
|
102 |
+
with gr.Tab("Step 1 - Selezione PDF"):
|
103 |
+
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
|
104 |
+
db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value="ChromaDB", type="index", info="Choose your vector database")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
with gr.Accordion("Advanced options - Document text splitter", open=False):
|
106 |
+
slider_chunk_size = gr.Slider(minimum=100, maximum=1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
|
107 |
+
slider_chunk_overlap = gr.Slider(minimum=10, maximum=200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
|
108 |
+
db_progress = gr.Textbox(label="Vector database initialization", value="None")
|
109 |
+
db_btn.click(initialize_database, inputs=[document, slider_chunk_size, slider_chunk_overlap], outputs=[vector_db, collection_name, db_progress])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
|
111 |
+
with gr.Tab("Step 2 - Inizializzazione QA"):
|
112 |
+
llm_btn = gr.Radio(llm_names_simple, label="LLM models", value=llm_names_simple[0], type="index", info="Choose your LLM model")
|
113 |
+
with gr.Accordion("Advanced options - LLM model", open=False):
|
114 |
+
slider_temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
|
115 |
+
slider_maxtokens = gr.Slider(minimum=224, maximum=4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
|
116 |
+
slider_topk = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
|
117 |
+
llm_progress = gr.Textbox(value="None", label="QA chain initialization")
|
118 |
+
qachain_btn = gr.Button("Initialize question-answering chain...")
|
119 |
+
qachain_btn.click(initialize_LLM, inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], outputs=[qa_chain, llm_progress]).then(lambda: [None, "", 0, "", 0], inputs=None, outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], queue=False)
|
120 |
+
|
121 |
+
with gr.Tab("Step 3 - Conversazione con Chatbot"):
|
122 |
chatbot = gr.Chatbot(height=300)
|
123 |
+
with gr.Accordion("Advanced - Document references", open=True):
|
124 |
+
doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
|
125 |
+
source1_page = gr.Number(label="Page", scale=1)
|
126 |
+
doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
|
127 |
+
source2_page = gr.Number(label="Page", scale=1)
|
128 |
+
msg = gr.Textbox(placeholder="Type message", container=True)
|
129 |
+
submit_btn = gr.Button("Submit")
|
130 |
+
clear_btn = gr.ClearButton([msg, chatbot])
|
131 |
+
|
132 |
+
msg.submit(conversation, inputs=[qa_chain, msg, chatbot], outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], queue=False)
|
133 |
+
submit_btn.click(conversation, inputs=[qa_chain, msg, chatbot], outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page], queue=False)
|
134 |
+
clear_btn.click(lambda: [None, "", 0, "", 0], inputs=None, outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page], queue=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
demo.queue().launch(debug=True)
|
137 |
|
|
|
138 |
if __name__ == "__main__":
|
139 |
+
demo()
|