Update frontend/app.py
Browse files- frontend/app.py +23 -15
frontend/app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
#--- START OF FILE app (
|
| 2 |
|
| 3 |
import chainlit as cl
|
| 4 |
import httpx
|
|
@@ -37,27 +37,28 @@ async def start():
|
|
| 37 |
# Inicia a mensagem de "Processando"
|
| 38 |
msg = cl.Message(content=f"Recebido: {file.name}. Processando...", author="Sistema")
|
| 39 |
await msg.send()
|
| 40 |
-
|
| 41 |
-
file_content = None
|
| 42 |
|
| 43 |
try:
|
| 44 |
-
# 1.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
# O Chainlit armazena o arquivo em disco e fornece o caminho (file.path)
|
| 46 |
with open(file.path, "rb") as f:
|
| 47 |
file_content = f.read()
|
| 48 |
|
| 49 |
-
# 2. Obtendo o MIME Type de forma robusta
|
| 50 |
-
# Usa file.type (padrão Chainlit) ou assume PDF
|
| 51 |
-
mime_type = getattr(file, 'type', 'application/pdf')
|
| 52 |
-
|
| 53 |
# 3. Criando o payload para httpx. O formato é (filename, file_content_bytes, mime_type)
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
# 4. Envia o arquivo para o backend
|
| 57 |
async with httpx.AsyncClient(timeout=300) as client:
|
| 58 |
response = await client.post(
|
| 59 |
UPLOAD_URL,
|
| 60 |
-
files=files_payload
|
| 61 |
)
|
| 62 |
|
| 63 |
# Se o upload/processamento for bem-sucedido (200 OK)
|
|
@@ -65,7 +66,7 @@ async def start():
|
|
| 65 |
RAG_INITIALIZED = True
|
| 66 |
# Usa content= para forçar o argumento nomeado e evitar TypeError
|
| 67 |
await msg.update(
|
| 68 |
-
content=f"✅ processado com sucesso! Agora você pode fazer perguntas sobre o conteúdo do documento."
|
| 69 |
)
|
| 70 |
else:
|
| 71 |
RAG_INITIALIZED = False
|
|
@@ -89,7 +90,7 @@ async def main(message: cl.Message):
|
|
| 89 |
|
| 90 |
if not RAG_INITIALIZED:
|
| 91 |
await cl.Message(
|
| 92 |
-
content="Por favor, aguarde o processamento do arquivo ou recarregue a página para um novo upload.",
|
| 93 |
author="Sistema"
|
| 94 |
).send()
|
| 95 |
return
|
|
@@ -105,15 +106,22 @@ async def main(message: cl.Message):
|
|
| 105 |
async with client.stream("POST", CHAT_URL, json={"content": message.content}) as response:
|
| 106 |
# Se a requisição falhar, mostra um erro
|
| 107 |
if response.status_code != 200:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
# Usa content= para forçar o argumento nomeado e evitar TypeError
|
| 109 |
-
await msg.update(content=f"Erro: {
|
| 110 |
return
|
| 111 |
|
| 112 |
# Itera sobre os pedaços (chunks) de texto recebidos do backend
|
| 113 |
async for chunk in response.aiter_text():
|
| 114 |
await msg.stream_token(chunk)
|
| 115 |
|
| 116 |
-
# Finaliza a mensagem.
|
| 117 |
await msg.update()
|
| 118 |
|
| 119 |
except httpx.ConnectError:
|
|
@@ -123,4 +131,4 @@ async def main(message: cl.Message):
|
|
| 123 |
# Usa content= para forçar o argumento nomeado e evitar TypeError
|
| 124 |
await msg.update(content=f"Ocorreu um erro: {e}")
|
| 125 |
|
| 126 |
-
#--- END OF FILE app (
|
|
|
|
| 1 |
+
#--- START OF FILE app (25).py ---
|
| 2 |
|
| 3 |
import chainlit as cl
|
| 4 |
import httpx
|
|
|
|
| 37 |
# Inicia a mensagem de "Processando"
|
| 38 |
msg = cl.Message(content=f"Recebido: {file.name}. Processando...", author="Sistema")
|
| 39 |
await msg.send()
|
|
|
|
|
|
|
| 40 |
|
| 41 |
try:
|
| 42 |
+
# 1. Obtendo o MIME Type de forma robusta
|
| 43 |
+
# Usa file.type (padrão Chainlit) ou assume PDF
|
| 44 |
+
mime_type = getattr(file, 'type', 'application/pdf') or 'application/pdf'
|
| 45 |
+
|
| 46 |
+
# 2. Lendo o conteúdo do arquivo do disco (file.path)
|
| 47 |
# O Chainlit armazena o arquivo em disco e fornece o caminho (file.path)
|
| 48 |
with open(file.path, "rb") as f:
|
| 49 |
file_content = f.read()
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
# 3. Criando o payload para httpx. O formato é (filename, file_content_bytes, mime_type)
|
| 52 |
+
# A chave "file" deve corresponder ao argumento "file" no FastAPI (main (1).py)
|
| 53 |
+
files_payload = {
|
| 54 |
+
"file": (file.name, file_content, mime_type)
|
| 55 |
+
}
|
| 56 |
|
| 57 |
# 4. Envia o arquivo para o backend
|
| 58 |
async with httpx.AsyncClient(timeout=300) as client:
|
| 59 |
response = await client.post(
|
| 60 |
UPLOAD_URL,
|
| 61 |
+
files=files_payload # Note: usando o argumento 'files'
|
| 62 |
)
|
| 63 |
|
| 64 |
# Se o upload/processamento for bem-sucedido (200 OK)
|
|
|
|
| 66 |
RAG_INITIALIZED = True
|
| 67 |
# Usa content= para forçar o argumento nomeado e evitar TypeError
|
| 68 |
await msg.update(
|
| 69 |
+
content=f"✅ Documento '{file.name}' processado com sucesso! Agora você pode fazer perguntas sobre o conteúdo do documento."
|
| 70 |
)
|
| 71 |
else:
|
| 72 |
RAG_INITIALIZED = False
|
|
|
|
| 90 |
|
| 91 |
if not RAG_INITIALIZED:
|
| 92 |
await cl.Message(
|
| 93 |
+
content="Por favor, aguarde o processamento do arquivo ou recarregue a página para um novo upload. Nenhum documento foi processado ainda.",
|
| 94 |
author="Sistema"
|
| 95 |
).send()
|
| 96 |
return
|
|
|
|
| 106 |
async with client.stream("POST", CHAT_URL, json={"content": message.content}) as response:
|
| 107 |
# Se a requisição falhar, mostra um erro
|
| 108 |
if response.status_code != 200:
|
| 109 |
+
# Tenta ler o erro do corpo da resposta, se disponível
|
| 110 |
+
try:
|
| 111 |
+
error_text = await response.aread()
|
| 112 |
+
error_detail = error_text.decode('utf-8')
|
| 113 |
+
except Exception:
|
| 114 |
+
error_detail = f"Status Code: {response.status_code}"
|
| 115 |
+
|
| 116 |
# Usa content= para forçar o argumento nomeado e evitar TypeError
|
| 117 |
+
await msg.update(content=f"❌ Erro na comunicação com o serviço de IA. Detalhe: {error_detail}")
|
| 118 |
return
|
| 119 |
|
| 120 |
# Itera sobre os pedaços (chunks) de texto recebidos do backend
|
| 121 |
async for chunk in response.aiter_text():
|
| 122 |
await msg.stream_token(chunk)
|
| 123 |
|
| 124 |
+
# Finaliza a mensagem.
|
| 125 |
await msg.update()
|
| 126 |
|
| 127 |
except httpx.ConnectError:
|
|
|
|
| 131 |
# Usa content= para forçar o argumento nomeado e evitar TypeError
|
| 132 |
await msg.update(content=f"Ocorreu um erro: {e}")
|
| 133 |
|
| 134 |
+
#--- END OF FILE app (25).py ---
|