Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
from langchain_community.document_loaders import PyPDFLoader
|
3 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
@@ -5,60 +6,135 @@ from langchain_community.embeddings import HuggingFaceEmbeddings
|
|
5 |
from langchain_community.vectorstores import FAISS
|
6 |
from langchain.chains import RetrievalQA
|
7 |
from langchain_community.llms import HuggingFaceHub
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
# Configurações
|
10 |
EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
|
11 |
-
LLM_REPO_ID = "google/flan-t5-large"
|
12 |
-
|
13 |
-
# Função para carregar e processar PDFs
|
14 |
-
def load_and_process_pdf(pdf_path):
|
15 |
-
# Carrega o PDF
|
16 |
-
loader = PyPDFLoader(pdf_path)
|
17 |
-
documents = loader.load()
|
18 |
-
|
19 |
-
# Divide o texto em chunks
|
20 |
-
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
21 |
-
texts = text_splitter.split_documents(documents)
|
22 |
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
-
|
30 |
-
|
|
|
|
|
31 |
if pdf_file is None:
|
32 |
return "Erro: Nenhum arquivo PDF foi carregado."
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
# Interface Gradio
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
-
|
|
|
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
from langchain_community.document_loaders import PyPDFLoader
|
4 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
6 |
from langchain_community.vectorstores import FAISS
|
7 |
from langchain.chains import RetrievalQA
|
8 |
from langchain_community.llms import HuggingFaceHub
|
9 |
+
from typing import Optional
|
10 |
+
import tempfile
|
11 |
+
|
12 |
+
# Configuração do token da Hugging Face (deve ser definido como variável de ambiente)
|
13 |
+
HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_API_TOKEN")
|
14 |
+
if not HUGGINGFACE_API_TOKEN:
|
15 |
+
raise ValueError("Por favor, defina a variável de ambiente HUGGINGFACE_API_TOKEN")
|
16 |
|
17 |
# Configurações
|
18 |
EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
|
19 |
+
LLM_REPO_ID = "google/flan-t5-large"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
+
def create_temporary_file(file_obj) -> str:
|
22 |
+
"""Cria um arquivo temporário a partir do objeto de arquivo do Gradio."""
|
23 |
+
temp_dir = tempfile.mkdtemp()
|
24 |
+
temp_path = os.path.join(temp_dir, "temp.pdf")
|
25 |
+
|
26 |
+
with open(temp_path, 'wb') as f:
|
27 |
+
f.write(file_obj.read())
|
28 |
+
|
29 |
+
return temp_path
|
30 |
|
31 |
+
def load_and_process_pdf(pdf_path: str) -> Optional[FAISS]:
|
32 |
+
"""
|
33 |
+
Carrega e processa o PDF, com tratamento de erros adequado.
|
34 |
+
"""
|
35 |
+
try:
|
36 |
+
# Carrega o PDF
|
37 |
+
loader = PyPDFLoader(pdf_path)
|
38 |
+
documents = loader.load()
|
39 |
+
|
40 |
+
if not documents:
|
41 |
+
return None
|
42 |
+
|
43 |
+
# Divide o texto em chunks
|
44 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
45 |
+
chunk_size=1000,
|
46 |
+
chunk_overlap=200,
|
47 |
+
length_function=len
|
48 |
+
)
|
49 |
+
texts = text_splitter.split_documents(documents)
|
50 |
+
|
51 |
+
# Cria embeddings e armazena no vetor store
|
52 |
+
embeddings = HuggingFaceEmbeddings(
|
53 |
+
model_name=EMBEDDING_MODEL,
|
54 |
+
model_kwargs={'device': 'cpu'}
|
55 |
+
)
|
56 |
+
db = FAISS.from_documents(texts, embeddings)
|
57 |
+
|
58 |
+
return db
|
59 |
+
|
60 |
+
except Exception as e:
|
61 |
+
print(f"Erro ao processar o PDF: {str(e)}")
|
62 |
+
return None
|
63 |
|
64 |
+
def generate_response(pdf_file: Optional[tempfile._TemporaryFileWrapper], query: str) -> str:
|
65 |
+
"""
|
66 |
+
Gera resposta para a consulta usando RAG, com tratamento de erros.
|
67 |
+
"""
|
68 |
if pdf_file is None:
|
69 |
return "Erro: Nenhum arquivo PDF foi carregado."
|
70 |
+
|
71 |
+
if not query.strip():
|
72 |
+
return "Erro: Por favor, insira uma pergunta."
|
73 |
+
|
74 |
+
try:
|
75 |
+
# Cria arquivo temporário e processa o PDF
|
76 |
+
temp_path = create_temporary_file(pdf_file)
|
77 |
+
db = load_and_process_pdf(temp_path)
|
78 |
+
|
79 |
+
if db is None:
|
80 |
+
return "Erro: Não foi possível processar o PDF."
|
81 |
+
|
82 |
+
# Configura o modelo de linguagem
|
83 |
+
llm = HuggingFaceHub(
|
84 |
+
repo_id=LLM_REPO_ID,
|
85 |
+
huggingfacehub_api_token=HUGGINGFACE_API_TOKEN,
|
86 |
+
model_kwargs={
|
87 |
+
"temperature": 0.7,
|
88 |
+
"max_length": 512,
|
89 |
+
"top_p": 0.95
|
90 |
+
}
|
91 |
+
)
|
92 |
+
|
93 |
+
# Cria a cadeia de RAG
|
94 |
+
qa_chain = RetrievalQA.from_chain_type(
|
95 |
+
llm=llm,
|
96 |
+
chain_type="stuff",
|
97 |
+
retriever=db.as_retriever(search_kwargs={"k": 3}),
|
98 |
+
return_source_documents=True,
|
99 |
+
verbose=True
|
100 |
+
)
|
101 |
+
|
102 |
+
# Executa a consulta
|
103 |
+
result = qa_chain({"query": query})
|
104 |
+
|
105 |
+
# Limpa arquivos temporários
|
106 |
+
os.remove(temp_path)
|
107 |
+
|
108 |
+
return result["result"]
|
109 |
+
|
110 |
+
except Exception as e:
|
111 |
+
return f"Erro ao gerar resposta: {str(e)}"
|
112 |
|
113 |
# Interface Gradio
|
114 |
+
def create_interface():
|
115 |
+
"""Cria e configura a interface Gradio."""
|
116 |
+
return gr.Interface(
|
117 |
+
fn=generate_response,
|
118 |
+
inputs=[
|
119 |
+
gr.File(
|
120 |
+
label="Upload PDF",
|
121 |
+
type="binary", # Alterado para binary
|
122 |
+
file_types=[".pdf"]
|
123 |
+
),
|
124 |
+
gr.Textbox(
|
125 |
+
label="Sua Pergunta",
|
126 |
+
placeholder="Digite sua pergunta aqui..."
|
127 |
+
)
|
128 |
+
],
|
129 |
+
outputs=gr.Textbox(label="Resposta Gerada"),
|
130 |
+
title="Sistema de RAG com LangChain",
|
131 |
+
description="Faça upload de um PDF e faça perguntas sobre o conteúdo.",
|
132 |
+
examples=[
|
133 |
+
[None, "Qual é o principal tema deste documento?"],
|
134 |
+
[None, "Pode resumir os pontos principais?"]
|
135 |
+
]
|
136 |
+
)
|
137 |
|
138 |
+
if __name__ == "__main__":
|
139 |
+
iface = create_interface()
|
140 |
+
iface.launch(share=True)
|