Update app.py
Browse files
app.py
CHANGED
|
@@ -1,175 +1,116 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
|
|
|
| 3 |
import streamlit as st
|
| 4 |
-
|
| 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
|
| 13 |
-
st.set_page_config(page_title="Asistente
|
| 14 |
|
| 15 |
-
# Cargar las
|
| 16 |
load_dotenv()
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
"role": "
|
| 51 |
-
"content":
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
#
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 84 |
-
|
| 85 |
-
# Funci贸n para
|
| 86 |
-
def
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
st.
|
| 97 |
-
|
| 98 |
-
#
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
)
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|