|
import streamlit as st |
|
from PIL import Image |
|
import speech_recognition as sr |
|
import google.generativeai as genai |
|
from pymongo import MongoClient |
|
from bson.objectid import ObjectId |
|
import pyttsx3 |
|
|
|
|
|
def obtener_cliente_mongo(): |
|
try: |
|
cliente = MongoClient("mongodb://localhost:27017/") |
|
cliente.server_info() |
|
return cliente |
|
except Exception as e: |
|
st.error(f"Error: No se pudo conectar a MongoDB. Verifica que el servidor esté en ejecución. Detalles: {e}") |
|
return None |
|
|
|
cliente = obtener_cliente_mongo() |
|
if cliente: |
|
db = cliente["historial_busquedas"] |
|
coleccion_historial = db["historial"] |
|
|
|
|
|
api_key = 'AIzaSyDJZ3r6VRhRivR0pb96cBRg_VvGg_fXq5k' |
|
params = { |
|
'key': api_key, |
|
} |
|
|
|
def guardar_historial(modo_entrada, entrada_usuario, respuesta): |
|
entrada_historial = { |
|
"modo_entrada": modo_entrada, |
|
"entrada_usuario": entrada_usuario, |
|
"respuesta": respuesta |
|
} |
|
coleccion_historial.insert_one(entrada_historial) |
|
|
|
def cargar_historial(): |
|
entradas_historial = list(coleccion_historial.find().sort("_id", -1)) |
|
return entradas_historial |
|
|
|
def eliminar_historial(id_entrada): |
|
coleccion_historial.delete_one({"_id": ObjectId(id_entrada)}) |
|
|
|
def procesar_texto(texto): |
|
genai.configure(api_key=api_key) |
|
modelo = genai.GenerativeModel('gemini-1.5-pro-latest') |
|
respuesta = modelo.generate_content(texto) |
|
resultado = respuesta.text |
|
guardar_historial("Texto", texto, resultado) |
|
return resultado |
|
|
|
def procesar_imagen(imagen): |
|
genai.configure(api_key=api_key) |
|
modelo = genai.GenerativeModel('gemini-1.5-pro-latest') |
|
respuesta = modelo.generate_content(imagen.name) |
|
resultado = respuesta.text |
|
guardar_historial("Imagen", imagen.name, resultado) |
|
return resultado |
|
|
|
def reconocer_voz(): |
|
reconocedor = sr.Recognizer() |
|
with sr.Microphone() as fuente: |
|
st.write("Escuchando...") |
|
audio = reconocedor.listen(fuente) |
|
try: |
|
texto = reconocedor.recognize_google(audio) |
|
return texto |
|
except sr.UnknownValueError: |
|
return "El reconocimiento de voz de Google no pudo entender el audio" |
|
except sr.RequestError as e: |
|
return f"No se pudieron solicitar resultados del servicio de reconocimiento de voz de Google; {e}" |
|
|
|
def hablar_texto(texto): |
|
motor = pyttsx3.init() |
|
motor.say(texto) |
|
motor.runAndWait() |
|
|
|
st.set_page_config(layout="wide") |
|
st.sidebar.title("Historial") |
|
|
|
historial = cargar_historial() |
|
respuesta_seleccionada = None |
|
|
|
|
|
for entrada in historial: |
|
with st.sidebar.expander(f"{entrada['entrada_usuario']}"): |
|
col1, col2 = st.columns([1, 1]) |
|
with col1: |
|
if st.button("Respuesta", key=str(entrada['_id'])): |
|
respuesta_seleccionada = entrada['respuesta'] |
|
with col2: |
|
if st.button("Eliminar", key=f"eliminar_{entrada['_id']}"): |
|
eliminar_historial(entrada['_id']) |
|
st.rerun() |
|
|
|
st.title("🤖 ChatBot") |
|
|
|
espacio_contenido_generado = st.empty() |
|
|
|
|
|
if respuesta_seleccionada: |
|
espacio_contenido_generado.write(respuesta_seleccionada) |
|
if st.button("🔊 Hablar"): |
|
hablar_texto(respuesta_seleccionada) |
|
|
|
|
|
with open("./style.css") as f: |
|
st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True) |
|
|
|
|
|
col1, col2 = st.columns([1, 3]) |
|
|
|
with col1: |
|
tipo_entrada = st.selectbox("Selecciona el tipo de entrada", ["Haz una pregunta❓", "🖼️ Subir imagen", "🎤 Usar micrófono"]) |
|
|
|
with col2: |
|
if tipo_entrada == "Haz una pregunta❓": |
|
entrada_texto = st.text_input("Ingresa tu pregunta aquí") |
|
if entrada_texto: |
|
with st.spinner("Generando respuesta..."): |
|
resultado = procesar_texto(entrada_texto) |
|
espacio_contenido_generado.write(resultado) |
|
if st.button("🔊 Hablar", key="hablar_entrada_texto"): |
|
hablar_texto(resultado) |
|
|
|
elif tipo_entrada == "🖼️ Subir imagen": |
|
entrada_imagen = st.file_uploader("Sube una imagen", type=["jpg", "png", "jpeg"]) |
|
if entrada_imagen: |
|
imagen = Image.open(entrada_imagen) |
|
st.image(imagen, caption='Imagen subida.', use_column_width=True) |
|
with st.spinner("Procesando imagen..."): |
|
respuesta = procesar_imagen(entrada_imagen) |
|
espacio_contenido_generado.write(respuesta) |
|
|
|
elif tipo_entrada == "🎤 Usar micrófono": |
|
if st.button("Grabar"): |
|
with st.spinner("Escuchando y procesando..."): |
|
texto_de_voz = reconocer_voz() |
|
if texto_de_voz: |
|
entrada_texto = st.text_input("Habla", value=texto_de_voz) |
|
if entrada_texto: |
|
with st.spinner("Generando respuesta..."): |
|
resultado = procesar_texto(entrada_texto) |
|
espacio_contenido_generado.write(resultado) |
|
if st.button("🔊 Hablar", key="hablar_entrada_voz"): |
|
hablar_texto(resultado) |
|
|