Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -9,24 +9,22 @@ 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(
|
22 |
-
"""Cria um arquivo temporário a partir
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
|
|
|
|
|
|
30 |
|
31 |
def load_and_process_pdf(pdf_path: str) -> Optional[FAISS]:
|
32 |
"""
|
@@ -61,11 +59,11 @@ def load_and_process_pdf(pdf_path: str) -> Optional[FAISS]:
|
|
61 |
print(f"Erro ao processar o PDF: {str(e)}")
|
62 |
return None
|
63 |
|
64 |
-
def generate_response(
|
65 |
"""
|
66 |
Gera resposta para a consulta usando RAG, com tratamento de erros.
|
67 |
"""
|
68 |
-
if
|
69 |
return "Erro: Nenhum arquivo PDF foi carregado."
|
70 |
|
71 |
if not query.strip():
|
@@ -73,7 +71,7 @@ def generate_response(pdf_file: Optional[tempfile._TemporaryFileWrapper], query:
|
|
73 |
|
74 |
try:
|
75 |
# Cria arquivo temporário e processa o PDF
|
76 |
-
temp_path = create_temporary_file(
|
77 |
db = load_and_process_pdf(temp_path)
|
78 |
|
79 |
if db is None:
|
@@ -82,7 +80,7 @@ def generate_response(pdf_file: Optional[tempfile._TemporaryFileWrapper], query:
|
|
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,
|
@@ -104,6 +102,7 @@ def generate_response(pdf_file: Optional[tempfile._TemporaryFileWrapper], query:
|
|
104 |
|
105 |
# Limpa arquivos temporários
|
106 |
os.remove(temp_path)
|
|
|
107 |
|
108 |
return result["result"]
|
109 |
|
@@ -111,30 +110,43 @@ def generate_response(pdf_file: Optional[tempfile._TemporaryFileWrapper], query:
|
|
111 |
return f"Erro ao gerar resposta: {str(e)}"
|
112 |
|
113 |
# Interface Gradio
|
114 |
-
|
115 |
-
"
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
120 |
label="Upload PDF",
|
121 |
-
type="binary",
|
122 |
file_types=[".pdf"]
|
123 |
-
)
|
124 |
-
gr.Textbox(
|
125 |
label="Sua Pergunta",
|
126 |
-
placeholder="Digite sua pergunta aqui..."
|
|
|
127 |
)
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
140 |
-
iface.launch(share=True)
|
|
|
9 |
from typing import Optional
|
10 |
import tempfile
|
11 |
|
|
|
|
|
|
|
|
|
|
|
12 |
# Configurações
|
13 |
EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
|
14 |
LLM_REPO_ID = "google/flan-t5-large"
|
15 |
|
16 |
+
def create_temporary_file(file_content: bytes) -> str:
|
17 |
+
"""Cria um arquivo temporário a partir dos bytes do arquivo."""
|
18 |
+
try:
|
19 |
+
temp_dir = tempfile.mkdtemp()
|
20 |
+
temp_path = os.path.join(temp_dir, "temp.pdf")
|
21 |
+
|
22 |
+
with open(temp_path, 'wb') as f:
|
23 |
+
f.write(file_content)
|
24 |
+
|
25 |
+
return temp_path
|
26 |
+
except Exception as e:
|
27 |
+
raise Exception(f"Erro ao criar arquivo temporário: {str(e)}")
|
28 |
|
29 |
def load_and_process_pdf(pdf_path: str) -> Optional[FAISS]:
|
30 |
"""
|
|
|
59 |
print(f"Erro ao processar o PDF: {str(e)}")
|
60 |
return None
|
61 |
|
62 |
+
def generate_response(file_obj, query: str) -> str:
|
63 |
"""
|
64 |
Gera resposta para a consulta usando RAG, com tratamento de erros.
|
65 |
"""
|
66 |
+
if file_obj is None:
|
67 |
return "Erro: Nenhum arquivo PDF foi carregado."
|
68 |
|
69 |
if not query.strip():
|
|
|
71 |
|
72 |
try:
|
73 |
# Cria arquivo temporário e processa o PDF
|
74 |
+
temp_path = create_temporary_file(file_obj)
|
75 |
db = load_and_process_pdf(temp_path)
|
76 |
|
77 |
if db is None:
|
|
|
80 |
# Configura o modelo de linguagem
|
81 |
llm = HuggingFaceHub(
|
82 |
repo_id=LLM_REPO_ID,
|
83 |
+
huggingfacehub_api_token=os.environ.get("HUGGINGFACE_API_TOKEN"),
|
84 |
model_kwargs={
|
85 |
"temperature": 0.7,
|
86 |
"max_length": 512,
|
|
|
102 |
|
103 |
# Limpa arquivos temporários
|
104 |
os.remove(temp_path)
|
105 |
+
os.rmdir(os.path.dirname(temp_path))
|
106 |
|
107 |
return result["result"]
|
108 |
|
|
|
110 |
return f"Erro ao gerar resposta: {str(e)}"
|
111 |
|
112 |
# Interface Gradio
|
113 |
+
with gr.Blocks() as demo:
|
114 |
+
gr.Markdown("# Sistema de RAG com LangChain")
|
115 |
+
gr.Markdown("Faça upload de um PDF e faça perguntas sobre o conteúdo.")
|
116 |
+
|
117 |
+
with gr.Row():
|
118 |
+
with gr.Column():
|
119 |
+
file_input = gr.File(
|
120 |
label="Upload PDF",
|
121 |
+
type="binary",
|
122 |
file_types=[".pdf"]
|
123 |
+
)
|
124 |
+
query_input = gr.Textbox(
|
125 |
label="Sua Pergunta",
|
126 |
+
placeholder="Digite sua pergunta aqui...",
|
127 |
+
lines=3
|
128 |
)
|
129 |
+
submit_btn = gr.Button("Enviar Pergunta")
|
130 |
+
|
131 |
+
with gr.Column():
|
132 |
+
output = gr.Textbox(
|
133 |
+
label="Resposta Gerada",
|
134 |
+
lines=10
|
135 |
+
)
|
136 |
+
|
137 |
+
submit_btn.click(
|
138 |
+
fn=generate_response,
|
139 |
+
inputs=[file_input, query_input],
|
140 |
+
outputs=output
|
141 |
+
)
|
142 |
+
|
143 |
+
gr.Examples(
|
144 |
examples=[
|
145 |
[None, "Qual é o principal tema deste documento?"],
|
146 |
[None, "Pode resumir os pontos principais?"]
|
147 |
+
],
|
148 |
+
inputs=[file_input, query_input]
|
149 |
)
|
150 |
|
151 |
if __name__ == "__main__":
|
152 |
+
demo.launch()
|
|