Spaces:
Sleeping

neuronalis / app.py
Nacho
Fix footer width using block clientWidth
810a01e
Raw History Blame Contribute Delete
22.4 kB
import streamlit as st
import os
import time
import io
from config import Config
from llm_client import LLMClient
from system_prompts import SystemPrompts
from chat_db import ChatDatabase
from styles import inject_global_styles
from components import voice_input
import streamlit.components.v1 as components
from streamlit_float import *
from branding import favicon_bytes, logo_bytes, logo_login_data_uri, user_avatar_bytes
from openai import OpenAI
# --- Ensure icons exist early for favicon ---
try:
if not os.path.exists("logo.png"):
with open("logo.png", "wb") as f:
f.write(logo_bytes())
if not os.path.exists("favicon.png"):
with open("favicon.png", "wb") as f:
f.write(favicon_bytes())
except Exception:
pass
# --- Page Config ---
st.set_page_config(
page_title="Neuronalis",
page_icon="favicon.png",
layout="wide",
initial_sidebar_state="expanded"
)
# --- Access Control (simple password gate) ---
APP_PASSWORD = os.getenv("APP_PASSWORD", "Venturada2")
if "auth_ok" not in st.session_state:
st.session_state.auth_ok = False
if not st.session_state.auth_ok:
# Ensure logo exists for the login screen
try:
if not os.path.exists("logo.png"):
with open("logo.png", "wb") as f:
f.write(logo_bytes())
except Exception:
pass
st.markdown(
"""
<style>
html, body, [data-testid="stAppViewContainer"] {
background: #ffffff !important;
color: #0f172a !important;
height: 100% !important;
margin: 0 !important;
}
[data-testid="stHeader"] {
display: none !important;
}
section.main .block-container {
padding-top: 1rem !important;
}
.login-center h2,
.login-center p {
color: #0f172a !important;
text-align: center !important;
}
.login-center img {
display: block;
margin: 0 auto;
}
div[data-testid="stForm"] {
width: min(360px, 90vw);
margin: 0 auto;
}
div[data-testid="stForm"] label {
color: #0f172a !important;
text-align: center !important;
width: 100% !important;
}
div[data-testid="stForm"] input {
background: #ffffff !important;
color: #0f172a !important;
border: 1px solid #e2e8f0 !important;
}
div[data-testid="stForm"] input:focus {
border-color: #0f172a !important;
}
div[data-testid="stForm"] button {
margin-top: 6px;
background: #000000 !important;
color: #ffffff !important;
display: block !important;
margin-left: auto !important;
margin-right: auto !important;
}
</style>
""",
unsafe_allow_html=True,
)
st.markdown('<div class="login-center">', unsafe_allow_html=True)
left, center, right = st.columns([1, 2, 1])
with center:
st.markdown(
f"""
<div style='display:flex; justify-content:center; margin-bottom: 8px;'>
<img src='{logo_login_data_uri()}' width='120' />
</div>
""",
unsafe_allow_html=True,
)
st.markdown("<h2 style='margin-bottom: 0.25rem; text-align:center;'>Acceso restringido</h2>", unsafe_allow_html=True)
st.markdown("<p style='color:#888; margin-top:0; text-align:center;'>Introduce la contraseña para continuar.</p>", unsafe_allow_html=True)
with st.form("auth_form", clear_on_submit=False):
password = st.text_input("Contraseña", type="password")
submitted = st.form_submit_button("Entrar")
if submitted:
if password == APP_PASSWORD:
st.session_state.auth_ok = True
st.rerun()
else:
st.error("Contraseña incorrecta.")
st.markdown("</div>", unsafe_allow_html=True)
st.stop()
WELCOME_MD = """
### Como **NEURONALIS**, puedo asistirle en las siguientes áreas, todas respaldadas por normativa específica:
1. **Análisis Fiscal Preventivo**
- Revisión de riesgos fiscales (Art. 179 LGT)
- Detección de contingencias tributarias
- Análisis de prescripción (Art. 66 LGT)
2. **Impuesto sobre Sociedades**
- Optimización de deducciones (Art. 12-38 LIS)
- Análisis de gastos deducibles
- Planificación de inversiones
- Estudio de operaciones vinculadas (Art. 18 LIS)
3. **IVA**
- Revisión de deducciones (Art. 92-114 LIVA)
- Análisis de operaciones intracomunitarias
- Estudio de sectores diferenciados
- Regímenes especiales (Art. 120-163 LIVA)
4. **Procedimientos Tributarios**
- Análisis de actas de inspección
- Preparación de recursos (Art. 213-249 LGT)
- Revisión de sanciones
- Aplazamientos y fraccionamientos (Art. 65 LGT)
"""
# --- Helpers ---
def is_presentation_view():
non_system = [m for m in st.session_state.messages if m.get("role") != "system"]
if len(non_system) != 1:
return False
first = non_system[0]
return first.get("role") == "assistant" and first.get("content", "").strip() == WELCOME_MD.strip()
def generate_chat_title(messages):
"""Generate a short title based on conversation content."""
user_msgs = [m for m in messages if m["role"] == "user"]
if not user_msgs:
return None
first_msg = user_msgs[0]["content"][:300]
client = LLMClient()
title_prompt = [
{"role": "system", "content": "Genera un título muy corto (máximo 4 palabras) para esta conversación basándote en el mensaje del usuario. Responde SOLO con el título, sin comillas ni puntos finales."},
{"role": "user", "content": first_msg}
]
try:
# Use non-streaming for title
response = client.chat_completion(title_prompt, stream=False)
if response and response.choices:
return response.choices[0].message.content.strip().replace('"', '')
except:
pass
return None
def is_audio_file(filename: str, mime_type: str | None):
ext = os.path.splitext(filename)[1].lower()
if ext in [".wav", ".mp3", ".m4a", ".webm", ".ogg", ".flac"]:
return True
if mime_type and mime_type.startswith("audio/"):
return True
return False
def transcribe_audio_bytes(file_bytes: bytes, filename: str):
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
return None, "Falta OPENAI_API_KEY para transcribir audio."
try:
client = OpenAI(api_key=api_key)
audio_file = io.BytesIO(file_bytes)
audio_file.name = filename
result = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
return result.text, None
except Exception as e:
return None, f"Error transcribiendo audio: {e}"
# --- Float Init ---
float_init()
# --- Inject CSS ---
inject_global_styles()
# --- Ensure branding assets (HF-safe: generated from base64) ---
def ensure_brand_assets():
try:
if not os.path.exists("logo.png"):
with open("logo.png", "wb") as f:
f.write(logo_bytes())
if not os.path.exists("favicon.png"):
with open("favicon.png", "wb") as f:
f.write(favicon_bytes())
if not os.path.exists("user_avatar.png"):
with open("user_avatar.png", "wb") as f:
f.write(user_avatar_bytes())
except Exception:
# If assets fail, app will fall back to text title/emoji avatars
pass
# --- Initialization ---
APP_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(APP_DIR)
ensure_brand_assets()
db = ChatDatabase()
if "current_conversation_id" not in st.session_state:
convs = db.get_all_conversations()
if convs:
st.session_state.current_conversation_id = convs[0][0]
st.session_state.messages = db.get_messages(convs[0][0])
st.session_state.cwd = convs[0][2] or os.getcwd()
else:
cwd = os.getcwd()
conv_id = db.create_conversation("Saludo Inicial", cwd)
st.session_state.current_conversation_id = conv_id
system_msg = {"role": "system", "content": SystemPrompts.get_main_prompt(cwd)}
welcome_msg = {"role": "assistant", "content": WELCOME_MD}
st.session_state.messages = [system_msg, welcome_msg]
db.add_message(conv_id, "system", system_msg["content"])
db.add_message(conv_id, "assistant", welcome_msg["content"])
st.session_state.cwd = cwd
if "draft_prompt" not in st.session_state:
st.session_state.draft_prompt = ""
# --- Sidebar ---
with st.sidebar:
# CLEAN LOGO: No HTML wrappers, just image
if os.path.exists("logo.png"):
st.image("logo.png", width="stretch")
else:
st.title("NEURONALIS")
st.markdown("---") # Native Divider
if st.button("+ Nuevo chat", key="new_chat_btn", width="stretch", type="primary"):
cwd = st.session_state.get("cwd", os.getcwd())
conv_id = db.create_conversation(f"Chat {len(db.get_all_conversations())+1}", cwd)
st.session_state.current_conversation_id = conv_id
system_msg = {"role": "system", "content": SystemPrompts.get_main_prompt(cwd)}
st.session_state.messages = [system_msg]
db.add_message(conv_id, "system", system_msg["content"])
st.rerun()
st.markdown("### Recientes")
# History List
convs = db.get_all_conversations()
# Limit to display last 10, but handle all logic
for conv in reversed(convs[-10:]):
c_id, c_name, _, _, _ = conv
# Grid for [Chat Name | x]
c_btn, c_del = st.columns([0.85, 0.15])
with c_btn:
# Highlight current chat
tipo = "primary" if c_id == st.session_state.current_conversation_id else "secondary"
if st.button(c_name, key=f"hist_{c_id}", width="stretch", type=tipo):
st.session_state.current_conversation_id = c_id
st.session_state.messages = db.get_messages(c_id)
st.rerun()
with c_del:
if st.button("✕", key=f"del_{c_id}", help="Borrar chat"):
db.delete_conversation(c_id)
# If we deleted the active chat, reset state
if c_id == st.session_state.current_conversation_id:
st.session_state.current_conversation_id = None
st.session_state.messages = []
st.rerun()
with st.expander("⚙️ Ajustes"):
st.markdown("**Cerebro de la IA**")
model_map = {
"Claude 3.5 Sonnet": ("openrouter", "anthropic/claude-3.5-sonnet"),
"DeepSeek R1 (Razonamiento)": ("openrouter", "deepseek/deepseek-r1"),
"GPT-4o (OpenAI)": ("openai", "gpt-4o"),
"Llama 3 Local (Ollama)": ("ollama", "llama3.1")
}
# Determine current index
current_label = "Claude 3.5 Sonnet" # Default
if Config.PROVIDER == "openai": current_label = "GPT-4o (OpenAI)"
elif Config.PROVIDER == "ollama": current_label = "Llama 3 Local (Ollama)"
elif Config.PROVIDER == "openrouter" and "deepseek" in Config.OPENROUTER_MODEL: current_label = "DeepSeek R1 (Razonamiento)"
selected_model = st.selectbox("Selecciona modelo", list(model_map.keys()), index=list(model_map.keys()).index(current_label))
# Apply selection
provider, model_id = model_map[selected_model]
Config.PROVIDER = provider
if provider == "openrouter": Config.OPENROUTER_MODEL = model_id
elif provider == "openai": Config.OPENAI_MODEL = model_id
elif provider == "ollama": Config.OLLAMA_MODEL = model_id
# --- Main Content ---
# 1. Upload Panel (At top if active)
if st.session_state.get("show_uploader"):
with st.container():
uploaded_file = st.file_uploader(
"Subir documentos o audio",
type=["pdf", "txt", "csv", "png", "jpg", "jpeg", "wav", "mp3", "m4a", "webm", "ogg", "flac"],
label_visibility="collapsed"
)
if uploaded_file:
# Save file to current workspace
save_path = os.path.join(os.getcwd(), uploaded_file.name)
with open(save_path, "wb") as f:
f.write(uploaded_file.getvalue())
# notify chat and trigger analysis
if "notified_files" not in st.session_state:
st.session_state.notified_files = []
if uploaded_file.name not in st.session_state.notified_files:
if is_audio_file(uploaded_file.name, uploaded_file.type):
text, err = transcribe_audio_bytes(uploaded_file.getvalue(), uploaded_file.name)
if err:
st.error(err)
elif text:
msg_content = text
st.session_state.messages.append({"role": "user", "content": msg_content})
db.add_message(st.session_state.current_conversation_id, "user", msg_content)
st.session_state.last_user_input = msg_content
st.session_state.notified_files.append(uploaded_file.name)
st.session_state.show_uploader = False
st.rerun()
else:
msg_content = f"He subido el archivo `{uploaded_file.name}`. Por favor, analízalo."
st.session_state.messages.append({"role": "user", "content": msg_content})
db.add_message(st.session_state.current_conversation_id, "user", msg_content)
st.session_state.last_user_input = msg_content
st.session_state.notified_files.append(uploaded_file.name)
st.session_state.show_uploader = False # Hide after upload
st.rerun()
# --- 3. Chat Messages Area (Main Flow) ---
for msg in st.session_state.messages:
if msg["role"] == "system":
continue
avatar = "logo.png" if msg["role"] == "assistant" else "user_avatar.png"
with st.chat_message(msg["role"], avatar=avatar):
st.write(msg["content"])
# --- AI Response Logic (Inline to avoid jump) ---
if st.session_state.get("last_user_input"):
prompt = st.session_state.last_user_input
st.session_state.last_user_input = None
with st.chat_message("assistant", avatar="logo.png"):
message_placeholder = st.empty()
full_response = ""
client = LLMClient()
try:
for chunk in client.get_completion_stream(st.session_state.messages, model=Config.get_model()):
if chunk:
full_response += chunk
message_placeholder.markdown(full_response + "▌")
# Force scroll during streaming
st.components.v1.html(
f"""
<script>
window.parent.document.querySelectorAll('[data-testid="stChatMessageContainer"]').forEach(el => {{
el.scrollIntoView({{behavior: 'auto', block: 'end'}});
}});
</script>
""",
height=0
)
message_placeholder.markdown(full_response)
st.session_state.messages.append({"role": "assistant", "content": full_response})
db.add_message(st.session_state.current_conversation_id, "assistant", full_response)
# AUTO-RENAME: If chat has a generic name, give it a real one
conv_details = db.get_conversation(st.session_state.current_conversation_id)
if conv_details and (conv_details[1] == "Nuevo chat" or conv_details[1].startswith("Chat ")):
new_title = generate_chat_title(st.session_state.messages)
if new_title:
db.rename_conversation(st.session_state.current_conversation_id, new_title)
st.rerun()
except Exception as e:
st.error(f"Error: {str(e)}")
# Add a spacer so the last message isn't hidden behind the fixed footer
st.markdown('<div style="height: 100px;"></div>', unsafe_allow_html=True)
# Final scroll-to-bottom anchor (skip on presentation screen)
if not is_presentation_view():
st.components.v1.html(
"""
<script>
const scrollChat = () => {
const static_elements = window.parent.document.querySelectorAll('[data-testid="stChatMessageContainer"]');
if (static_elements.length > 0) {
const lastElement = static_elements[static_elements.length - 1];
lastElement.scrollIntoView({behavior: 'smooth', block: 'end'});
}
}
setTimeout(scrollChat, 100);
</script>
""",
height=0
)
# --- 4. THE "BRUTE FORCE" BAR (Custom Fixed Bottom Toolbar) ---
# We build our own toolbar using columns and float it ENTIRELY to the bottom.
# This guarantees buttons + text are together "in the bar".
footer = st.container()
with footer:
st.markdown("<div id='footer-anchor' style='height:0;'></div>", unsafe_allow_html=True)
# Tightened columns to group elements together
c_mic, c_plus, c_input, c_send = st.columns([0.8, 0.6, 9.5, 0.6], vertical_alignment="center")
with c_mic:
# 🎙️ CUSTOM NOIR MIC (Strict Circle)
voice_res = voice_input.voice_input(key="bar_mic")
if voice_res and voice_res.get("text"):
status = voice_res.get("status")
text = voice_res.get("text")
if status == "finished" and text:
if text != st.session_state.get("last_voice_text"):
st.session_state.main_chat_input = text
st.session_state.last_voice_text = text
with c_plus:
if st.button("+", key="cmd_plus", help="Adjuntar"):
st.session_state.show_uploader = not st.session_state.get("show_uploader", False)
st.rerun()
with c_input:
# Callback to handle sending immediately on Enter
def on_enter_key():
text = st.session_state.main_chat_input
if text.strip():
st.session_state.messages.append({"role": "user", "content": text})
db.add_message(st.session_state.current_conversation_id, "user", text)
st.session_state.last_user_input = text # Flag for processing
st.session_state.main_chat_input = "" # Clear input
st.session_state.last_voice_text = ""
# We bind value to a session key that we can update from voice
if "input_value" not in st.session_state:
st.session_state.input_value = ""
st.text_input(
"Mensaje",
key="main_chat_input",
label_visibility="collapsed",
placeholder="Escribe un mensaje...",
on_change=on_enter_key
)
with c_send:
# The separate send button
if st.button("➤", key="cmd_send", type="primary"):
val = st.session_state.main_chat_input
if val.strip():
st.session_state.messages.append({"role": "user", "content": val})
db.add_message(st.session_state.current_conversation_id, "user", val)
st.session_state.last_user_input = val
st.session_state.main_chat_input = ""
st.session_state.last_voice_text = ""
st.rerun()
# Tag the "+" button so CSS can target it reliably
st.components.v1.html(
"""
<script>
const doc = window.parent.document;
const win = window.parent;
const tagPlusButton = () => {
doc.querySelectorAll('button').forEach((btn) => {
if (btn.innerText && btn.innerText.trim() === '+') {
btn.classList.add('plus-btn');
}
});
};
const footerAnchor = doc.getElementById('footer-anchor');
const footerBlock = footerAnchor ? footerAnchor.closest('[data-testid="stVerticalBlock"]') : null;
let lastLeft = null;
let lastWidth = null;
const applyFooterBaseStyles = () => {
if (!footerBlock) return;
footerBlock.style.position = 'fixed';
footerBlock.style.bottom = '0';
footerBlock.style.background = '#ffffff';
footerBlock.style.zIndex = '999999';
footerBlock.style.boxSizing = 'border-box';
footerBlock.style.padding = '8px 0 15px 0';
};
const syncFooterBounds = () => {
if (!footerBlock) return;
const block = doc.querySelector('[data-testid="stAppViewContainer"] .main .block-container');
if (!block) return;
const rect = block.getBoundingClientRect();
const styles = win.getComputedStyle(block);
const padL = parseFloat(styles.paddingLeft) || 0;
const padR = parseFloat(styles.paddingRight) || 0;
const leftEdge = rect.left + padL;
const width = Math.max(0, block.clientWidth - padL - padR);
if (leftEdge !== lastLeft || width !== lastWidth) {
footerBlock.style.left = `${leftEdge}px`;
footerBlock.style.width = `${width}px`;
lastLeft = leftEdge;
lastWidth = width;
}
};
setTimeout(tagPlusButton, 50);
setTimeout(tagPlusButton, 300);
setTimeout(applyFooterBaseStyles, 50);
setTimeout(applyFooterBaseStyles, 300);
setTimeout(syncFooterBounds, 50);
setTimeout(syncFooterBounds, 300);
win.addEventListener('resize', syncFooterBounds);
setInterval(syncFooterBounds, 500);
</script>
""",
height=0
)