Update frontend/app.py
Browse files- frontend/app.py +27 -35
frontend/app.py
CHANGED
|
@@ -1,11 +1,13 @@
|
|
| 1 |
-
#--- START OF FILE app
|
| 2 |
|
| 3 |
import chainlit as cl
|
| 4 |
import httpx
|
| 5 |
import os
|
| 6 |
-
import mimetypes
|
| 7 |
|
| 8 |
# URL do nosso backend FastAPI
|
|
|
|
|
|
|
|
|
|
| 9 |
API_URL = "http://localhost:8000"
|
| 10 |
UPLOAD_URL = f"{API_URL}/upload-document"
|
| 11 |
CHAT_URL = f"{API_URL}/chat"
|
|
@@ -40,16 +42,13 @@ async def start():
|
|
| 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
|
| 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
|
| 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 |
}
|
|
@@ -58,31 +57,27 @@ async def start():
|
|
| 58 |
async with httpx.AsyncClient(timeout=300) as client:
|
| 59 |
response = await client.post(
|
| 60 |
UPLOAD_URL,
|
| 61 |
-
files=files_payload
|
| 62 |
)
|
| 63 |
|
| 64 |
-
#
|
| 65 |
if response.status_code == 200:
|
| 66 |
RAG_INITIALIZED = True
|
| 67 |
-
|
| 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
|
| 73 |
error_detail = response.json().get('detail', 'Erro desconhecido')
|
| 74 |
-
|
| 75 |
-
await msg.update(
|
| 76 |
-
content=f"❌ Erro ao processar o arquivo. Código: {response.status_code}. Detalhe: {error_detail}"
|
| 77 |
-
)
|
| 78 |
|
| 79 |
except httpx.ConnectError:
|
| 80 |
-
|
| 81 |
-
await msg.update(
|
| 82 |
|
| 83 |
except Exception as e:
|
| 84 |
-
|
| 85 |
-
await msg.update(
|
| 86 |
|
| 87 |
@cl.on_message
|
| 88 |
async def main(message: cl.Message):
|
|
@@ -100,35 +95,32 @@ async def main(message: cl.Message):
|
|
| 100 |
await msg.send()
|
| 101 |
|
| 102 |
try:
|
| 103 |
-
# Usamos httpx para fazer uma requisição de streaming para o nosso backend
|
| 104 |
async with httpx.AsyncClient(timeout=60) as client:
|
| 105 |
-
# Fazemos um POST para o endpoint /chat com a mensagem do usuário
|
| 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 |
-
#
|
| 117 |
-
|
|
|
|
| 118 |
return
|
| 119 |
|
| 120 |
-
#
|
| 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:
|
| 128 |
-
|
| 129 |
-
await msg.update(
|
| 130 |
except Exception as e:
|
| 131 |
-
|
| 132 |
-
await msg.update(
|
| 133 |
-
|
| 134 |
-
#--- END OF FILE app
|
|
|
|
| 1 |
+
#--- START OF FILE app.py ---
|
| 2 |
|
| 3 |
import chainlit as cl
|
| 4 |
import httpx
|
| 5 |
import os
|
|
|
|
| 6 |
|
| 7 |
# URL do nosso backend FastAPI
|
| 8 |
+
# Se estiver rodando no Docker, localhost geralmente funciona se usar network host,
|
| 9 |
+
# mas em bridge pode precisar do nome do serviço.
|
| 10 |
+
# Mantendo localhost conforme seu log de sucesso anterior (200 OK).
|
| 11 |
API_URL = "http://localhost:8000"
|
| 12 |
UPLOAD_URL = f"{API_URL}/upload-document"
|
| 13 |
CHAT_URL = f"{API_URL}/chat"
|
|
|
|
| 42 |
|
| 43 |
try:
|
| 44 |
# 1. Obtendo o MIME Type de forma robusta
|
|
|
|
| 45 |
mime_type = getattr(file, 'type', 'application/pdf') or 'application/pdf'
|
| 46 |
|
| 47 |
+
# 2. Lendo o conteúdo do arquivo
|
|
|
|
| 48 |
with open(file.path, "rb") as f:
|
| 49 |
file_content = f.read()
|
| 50 |
|
| 51 |
+
# 3. Criando o payload
|
|
|
|
| 52 |
files_payload = {
|
| 53 |
"file": (file.name, file_content, mime_type)
|
| 54 |
}
|
|
|
|
| 57 |
async with httpx.AsyncClient(timeout=300) as client:
|
| 58 |
response = await client.post(
|
| 59 |
UPLOAD_URL,
|
| 60 |
+
files=files_payload
|
| 61 |
)
|
| 62 |
|
| 63 |
+
# CORREÇÃO AQUI: Atualiza o atributo content e depois chama update() sem argumentos
|
| 64 |
if response.status_code == 200:
|
| 65 |
RAG_INITIALIZED = True
|
| 66 |
+
msg.content = f"✅ Documento '{file.name}' processado com sucesso! Agora você pode fazer perguntas sobre o conteúdo do documento."
|
| 67 |
+
await msg.update()
|
|
|
|
|
|
|
| 68 |
else:
|
| 69 |
RAG_INITIALIZED = False
|
| 70 |
error_detail = response.json().get('detail', 'Erro desconhecido')
|
| 71 |
+
msg.content = f"❌ Erro ao processar o arquivo. Código: {response.status_code}. Detalhe: {error_detail}"
|
| 72 |
+
await msg.update()
|
|
|
|
|
|
|
| 73 |
|
| 74 |
except httpx.ConnectError:
|
| 75 |
+
msg.content = "Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando."
|
| 76 |
+
await msg.update()
|
| 77 |
|
| 78 |
except Exception as e:
|
| 79 |
+
msg.content = f"Ocorreu um erro: {e}"
|
| 80 |
+
await msg.update()
|
| 81 |
|
| 82 |
@cl.on_message
|
| 83 |
async def main(message: cl.Message):
|
|
|
|
| 95 |
await msg.send()
|
| 96 |
|
| 97 |
try:
|
|
|
|
| 98 |
async with httpx.AsyncClient(timeout=60) as client:
|
|
|
|
| 99 |
async with client.stream("POST", CHAT_URL, json={"content": message.content}) as response:
|
|
|
|
| 100 |
if response.status_code != 200:
|
|
|
|
| 101 |
try:
|
| 102 |
error_text = await response.aread()
|
| 103 |
error_detail = error_text.decode('utf-8')
|
| 104 |
except Exception:
|
| 105 |
error_detail = f"Status Code: {response.status_code}"
|
| 106 |
|
| 107 |
+
# CORREÇÃO AQUI TAMBÉM
|
| 108 |
+
msg.content = f"❌ Erro na comunicação com o serviço de IA. Detalhe: {error_detail}"
|
| 109 |
+
await msg.update()
|
| 110 |
return
|
| 111 |
|
| 112 |
+
# Streaming
|
| 113 |
async for chunk in response.aiter_text():
|
| 114 |
await msg.stream_token(chunk)
|
| 115 |
|
| 116 |
+
# Finaliza a mensagem (stream_token atualiza automaticamente, update final garante persistência)
|
| 117 |
await msg.update()
|
| 118 |
|
| 119 |
except httpx.ConnectError:
|
| 120 |
+
msg.content = "Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando."
|
| 121 |
+
await msg.update()
|
| 122 |
except Exception as e:
|
| 123 |
+
msg.content = f"Ocorreu um erro: {e}"
|
| 124 |
+
await msg.update()
|
| 125 |
+
|
| 126 |
+
#--- END OF FILE app.py ---
|