JeCabrera commited on
Commit
9167aa4
·
verified ·
1 Parent(s): 87615ac

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -55
app.py CHANGED
@@ -5,34 +5,43 @@ import streamlit as st
5
  import google.generativeai as genai
6
  from dotenv import load_dotenv
7
 
8
- # Configuración inicial de la página (DEBE IR AL INICIO)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  st.set_page_config(
10
- page_title="RoboCopy - Creador de PUVs",
11
- page_icon="🚀",
12
- layout="wide"
13
  )
14
 
15
- # Función para cargar CSS personalizado
16
  def load_css(file_path):
17
- with open(file_path) as f:
18
- st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
19
-
20
- # Intentar cargar el CSS personalizado con ruta absoluta para mayor seguridad
21
- try:
22
- css_path = os.path.join(os.path.dirname(__file__), 'static', 'css', 'style.css')
23
- load_css(css_path)
24
- except Exception as e:
25
- print(f"Error al cargar CSS: {e}")
26
- # Si el archivo no existe, crear un estilo básico en línea
27
- st.markdown("""
28
- <style>
29
- .robocopy-title {
30
- color: #4ECDC4 !important;
31
- font-weight: bold;
32
- font-size: 2em;
33
- }
34
- </style>
35
- """, unsafe_allow_html=True)
36
 
37
  load_dotenv()
38
  GOOGLE_API_KEY=os.environ.get('GOOGLE_API_KEY')
@@ -192,26 +201,23 @@ Creo PUVs persuasivas que:
192
 
193
  # Función para mostrar texto con efecto de escritura
194
  def mostrar_con_efecto_escritura(mensaje, velocidad=0.05):
195
- with st.chat_message(name=MODEL_ROLE, avatar=AI_AVATAR_ICON):
196
- # Contenedor para el mensaje con ancho completo
197
- message_container = st.container()
198
- message_placeholder = message_container.empty()
199
- full_response = ''
200
-
201
- # Indicador de escritura en el contenedor
202
- typing_indicator = message_container.empty()
203
- typing_indicator.markdown("*RoboCopy está escribiendo...*")
204
-
205
- # Mostrar respuesta por fragmentos con formato mejorado
206
- for palabra in mensaje.split(' '):
207
- full_response += palabra + ' '
208
- time.sleep(velocidad)
209
- # Usar markdown para mejor formato
210
- message_placeholder.markdown(full_response + '▌')
211
-
212
- # Eliminar indicador y mostrar respuesta completa con formato
213
- typing_indicator.empty()
214
- message_placeholder.markdown(mensaje)
215
 
216
  return mensaje
217
 
@@ -434,22 +440,25 @@ if 'show_examples' not in st.session_state:
434
 
435
  # Función para manejar los clics de los botones
436
  def handle_example_click(prompt_text):
437
- st.session_state.show_examples = False
438
- st.session_state.messages = []
439
- st.session_state.current_chat_id = str(time.time())
440
-
441
- # Mostrar mensaje del usuario
442
- with st.chat_message('user', avatar=USER_AVATAR_ICON):
443
- st.markdown(prompt_text)
444
 
445
- # Añadir mensaje del usuario al historial
446
- st.session_state.messages.append({
447
  'role': 'user',
448
  'content': prompt_text,
449
  'avatar': USER_AVATAR_ICON
450
- })
 
 
 
 
451
 
452
- # Asegurarnos de que el chat existe en memoria
453
  if st.session_state.current_chat_id not in st.session_state.chats_in_memory:
454
  st.session_state.chats_in_memory[st.session_state.current_chat_id] = {
455
  'messages': st.session_state.messages,
@@ -547,3 +556,48 @@ if hasattr(st.session_state, 'temp_prompt') and st.session_state.temp_prompt:
547
  st.rerun()
548
  st.rerun()
549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  import google.generativeai as genai
6
  from dotenv import load_dotenv
7
 
8
+ # Configuración global
9
+ CONFIG = {
10
+ 'model': {
11
+ 'role': 'ai',
12
+ 'avatar': '🤖'
13
+ },
14
+ 'user': {
15
+ 'avatar': '👤'
16
+ },
17
+ 'page': {
18
+ 'title': "RoboCopy - Creador de PUVs",
19
+ 'icon': "🚀",
20
+ 'layout': "wide"
21
+ }
22
+ }
23
+
24
+ # Usar CONFIG en lugar de constantes separadas
25
  st.set_page_config(
26
+ page_title=CONFIG['page']['title'],
27
+ page_icon=CONFIG['page']['icon'],
28
+ layout=CONFIG['page']['layout']
29
  )
30
 
 
31
  def load_css(file_path):
32
+ try:
33
+ with open(file_path) as f:
34
+ st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
35
+ except Exception as e:
36
+ st.markdown("""
37
+ <style>
38
+ .robocopy-title {
39
+ color: #4ECDC4 !important;
40
+ font-weight: bold;
41
+ font-size: 2em;
42
+ }
43
+ </style>
44
+ """, unsafe_allow_html=True)
 
 
 
 
 
 
45
 
46
  load_dotenv()
47
  GOOGLE_API_KEY=os.environ.get('GOOGLE_API_KEY')
 
201
 
202
  # Función para mostrar texto con efecto de escritura
203
  def mostrar_con_efecto_escritura(mensaje, velocidad=0.05):
204
+ # Crear un contenedor principal que ocupe todo el ancho
205
+ main_container = st.container()
206
+
207
+ with main_container:
208
+ with st.chat_message(name=MODEL_ROLE, avatar=AI_AVATAR_ICON):
209
+ message_placeholder = st.empty()
210
+ typing_indicator = st.empty()
211
+ typing_indicator.markdown("*RoboCopy está escribiendo...*")
212
+
213
+ full_response = ''
214
+ for palabra in mensaje.split(' '):
215
+ full_response += palabra + ' '
216
+ time.sleep(velocidad)
217
+ message_placeholder.markdown(full_response + '▌')
218
+
219
+ typing_indicator.empty()
220
+ message_placeholder.markdown(mensaje)
 
 
 
221
 
222
  return mensaje
223
 
 
440
 
441
  # Función para manejar los clics de los botones
442
  def handle_example_click(prompt_text):
443
+ # Reiniciar estado
444
+ st.session_state.update({
445
+ 'show_examples': False,
446
+ 'messages': [],
447
+ 'current_chat_id': str(time.time())
448
+ })
 
449
 
450
+ # Añadir mensaje del usuario
451
+ message = {
452
  'role': 'user',
453
  'content': prompt_text,
454
  'avatar': USER_AVATAR_ICON
455
+ }
456
+ st.session_state.messages.append(message)
457
+
458
+ with st.chat_message('user', avatar=USER_AVATAR_ICON):
459
+ st.markdown(prompt_text)
460
 
461
+ # Actualizar chat en memoria
462
  if st.session_state.current_chat_id not in st.session_state.chats_in_memory:
463
  st.session_state.chats_in_memory[st.session_state.current_chat_id] = {
464
  'messages': st.session_state.messages,
 
556
  st.rerun()
557
  st.rerun()
558
 
559
+ # Modificar la sección de historial de chat
560
+ with st.sidebar:
561
+ # Centrar el logo y eliminar el título de RoboCopy
562
+ col1, col2, col3 = st.columns([1, 2, 1])
563
+ with col2:
564
+ st.image("assets/robocopy_logo.png", width=300)
565
+
566
+ st.write('# Chats Anteriores')
567
+ if st.session_state.get('current_chat_id') is None:
568
+ st.session_state.current_chat_id = st.selectbox(
569
+ label='Selecciona un chat anterior',
570
+ options=[new_chat_id] + list(st.session_state.chats_in_memory.keys()),
571
+ format_func=lambda x: st.session_state.chats_in_memory.get(x, {}).get('title', 'Nuevo Chat') if isinstance(x, str) else 'Nuevo Chat',
572
+ placeholder='_',
573
+ )
574
+ else:
575
+ st.session_state.current_chat_id = st.selectbox(
576
+ label='Selecciona un chat anterior',
577
+ options=[new_chat_id, st.session_state.current_chat_id] + list(st.session_state.chats_in_memory.keys()),
578
+ index=1,
579
+ format_func=lambda x: st.session_state.chats_in_memory.get(x, {}).get('title', 'Nuevo Chat') if isinstance(x, str) else 'Nuevo Chat',
580
+ placeholder='_',
581
+ )
582
+
583
+ # Modificar el selectbox para el historial
584
+ chat_options = [new_chat_id] + list(st.session_state.chats_in_memory.keys())
585
+ selected_chat = st.selectbox(
586
+ label='Selecciona un chat anterior',
587
+ options=chat_options,
588
+ format_func=lambda x: st.session_state.chats_in_memory.get(x, {}).get('title', 'Nuevo Chat'),
589
+ index=chat_options.index(st.session_state.current_chat_id) if st.session_state.current_chat_id in chat_options else 0
590
+ )
591
+
592
+ # Actualizar el chat actual si cambia la selección
593
+ if selected_chat != st.session_state.current_chat_id:
594
+ st.session_state.current_chat_id = selected_chat
595
+ if selected_chat in st.session_state.chats_in_memory:
596
+ st.session_state.messages = st.session_state.chats_in_memory[selected_chat].get('messages', [])
597
+ st.session_state.gemini_history = st.session_state.chats_in_memory[selected_chat].get('gemini_history', [])
598
+ st.session_state.chat_title = st.session_state.chats_in_memory[selected_chat].get('title', 'Nuevo Chat')
599
+ else:
600
+ st.session_state.messages = []
601
+ st.session_state.gemini_history = []
602
+ st.session_state.chat_title = 'Nuevo Chat'
603
+ st.rerun()