File size: 5,389 Bytes
6a2680d
 
 
 
 
 
 
 
fe1ed8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a2680d
 
 
 
 
fe1ed8d
 
 
 
 
6a2680d
fe1ed8d
6a2680d
fe1ed8d
 
 
6a2680d
fe1ed8d
 
6a2680d
fe1ed8d
6a2680d
fe1ed8d
 
 
 
 
6a2680d
fe1ed8d
6a2680d
fe1ed8d
 
 
 
 
 
 
 
 
 
 
6a2680d
fe1ed8d
 
6a2680d
fe1ed8d
6a2680d
fe1ed8d
6a2680d
fe1ed8d
 
 
 
6a2680d
 
fe1ed8d
6a2680d
fe1ed8d
 
6a2680d
fe1ed8d
 
 
6a2680d
 
fe1ed8d
 
6a2680d
fe1ed8d
 
 
6a2680d
 
 
fe1ed8d
6a2680d
fe1ed8d
 
 
 
 
6a2680d
fe1ed8d
6a2680d
 
 
fe1ed8d
6a2680d
 
 
fe1ed8d
6a2680d
 
fe1ed8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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
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

# Configuración de la base de datos MongoDB
def obtener_cliente_mongo():
    try:
        cliente = MongoClient("mongodb://localhost:27017/")
        cliente.server_info()  # Verifica la conexión
        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"]

# Clave API para Google Generative AI
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)  # Asume que `generate_content` maneja el nombre de la imagen como entrada válida
    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

# Mostrar historial en la barra lateral
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()  # Usa `st.rerun()` en lugar de `st.experimental_rerun()`

st.title("🤖 ChatBot")

espacio_contenido_generado = st.empty()

# Mostrar respuesta seleccionada
if respuesta_seleccionada:
    espacio_contenido_generado.write(respuesta_seleccionada)
    if st.button("🔊 Hablar"):
        hablar_texto(respuesta_seleccionada)

# Cargar y aplicar CSS personalizado
with open("./style.css") as f:
    st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

# Contenido principal
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)