import time import os import joblib import streamlit as st import google.generativeai as genai from dotenv import load_dotenv from puv_formulas import puv_formulas from system_prompts import get_unified_puv_prompt from session_state import SessionState # Inicializar el estado de la sesión state = SessionState() # Función para detectar saludos y generar respuestas personalizadas def is_greeting(text): text = text.lower().strip() greetings = ['hola', 'hey', 'saludos', 'buenos días', 'buenas tardes', 'buenas noches', 'hi', 'hello'] is_simple_greeting = any(greeting in text for greeting in greetings) and len(text.split()) < 4 return is_simple_greeting and len(state.messages) == 0 def process_message(prompt, is_example=False): handle_chat_title(prompt) with st.chat_message('user', avatar=USER_AVATAR_ICON): st.markdown(prompt) state.add_message('user', prompt, USER_AVATAR_ICON) enhanced_prompt = get_enhanced_prompt(prompt, is_example) with st.chat_message(MODEL_ROLE, avatar=AI_AVATAR_ICON): try: message_placeholder = st.empty() typing_indicator = st.empty() typing_indicator.markdown("*Generando respuesta...*") response = state.send_message(enhanced_prompt) full_response = stream_response(response, message_placeholder, typing_indicator) if full_response: state.add_message(MODEL_ROLE, full_response, AI_AVATAR_ICON) state.gemini_history = state.chat.history state.save_chat_history() except Exception as e: st.error(f"Error en el streaming: {str(e)}") return def handle_chat_title(prompt): if state.chat_id not in past_chats: temp_title = f'SesiónChat-{state.chat_id}' generated_title = state.generate_chat_title(prompt) state.chat_title = generated_title or temp_title past_chats[state.chat_id] = state.chat_title else: state.chat_title = past_chats[state.chat_id] joblib.dump(past_chats, 'data/past_chats_list') def get_enhanced_prompt(prompt, is_example): if is_greeting(prompt): return f"El usuario te ha saludado con '{prompt}'. Preséntate brevemente, explica qué es una PUV en 1-2 líneas, y haz 1-2 preguntas iniciales para comenzar a crear la PUV del usuario (como a quién se dirige su producto/servicio o qué ofrece). Sé amigable, breve y toma la iniciativa como el experto que eres." elif is_example: return f"El usuario ha seleccionado un ejemplo: '{prompt}'. Responde de manera conversacional y sencilla, como si estuvieras hablando con un amigo. Evita tecnicismos innecesarios. Enfócate en dar información práctica que ayude al usuario a crear su PUV. Usa ejemplos concretos cuando sea posible. Termina tu respuesta con una pregunta que invite al usuario a compartir información sobre su negocio para poder ayudarle a crear su PUV personalizada." return prompt def stream_response(response, message_placeholder, typing_indicator): full_response = '' try: for chunk in response: if chunk.text: for ch in chunk.text: full_response += ch time.sleep(0.01) typing_indicator.markdown("*Generando respuesta...*") message_placeholder.markdown(full_response + '▌') except Exception as e: st.error(f"Error en el streaming: {str(e)}") return '' typing_indicator.empty() message_placeholder.markdown(full_response) return full_response def load_css(file_path): with open(file_path) as f: st.markdown(f'', unsafe_allow_html=True) try: css_path = os.path.join(os.path.dirname(__file__), 'static', 'css', 'style.css') load_css(css_path) except Exception as e: print(f"Error al cargar CSS: {e}") st.markdown(""" """, unsafe_allow_html=True) def display_initial_header(): col1, col2, col3 = st.columns([1, 2, 1]) with col2: st.markdown(""" """, unsafe_allow_html=True) st.image("robocopy_logo.png", width=300, use_container_width=True) st.markdown("""
By Jesús Cabrera
🎯 Experto en crear Propuestas de Valor Únicas que convierten audiencia en clientes