Spaces:
Sleeping
Sleeping
File size: 9,278 Bytes
8af6919 a9405cc 28574ad c378bb7 28574ad 5d9778c dd86a62 7647b45 9063d97 5d9778c c378bb7 d9fd372 a9405cc d9fd372 45a3c45 0629ab8 45a3c45 4cb971f 45a3c45 4cb971f 45a3c45 4cb971f 45a3c45 0629ab8 4cb971f 0629ab8 4cb971f 0629ab8 45a3c45 4fa1a25 0629ab8 45a3c45 74ff3e4 6d3695c a9405cc 74ff3e4 6d3695c 74ff3e4 60ceb5e 242324f 9063d97 a9405cc 9063d97 a9405cc 9063d97 91a773b a9405cc 9063d97 f58299a a9405cc f58299a a9405cc 9063d97 e2047c7 91bb02a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | import streamlit as st
from transformers import pipeline
from dotenv import load_dotenv
import openai
import os
import time
import base64
import tempfile
from google.cloud import texttospeech
from google.cloud.speech import SpeechClient, RecognitionAudio, RecognitionConfig
from streamlit_webrtc import webrtc_streamer, WebRtcMode, AudioProcessorBase
# Configuración de la clave API
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
# Configuración de Streamlit
st.set_page_config(page_title="Asistente Teológico", page_icon="📖")
# Estilos CSS personalizados
st.markdown(
"""
<style>
body {
background: linear-gradient(to right, #f2f3f5, #ffcccb);
color: #333;
}
.stButton>button {
background-color: #4CAF50;
color: white;
border-radius: 10px;
}
.stTextInput>div>div>input {
border: 1px solid #4CAF50;
border-radius: 10px;
}
.stMarkdown>div>p {
color: #4CAF50;
font-weight: bold.
}
.stAudio {
margin-top: 20px;
border: 2px solid #4CAF50;
border-radius: 10px.
}
.stFileUploader>div>div>input {
border: 1px solid #4CAF50.
border-radius: 10px.
}
.spinner {
border: 8px solid #f3f3f3.
border-top: 8px solid #4CAF50.
border-radius: 50%.
width: 60px.
height: 60px.
animation: spin 1s linear infinite.
}
@keyframes spin {
0% { transform: rotate(0deg). }
100% { transform: rotate(360deg). }
}
</style>
""",
unsafe_allow_html=True,
)
# Encabezado
st.image("biblie.jpg")
st.title("📖 LOS CÓDIGOS DE DIOS - BOTIDINAMIX AI")
st.markdown("Bienvenido al Asistente Teológico, donde puedes preguntar sobre interpretaciones y reflexiones bíblicas.")
# Barra lateral para la navegación
st.sidebar.title("Navegación")
page = st.sidebar.selectbox("Selecciona una página", ["Chat Asistente", "Gestión de Pedidos", "Generador de Frases Bíblicas"])
# Cargar el modelo de Hugging Face
@st.cache(allow_output_mutation=True)
def cargar_modelo():
return pipeline('text-to-image', model='CompVis/stable-diffusion-v1-4')
modelo_generacion_imagenes = cargar_modelo()
if page == "Chat Asistente":
# Chat con el asistente
st.subheader("🗣️ Chat con el Asistente")
if 'mensajes' not in st.session_state:
st.session_state.mensajes = []
for mensaje in st.session_state.mensajes:
with st.chat_message(mensaje["role"]):
if isinstance(mensaje["content"], str):
st.markdown(mensaje["content"])
elif isinstance(mensaje["content"], bytes):
st.image(mensaje["content"])
pregunta_usuario = st.text_input("Escribe tu pregunta sobre la Biblia:", key="pregunta_input")
imagen_usuario = st.file_uploader("Sube una imagen (opcional):", type=["png", "jpg", "jpeg"])
if st.button("Enviar"):
if pregunta_usuario or imagen_usuario:
if pregunta_usuario:
st.session_state.mensajes.append({"role": "user", "content": pregunta_usuario, "timestamp": time.time()})
with st.chat_message("user"):
st.markdown(pregunta_usuario)
if imagen_usuario:
imagen_bytes = imagen_usuario.getvalue()
st.session_state.mensajes.append({"role": "user", "content": imagen_bytes, "timestamp": time.time()})
with st.chat_message("user"):
st.image(imagen_bytes)
st.session_state.pregunta_input = "" # Borrar el campo de texto después de enviar la pregunta
with st.spinner("Generando respuesta..."):
with st.empty():
spinner = st.markdown('<div class="spinner"></div>', unsafe_allow_html=True)
time.sleep(1) # Simulación del tiempo de procesamiento
spinner.empty()
if pregunta_usuario:
respuesta = obtener_respuesta(pregunta_usuario)
st.session_state.mensajes.append({"role": "assistant", "content": respuesta, "timestamp": time.time()})
with st.chat_message("assistant"):
st.markdown(respuesta)
st.video("https://cdn.pika.art/v1/0fe46d03-efd2-49d8-86a2-9230769af8cd/Talking_seed1363056373525570.mp4", start_time=0)
# Convertir texto a voz
audio_base64 = text_to_speech_base64(respuesta)
audio_html = f"""
<audio autoplay>
<source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
</audio>
"""
st.markdown(audio_html, unsafe_allow_html=True)
else:
st.warning("Por favor, ingresa una pregunta antes de enviar.")
elif page == "Gestión de Pedidos":
st.subheader("📋 Gestión de Pedidos")
menu_csv_path = "menu.csv" # Ruta al archivo CSV del menú
if 'pedidos' not in st.session_state:
st.session_state.pedidos = []
pedido_agent = PedidoAgent(menu_csv_path)
calculo_pedido_agent = CalculoPedidoAgent()
pedido_agent.realizar_pedido(st.session_state)
calculo_pedido_agent.calcular_total(st.session_state)
elif page == "Generador de Frases Bíblicas":
# Función para generar una imagen alusiva usando Hugging Face
def generar_imagen(frase):
try:
images = modelo_generacion_imagenes(frase, num_return_sequences=1)
image = images[0]["generated_image"]
return image
except Exception as e:
st.error(f"Error al generar la imagen: {e}")
return None
# Encabezado
st.subheader("📜 Generador de Frases Bíblicas")
st.markdown("Escribe un versículo o una palabra y obtén una imagen alusiva usando Hugging Face.")
# Entrada de texto para el versículo o palabra
versiculo_usuario = st.text_input("Escribe un versículo o una palabra:")
if st.button("Generar"):
if versiculo_usuario:
with st.spinner("Generando imagen..."):
imagen_generada = generar_imagen(versiculo_usuario)
if imagen_generada:
st.subheader("Imagen alusiva:")
st.image(imagen_generada)
else:
st.warning("Por favor, ingresa un versículo o una palabra antes de generar.")
# Función para obtener respuesta de OpenAI
def obtener_respuesta(pregunta, modelo="gpt-4", temperatura=0.5):
response = openai.ChatCompletion.create(
model=modelo,
messages=[{"role": "system", "content": "You are a knowledgeable theological assistant."},
{"role": "user", "content": pregunta}],
temperature=temperatura,
max_tokens=150,
)
respuesta = response['choices'][0]['message']['content']
return respuesta
# Función para convertir texto a voz usando Google Cloud Text-to-Speech
def text_to_speech(text):
client = texttospeech.TextToSpeechClient()
synthesis_input = texttospeech.SynthesisInput(text=text)
voice = texttospeech.VoiceSelectionParams(language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)
audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)
audio_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3").name
with open(audio_path, "wb") as out:
out.write(response.audio_content)
return audio_path
# Función para convertir texto a voz y devolver base64
def text_to_speech_base64(text):
client = texttospeech.TextToSpeechClient()
synthesis_input = texttospeech.SynthesisInput(text=text)
voice = texttospeech.VoiceSelectionParams(language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL)
audio_config = texttospeech.AudioConfig(audio_encoding=texttospeech.AudioEncoding.MP3)
response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config)
audio_base64 = base64.b64encode(response.audio_content).decode('utf-8')
return audio_base64
# Clase para procesar audio
class AudioProcessor(AudioProcessorBase):
def __init__(self):
self.audio_bytes = b''
def recv(self, frame):
self.audio_bytes += frame.to_ndarray().tobytes()
return frame
# Función para transcribir audio a texto usando Google Cloud Speech-to-Text
def transcribir_audio(audio_bytes):
client = SpeechClient()
audio = RecognitionAudio(content=audio_bytes)
config = RecognitionConfig(
encoding=RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code="es-ES",
)
response = client.recognize(config=config, audio=audio)
for result in response.results:
return result.alternatives[0].transcript
return ""
|