Update frontend/app.py
Browse files- frontend/app.py +21 -15
frontend/app.py
CHANGED
|
@@ -2,6 +2,8 @@
|
|
| 2 |
|
| 3 |
import chainlit as cl
|
| 4 |
import httpx
|
|
|
|
|
|
|
| 5 |
|
| 6 |
# URL do nosso backend FastAPI
|
| 7 |
API_URL = "http://localhost:8000"
|
|
@@ -35,12 +37,23 @@ async def start():
|
|
| 35 |
msg = cl.Message(content=f"Recebido: {file.name}. Processando...", author="Sistema")
|
| 36 |
await msg.send()
|
| 37 |
|
| 38 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
try:
|
| 40 |
async with httpx.AsyncClient(timeout=300) as client:
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
-
files_payload = {"file": (file.name, file.content, file.mime)}
|
| 44 |
|
| 45 |
response = await client.post(
|
| 46 |
UPLOAD_URL,
|
|
@@ -50,29 +63,25 @@ async def start():
|
|
| 50 |
# Se o upload/processamento for bem-sucedido
|
| 51 |
if response.status_code == 200:
|
| 52 |
RAG_INITIALIZED = True
|
| 53 |
-
#
|
| 54 |
await msg.update(
|
| 55 |
f"✅ **{file.name}** processado com sucesso! Agora você pode fazer perguntas sobre o conteúdo do documento."
|
| 56 |
)
|
| 57 |
else:
|
| 58 |
RAG_INITIALIZED = False
|
| 59 |
-
#
|
| 60 |
error_detail = response.json().get('detail', 'Erro desconhecido')
|
| 61 |
await msg.update(
|
| 62 |
f"❌ Erro ao processar o arquivo. Código: {response.status_code}. Detalhe: {error_detail}"
|
| 63 |
)
|
| 64 |
|
| 65 |
except httpx.ConnectError:
|
| 66 |
-
#
|
| 67 |
await msg.update("Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando.")
|
| 68 |
-
# Para manter o autor 'Sistema', enviamos uma nova mensagem
|
| 69 |
-
await cl.Message(content="Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando.", author="Sistema").send()
|
| 70 |
|
| 71 |
except Exception as e:
|
| 72 |
-
#
|
| 73 |
await msg.update(f"Ocorreu um erro: {e}")
|
| 74 |
-
# Para manter o autor 'Sistema', enviamos uma nova mensagem
|
| 75 |
-
await cl.Message(content=f"Ocorreu um erro: {e}", author="Sistema").send()
|
| 76 |
|
| 77 |
@cl.on_message
|
| 78 |
async def main(message: cl.Message):
|
|
@@ -96,7 +105,6 @@ async def main(message: cl.Message):
|
|
| 96 |
async with client.stream("POST", CHAT_URL, json={"content": message.content}) as response:
|
| 97 |
# Se a requisição falhar, mostra um erro
|
| 98 |
if response.status_code != 200:
|
| 99 |
-
# CORRIGIDO: Uso correto do msg.update(content)
|
| 100 |
await msg.update(f"Erro: {response.text}")
|
| 101 |
return
|
| 102 |
|
|
@@ -108,10 +116,8 @@ async def main(message: cl.Message):
|
|
| 108 |
await msg.update()
|
| 109 |
|
| 110 |
except httpx.ConnectError:
|
| 111 |
-
# CORRIGIDO: Uso correto do msg.update(content)
|
| 112 |
await msg.update("Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando.")
|
| 113 |
except Exception as e:
|
| 114 |
-
# CORRIGIDO: Uso correto do msg.update(content)
|
| 115 |
await msg.update(f"Ocorreu um erro: {e}")
|
| 116 |
|
| 117 |
#--- END OF FILE app (24).py ---
|
|
|
|
| 2 |
|
| 3 |
import chainlit as cl
|
| 4 |
import httpx
|
| 5 |
+
import os # NOVO: Necessário para manipulação de arquivos
|
| 6 |
+
import aiofiles # Opcional, mas melhor para leitura assíncrona. Vamos usar `open` para simplificar.
|
| 7 |
|
| 8 |
# URL do nosso backend FastAPI
|
| 9 |
API_URL = "http://localhost:8000"
|
|
|
|
| 37 |
msg = cl.Message(content=f"Recebido: {file.name}. Processando...", author="Sistema")
|
| 38 |
await msg.send()
|
| 39 |
|
| 40 |
+
# 1. CORREÇÃO: Lendo o conteúdo do arquivo do disco (file.path)
|
| 41 |
+
file_content = None
|
| 42 |
+
try:
|
| 43 |
+
# Lendo o arquivo binário. O Chainlit já salvou o arquivo em um caminho temporário (file.path)
|
| 44 |
+
with open(file.path, "rb") as f:
|
| 45 |
+
file_content = f.read()
|
| 46 |
+
|
| 47 |
+
except Exception as e:
|
| 48 |
+
# CORREÇÃO: Garante que é 1 argumento posicional
|
| 49 |
+
await msg.update(f"❌ Erro ao ler o arquivo no frontend: {e}")
|
| 50 |
+
return
|
| 51 |
+
|
| 52 |
+
# 2. Envia o arquivo para o backend
|
| 53 |
try:
|
| 54 |
async with httpx.AsyncClient(timeout=300) as client:
|
| 55 |
+
# CORREÇÃO: O payload agora usa o `file_content` lido
|
| 56 |
+
files_payload = {"file": (file.name, file_content, file.mime)}
|
|
|
|
| 57 |
|
| 58 |
response = await client.post(
|
| 59 |
UPLOAD_URL,
|
|
|
|
| 63 |
# Se o upload/processamento for bem-sucedido
|
| 64 |
if response.status_code == 200:
|
| 65 |
RAG_INITIALIZED = True
|
| 66 |
+
# CORREÇÃO: Garante que é 1 argumento posicional
|
| 67 |
await msg.update(
|
| 68 |
f"✅ **{file.name}** processado com sucesso! Agora você pode fazer perguntas sobre o conteúdo do documento."
|
| 69 |
)
|
| 70 |
else:
|
| 71 |
RAG_INITIALIZED = False
|
| 72 |
+
# CORREÇÃO: Garante que é 1 argumento posicional
|
| 73 |
error_detail = response.json().get('detail', 'Erro desconhecido')
|
| 74 |
await msg.update(
|
| 75 |
f"❌ Erro ao processar o arquivo. Código: {response.status_code}. Detalhe: {error_detail}"
|
| 76 |
)
|
| 77 |
|
| 78 |
except httpx.ConnectError:
|
| 79 |
+
# CORREÇÃO: Garante que é 1 argumento posicional
|
| 80 |
await msg.update("Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando.")
|
|
|
|
|
|
|
| 81 |
|
| 82 |
except Exception as e:
|
| 83 |
+
# CORREÇÃO: Garante que é 1 argumento posicional
|
| 84 |
await msg.update(f"Ocorreu um erro: {e}")
|
|
|
|
|
|
|
| 85 |
|
| 86 |
@cl.on_message
|
| 87 |
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 |
await msg.update(f"Erro: {response.text}")
|
| 109 |
return
|
| 110 |
|
|
|
|
| 116 |
await msg.update()
|
| 117 |
|
| 118 |
except httpx.ConnectError:
|
|
|
|
| 119 |
await msg.update("Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando.")
|
| 120 |
except Exception as e:
|
|
|
|
| 121 |
await msg.update(f"Ocorreu um erro: {e}")
|
| 122 |
|
| 123 |
#--- END OF FILE app (24).py ---
|