Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -22,8 +22,6 @@ import tqdm
|
|
22 |
import accelerate
|
23 |
import re
|
24 |
|
25 |
-
|
26 |
-
|
27 |
# default_persist_directory = './chroma_HF/'
|
28 |
list_llm = [
|
29 |
"mistralai/Mistral-7B-Instruct-v0.2",
|
@@ -43,21 +41,16 @@ list_llm_simple = [os.path.basename(llm) for llm in list_llm]
|
|
43 |
|
44 |
# Load PDF document and create doc splits
|
45 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
46 |
-
# Processing for one document only
|
47 |
-
# loader = PyPDFLoader(file_path)
|
48 |
-
# pages = loader.load()
|
49 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
50 |
pages = []
|
51 |
for loader in loaders:
|
52 |
pages.extend(loader.load())
|
53 |
-
# text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
|
54 |
text_splitter = RecursiveCharacterTextSplitter(
|
55 |
chunk_size = chunk_size,
|
56 |
chunk_overlap = chunk_overlap)
|
57 |
doc_splits = text_splitter.split_documents(pages)
|
58 |
return doc_splits
|
59 |
|
60 |
-
|
61 |
# Create vector database
|
62 |
def create_db(splits, collection_name):
|
63 |
embedding = HuggingFaceEmbeddings()
|
@@ -67,70 +60,33 @@ def create_db(splits, collection_name):
|
|
67 |
embedding=embedding,
|
68 |
client=new_client,
|
69 |
collection_name=collection_name,
|
70 |
-
# persist_directory=default_persist_directory
|
71 |
)
|
72 |
return vectordb
|
73 |
|
74 |
-
|
75 |
# Load vector database
|
76 |
def load_db():
|
77 |
embedding = HuggingFaceEmbeddings()
|
78 |
vectordb = Chroma(
|
79 |
-
# persist_directory=default_persist_directory,
|
80 |
embedding_function=embedding)
|
81 |
return vectordb
|
82 |
|
83 |
-
|
84 |
# Initialize langchain LLM chain
|
85 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
86 |
-
progress(0.1, desc="
|
87 |
-
|
88 |
-
# Note: it will download model locally...
|
89 |
-
# tokenizer=AutoTokenizer.from_pretrained(llm_model)
|
90 |
-
# progress(0.5, desc="Initializing HF pipeline...")
|
91 |
-
# pipeline=transformers.pipeline(
|
92 |
-
# "text-generation",
|
93 |
-
# model=llm_model,
|
94 |
-
# tokenizer=tokenizer,
|
95 |
-
# torch_dtype=torch.bfloat16,
|
96 |
-
# trust_remote_code=True,
|
97 |
-
# device_map="auto",
|
98 |
-
# # max_length=1024,
|
99 |
-
# max_new_tokens=max_tokens,
|
100 |
-
# do_sample=True,
|
101 |
-
# top_k=top_k,
|
102 |
-
# num_return_sequences=1,
|
103 |
-
# eos_token_id=tokenizer.eos_token_id
|
104 |
-
# )
|
105 |
-
# llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
|
106 |
-
|
107 |
-
# HuggingFaceHub uses HF inference endpoints
|
108 |
-
progress(0.5, desc="Initializing HF Hub...")
|
109 |
-
# Use of trust_remote_code as model_kwargs
|
110 |
-
# Warning: langchain issue
|
111 |
-
# URL: https://github.com/langchain-ai/langchain/issues/6080
|
112 |
if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
|
113 |
llm = HuggingFaceEndpoint(
|
114 |
repo_id=llm_model,
|
115 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True}
|
116 |
temperature = temperature,
|
117 |
max_new_tokens = max_tokens,
|
118 |
top_k = top_k,
|
119 |
load_in_8bit = True,
|
120 |
)
|
121 |
elif llm_model in ["HuggingFaceH4/zephyr-7b-gemma-v0.1","mosaicml/mpt-7b-instruct"]:
|
122 |
-
raise gr.Error("LLM
|
123 |
-
llm = HuggingFaceEndpoint(
|
124 |
-
repo_id=llm_model,
|
125 |
-
temperature = temperature,
|
126 |
-
max_new_tokens = max_tokens,
|
127 |
-
top_k = top_k,
|
128 |
-
)
|
129 |
elif llm_model == "microsoft/phi-2":
|
130 |
-
# raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")
|
131 |
llm = HuggingFaceEndpoint(
|
132 |
repo_id=llm_model,
|
133 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
134 |
temperature = temperature,
|
135 |
max_new_tokens = max_tokens,
|
136 |
top_k = top_k,
|
@@ -140,221 +96,172 @@ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, pr
|
|
140 |
elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
|
141 |
llm = HuggingFaceEndpoint(
|
142 |
repo_id=llm_model,
|
143 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}
|
144 |
temperature = temperature,
|
145 |
max_new_tokens = 250,
|
146 |
top_k = top_k,
|
147 |
)
|
148 |
elif llm_model == "meta-llama/Llama-2-7b-chat-hf":
|
149 |
-
raise gr.Error("Llama-2-7b-chat-hf
|
150 |
-
llm = HuggingFaceEndpoint(
|
151 |
-
repo_id=llm_model,
|
152 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
153 |
-
temperature = temperature,
|
154 |
-
max_new_tokens = max_tokens,
|
155 |
-
top_k = top_k,
|
156 |
-
)
|
157 |
else:
|
158 |
llm = HuggingFaceEndpoint(
|
159 |
repo_id=llm_model,
|
160 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
|
161 |
-
# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
|
162 |
temperature = temperature,
|
163 |
max_new_tokens = max_tokens,
|
164 |
top_k = top_k,
|
165 |
)
|
166 |
|
167 |
-
progress(0.75, desc="
|
168 |
memory = ConversationBufferMemory(
|
169 |
memory_key="chat_history",
|
170 |
output_key='answer',
|
171 |
return_messages=True
|
172 |
)
|
173 |
-
# retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
|
174 |
retriever=vector_db.as_retriever()
|
175 |
-
progress(0.8, desc="
|
176 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
177 |
llm,
|
178 |
retriever=retriever,
|
179 |
chain_type="stuff",
|
180 |
memory=memory,
|
181 |
-
# combine_docs_chain_kwargs={"prompt": your_prompt})
|
182 |
return_source_documents=True,
|
183 |
-
#return_generated_question=False,
|
184 |
verbose=False,
|
185 |
)
|
186 |
-
progress(0.9, desc="
|
187 |
return qa_chain
|
188 |
|
189 |
-
|
190 |
# Generate collection name for vector database
|
191 |
-
# - Use filepath as input, ensuring unicode text
|
192 |
def create_collection_name(filepath):
|
193 |
-
# Extract filename without extension
|
194 |
collection_name = Path(filepath).stem
|
195 |
-
# Fix potential issues from naming convention
|
196 |
-
## Remove space
|
197 |
collection_name = collection_name.replace(" ","-")
|
198 |
-
## ASCII transliterations of Unicode text
|
199 |
collection_name = unidecode(collection_name)
|
200 |
-
## Remove special characters
|
201 |
-
#collection_name = re.findall("[\dA-Za-z]*", collection_name)[0]
|
202 |
collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
|
203 |
-
## Limit length to 50 characters
|
204 |
collection_name = collection_name[:50]
|
205 |
-
## Minimum length of 3 characters
|
206 |
if len(collection_name) < 3:
|
207 |
collection_name = collection_name + 'xyz'
|
208 |
-
## Enforce start and end as alphanumeric character
|
209 |
if not collection_name[0].isalnum():
|
210 |
collection_name = 'A' + collection_name[1:]
|
211 |
if not collection_name[-1].isalnum():
|
212 |
collection_name = collection_name[:-1] + 'Z'
|
213 |
-
print('
|
214 |
-
print('
|
215 |
return collection_name
|
216 |
|
217 |
-
|
218 |
# Initialize database
|
219 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
220 |
-
# Create list of documents (when valid)
|
221 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
222 |
-
|
223 |
-
progress(0.1, desc="Creating collection name...")
|
224 |
collection_name = create_collection_name(list_file_path[0])
|
225 |
-
progress(0.25, desc="
|
226 |
-
# Load document and create splits
|
227 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
228 |
-
|
229 |
-
progress(0.5, desc="Generating vector database...")
|
230 |
-
# global vector_db
|
231 |
vector_db = create_db(doc_splits, collection_name)
|
232 |
-
progress(0.9, desc="
|
233 |
-
return vector_db, collection_name, "
|
234 |
-
|
235 |
|
236 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
237 |
-
# print("llm_option",llm_option)
|
238 |
llm_name = list_llm[llm_option]
|
239 |
-
print("
|
240 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
241 |
-
return qa_chain, "
|
242 |
-
|
243 |
|
244 |
def format_chat_history(message, chat_history):
|
245 |
formatted_chat_history = []
|
246 |
for user_message, bot_message in chat_history:
|
247 |
-
formatted_chat_history.append(f"
|
248 |
-
formatted_chat_history.append(f"
|
249 |
return formatted_chat_history
|
250 |
-
|
251 |
|
252 |
def conversation(qa_chain, message, history):
|
253 |
formatted_chat_history = format_chat_history(message, history)
|
254 |
-
#print("formatted_chat_history",formatted_chat_history)
|
255 |
-
|
256 |
-
# Generate response using QA chain
|
257 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
258 |
response_answer = response["answer"]
|
259 |
-
if response_answer.find("
|
260 |
-
response_answer = response_answer.split("
|
261 |
response_sources = response["source_documents"]
|
262 |
response_source1 = response_sources[0].page_content.strip()
|
263 |
response_source2 = response_sources[1].page_content.strip()
|
264 |
response_source3 = response_sources[2].page_content.strip()
|
265 |
-
# Langchain sources are zero-based
|
266 |
response_source1_page = response_sources[0].metadata["page"] + 1
|
267 |
response_source2_page = response_sources[1].metadata["page"] + 1
|
268 |
response_source3_page = response_sources[2].metadata["page"] + 1
|
269 |
-
# print ('chat response: ', response_answer)
|
270 |
-
# print('DB source', response_sources)
|
271 |
-
|
272 |
-
# Append user message and response to chat history
|
273 |
new_history = history + [(message, response_answer)]
|
274 |
-
# return gr.update(value=""), new_history, response_sources[0], response_sources[1]
|
275 |
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
276 |
-
|
277 |
|
278 |
def upload_file(file_obj):
|
279 |
list_file_path = []
|
280 |
for idx, file in enumerate(file_obj):
|
281 |
file_path = file_obj.name
|
282 |
list_file_path.append(file_path)
|
283 |
-
# print(file_path)
|
284 |
-
# initialize_database(file_path, progress)
|
285 |
return list_file_path
|
286 |
|
287 |
-
|
288 |
def demo():
|
289 |
-
with gr.Blocks(theme="
|
290 |
vector_db = gr.State()
|
291 |
qa_chain = gr.State()
|
292 |
collection_name = gr.State()
|
293 |
|
294 |
gr.Markdown(
|
295 |
-
"""<center><h2>PDF
|
296 |
-
<h3>
|
297 |
gr.Markdown(
|
298 |
-
"""<b>
|
299 |
-
|
300 |
-
|
301 |
-
<br><b>
|
302 |
""")
|
303 |
|
304 |
-
with gr.Tab("
|
305 |
with gr.Row():
|
306 |
-
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="
|
307 |
-
# upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
|
308 |
|
309 |
-
with gr.Tab("
|
310 |
with gr.Row():
|
311 |
-
db_btn = gr.Radio(["ChromaDB"], label="
|
312 |
-
with gr.Accordion("
|
313 |
with gr.Row():
|
314 |
-
slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="
|
315 |
with gr.Row():
|
316 |
-
slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="
|
317 |
with gr.Row():
|
318 |
-
db_progress = gr.Textbox(label="
|
319 |
with gr.Row():
|
320 |
-
db_btn = gr.Button("
|
321 |
|
322 |
-
with gr.Tab("
|
323 |
with gr.Row():
|
324 |
llm_btn = gr.Radio(list_llm_simple, \
|
325 |
-
label="LLM
|
326 |
-
with gr.Accordion("
|
327 |
with gr.Row():
|
328 |
-
slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.7, step=0.1, label="
|
329 |
with gr.Row():
|
330 |
-
slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="
|
331 |
with gr.Row():
|
332 |
-
slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k
|
333 |
with gr.Row():
|
334 |
-
llm_progress = gr.Textbox(value="
|
335 |
with gr.Row():
|
336 |
-
qachain_btn = gr.Button("
|
337 |
|
338 |
-
with gr.Tab("
|
339 |
chatbot = gr.Chatbot(height=300)
|
340 |
-
with gr.Accordion("
|
341 |
with gr.Row():
|
342 |
-
doc_source1 = gr.Textbox(label="
|
343 |
-
source1_page = gr.Number(label="
|
344 |
with gr.Row():
|
345 |
-
doc_source2 = gr.Textbox(label="
|
346 |
-
source2_page = gr.Number(label="
|
347 |
with gr.Row():
|
348 |
-
doc_source3 = gr.Textbox(label="
|
349 |
-
source3_page = gr.Number(label="
|
350 |
with gr.Row():
|
351 |
-
msg = gr.Textbox(placeholder="
|
352 |
with gr.Row():
|
353 |
-
submit_btn = gr.Button("
|
354 |
-
clear_btn = gr.ClearButton([msg, chatbot], value="
|
355 |
|
356 |
# Preprocessing events
|
357 |
-
#upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
|
358 |
db_btn.click(initialize_database, \
|
359 |
inputs=[document, slider_chunk_size, slider_chunk_overlap], \
|
360 |
outputs=[vector_db, collection_name, db_progress])
|
@@ -380,6 +287,5 @@ def demo():
|
|
380 |
queue=False)
|
381 |
demo.queue().launch(debug=True)
|
382 |
|
383 |
-
|
384 |
if __name__ == "__main__":
|
385 |
demo()
|
|
|
22 |
import accelerate
|
23 |
import re
|
24 |
|
|
|
|
|
25 |
# default_persist_directory = './chroma_HF/'
|
26 |
list_llm = [
|
27 |
"mistralai/Mistral-7B-Instruct-v0.2",
|
|
|
41 |
|
42 |
# Load PDF document and create doc splits
|
43 |
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
|
|
|
|
|
|
44 |
loaders = [PyPDFLoader(x) for x in list_file_path]
|
45 |
pages = []
|
46 |
for loader in loaders:
|
47 |
pages.extend(loader.load())
|
|
|
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 |
# Create vector database
|
55 |
def create_db(splits, collection_name):
|
56 |
embedding = HuggingFaceEmbeddings()
|
|
|
60 |
embedding=embedding,
|
61 |
client=new_client,
|
62 |
collection_name=collection_name,
|
|
|
63 |
)
|
64 |
return vectordb
|
65 |
|
|
|
66 |
# Load vector database
|
67 |
def load_db():
|
68 |
embedding = HuggingFaceEmbeddings()
|
69 |
vectordb = Chroma(
|
|
|
70 |
embedding_function=embedding)
|
71 |
return vectordb
|
72 |
|
|
|
73 |
# Initialize langchain LLM chain
|
74 |
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
75 |
+
progress(0.1, desc="Inicializando tokenizer da HF...")
|
76 |
+
progress(0.5, desc="Inicializando Hub da HF...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
|
78 |
llm = HuggingFaceEndpoint(
|
79 |
repo_id=llm_model,
|
|
|
80 |
temperature = temperature,
|
81 |
max_new_tokens = max_tokens,
|
82 |
top_k = top_k,
|
83 |
load_in_8bit = True,
|
84 |
)
|
85 |
elif llm_model in ["HuggingFaceH4/zephyr-7b-gemma-v0.1","mosaicml/mpt-7b-instruct"]:
|
86 |
+
raise gr.Error("O modelo LLM é muito grande para ser carregado automaticamente no endpoint de inferência gratuito")
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
elif llm_model == "microsoft/phi-2":
|
|
|
88 |
llm = HuggingFaceEndpoint(
|
89 |
repo_id=llm_model,
|
|
|
90 |
temperature = temperature,
|
91 |
max_new_tokens = max_tokens,
|
92 |
top_k = top_k,
|
|
|
96 |
elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
|
97 |
llm = HuggingFaceEndpoint(
|
98 |
repo_id=llm_model,
|
|
|
99 |
temperature = temperature,
|
100 |
max_new_tokens = 250,
|
101 |
top_k = top_k,
|
102 |
)
|
103 |
elif llm_model == "meta-llama/Llama-2-7b-chat-hf":
|
104 |
+
raise gr.Error("O modelo Llama-2-7b-chat-hf requer uma assinatura Pro...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
else:
|
106 |
llm = HuggingFaceEndpoint(
|
107 |
repo_id=llm_model,
|
|
|
|
|
108 |
temperature = temperature,
|
109 |
max_new_tokens = max_tokens,
|
110 |
top_k = top_k,
|
111 |
)
|
112 |
|
113 |
+
progress(0.75, desc="Definindo memória de buffer...")
|
114 |
memory = ConversationBufferMemory(
|
115 |
memory_key="chat_history",
|
116 |
output_key='answer',
|
117 |
return_messages=True
|
118 |
)
|
|
|
119 |
retriever=vector_db.as_retriever()
|
120 |
+
progress(0.8, desc="Definindo cadeia de recuperação...")
|
121 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
122 |
llm,
|
123 |
retriever=retriever,
|
124 |
chain_type="stuff",
|
125 |
memory=memory,
|
|
|
126 |
return_source_documents=True,
|
|
|
127 |
verbose=False,
|
128 |
)
|
129 |
+
progress(0.9, desc="Concluído!")
|
130 |
return qa_chain
|
131 |
|
|
|
132 |
# Generate collection name for vector database
|
|
|
133 |
def create_collection_name(filepath):
|
|
|
134 |
collection_name = Path(filepath).stem
|
|
|
|
|
135 |
collection_name = collection_name.replace(" ","-")
|
|
|
136 |
collection_name = unidecode(collection_name)
|
|
|
|
|
137 |
collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
|
|
|
138 |
collection_name = collection_name[:50]
|
|
|
139 |
if len(collection_name) < 3:
|
140 |
collection_name = collection_name + 'xyz'
|
|
|
141 |
if not collection_name[0].isalnum():
|
142 |
collection_name = 'A' + collection_name[1:]
|
143 |
if not collection_name[-1].isalnum():
|
144 |
collection_name = collection_name[:-1] + 'Z'
|
145 |
+
print('Caminho do arquivo: ', filepath)
|
146 |
+
print('Nome da coleção: ', collection_name)
|
147 |
return collection_name
|
148 |
|
|
|
149 |
# Initialize database
|
150 |
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
|
|
151 |
list_file_path = [x.name for x in list_file_obj if x is not None]
|
152 |
+
progress(0.1, desc="Criando nome da coleção...")
|
|
|
153 |
collection_name = create_collection_name(list_file_path[0])
|
154 |
+
progress(0.25, desc="Carregando documento...")
|
|
|
155 |
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
156 |
+
progress(0.5, desc="Gerando banco de dados vetorial...")
|
|
|
|
|
157 |
vector_db = create_db(doc_splits, collection_name)
|
158 |
+
progress(0.9, desc="Concluído!")
|
159 |
+
return vector_db, collection_name, "Completo!"
|
|
|
160 |
|
161 |
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
|
|
162 |
llm_name = list_llm[llm_option]
|
163 |
+
print("Nome do LLM: ",llm_name)
|
164 |
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
165 |
+
return qa_chain, "Completo!"
|
|
|
166 |
|
167 |
def format_chat_history(message, chat_history):
|
168 |
formatted_chat_history = []
|
169 |
for user_message, bot_message in chat_history:
|
170 |
+
formatted_chat_history.append(f"Usuário: {user_message}")
|
171 |
+
formatted_chat_history.append(f"Assistente: {bot_message}")
|
172 |
return formatted_chat_history
|
|
|
173 |
|
174 |
def conversation(qa_chain, message, history):
|
175 |
formatted_chat_history = format_chat_history(message, history)
|
|
|
|
|
|
|
176 |
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
177 |
response_answer = response["answer"]
|
178 |
+
if response_answer.find("Resposta útil:") != -1:
|
179 |
+
response_answer = response_answer.split("Resposta útil:")[-1]
|
180 |
response_sources = response["source_documents"]
|
181 |
response_source1 = response_sources[0].page_content.strip()
|
182 |
response_source2 = response_sources[1].page_content.strip()
|
183 |
response_source3 = response_sources[2].page_content.strip()
|
|
|
184 |
response_source1_page = response_sources[0].metadata["page"] + 1
|
185 |
response_source2_page = response_sources[1].metadata["page"] + 1
|
186 |
response_source3_page = response_sources[2].metadata["page"] + 1
|
|
|
|
|
|
|
|
|
187 |
new_history = history + [(message, response_answer)]
|
|
|
188 |
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
|
|
189 |
|
190 |
def upload_file(file_obj):
|
191 |
list_file_path = []
|
192 |
for idx, file in enumerate(file_obj):
|
193 |
file_path = file_obj.name
|
194 |
list_file_path.append(file_path)
|
|
|
|
|
195 |
return list_file_path
|
196 |
|
|
|
197 |
def demo():
|
198 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="gray")) as demo:
|
199 |
vector_db = gr.State()
|
200 |
qa_chain = gr.State()
|
201 |
collection_name = gr.State()
|
202 |
|
203 |
gr.Markdown(
|
204 |
+
"""<center><h2>Chatbot baseado em PDF</center></h2>
|
205 |
+
<h3>Faça perguntas sobre seus documentos PDF</h3>""")
|
206 |
gr.Markdown(
|
207 |
+
"""<b>Nota:</b> Este assistente AI, usando Langchain e LLMs de código aberto, realiza geração aumentada por recuperação (RAG) a partir de seus documentos PDF. \
|
208 |
+
A interface do usuário explicitamente mostra múltiplos passos para ajudar a entender o fluxo de trabalho do RAG.
|
209 |
+
Este chatbot leva em consideração perguntas anteriores ao gerar respostas (via memória conversacional) e inclui referências de documentos para maior clareza.<br>
|
210 |
+
<br><b>Aviso:</b> Este espaço usa o hardware básico gratuito da Hugging Face. Alguns passos e modelos LLM usados abaixo (endpoints de inferência gratuitos) podem levar algum tempo para gerar uma resposta.
|
211 |
""")
|
212 |
|
213 |
+
with gr.Tab("Passo 1 - Carregar PDF"):
|
214 |
with gr.Row():
|
215 |
+
document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Carregue seus documentos PDF (único ou múltiplos)")
|
|
|
216 |
|
217 |
+
with gr.Tab("Passo 2 - Processar documento"):
|
218 |
with gr.Row():
|
219 |
+
db_btn = gr.Radio(["ChromaDB"], label="Tipo de banco de dados vetorial", value = "ChromaDB", type="index", info="Escolha seu banco de dados vetorial")
|
220 |
+
with gr.Accordion("Opções avançadas - Divisor de texto do documento", open=False):
|
221 |
with gr.Row():
|
222 |
+
slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Tamanho do chunk", info="Tamanho do chunk", interactive=True)
|
223 |
with gr.Row():
|
224 |
+
slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Sobreposição do chunk", info="Sobreposição do chunk", interactive=True)
|
225 |
with gr.Row():
|
226 |
+
db_progress = gr.Textbox(label="Inicialização do banco de dados vetorial", value="Nenhum")
|
227 |
with gr.Row():
|
228 |
+
db_btn = gr.Button("Gerar banco de dados vetorial")
|
229 |
|
230 |
+
with gr.Tab("Passo 3 - Inicializar cadeia de QA"):
|
231 |
with gr.Row():
|
232 |
llm_btn = gr.Radio(list_llm_simple, \
|
233 |
+
label="Modelos LLM", value = list_llm_simple[0], type="index", info="Escolha seu modelo LLM")
|
234 |
+
with gr.Accordion("Opções avançadas - Modelo LLM", open=False):
|
235 |
with gr.Row():
|
236 |
+
slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.7, step=0.1, label="Temperatura", info="Temperatura do modelo", interactive=True)
|
237 |
with gr.Row():
|
238 |
+
slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Máximo de Tokens", info="Máximo de tokens do modelo", interactive=True)
|
239 |
with gr.Row():
|
240 |
+
slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="Amostras top-k", info="Amostras top-k do modelo", interactive=True)
|
241 |
with gr.Row():
|
242 |
+
llm_progress = gr.Textbox(value="Nenhum",label="Inicialização da cadeia de QA")
|
243 |
with gr.Row():
|
244 |
+
qachain_btn = gr.Button("Inicializar cadeia de Perguntas e Respostas")
|
245 |
|
246 |
+
with gr.Tab("Passo 4 - Chatbot"):
|
247 |
chatbot = gr.Chatbot(height=300)
|
248 |
+
with gr.Accordion("Avançado - Referências de documentos", open=False):
|
249 |
with gr.Row():
|
250 |
+
doc_source1 = gr.Textbox(label="Referência 1", lines=2, container=True, scale=20)
|
251 |
+
source1_page = gr.Number(label="Página", scale=1)
|
252 |
with gr.Row():
|
253 |
+
doc_source2 = gr.Textbox(label="Referência 2", lines=2, container=True, scale=20)
|
254 |
+
source2_page = gr.Number(label="Página", scale=1)
|
255 |
with gr.Row():
|
256 |
+
doc_source3 = gr.Textbox(label="Referência 3", lines=2, container=True, scale=20)
|
257 |
+
source3_page = gr.Number(label="Página", scale=1)
|
258 |
with gr.Row():
|
259 |
+
msg = gr.Textbox(placeholder="Digite uma mensagem (ex: 'Sobre o que é este documento?')", container=True)
|
260 |
with gr.Row():
|
261 |
+
submit_btn = gr.Button("Enviar mensagem")
|
262 |
+
clear_btn = gr.ClearButton([msg, chatbot], value="Limpar conversa")
|
263 |
|
264 |
# Preprocessing events
|
|
|
265 |
db_btn.click(initialize_database, \
|
266 |
inputs=[document, slider_chunk_size, slider_chunk_overlap], \
|
267 |
outputs=[vector_db, collection_name, db_progress])
|
|
|
287 |
queue=False)
|
288 |
demo.queue().launch(debug=True)
|
289 |
|
|
|
290 |
if __name__ == "__main__":
|
291 |
demo()
|