Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,201 +1,154 @@
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import openai
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
-
import
|
| 5 |
import os
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from nltk.corpus import stopwords
|
| 9 |
-
from nltk.stem import SnowballStemmer
|
| 10 |
-
import PyPDF2
|
| 11 |
-
import time
|
| 12 |
-
from google.cloud import texttospeech
|
| 13 |
-
from streamlit_webrtc import webrtc_streamer, WebRtcMode, AudioProcessorBase
|
| 14 |
-
|
| 15 |
-
# Configuración de NLTK
|
| 16 |
-
nltk.download('punkt')
|
| 17 |
-
nltk.download('stopwords')
|
| 18 |
-
|
| 19 |
-
# Cargar la clave API desde el archivo .env
|
| 20 |
load_dotenv()
|
| 21 |
-
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
|
| 22 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 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 |
temperature=temperatura,
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
client = texttospeech.TextToSpeechClient()
|
| 67 |
-
synthesis_input = texttospeech.SynthesisInput(text=respuesta)
|
| 68 |
-
voice = texttospeech.VoiceSelectionParams(
|
| 69 |
-
language_code="es-ES",
|
| 70 |
-
ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL,
|
| 71 |
-
)
|
| 72 |
-
audio_config = texttospeech.AudioConfig(
|
| 73 |
-
audio_encoding=texttospeech.AudioEncoding.MP3,
|
| 74 |
-
)
|
| 75 |
-
response = client.synthesize_speech(
|
| 76 |
-
input=synthesis_input, voice=voice, audio_config=audio_config
|
| 77 |
-
)
|
| 78 |
-
audio_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3").name
|
| 79 |
-
with open(audio_path, "wb") as out:
|
| 80 |
-
out.write(response.audio_content)
|
| 81 |
-
|
| 82 |
-
return respuesta, audio_path
|
| 83 |
-
|
| 84 |
-
# Main App
|
| 85 |
-
def main():
|
| 86 |
-
# --- Diseño general ---
|
| 87 |
-
st.set_page_config(page_title="Asistente Teológico", page_icon="📖")
|
| 88 |
-
|
| 89 |
-
# --- Estilos CSS personalizados ---
|
| 90 |
-
st.markdown(
|
| 91 |
-
"""
|
| 92 |
-
<style>
|
| 93 |
-
body {
|
| 94 |
-
background: #f2f3f5;
|
| 95 |
-
color: #333;
|
| 96 |
-
}
|
| 97 |
-
.stButton>button {
|
| 98 |
-
background-color: #4CAF50;
|
| 99 |
-
color: white;
|
| 100 |
-
border-radius: 10px;
|
| 101 |
-
}
|
| 102 |
-
.stTextInput>div>div>input {
|
| 103 |
-
border: 1px solid #4CAF50;
|
| 104 |
-
border-radius: 10px;
|
| 105 |
-
}
|
| 106 |
-
.stMarkdown>div>p {
|
| 107 |
-
color: #4CAF50;
|
| 108 |
-
font-weight: bold;
|
| 109 |
-
}
|
| 110 |
-
.stAudio {
|
| 111 |
-
margin-top: 20px;
|
| 112 |
-
border: 2px solid #4CAF50;
|
| 113 |
-
border-radius: 10px;
|
| 114 |
-
}
|
| 115 |
-
.stFileUploader>div>div>input {
|
| 116 |
-
border: 1px solid #4CAF50;
|
| 117 |
-
border-radius: 10px;
|
| 118 |
-
}
|
| 119 |
-
</style>
|
| 120 |
-
""",
|
| 121 |
-
unsafe_allow_html=True,
|
| 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 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
import streamlit as st
|
|
|
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
+
import openai
|
| 5 |
import os
|
| 6 |
+
|
| 7 |
+
# Configuración de la clave API
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
load_dotenv()
|
|
|
|
| 9 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 10 |
|
| 11 |
+
# Clases para la gestión de pedidos
|
| 12 |
+
class PedidoAgent:
|
| 13 |
+
def __init__(self, menu_csv_path):
|
| 14 |
+
self.menu_csv_path = menu_csv_path
|
| 15 |
+
self.menu_data = self.load_menu()
|
| 16 |
+
|
| 17 |
+
def load_menu(self):
|
| 18 |
+
try:
|
| 19 |
+
df_menu = pd.read_csv(self.menu_csv_path)
|
| 20 |
+
productos = df_menu["Producto"].tolist()
|
| 21 |
+
precios = df_menu["Precio"].tolist()
|
| 22 |
+
return {"productos": productos, "precios": precios}
|
| 23 |
+
except Exception as e:
|
| 24 |
+
st.error(f"Error al cargar el menú: {e}")
|
| 25 |
+
return None
|
| 26 |
+
|
| 27 |
+
def realizar_pedido(self, state):
|
| 28 |
+
if not self.menu_data:
|
| 29 |
+
st.warning("No se pudo cargar el menú.")
|
| 30 |
+
return
|
| 31 |
+
|
| 32 |
+
productos = self.menu_data["productos"]
|
| 33 |
+
precios = self.menu_data["precios"]
|
| 34 |
+
|
| 35 |
+
# Interfaz de usuario para seleccionar productos y cantidades
|
| 36 |
+
with st.form("pedido_form"):
|
| 37 |
+
producto_seleccionado = st.selectbox("Producto:", productos)
|
| 38 |
+
cantidad = st.number_input("Cantidad:", min_value=1, value=1)
|
| 39 |
+
submitted = st.form_submit_button("Agregar al pedido")
|
| 40 |
+
|
| 41 |
+
if submitted:
|
| 42 |
+
precio = precios[productos.index(producto_seleccionado)]
|
| 43 |
+
state.pedidos.append(
|
| 44 |
+
{"Producto": producto_seleccionado, "Cantidad": cantidad, "Precio": precio}
|
| 45 |
+
)
|
| 46 |
+
st.success("Pedido agregado correctamente")
|
| 47 |
+
|
| 48 |
+
# Mostrar el pedido actual
|
| 49 |
+
st.subheader("Pedido actual:")
|
| 50 |
+
if state.pedidos:
|
| 51 |
+
df_pedidos = pd.DataFrame(state.pedidos)
|
| 52 |
+
st.table(df_pedidos)
|
| 53 |
+
|
| 54 |
+
class CalculoPedidoAgent:
|
| 55 |
+
def calcular_total(self, state):
|
| 56 |
+
st.subheader("Resumen del Pedido")
|
| 57 |
+
if state.pedidos:
|
| 58 |
+
df_pedidos = pd.DataFrame(state.pedidos)
|
| 59 |
+
st.table(df_pedidos)
|
| 60 |
+
total = df_pedidos["Cantidad"].mul(df_pedidos["Precio"]).sum()
|
| 61 |
+
st.markdown(f"**Total: ${total:.2f}**")
|
| 62 |
+
else:
|
| 63 |
+
st.info("El pedido está vacío.")
|
| 64 |
+
|
| 65 |
+
# Función para obtener respuesta de OpenAI
|
| 66 |
+
def obtener_respuesta(pregunta, modelo="gpt-4", temperatura=0.5):
|
| 67 |
+
response = openai.ChatCompletion.create(
|
| 68 |
+
model=modelo,
|
| 69 |
+
messages=[{"role": "system", "content": "You are a knowledgeable theological assistant."},
|
| 70 |
+
{"role": "user", "content": pregunta}],
|
| 71 |
temperature=temperatura,
|
| 72 |
+
max_tokens=150,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
)
|
| 74 |
+
respuesta = response['choices'][0]['message']['content']
|
| 75 |
+
return respuesta
|
| 76 |
+
|
| 77 |
+
# Configuración de Streamlit
|
| 78 |
+
st.set_page_config(page_title="Asistente Teológico", page_icon="📖")
|
| 79 |
+
|
| 80 |
+
# Estilos CSS personalizados
|
| 81 |
+
st.markdown(
|
| 82 |
+
"""
|
| 83 |
+
<style>
|
| 84 |
+
body {
|
| 85 |
+
background: #f2f3f5;
|
| 86 |
+
color: #333;
|
| 87 |
+
}
|
| 88 |
+
.stButton>button {
|
| 89 |
+
background-color: #4CAF50;
|
| 90 |
+
color: white;
|
| 91 |
+
border-radius: 10px;
|
| 92 |
+
}
|
| 93 |
+
.stTextInput>div>div>input {
|
| 94 |
+
border: 1px solid #4CAF50;
|
| 95 |
+
border-radius: 10px;
|
| 96 |
+
}
|
| 97 |
+
.stMarkdown>div>p {
|
| 98 |
+
color: #4CAF50;
|
| 99 |
+
font-weight: bold;
|
| 100 |
+
}
|
| 101 |
+
.stAudio {
|
| 102 |
+
margin-top: 20px;
|
| 103 |
+
border: 2px solid #4CAF50;
|
| 104 |
+
border-radius: 10px;
|
| 105 |
+
}
|
| 106 |
+
.stFileUploader>div>div>input {
|
| 107 |
+
border: 1px solid #4CAF50;
|
| 108 |
+
border-radius: 10px;
|
| 109 |
+
}
|
| 110 |
+
</style>
|
| 111 |
+
""",
|
| 112 |
+
unsafe_allow_html=True,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Encabezado
|
| 116 |
+
st.image("biblia.jpg")
|
| 117 |
+
st.title("📖 Asistente Teológico - BOTIDINAMIX AI")
|
| 118 |
+
st.markdown("Bienvenido al Asistente Teológico, donde puedes preguntar sobre interpretaciones y reflexiones bíblicas.")
|
| 119 |
+
|
| 120 |
+
# Chat
|
| 121 |
+
st.subheader("🗣️ Chat con el Asistente")
|
| 122 |
+
if 'mensajes' not in st.session_state:
|
| 123 |
+
st.session_state.mensajes = []
|
| 124 |
+
|
| 125 |
+
for mensaje in st.session_state.mensajes:
|
| 126 |
+
with st.chat_message(mensaje["role"]):
|
| 127 |
+
st.markdown(mensaje["content"])
|
| 128 |
+
|
| 129 |
+
pregunta_usuario = st.text_input("Escribe tu pregunta sobre la Biblia:")
|
| 130 |
+
if st.button("Enviar"):
|
| 131 |
+
if pregunta_usuario:
|
| 132 |
+
st.session_state.mensajes.append({"role": "user", "content": pregunta_usuario, "timestamp": time.time()})
|
| 133 |
+
with st.chat_message("user"):
|
| 134 |
+
st.markdown(pregunta_usuario)
|
| 135 |
+
|
| 136 |
+
with st.spinner("Generando respuesta..."):
|
| 137 |
+
respuesta = obtener_respuesta(pregunta_usuario)
|
| 138 |
+
st.session_state.mensajes.append({"role": "assistant", "content": respuesta, "timestamp": time.time()})
|
| 139 |
+
with st.chat_message("assistant"):
|
| 140 |
+
st.markdown(respuesta)
|
| 141 |
+
else:
|
| 142 |
+
st.warning("Por favor, ingresa una pregunta antes de enviar.")
|
| 143 |
+
|
| 144 |
+
# Gestión de pedidos
|
| 145 |
+
st.subheader("📋 Gestión de Pedidos")
|
| 146 |
+
menu_csv_path = "menu.csv" # Ruta al archivo CSV del menú
|
| 147 |
+
if 'pedidos' not in st.session_state:
|
| 148 |
+
st.session_state.pedidos = []
|
| 149 |
+
|
| 150 |
+
pedido_agent = PedidoAgent(menu_csv_path)
|
| 151 |
+
calculo_pedido_agent = CalculoPedidoAgent()
|
| 152 |
+
|
| 153 |
+
pedido_agent.realizar_pedido(st.session_state)
|
| 154 |
+
calculo_pedido_agent.calcular_total(st.session_state)
|