jeysshon commited on
Commit
fe1ed8d
·
verified ·
1 Parent(s): 6a2680d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -89
app.py CHANGED
@@ -6,128 +6,142 @@ from pymongo import MongoClient
6
  from bson.objectid import ObjectId
7
  import pyttsx3
8
 
9
- client = MongoClient("mongodb://localhost:27017/")
10
- db = client["search_history"]
11
- history_collection = db["history"]
12
-
 
 
 
 
 
 
 
 
 
 
 
 
13
  api_key = 'AIzaSyDJZ3r6VRhRivR0pb96cBRg_VvGg_fXq5k'
14
  params = {
15
  'key': api_key,
16
  }
17
 
18
- def save_history(input_mode, user_input, response):
19
- history_entry = {
20
- "input_mode": input_mode,
21
- "user_input": user_input,
22
- "response": response
23
  }
24
- history_collection.insert_one(history_entry)
25
 
26
- def load_history():
27
- history_entries = list(history_collection.find().sort("_id", -1))
28
- return history_entries
29
 
30
- def delete_history(entry_id):
31
- history_collection.delete_one({"_id": ObjectId(entry_id)})
32
 
33
- def process_text(text):
34
  genai.configure(api_key=api_key)
35
- model = genai.GenerativeModel('gemini-1.5-pro-latest')
36
- response = model.generate_content(text)
37
- result = response.text
38
- save_history("Text", text, result)
39
- return result
40
 
41
- def process_image(text):
42
  genai.configure(api_key=api_key)
43
- model = genai.GenerativeModel('gemini-1.5-pro-latest')
44
- response = model.generate_content(text)
45
- save_history("Image", image.name, response)
46
- return response
47
-
48
- def recognize_speech():
49
- recognizer = sr.Recognizer()
50
- with sr.Microphone() as source:
51
- st.write("Listening...")
52
- audio = recognizer.listen(source)
 
53
  try:
54
- text = recognizer.recognize_google(audio)
55
- return text
56
  except sr.UnknownValueError:
57
- return "Google Speech Recognition could not understand audio"
58
  except sr.RequestError as e:
59
- return f"Could not request results from Google Speech Recognition service; {e}"
60
 
61
- def speak_text(text):
62
- engine = pyttsx3.init()
63
- engine.say(text)
64
- engine.runAndWait()
65
 
66
  st.set_page_config(layout="wide")
67
- st.sidebar.title("History")
68
 
69
- history = load_history()
70
- selected_response = None
71
 
72
- for entry in history:
73
- with st.sidebar.expander(f"{entry['user_input']}"):
 
74
  col1, col2 = st.columns([1, 1])
75
  with col1:
76
- if st.button("Response", key=str(entry['_id'])):
77
- selected_response = entry['response']
78
  with col2:
79
- if st.button("Delete", key=f"delete_{entry['_id']}"):
80
- delete_history(entry['_id'])
81
- st.experimental_rerun()
82
 
83
  st.title("🤖 ChatBot")
84
 
85
- generated_content_placeholder = st.empty()
86
 
87
- if selected_response:
88
- generated_content_placeholder.write(selected_response)
89
- if st.button("🔊 Speak"):
90
- speak_text(selected_response)
 
91
 
92
- # Load and apply custom CSS
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
- input_type = st.selectbox("Select input type", ["Ask a Question❓", "🖼️ upload Image", "🎤 use Microphone"])
102
 
103
  with col2:
104
- if input_type == "Ask a Question❓":
105
- text_input = st.text_input("Enter your prompt here")
106
- if text_input:
107
- with st.spinner("Generating response..."):
108
- result = process_text(text_input)
109
- generated_content_placeholder.write(result)
110
- if st.button("🔊 Speak", key="speak_text_input"):
111
- speak_text(result)
112
-
113
- elif input_type == "🖼️ upload Image":
114
- image_input = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
115
- if image_input:
116
- image = Image.open(image_input)
117
- st.image(image, caption='Uploaded Image.', use_column_width=True)
118
- with st.spinner("Processing image..."):
119
- response = process_text(image_input)
120
- generated_content_placeholder.write(response)
121
-
122
- elif input_type == "🎤 use Microphone":
123
- if st.button("Record"):
124
- with st.spinner("Listening and processing..."):
125
- text_from_speech = recognize_speech()
126
- if text_from_speech:
127
- text_input = st.text_input("Speak", value=text_from_speech)
128
- if text_input:
129
- with st.spinner("Generating response..."):
130
- result = process_text(text_input)
131
- generated_content_placeholder.write(result)
132
- if st.button("🔊 Speak", key="speak_speech_input"):
133
- speak_text(result)
 
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)