Update app.py
Browse files
app.py
CHANGED
@@ -6,128 +6,142 @@ from pymongo import MongoClient
|
|
6 |
from bson.objectid import ObjectId
|
7 |
import pyttsx3
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
api_key = 'AIzaSyDJZ3r6VRhRivR0pb96cBRg_VvGg_fXq5k'
|
14 |
params = {
|
15 |
'key': api_key,
|
16 |
}
|
17 |
|
18 |
-
def
|
19 |
-
|
20 |
-
"
|
21 |
-
"
|
22 |
-
"
|
23 |
}
|
24 |
-
|
25 |
|
26 |
-
def
|
27 |
-
|
28 |
-
return
|
29 |
|
30 |
-
def
|
31 |
-
|
32 |
|
33 |
-
def
|
34 |
genai.configure(api_key=api_key)
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
return
|
40 |
|
41 |
-
def
|
42 |
genai.configure(api_key=api_key)
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
|
|
53 |
try:
|
54 |
-
|
55 |
-
return
|
56 |
except sr.UnknownValueError:
|
57 |
-
return "Google
|
58 |
except sr.RequestError as e:
|
59 |
-
return f"
|
60 |
|
61 |
-
def
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
|
66 |
st.set_page_config(layout="wide")
|
67 |
-
st.sidebar.title("
|
68 |
|
69 |
-
|
70 |
-
|
71 |
|
72 |
-
|
73 |
-
|
|
|
74 |
col1, col2 = st.columns([1, 1])
|
75 |
with col1:
|
76 |
-
if st.button("
|
77 |
-
|
78 |
with col2:
|
79 |
-
if st.button("
|
80 |
-
|
81 |
-
st.experimental_rerun()
|
82 |
|
83 |
st.title("🤖 ChatBot")
|
84 |
|
85 |
-
|
86 |
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
|
|
91 |
|
92 |
-
#
|
93 |
with open("./style.css") as f:
|
94 |
st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
|
95 |
|
96 |
-
|
97 |
-
# Main content
|
98 |
col1, col2 = st.columns([1, 3])
|
99 |
|
100 |
with col1:
|
101 |
-
|
102 |
|
103 |
with col2:
|
104 |
-
if
|
105 |
-
|
106 |
-
if
|
107 |
-
with st.spinner("
|
108 |
-
|
109 |
-
|
110 |
-
if st.button("🔊
|
111 |
-
|
112 |
-
|
113 |
-
elif
|
114 |
-
|
115 |
-
if
|
116 |
-
|
117 |
-
st.image(
|
118 |
-
with st.spinner("
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
elif
|
123 |
-
if st.button("
|
124 |
-
with st.spinner("
|
125 |
-
|
126 |
-
if
|
127 |
-
|
128 |
-
if
|
129 |
-
with st.spinner("
|
130 |
-
|
131 |
-
|
132 |
-
if st.button("🔊
|
133 |
-
|
|
|
6 |
from bson.objectid import ObjectId
|
7 |
import pyttsx3
|
8 |
|
9 |
+
# Configuración de la base de datos MongoDB
|
10 |
+
def obtener_cliente_mongo():
|
11 |
+
try:
|
12 |
+
cliente = MongoClient("mongodb://localhost:27017/")
|
13 |
+
cliente.server_info() # Verifica la conexión
|
14 |
+
return cliente
|
15 |
+
except Exception as e:
|
16 |
+
st.error(f"Error: No se pudo conectar a MongoDB. Verifica que el servidor esté en ejecución. Detalles: {e}")
|
17 |
+
return None
|
18 |
+
|
19 |
+
cliente = obtener_cliente_mongo()
|
20 |
+
if cliente:
|
21 |
+
db = cliente["historial_busquedas"]
|
22 |
+
coleccion_historial = db["historial"]
|
23 |
+
|
24 |
+
# Clave API para Google Generative AI
|
25 |
api_key = 'AIzaSyDJZ3r6VRhRivR0pb96cBRg_VvGg_fXq5k'
|
26 |
params = {
|
27 |
'key': api_key,
|
28 |
}
|
29 |
|
30 |
+
def guardar_historial(modo_entrada, entrada_usuario, respuesta):
|
31 |
+
entrada_historial = {
|
32 |
+
"modo_entrada": modo_entrada,
|
33 |
+
"entrada_usuario": entrada_usuario,
|
34 |
+
"respuesta": respuesta
|
35 |
}
|
36 |
+
coleccion_historial.insert_one(entrada_historial)
|
37 |
|
38 |
+
def cargar_historial():
|
39 |
+
entradas_historial = list(coleccion_historial.find().sort("_id", -1))
|
40 |
+
return entradas_historial
|
41 |
|
42 |
+
def eliminar_historial(id_entrada):
|
43 |
+
coleccion_historial.delete_one({"_id": ObjectId(id_entrada)})
|
44 |
|
45 |
+
def procesar_texto(texto):
|
46 |
genai.configure(api_key=api_key)
|
47 |
+
modelo = genai.GenerativeModel('gemini-1.5-pro-latest')
|
48 |
+
respuesta = modelo.generate_content(texto)
|
49 |
+
resultado = respuesta.text
|
50 |
+
guardar_historial("Texto", texto, resultado)
|
51 |
+
return resultado
|
52 |
|
53 |
+
def procesar_imagen(imagen):
|
54 |
genai.configure(api_key=api_key)
|
55 |
+
modelo = genai.GenerativeModel('gemini-1.5-pro-latest')
|
56 |
+
respuesta = modelo.generate_content(imagen.name) # Asume que `generate_content` maneja el nombre de la imagen como entrada válida
|
57 |
+
resultado = respuesta.text
|
58 |
+
guardar_historial("Imagen", imagen.name, resultado)
|
59 |
+
return resultado
|
60 |
+
|
61 |
+
def reconocer_voz():
|
62 |
+
reconocedor = sr.Recognizer()
|
63 |
+
with sr.Microphone() as fuente:
|
64 |
+
st.write("Escuchando...")
|
65 |
+
audio = reconocedor.listen(fuente)
|
66 |
try:
|
67 |
+
texto = reconocedor.recognize_google(audio)
|
68 |
+
return texto
|
69 |
except sr.UnknownValueError:
|
70 |
+
return "El reconocimiento de voz de Google no pudo entender el audio"
|
71 |
except sr.RequestError as e:
|
72 |
+
return f"No se pudieron solicitar resultados del servicio de reconocimiento de voz de Google; {e}"
|
73 |
|
74 |
+
def hablar_texto(texto):
|
75 |
+
motor = pyttsx3.init()
|
76 |
+
motor.say(texto)
|
77 |
+
motor.runAndWait()
|
78 |
|
79 |
st.set_page_config(layout="wide")
|
80 |
+
st.sidebar.title("Historial")
|
81 |
|
82 |
+
historial = cargar_historial()
|
83 |
+
respuesta_seleccionada = None
|
84 |
|
85 |
+
# Mostrar historial en la barra lateral
|
86 |
+
for entrada in historial:
|
87 |
+
with st.sidebar.expander(f"{entrada['entrada_usuario']}"):
|
88 |
col1, col2 = st.columns([1, 1])
|
89 |
with col1:
|
90 |
+
if st.button("Respuesta", key=str(entrada['_id'])):
|
91 |
+
respuesta_seleccionada = entrada['respuesta']
|
92 |
with col2:
|
93 |
+
if st.button("Eliminar", key=f"eliminar_{entrada['_id']}"):
|
94 |
+
eliminar_historial(entrada['_id'])
|
95 |
+
st.rerun() # Usa `st.rerun()` en lugar de `st.experimental_rerun()`
|
96 |
|
97 |
st.title("🤖 ChatBot")
|
98 |
|
99 |
+
espacio_contenido_generado = st.empty()
|
100 |
|
101 |
+
# Mostrar respuesta seleccionada
|
102 |
+
if respuesta_seleccionada:
|
103 |
+
espacio_contenido_generado.write(respuesta_seleccionada)
|
104 |
+
if st.button("🔊 Hablar"):
|
105 |
+
hablar_texto(respuesta_seleccionada)
|
106 |
|
107 |
+
# Cargar y aplicar CSS personalizado
|
108 |
with open("./style.css") as f:
|
109 |
st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
|
110 |
|
111 |
+
# Contenido principal
|
|
|
112 |
col1, col2 = st.columns([1, 3])
|
113 |
|
114 |
with col1:
|
115 |
+
tipo_entrada = st.selectbox("Selecciona el tipo de entrada", ["Haz una pregunta❓", "🖼️ Subir imagen", "🎤 Usar micrófono"])
|
116 |
|
117 |
with col2:
|
118 |
+
if tipo_entrada == "Haz una pregunta❓":
|
119 |
+
entrada_texto = st.text_input("Ingresa tu pregunta aquí")
|
120 |
+
if entrada_texto:
|
121 |
+
with st.spinner("Generando respuesta..."):
|
122 |
+
resultado = procesar_texto(entrada_texto)
|
123 |
+
espacio_contenido_generado.write(resultado)
|
124 |
+
if st.button("🔊 Hablar", key="hablar_entrada_texto"):
|
125 |
+
hablar_texto(resultado)
|
126 |
+
|
127 |
+
elif tipo_entrada == "🖼️ Subir imagen":
|
128 |
+
entrada_imagen = st.file_uploader("Sube una imagen", type=["jpg", "png", "jpeg"])
|
129 |
+
if entrada_imagen:
|
130 |
+
imagen = Image.open(entrada_imagen)
|
131 |
+
st.image(imagen, caption='Imagen subida.', use_column_width=True)
|
132 |
+
with st.spinner("Procesando imagen..."):
|
133 |
+
respuesta = procesar_imagen(entrada_imagen)
|
134 |
+
espacio_contenido_generado.write(respuesta)
|
135 |
+
|
136 |
+
elif tipo_entrada == "🎤 Usar micrófono":
|
137 |
+
if st.button("Grabar"):
|
138 |
+
with st.spinner("Escuchando y procesando..."):
|
139 |
+
texto_de_voz = reconocer_voz()
|
140 |
+
if texto_de_voz:
|
141 |
+
entrada_texto = st.text_input("Habla", value=texto_de_voz)
|
142 |
+
if entrada_texto:
|
143 |
+
with st.spinner("Generando respuesta..."):
|
144 |
+
resultado = procesar_texto(entrada_texto)
|
145 |
+
espacio_contenido_generado.write(resultado)
|
146 |
+
if st.button("🔊 Hablar", key="hablar_entrada_voz"):
|
147 |
+
hablar_texto(resultado)
|