Spaces:
Runtime error

TaxBotAlpha / app.py
DCezaum's picture
Update app.py
1f373cb verified
Raw History Blame Contribute Delete
4.45 kB
# -*- coding: utf-8 -*-
import os
import unicodedata
import streamlit as st
from pergunte_2 import build_chain, retrieve_with_local_filter
# ===================== HELPERS =====================
def build_chat_ctx(history, max_chars=1200, max_turns=6):
msgs = history[-max_turns:]
lines = []
for m in msgs:
role = "Usuário" if m["role"] == "user" else "Assistente"
lines.append(f"{role}: {m['content']}")
s = "\n".join(lines)
if len(s) > max_chars:
s = "… " + s[-max_chars:]
return s
def normalize_text(s: str) -> str:
if s is None:
return ""
s = unicodedata.normalize("NFC", s)
s = s.replace("\\", "\\\\")
s = s.replace("_", "\\_")
s = s.replace("*", "\\*")
s = s.replace("$", "\\$")
s = s.replace("|", "\\|")
return s
# ===================== API KEY (fallback) =====================
if not os.getenv("OPENAI_API_KEY"):
with st.sidebar:
st.info("Defina sua chave da OpenAI (ou use o .env).")
api_key_input = st.text_input("OPENAI_API_KEY", type="password")
if api_key_input:
os.environ["OPENAI_API_KEY"] = api_key_input
# ===================== CONTROLES DA UI =====================
st.set_page_config(
page_title="TaxBot — O Agente do Imposto de Renda",
page_icon="💬",
layout="centered",
initial_sidebar_state="collapsed",
)
modo = st.sidebar.selectbox("🧰 Nível de detalhe", ["resumido", "detalhado"], index=0)
with st.sidebar.expander("⚙️ Opções avançadas", expanded=False):
k = st.slider("Top-k (trechos de contexto)", 3, 12, 6)
# tipo fixo: sempre "any"
tipo = "any"
if "runner" not in st.session_state or st.session_state.get("k") != k:
st.session_state.runner = build_chain(retrieve_with_local_filter)
st.session_state.k = k
# ===================== ESTILO =====================
st.markdown(
"""
<style>
.main .block-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 85vh;
text-align: center;
}
[data-testid="stChatInput"] {
width: 72%;
margin: 0 auto;
}
.intro-text { font-size: 1.2rem; color: #ddd; margin-bottom: 2rem; line-height: 1.5; }
.title { font-size: 1.8rem; font-weight: 600; color: #fff; margin-bottom: 0.5rem; }
.disclaimer { opacity: .9; margin-top: 1.25rem; }
</style>
""",
unsafe_allow_html=True
)
st.markdown(
"""
<style>
.stChatMessage, .stChatMessage p, .stChatMessage li, .stChatMessage ul, .stChatMessage ol {
text-align: left !important;
}
</style>
""",
unsafe_allow_html=True
)
# ===================== HEADER =====================
st.markdown(
"""
<div class="title">💬 TaxBot — O Agente do Imposto de Renda</div>
<div class="intro-text">
Pergunte o que quiser sobre a Reforma do Imposto de Renda.
Eu explico as novas regras, simulo cálculos (quando você pedir) e comparo mudanças no IRPF.
</div>
""",
unsafe_allow_html=True
)
st.caption("Respostas baseadas em documentos oficiais e científicos.")
# ===================== HISTÓRICO =====================
if "history" not in st.session_state:
st.session_state.history = []
for m in st.session_state.history:
with st.chat_message(m["role"]):
st.markdown(normalize_text(m["content"]), unsafe_allow_html=False)
# ===================== CHAT INPUT =====================
if prompt := st.chat_input("Escreva sua pergunta..."):
st.session_state.history.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(normalize_text(prompt), unsafe_allow_html=False)
with st.chat_message("assistant"):
with st.spinner("🔎 Consultando memória e calculando quando necessário..."):
try:
answer = st.session_state.runner(prompt, "all", tipo, k)
except Exception as e:
answer = f"⚠️ Erro: `{e}`"
st.markdown(normalize_text(answer), unsafe_allow_html=False)
st.session_state.history.append({"role": "assistant", "content": answer})
# ===================== AVISO FIXO =====================
st.markdown(
"""
<div class="disclaimer">
⚠️ Isto é informação geral e <u>não</u> constitui aconselhamento tributário, contábil ou jurídico.
</div>
""",
unsafe_allow_html=True
)