Spaces:
Sleeping
Sleeping
| 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 | |
| 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 "" | |