Josedcape commited on
Commit
bb2f632
verified
1 Parent(s): 10b5fd8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -161
app.py CHANGED
@@ -1,175 +1,116 @@
1
  import os
2
- import time
 
3
  import streamlit as st
4
- from google.cloud import texttospeech
5
  from dotenv import load_dotenv
6
- import tempfile
7
- import base64
8
- from groq import Groq
9
- from datetime import datetime, timedelta
10
- from streamlit_autorefresh import st_autorefresh
11
 
12
- # Configurar la p谩gina de Streamlit (esto debe ir primero en el script)
13
- st.set_page_config(page_title="Asistente de Recordatorios", page_icon="馃搮", layout="centered")
14
 
15
- # Cargar las variables de entorno desde el archivo .env
16
  load_dotenv()
 
 
17
 
18
- # Configura las claves de API
19
- os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "credentials/botidinamix-g.json"
 
 
 
20
 
21
- # Inicializar cliente de Groq
22
- client_groq = Groq(api_key=os.getenv("GROQ_API_KEY"))
 
 
 
23
 
24
- # Crear carpeta para almacenar audios si no existe
25
- if not os.path.exists('audios'):
26
- os.makedirs('audios')
27
-
28
- # Inicializar las variables en el estado de la sesi贸n si no existen
29
- if 'reminders' not in st.session_state:
30
- st.session_state.reminders = []
31
-
32
- if 'respuestas_anteriores' not in st.session_state:
33
- st.session_state.respuestas_anteriores = []
34
-
35
- if 'fin_tiempo' not in st.session_state:
36
- st.session_state.fin_tiempo = None
37
-
38
- if 'mensaje_recordatorio' not in st.session_state:
39
- st.session_state.mensaje_recordatorio = None
40
-
41
- # Funci贸n para obtener respuesta de Groq actuando como Galatea
42
- def obtener_respuesta_groq(texto):
43
- prompt = f"Act煤a como Galatea, la asistente virtual de la cl铆nica odontol贸gica Omardent. Tienes la funci贸n de recordarme todo lo que se te pida. Responde de manera breve y amable: {texto}"
44
-
45
  try:
46
- # Crear la solicitud de completado con el modelo de Groq
47
- chat_completion = client_groq.chat.completions.create(
48
- messages=[
49
- {
50
- "role": "user",
51
- "content": prompt
52
- }
53
- ],
54
- model="llama3-8b-8192",
 
 
 
 
 
 
 
 
 
 
55
  )
56
- # Extraer el mensaje generado por Groq
57
- return chat_completion.choices[0].message.content.strip()
58
- except Exception as e:
59
- st.error(f"Error al generar el mensaje desde Groq: {e}")
60
- return "Lo siento, hubo un problema al generar el mensaje desde Groq."
61
 
62
- # Funci贸n para generar una respuesta de voz usando Google Cloud Text-to-Speech
63
- def generar_respuesta_de_voz(text):
64
- client = texttospeech.TextToSpeechClient()
65
- synthesis_input = texttospeech.SynthesisInput(text=text)
66
- voice = texttospeech.VoiceSelectionParams(language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.FEMALE)
67
- audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
 
 
 
 
 
 
68
 
69
- try:
70
- response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)
71
-
72
- # Ruta del archivo de audio en la carpeta audios
73
- timestamp = int(time.time())
74
- audio_file_path = os.path.join('audios', f'recordatorio_{timestamp}.mp3')
75
-
76
- # Guardar el archivo de audio en la carpeta audios
77
- with open(audio_file_path, 'wb') as tmp_file:
78
- tmp_file.write(response.audio_content)
79
-
80
- return audio_file_path # Devolver la ruta del archivo
81
  except Exception as e:
82
- st.error(f"Error al generar el audio: {e}")
83
- return None
84
-
85
- # Funci贸n para reproducir el mensaje y mostrar texto
86
- def reproducir_mensaje(mensaje, audio_path):
87
- # Mostrar el mensaje en texto
88
- st.success(f"**Recordatorio:** {mensaje}")
89
-
90
- # Reproducir el audio
91
- if audio_path:
92
- with open(audio_path, "rb") as audio_file:
93
- audio_bytes = audio_file.read()
94
- st.audio(audio_bytes, format="audio/mp3")
95
- else:
96
- st.error("No se pudo generar el audio para el mensaje.")
97
-
98
- # Funci贸n para programar un recordatorio usando Groq como Galatea
99
- def programar_recordatorio_groq(mensaje, intervalo):
100
- respuesta_generada = obtener_respuesta_groq(mensaje)
101
-
102
- # Calcular el tiempo de finalizaci贸n
103
- fin_tiempo = datetime.now() + timedelta(minutes=intervalo)
104
-
105
- # Generar la ruta del archivo de audio
106
- audio_path = generar_respuesta_de_voz(respuesta_generada)
107
-
108
- # Agregar el recordatorio a la lista en la sesi贸n
109
- st.session_state.reminders.append({
110
- 'mensaje': respuesta_generada,
111
- 'fin_tiempo': fin_tiempo,
112
- 'audio_path': audio_path
113
- })
114
-
115
- st.session_state.respuestas_anteriores.append(respuesta_generada)
116
- st.success(f"Recordatorio programado para dentro de {intervalo} minutos con Galatea.")
117
-
118
- # Autorefresh cada segundo para actualizar la cuenta regresiva
119
- st_autorefresh(interval=1000, key="datarefresh")
120
-
121
- # Estilo CSS para el fondo
122
- st.markdown(
123
- """
124
- <style>
125
- .reportview-container {
126
- background: radial-gradient(circle, rgba(209,238,174,1) 0%, rgba(11,135,128,1) 90%);
127
- }
128
- </style>
129
- """,
130
- unsafe_allow_html=True
131
- )
132
-
133
- # Agregar el logo
134
- st.image("Logo icon.jpg", use_column_width=True) # Aseg煤rate de que el archivo icon.jpg est茅 en la misma carpeta
135
-
136
- # Contenido de la aplicaci贸n
137
- st.title("Asistente de Recordatorios - Galatea de Omardent")
138
- st.write("Crea recordatorios y elige el intervalo de tiempo para recibir notificaciones de Galatea.")
139
-
140
- # Campo de texto para ingresar el recordatorio
141
- mensaje_recordatorio = st.text_input("驴Qu茅 recordatorio deseas establecer?", "")
142
-
143
- # Selector desplegable para seleccionar el intervalo de tiempo
144
- intervalo_opciones = [1, 2, 5, 10, 15, 30, 60, 120]
145
- intervalo = st.selectbox("Selecciona el intervalo de tiempo (minutos)", intervalo_opciones)
146
-
147
- # Bot贸n para programar el recordatorio con Groq
148
- if st.button("Programar Recordatorio con Galatea (Groq)"):
149
- if mensaje_recordatorio:
150
- programar_recordatorio_groq(mensaje_recordatorio, intervalo)
151
- else:
152
- st.warning("Por favor, ingresa un recordatorio.")
153
-
154
- # Mostrar los recordatorios activos
155
- if st.session_state.reminders:
156
- st.subheader("Recordatorios Activos")
157
- for idx, reminder in enumerate(st.session_state.reminders):
158
- tiempo_restante = reminder['fin_tiempo'] - datetime.now()
159
- if tiempo_restante.total_seconds() > 0:
160
- minutos, segundos = divmod(int(tiempo_restante.total_seconds()), 60)
161
- horas, minutos = divmod(minutos, 60)
162
- tiempo_str = f"{horas}h {minutos}m {segundos}s" if horas > 0 else f"{minutos}m {segundos}s"
163
- st.write(f"**Recordatorio {idx + 1}:** {reminder['mensaje']}")
164
- st.write(f"**Tiempo restante:** {tiempo_str}")
165
- else:
166
- # Reproducir el mensaje y mostrar texto
167
- reproducir_mensaje(reminder['mensaje'], reminder['audio_path'])
168
- # Eliminar el recordatorio de la lista
169
- st.session_state.reminders.pop(idx)
170
-
171
- # Mostrar el estado de los recordatorios programados
172
- if st.session_state.reminders:
173
- st.write("**Recordatorios Activos:**")
174
- for reminder in st.session_state.reminders:
175
- st.write(f"- {reminder['mensaje']} (Finaliza en: {reminder['fin_tiempo']})")
 
1
  import os
2
+ import openai
3
+ from google.cloud import texttospeech_v1 as texttospeech
4
  import streamlit as st
5
+ import speech_recognition as sr
6
  from dotenv import load_dotenv
 
 
 
 
 
7
 
8
+ # Configurar la p谩gina de Streamlit
9
+ st.set_page_config(page_title="Galatea Asistente - OMARDENT", layout="wide")
10
 
11
+ # Cargar las claves API desde el archivo .env
12
  load_dotenv()
13
+ openai_api_key = os.getenv("OPENAI_API_KEY")
14
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
15
 
16
+ # Verificar que las claves API est谩n configuradas
17
+ if not openai_api_key:
18
+ st.error("No API key provided for OpenAI. Please set your API key in the .env file.")
19
+ else:
20
+ openai.api_key = openai_api_key
21
 
22
+ # Funci贸n para obtener respuesta de OpenAI y generar audio con Google TTS
23
+ def obtener_respuesta(pregunta, contexto="", modelo="gpt-3.5-turbo", temperatura=0.5):
24
+ if not pregunta:
25
+ st.error("La pregunta no puede estar vac铆a.")
26
+ return "Lo siento, la pregunta no puede estar vac铆a."
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  try:
29
+ with st.spinner('Evaluando su respuesta...'):
30
+ response = openai.ChatCompletion.create(
31
+ model=modelo,
32
+ messages=[
33
+ {"role": "system", "content": contexto},
34
+ {"role": "user", "content": pregunta}
35
+ ],
36
+ temperature=temperatura
37
+ )
38
+ respuesta = response.choices[0].message['content'].strip()
39
+
40
+ # Configura la solicitud de s铆ntesis de voz
41
+ client = texttospeech.TextToSpeechClient()
42
+ input_text = texttospeech.SynthesisInput(text=respuesta)
43
+ voice = texttospeech.VoiceSelectionParams(
44
+ language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.FEMALE
45
+ )
46
+ audio_config = texttospeech.AudioConfig(
47
+ audio_encoding=texttospeech.AudioEncoding.MP3
48
  )
 
 
 
 
 
49
 
50
+ # Realiza la solicitud de s铆ntesis de voz
51
+ response = client.synthesize_speech(
52
+ input=input_text, voice=voice, audio_config=audio_config
53
+ )
54
+
55
+ # Reproduce el audio en Streamlit
56
+ st.audio(response.audio_content, format="audio/mp3")
57
+ return respuesta
58
+
59
+ except openai.OpenAIError as e:
60
+ st.error(f"Error al comunicarse con OpenAI: {e}")
61
+ return "Lo siento, no puedo procesar tu solicitud en este momento."
62
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  except Exception as e:
64
+ st.error(f"Error al generar la respuesta y el audio: {e}")
65
+ return "Lo siento, ocurri贸 un error al procesar tu solicitud."
66
+
67
+ # Funci贸n para manejar el chat del asistente
68
+ def mostrar_galatea_asistente():
69
+ st.title("馃Ψ Galatea - Asistente Virtual OMARDENT")
70
+
71
+ # Inicializa el historial del chat
72
+ if 'mensajes_chat' not in st.session_state:
73
+ st.session_state['mensajes_chat'] = []
74
+
75
+ # Mostrar los mensajes del chat
76
+ for mensaje in st.session_state['mensajes_chat']:
77
+ clase = "user" if mensaje["role"] == "user" else "assistant"
78
+ st.markdown(f'<div class="chat-message {clase}">{mensaje["content"]}</div>', unsafe_allow_html=True)
79
+
80
+ # Entrada de texto para la pregunta del usuario
81
+ pregunta_usuario = st.text_input("Escribe tu pregunta aqu铆:")
82
+
83
+ # Grabar y transcribir audio
84
+ if st.button("Grabar y Transcribir Audio"):
85
+ recognizer = sr.Recognizer()
86
+ with sr.Microphone() as source:
87
+ st.info("Grabando...")
88
+ audio = recognizer.listen(source, timeout=5)
89
+ st.info("Grabaci贸n completa")
90
+
91
+ try:
92
+ text = recognizer.recognize_google(audio, language="es-ES")
93
+ pregunta_usuario = text # Usar la transcripci贸n como la pregunta
94
+ except sr.UnknownValueError:
95
+ st.error("No se pudo entender el audio")
96
+ except sr.RequestError:
97
+ st.error("Error al solicitar el servicio de reconocimiento de voz")
98
+
99
+ # Enviar la pregunta y obtener la respuesta
100
+ if st.button("Enviar Pregunta"):
101
+ if pregunta_usuario:
102
+ # Guardar la pregunta en el historial
103
+ st.session_state['mensajes_chat'].append({"role": "user", "content": pregunta_usuario})
104
+
105
+ # Obtener respuesta de OpenAI
106
+ respuesta = obtener_respuesta(pregunta_usuario)
107
+
108
+ # Guardar la respuesta en el historial
109
+ st.session_state['mensajes_chat'].append({"role": "assistant", "content": respuesta})
110
+
111
+ # Funci贸n principal
112
+ def main():
113
+ mostrar_galatea_asistente()
114
+
115
+ if __name__ == "__main__":
116
+ main()