Spaces:
Build error
Build error
Update chat.py
Browse files
chat.py
CHANGED
|
@@ -1,249 +1,249 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import openai
|
| 3 |
-
from dotenv import load_dotenv
|
| 4 |
-
import nltk
|
| 5 |
-
import os
|
| 6 |
-
import tempfile
|
| 7 |
-
from nltk.tokenize import word_tokenize
|
| 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 Historial.historial_chat import cargar_historial, guardar_historial # Importa las funciones
|
| 14 |
-
from streamlit_webrtc import webrtc_streamer, WebRtcMode
|
| 15 |
-
import av
|
| 16 |
-
|
| 17 |
-
# Configuración de NLTK
|
| 18 |
-
nltk.download('punkt')
|
| 19 |
-
nltk.download('stopwords')
|
| 20 |
-
|
| 21 |
-
# Función para cargar el texto del PDF
|
| 22 |
-
def extraer_texto_pdf(archivo):
|
| 23 |
-
texto = ""
|
| 24 |
-
if archivo:
|
| 25 |
-
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
| 26 |
-
temp_file.write(archivo.read())
|
| 27 |
-
temp_file_path = temp_file.name
|
| 28 |
-
with open(temp_file_path, 'rb') as file:
|
| 29 |
-
reader = PyPDF2.PdfReader(file)
|
| 30 |
-
for page in range(len(reader.pages)):
|
| 31 |
-
texto += reader.pages[page].extract_text()
|
| 32 |
-
os.unlink(temp_file_path)
|
| 33 |
-
return texto
|
| 34 |
-
|
| 35 |
-
# Función para preprocesar texto
|
| 36 |
-
def preprocesar_texto(texto):
|
| 37 |
-
tokens = word_tokenize(texto, language='spanish')
|
| 38 |
-
tokens = [word.lower() for word in tokens if word.isalpha()]
|
| 39 |
-
stopwords_es = set(stopwords.words('spanish'))
|
| 40 |
-
tokens = [word for word in tokens if word not in stopwords_es]
|
| 41 |
-
stemmer = SnowballStemmer('spanish')
|
| 42 |
-
tokens = [stemmer.stem(word) for word in tokens]
|
| 43 |
-
return " ".join(tokens)
|
| 44 |
-
|
| 45 |
-
# Cargar la clave API desde el archivo .env
|
| 46 |
-
load_dotenv()
|
| 47 |
-
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json" # Reemplaza 'key.json' con el nombre de tu archivo de credenciales
|
| 48 |
-
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 49 |
-
|
| 50 |
-
# Instancia el cliente de Text-to-Speech
|
| 51 |
-
client = texttospeech.TextToSpeechClient()
|
| 52 |
-
|
| 53 |
-
# Función para obtener respuesta de OpenAI usando el modelo GPT y convertir a audio
|
| 54 |
-
def obtener_respuesta(pregunta, texto_preprocesado, modelo, temperatura=0.5):
|
| 55 |
-
try:
|
| 56 |
-
response = openai.ChatCompletion.create(
|
| 57 |
-
model=modelo,
|
| 58 |
-
messages=[
|
| 59 |
-
{"role": "system", "content": "Actua como
|
| 60 |
-
{"role": "user", "content": f"{pregunta}\n\nContexto: {texto_preprocesado}"}
|
| 61 |
-
],
|
| 62 |
-
temperature=temperatura
|
| 63 |
-
)
|
| 64 |
-
respuesta = response.choices[0].message['content'].strip()
|
| 65 |
-
|
| 66 |
-
# Configura la solicitud de síntesis de voz
|
| 67 |
-
input_text = texttospeech.SynthesisInput(text=respuesta)
|
| 68 |
-
voice = texttospeech.VoiceSelectionParams(
|
| 69 |
-
language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.MALE,
|
| 70 |
-
)
|
| 71 |
-
audio_config = texttospeech.AudioConfig(
|
| 72 |
-
audio_encoding=texttospeech.AudioEncoding.MP3
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
-
# Realiza la solicitud de síntesis de voz
|
| 76 |
-
response = client.synthesize_speech(
|
| 77 |
-
input=input_text, voice=voice, audio_config=audio_config
|
| 78 |
-
)
|
| 79 |
-
|
| 80 |
-
# Reproduce el audio en Streamlit
|
| 81 |
-
st.audio(response.audio_content, format="audio/mp3")
|
| 82 |
-
return respuesta
|
| 83 |
-
|
| 84 |
-
except openai.OpenAIError as e:
|
| 85 |
-
st.error(f"Error al comunicarse con OpenAI: {e}")
|
| 86 |
-
return "Lo siento, no puedo procesar tu solicitud en este momento."
|
| 87 |
-
|
| 88 |
-
def main():
|
| 89 |
-
# --- Diseño general ---
|
| 90 |
-
st.set_page_config(page_title="Asistente Virtual", page_icon="🤖")
|
| 91 |
-
|
| 92 |
-
# --- Barra lateral ---
|
| 93 |
-
with st.sidebar:
|
| 94 |
-
st.image("Holybiblie.jpg")
|
| 95 |
-
st.title("🤖 LOS CODIGOS DE DIOS-BOTIDINAMIX AI")
|
| 96 |
-
st.markdown("---")
|
| 97 |
-
# --- Estilos CSS personalizados ---
|
| 98 |
-
st.markdown(
|
| 99 |
-
"""
|
| 100 |
-
<style>
|
| 101 |
-
body {
|
| 102 |
-
background-image: linear-gradient(to right, #4B0082, #0000FF); /* Fondo degradado */
|
| 103 |
-
}
|
| 104 |
-
.stChatFloatingInputContainer { /* Estilos para el contenedor del input del chat */
|
| 105 |
-
background-color: rgba(255, 255, 255, 0.8); /* Fondo blanco con opacidad */
|
| 106 |
-
border-radius: 10px; /* Bordes redondeados */
|
| 107 |
-
}
|
| 108 |
-
.stTextInput > div > div > input { /* Input de texto del chat */
|
| 109 |
-
color: #333; /* Color de texto más oscuro */
|
| 110 |
-
}
|
| 111 |
-
[data-testid="stChatMessage"] { /* Burbujas de chat */
|
| 112 |
-
background-color: black !important; /* Color de fondo negro */
|
| 113 |
-
color: gold !important; /* Color de texto dorado */
|
| 114 |
-
border-radius: 10px;
|
| 115 |
-
}
|
| 116 |
-
[data-testid="stChatMessage"] p { /* Párrafos dentro de las burbujas */
|
| 117 |
-
color: gold !important;
|
| 118 |
-
}
|
| 119 |
-
</style>
|
| 120 |
-
""",
|
| 121 |
-
unsafe_allow_html=True,
|
| 122 |
-
)
|
| 123 |
-
# --- Botones de historial ---
|
| 124 |
-
if st.button("Buscar Historial"):
|
| 125 |
-
st.session_state.mostrar_historial = True
|
| 126 |
-
if st.button("Borrar Historial"):
|
| 127 |
-
st.session_state.mensajes = []
|
| 128 |
-
st.session_state.mostrar_historial = False
|
| 129 |
-
st.success("Historial borrado correctamente")
|
| 130 |
-
# --- Chatbot ---
|
| 131 |
-
if 'mensajes' not in st.session_state:
|
| 132 |
-
st.session_state.mensajes = cargar_historial()
|
| 133 |
-
|
| 134 |
-
for mensaje in st.session_state.mensajes:
|
| 135 |
-
with st.chat_message(mensaje["role"]):
|
| 136 |
-
st.markdown(mensaje["content"])
|
| 137 |
-
# Función para manejar la entrada de audio
|
| 138 |
-
def on_audio(audio_bytes):
|
| 139 |
-
with st.spinner("Transcribiendo..."):
|
| 140 |
-
transcript = openai.Audio.transcribe("whisper-1", audio_bytes)
|
| 141 |
-
pregunta_usuario = transcript["text"]
|
| 142 |
-
st.session_state.mensajes.append({"role": "user", "content": pregunta_usuario, "timestamp": time.time()})
|
| 143 |
-
with st.chat_message("user"):
|
| 144 |
-
st.markdown(pregunta_usuario)
|
| 145 |
-
|
| 146 |
-
st.subheader("🎤 Captura de voz")
|
| 147 |
-
st.info("Haz clic en el micrófono y comienza a hablar. Tu pregunta se transcribirá automáticamente.")
|
| 148 |
-
with st.container():
|
| 149 |
-
if st.button("Grabar 🎙️"):
|
| 150 |
-
st.session_state.run_webrtc = True
|
| 151 |
-
if st.session_state.get("run_webrtc", False):
|
| 152 |
-
webrtc_streamer(
|
| 153 |
-
key="speech-to-text",
|
| 154 |
-
mode=WebRtcMode.SENDONLY,
|
| 155 |
-
rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]},
|
| 156 |
-
media_stream_constraints={"video": False, "audio": True},
|
| 157 |
-
on_audio=on_audio,
|
| 158 |
-
)
|
| 159 |
-
st.session_state["run_webrtc"] = False
|
| 160 |
-
|
| 161 |
-
# Mostrar historial si el botón fue presionado
|
| 162 |
-
if st.session_state.get("mostrar_historial", False):
|
| 163 |
-
st.subheader("Historial de Chat:")
|
| 164 |
-
if st.session_state.mensajes:
|
| 165 |
-
for mensaje in st.session_state.mensajes:
|
| 166 |
-
with st.chat_message(mensaje["role"]):
|
| 167 |
-
st.markdown(mensaje["content"])
|
| 168 |
-
else:
|
| 169 |
-
st.info("No hay mensajes en el historial.")
|
| 170 |
-
else:
|
| 171 |
-
for mensaje in st.session_state.mensajes:
|
| 172 |
-
with st.chat_message(mensaje["role"]):
|
| 173 |
-
st.markdown(mensaje["content"])
|
| 174 |
-
|
| 175 |
-
# Selección de modelo de lenguaje
|
| 176 |
-
st.subheader("🧠 Configuración del Modelo")
|
| 177 |
-
modelo = st.selectbox(
|
| 178 |
-
"Selecciona el modelo:",
|
| 179 |
-
["gpt-3.5-turbo", "gpt-4"],
|
| 180 |
-
index=0,
|
| 181 |
-
help="Elige el modelo de lenguaje de OpenAI que prefieras."
|
| 182 |
-
)
|
| 183 |
-
|
| 184 |
-
# --- Opciones adicionales ---
|
| 185 |
-
st.markdown("---")
|
| 186 |
-
temperatura = st.slider("🌡️ Temperatura", min_value=0.0, max_value=1.0, value=0.5, step=0.1)
|
| 187 |
-
|
| 188 |
-
# --- Video de fondo ---
|
| 189 |
-
with st.container():
|
| 190 |
-
st.markdown(
|
| 191 |
-
f"""
|
| 192 |
-
<style>
|
| 193 |
-
#video-container {{
|
| 194 |
-
position: relative;
|
| 195 |
-
width: 100%;
|
| 196 |
-
padding-bottom: 56.25%;
|
| 197 |
-
background-color: lightblue;
|
| 198 |
-
overflow: hidden;
|
| 199 |
-
}}
|
| 200 |
-
#background-video {{
|
| 201 |
-
position: absolute;
|
| 202 |
-
top: 0;
|
| 203 |
-
left: 0;
|
| 204 |
-
width: 100%;
|
| 205 |
-
height: 100%;
|
| 206 |
-
}}
|
| 207 |
-
</style>
|
| 208 |
-
<div id="video-container">
|
| 209 |
-
<video id="background-video" autoplay loop muted playsinline>
|
| 210 |
-
<source src="https://cdn.pika.art/v1/f41adf48-a6db-4c6e-a93e-cd8db88f469d/movimiento_del_cuerpo_sutil_seed902109641145783.mp4" type="video/mp4">
|
| 211 |
-
</video>
|
| 212 |
-
</div>
|
| 213 |
-
""",
|
| 214 |
-
unsafe_allow_html=True,
|
| 215 |
-
)
|
| 216 |
-
|
| 217 |
-
# --- Área principal de la aplicación ---
|
| 218 |
-
st.header("💬 Relexionar con Elias")
|
| 219 |
-
|
| 220 |
-
# Carga de archivo PDF
|
| 221 |
-
archivo_pdf = st.file_uploader("📂 Cargar PDF", type='pdf')
|
| 222 |
-
|
| 223 |
-
# --- Chatbot ---
|
| 224 |
-
if 'mensajes' not in st.session_state:
|
| 225 |
-
st.session_state.mensajes = []
|
| 226 |
-
|
| 227 |
-
for mensaje in st.session_state.mensajes:
|
| 228 |
-
with st.chat_message(mensaje["role"]):
|
| 229 |
-
st.markdown(mensaje["content"])
|
| 230 |
-
|
| 231 |
-
pregunta_usuario = st.chat_input("Pregunta:")
|
| 232 |
-
if pregunta_usuario:
|
| 233 |
-
st.session_state.mensajes.append({"role": "user", "content": pregunta_usuario})
|
| 234 |
-
with st.chat_message("user"):
|
| 235 |
-
st.markdown(pregunta_usuario)
|
| 236 |
-
|
| 237 |
-
if archivo_pdf:
|
| 238 |
-
texto_pdf = extraer_texto_pdf(archivo_pdf)
|
| 239 |
-
texto_preprocesado = preprocesar_texto(texto_pdf)
|
| 240 |
-
else:
|
| 241 |
-
texto_preprocesado = "" # Sin contexto de PDF si no se carga un archivo
|
| 242 |
-
|
| 243 |
-
respuesta = obtener_respuesta(pregunta_usuario, texto_preprocesado, modelo, temperatura)
|
| 244 |
-
st.session_state.mensajes.append({"role": "assistant", "content": respuesta})
|
| 245 |
-
with st.chat_message("assistant"):
|
| 246 |
-
st.markdown(respuesta)
|
| 247 |
-
|
| 248 |
-
if __name__ == "__main__":
|
| 249 |
-
main()
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import openai
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
import nltk
|
| 5 |
+
import os
|
| 6 |
+
import tempfile
|
| 7 |
+
from nltk.tokenize import word_tokenize
|
| 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 Historial.historial_chat import cargar_historial, guardar_historial # Importa las funciones
|
| 14 |
+
from streamlit_webrtc import webrtc_streamer, WebRtcMode
|
| 15 |
+
import av
|
| 16 |
+
|
| 17 |
+
# Configuración de NLTK
|
| 18 |
+
nltk.download('punkt')
|
| 19 |
+
nltk.download('stopwords')
|
| 20 |
+
|
| 21 |
+
# Función para cargar el texto del PDF
|
| 22 |
+
def extraer_texto_pdf(archivo):
|
| 23 |
+
texto = ""
|
| 24 |
+
if archivo:
|
| 25 |
+
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
| 26 |
+
temp_file.write(archivo.read())
|
| 27 |
+
temp_file_path = temp_file.name
|
| 28 |
+
with open(temp_file_path, 'rb') as file:
|
| 29 |
+
reader = PyPDF2.PdfReader(file)
|
| 30 |
+
for page in range(len(reader.pages)):
|
| 31 |
+
texto += reader.pages[page].extract_text()
|
| 32 |
+
os.unlink(temp_file_path)
|
| 33 |
+
return texto
|
| 34 |
+
|
| 35 |
+
# Función para preprocesar texto
|
| 36 |
+
def preprocesar_texto(texto):
|
| 37 |
+
tokens = word_tokenize(texto, language='spanish')
|
| 38 |
+
tokens = [word.lower() for word in tokens if word.isalpha()]
|
| 39 |
+
stopwords_es = set(stopwords.words('spanish'))
|
| 40 |
+
tokens = [word for word in tokens if word not in stopwords_es]
|
| 41 |
+
stemmer = SnowballStemmer('spanish')
|
| 42 |
+
tokens = [stemmer.stem(word) for word in tokens]
|
| 43 |
+
return " ".join(tokens)
|
| 44 |
+
|
| 45 |
+
# Cargar la clave API desde el archivo .env
|
| 46 |
+
load_dotenv()
|
| 47 |
+
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json" # Reemplaza 'key.json' con el nombre de tu archivo de credenciales
|
| 48 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 49 |
+
|
| 50 |
+
# Instancia el cliente de Text-to-Speech
|
| 51 |
+
client = texttospeech.TextToSpeechClient()
|
| 52 |
+
|
| 53 |
+
# Función para obtener respuesta de OpenAI usando el modelo GPT y convertir a audio
|
| 54 |
+
def obtener_respuesta(pregunta, texto_preprocesado, modelo, temperatura=0.5):
|
| 55 |
+
try:
|
| 56 |
+
response = openai.ChatCompletion.create(
|
| 57 |
+
model=modelo,
|
| 58 |
+
messages=[
|
| 59 |
+
{"role": "system", "content": "Actua como Ana una asesora de ventas del restaurante Sazon Burguer, tienes un tono muy amable y cordial"},
|
| 60 |
+
{"role": "user", "content": f"{pregunta}\n\nContexto: {texto_preprocesado}"}
|
| 61 |
+
],
|
| 62 |
+
temperature=temperatura
|
| 63 |
+
)
|
| 64 |
+
respuesta = response.choices[0].message['content'].strip()
|
| 65 |
+
|
| 66 |
+
# Configura la solicitud de síntesis de voz
|
| 67 |
+
input_text = texttospeech.SynthesisInput(text=respuesta)
|
| 68 |
+
voice = texttospeech.VoiceSelectionParams(
|
| 69 |
+
language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.MALE,
|
| 70 |
+
)
|
| 71 |
+
audio_config = texttospeech.AudioConfig(
|
| 72 |
+
audio_encoding=texttospeech.AudioEncoding.MP3
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Realiza la solicitud de síntesis de voz
|
| 76 |
+
response = client.synthesize_speech(
|
| 77 |
+
input=input_text, voice=voice, audio_config=audio_config
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# Reproduce el audio en Streamlit
|
| 81 |
+
st.audio(response.audio_content, format="audio/mp3")
|
| 82 |
+
return respuesta
|
| 83 |
+
|
| 84 |
+
except openai.OpenAIError as e:
|
| 85 |
+
st.error(f"Error al comunicarse con OpenAI: {e}")
|
| 86 |
+
return "Lo siento, no puedo procesar tu solicitud en este momento."
|
| 87 |
+
|
| 88 |
+
def main():
|
| 89 |
+
# --- Diseño general ---
|
| 90 |
+
st.set_page_config(page_title="Asistente Virtual", page_icon="🤖")
|
| 91 |
+
|
| 92 |
+
# --- Barra lateral ---
|
| 93 |
+
with st.sidebar:
|
| 94 |
+
st.image("Holybiblie.jpg")
|
| 95 |
+
st.title("🤖 LOS CODIGOS DE DIOS-BOTIDINAMIX AI")
|
| 96 |
+
st.markdown("---")
|
| 97 |
+
# --- Estilos CSS personalizados ---
|
| 98 |
+
st.markdown(
|
| 99 |
+
"""
|
| 100 |
+
<style>
|
| 101 |
+
body {
|
| 102 |
+
background-image: linear-gradient(to right, #4B0082, #0000FF); /* Fondo degradado */
|
| 103 |
+
}
|
| 104 |
+
.stChatFloatingInputContainer { /* Estilos para el contenedor del input del chat */
|
| 105 |
+
background-color: rgba(255, 255, 255, 0.8); /* Fondo blanco con opacidad */
|
| 106 |
+
border-radius: 10px; /* Bordes redondeados */
|
| 107 |
+
}
|
| 108 |
+
.stTextInput > div > div > input { /* Input de texto del chat */
|
| 109 |
+
color: #333; /* Color de texto más oscuro */
|
| 110 |
+
}
|
| 111 |
+
[data-testid="stChatMessage"] { /* Burbujas de chat */
|
| 112 |
+
background-color: black !important; /* Color de fondo negro */
|
| 113 |
+
color: gold !important; /* Color de texto dorado */
|
| 114 |
+
border-radius: 10px;
|
| 115 |
+
}
|
| 116 |
+
[data-testid="stChatMessage"] p { /* Párrafos dentro de las burbujas */
|
| 117 |
+
color: gold !important;
|
| 118 |
+
}
|
| 119 |
+
</style>
|
| 120 |
+
""",
|
| 121 |
+
unsafe_allow_html=True,
|
| 122 |
+
)
|
| 123 |
+
# --- Botones de historial ---
|
| 124 |
+
if st.button("Buscar Historial"):
|
| 125 |
+
st.session_state.mostrar_historial = True
|
| 126 |
+
if st.button("Borrar Historial"):
|
| 127 |
+
st.session_state.mensajes = []
|
| 128 |
+
st.session_state.mostrar_historial = False
|
| 129 |
+
st.success("Historial borrado correctamente")
|
| 130 |
+
# --- Chatbot ---
|
| 131 |
+
if 'mensajes' not in st.session_state:
|
| 132 |
+
st.session_state.mensajes = cargar_historial()
|
| 133 |
+
|
| 134 |
+
for mensaje in st.session_state.mensajes:
|
| 135 |
+
with st.chat_message(mensaje["role"]):
|
| 136 |
+
st.markdown(mensaje["content"])
|
| 137 |
+
# Función para manejar la entrada de audio
|
| 138 |
+
def on_audio(audio_bytes):
|
| 139 |
+
with st.spinner("Transcribiendo..."):
|
| 140 |
+
transcript = openai.Audio.transcribe("whisper-1", audio_bytes)
|
| 141 |
+
pregunta_usuario = transcript["text"]
|
| 142 |
+
st.session_state.mensajes.append({"role": "user", "content": pregunta_usuario, "timestamp": time.time()})
|
| 143 |
+
with st.chat_message("user"):
|
| 144 |
+
st.markdown(pregunta_usuario)
|
| 145 |
+
|
| 146 |
+
st.subheader("🎤 Captura de voz")
|
| 147 |
+
st.info("Haz clic en el micrófono y comienza a hablar. Tu pregunta se transcribirá automáticamente.")
|
| 148 |
+
with st.container():
|
| 149 |
+
if st.button("Grabar 🎙️"):
|
| 150 |
+
st.session_state.run_webrtc = True
|
| 151 |
+
if st.session_state.get("run_webrtc", False):
|
| 152 |
+
webrtc_streamer(
|
| 153 |
+
key="speech-to-text",
|
| 154 |
+
mode=WebRtcMode.SENDONLY,
|
| 155 |
+
rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]},
|
| 156 |
+
media_stream_constraints={"video": False, "audio": True},
|
| 157 |
+
on_audio=on_audio,
|
| 158 |
+
)
|
| 159 |
+
st.session_state["run_webrtc"] = False
|
| 160 |
+
|
| 161 |
+
# Mostrar historial si el botón fue presionado
|
| 162 |
+
if st.session_state.get("mostrar_historial", False):
|
| 163 |
+
st.subheader("Historial de Chat:")
|
| 164 |
+
if st.session_state.mensajes:
|
| 165 |
+
for mensaje in st.session_state.mensajes:
|
| 166 |
+
with st.chat_message(mensaje["role"]):
|
| 167 |
+
st.markdown(mensaje["content"])
|
| 168 |
+
else:
|
| 169 |
+
st.info("No hay mensajes en el historial.")
|
| 170 |
+
else:
|
| 171 |
+
for mensaje in st.session_state.mensajes:
|
| 172 |
+
with st.chat_message(mensaje["role"]):
|
| 173 |
+
st.markdown(mensaje["content"])
|
| 174 |
+
|
| 175 |
+
# Selección de modelo de lenguaje
|
| 176 |
+
st.subheader("🧠 Configuración del Modelo")
|
| 177 |
+
modelo = st.selectbox(
|
| 178 |
+
"Selecciona el modelo:",
|
| 179 |
+
["gpt-3.5-turbo", "gpt-4"],
|
| 180 |
+
index=0,
|
| 181 |
+
help="Elige el modelo de lenguaje de OpenAI que prefieras."
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# --- Opciones adicionales ---
|
| 185 |
+
st.markdown("---")
|
| 186 |
+
temperatura = st.slider("🌡️ Temperatura", min_value=0.0, max_value=1.0, value=0.5, step=0.1)
|
| 187 |
+
|
| 188 |
+
# --- Video de fondo ---
|
| 189 |
+
with st.container():
|
| 190 |
+
st.markdown(
|
| 191 |
+
f"""
|
| 192 |
+
<style>
|
| 193 |
+
#video-container {{
|
| 194 |
+
position: relative;
|
| 195 |
+
width: 100%;
|
| 196 |
+
padding-bottom: 56.25%;
|
| 197 |
+
background-color: lightblue;
|
| 198 |
+
overflow: hidden;
|
| 199 |
+
}}
|
| 200 |
+
#background-video {{
|
| 201 |
+
position: absolute;
|
| 202 |
+
top: 0;
|
| 203 |
+
left: 0;
|
| 204 |
+
width: 100%;
|
| 205 |
+
height: 100%;
|
| 206 |
+
}}
|
| 207 |
+
</style>
|
| 208 |
+
<div id="video-container">
|
| 209 |
+
<video id="background-video" autoplay loop muted playsinline>
|
| 210 |
+
<source src="https://cdn.pika.art/v1/f41adf48-a6db-4c6e-a93e-cd8db88f469d/movimiento_del_cuerpo_sutil_seed902109641145783.mp4" type="video/mp4">
|
| 211 |
+
</video>
|
| 212 |
+
</div>
|
| 213 |
+
""",
|
| 214 |
+
unsafe_allow_html=True,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# --- Área principal de la aplicación ---
|
| 218 |
+
st.header("💬 Relexionar con Elias")
|
| 219 |
+
|
| 220 |
+
# Carga de archivo PDF
|
| 221 |
+
archivo_pdf = st.file_uploader("📂 Cargar PDF", type='pdf')
|
| 222 |
+
|
| 223 |
+
# --- Chatbot ---
|
| 224 |
+
if 'mensajes' not in st.session_state:
|
| 225 |
+
st.session_state.mensajes = []
|
| 226 |
+
|
| 227 |
+
for mensaje in st.session_state.mensajes:
|
| 228 |
+
with st.chat_message(mensaje["role"]):
|
| 229 |
+
st.markdown(mensaje["content"])
|
| 230 |
+
|
| 231 |
+
pregunta_usuario = st.chat_input("Pregunta:")
|
| 232 |
+
if pregunta_usuario:
|
| 233 |
+
st.session_state.mensajes.append({"role": "user", "content": pregunta_usuario})
|
| 234 |
+
with st.chat_message("user"):
|
| 235 |
+
st.markdown(pregunta_usuario)
|
| 236 |
+
|
| 237 |
+
if archivo_pdf:
|
| 238 |
+
texto_pdf = extraer_texto_pdf(archivo_pdf)
|
| 239 |
+
texto_preprocesado = preprocesar_texto(texto_pdf)
|
| 240 |
+
else:
|
| 241 |
+
texto_preprocesado = "" # Sin contexto de PDF si no se carga un archivo
|
| 242 |
+
|
| 243 |
+
respuesta = obtener_respuesta(pregunta_usuario, texto_preprocesado, modelo, temperatura)
|
| 244 |
+
st.session_state.mensajes.append({"role": "assistant", "content": respuesta})
|
| 245 |
+
with st.chat_message("assistant"):
|
| 246 |
+
st.markdown(respuesta)
|
| 247 |
+
|
| 248 |
+
if __name__ == "__main__":
|
| 249 |
+
main()
|