Josedcape commited on
Commit
0f9e2a3
·
verified ·
1 Parent(s): df0c8b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -41
app.py CHANGED
@@ -7,8 +7,11 @@ from dotenv import load_dotenv
7
  from docx import Document
8
  import base64
9
  from streamlit_player import st_player
10
- import firebase_admin
11
- from firebase_admin import credentials, firestore
 
 
 
12
  import time
13
 
14
  # Configuración de la interfaz
@@ -19,12 +22,6 @@ load_dotenv()
19
  openai.api_key = os.getenv("OPENAI_API_KEY")
20
  os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
21
 
22
- # Inicializar Firebase
23
- if not firebase_admin._apps:
24
- cred = credentials.Certificate("ruta/a/tu/archivo-de-credenciales.json")
25
- firebase_admin.initialize_app(cred)
26
- db = firestore.client()
27
-
28
  # Función para obtener respuesta de OpenAI con historial de conversación
29
  def obtener_respuesta(pregunta, historial, modelo="gpt-4", temperatura=0.5):
30
  mensajes = historial + [
@@ -67,11 +64,6 @@ def reproducir_audio(file_path):
67
  unsafe_allow_html=True
68
  )
69
 
70
- # Función para guardar datos en Firestore
71
- def guardar_datos_en_firestore(datos):
72
- doc_ref = db.collection("encuestas").add(datos)
73
- return doc_ref
74
-
75
  # Función para manejar la encuesta dinámica
76
  def encuesta_asistente():
77
  if st.session_state.idioma == "Español":
@@ -218,26 +210,12 @@ def encuesta_asistente():
218
  st.image("videos/robot-22.gif")
219
  time.sleep(60) # Temporizador de 1 minuto
220
  st.markdown(f"<span style='color: yellow; font-size: 30px;'>{mensaje_final}</span>", unsafe_allow_html=True)
221
-
222
- # Guardar datos en Firestore
223
- guardar_datos_en_firestore(st.session_state.respuestas)
224
-
225
- # Solicitar información de correo del usuario
226
- st.write("Por favor, ingrese su correo electrónico para enviar el resultado:" if st.session_state.idioma == "Español" else "Please enter your email to send the result:")
227
- email = st.text_input("Correo electrónico:" if st.session_state.idioma == "Español" else "Email:")
228
- if st.button("Enviar correo" if st.session_state.idioma == "Español" else "Send Email"):
229
- try:
230
- archivo_path = generar_documento(resumen)
231
- status_code = enviar_correo_sendgrid(email, "Resumen de la Encuesta", resumen, archivo_path)
232
- if status_code == 202:
233
- st.success("Correo enviado exitosamente." if st.session_state.idioma == "Español" else "Email sent successfully.")
234
- else:
235
- st.error("Error al enviar el correo." if st.session_state.idioma == "Español" else "Error sending email.")
236
- except Exception as e:
237
- st.error(f"{error_red} {str(e)}")
238
  st.success(encuesta_exitosa)
239
- else:
240
- generar_documento(resumen)
 
241
 
242
  if 'respuesta_actual' in st.session_state:
243
  st.write("Respuesta del asistente:" if st.session_state.idioma == "Español" else "Assistant's answer:")
@@ -297,7 +275,6 @@ def generar_documento(resumen):
297
  mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
298
  key=f"btn_descargar_archivo_{temp_file.name}"
299
  )
300
- return temp_file.name
301
 
302
  def generar_informe_completo(respuestas):
303
  informe = "Informe detallado del asistente solicitado:\n\n" if st.session_state.idioma == "Español" else "Detailed report of the requested assistant:\n\n"
@@ -312,6 +289,27 @@ def generar_informe_completo(respuestas):
312
  informe += "Este asistente será una herramienta invaluable para tu vida diaria, facilitando la organización, el aprendizaje y el manejo de tus responsabilidades. Con interfaces intuitivas y accesibles desde diversas plataformas, este asistente estará siempre disponible para ayudarte en cualquier momento y lugar. Su implementación no solo mejorará tu eficiencia sino también te brindará un soporte constante y personalizado.\n\n" if st.session_state.idioma == "Español" else "This assistant will be an invaluable tool for your daily life, facilitating organization, learning, and handling your responsibilities. With intuitive interfaces accessible from various platforms, this assistant will always be available to help you at any time and place. Its implementation will not only improve your efficiency but also provide you with constant and personalized support.\n\n"
313
  return informe
314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  # Función para incrustar video en la página principal
316
  def incrustar_video_principal():
317
  video_url = "https://www.youtube.com/watch?v=uGzZe1LxVPk" # Reemplaza con el enlace correcto
@@ -411,13 +409,5 @@ def main():
411
  elif page == "asistente":
412
  pagina_asistente()
413
 
414
- # Mostrar datos de encuestas en tiempo real
415
- def mostrar_datos_encuestas():
416
- st.title("Datos de Encuestas en Tiempo Real" if st.session_state.idioma == "Español" else "Real-time Survey Data")
417
- encuestas = db.collection("encuestas").stream()
418
-
419
- for encuesta in encuestas:
420
- st.write(encuesta.to_dict())
421
-
422
  if __name__ == "__main__":
423
  main()
 
7
  from docx import Document
8
  import base64
9
  from streamlit_player import st_player
10
+ import smtplib
11
+ from email.mime.multipart import MIMEMultipart
12
+ from email.mime.text import MIMEText
13
+ from email.mime.application import MIMEApplication
14
+ import socket
15
  import time
16
 
17
  # Configuración de la interfaz
 
22
  openai.api_key = os.getenv("OPENAI_API_KEY")
23
  os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
24
 
 
 
 
 
 
 
25
  # Función para obtener respuesta de OpenAI con historial de conversación
26
  def obtener_respuesta(pregunta, historial, modelo="gpt-4", temperatura=0.5):
27
  mensajes = historial + [
 
64
  unsafe_allow_html=True
65
  )
66
 
 
 
 
 
 
67
  # Función para manejar la encuesta dinámica
68
  def encuesta_asistente():
69
  if st.session_state.idioma == "Español":
 
210
  st.image("videos/robot-22.gif")
211
  time.sleep(60) # Temporizador de 1 minuto
212
  st.markdown(f"<span style='color: yellow; font-size: 30px;'>{mensaje_final}</span>", unsafe_allow_html=True)
213
+ try:
214
+ enviar_correo(resumen)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  st.success(encuesta_exitosa)
216
+ except (socket.gaierror, OSError):
217
+ st.error(error_red)
218
+ generar_documento(resumen)
219
 
220
  if 'respuesta_actual' in st.session_state:
221
  st.write("Respuesta del asistente:" if st.session_state.idioma == "Español" else "Assistant's answer:")
 
275
  mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
276
  key=f"btn_descargar_archivo_{temp_file.name}"
277
  )
 
278
 
279
  def generar_informe_completo(respuestas):
280
  informe = "Informe detallado del asistente solicitado:\n\n" if st.session_state.idioma == "Español" else "Detailed report of the requested assistant:\n\n"
 
289
  informe += "Este asistente será una herramienta invaluable para tu vida diaria, facilitando la organización, el aprendizaje y el manejo de tus responsabilidades. Con interfaces intuitivas y accesibles desde diversas plataformas, este asistente estará siempre disponible para ayudarte en cualquier momento y lugar. Su implementación no solo mejorará tu eficiencia sino también te brindará un soporte constante y personalizado.\n\n" if st.session_state.idioma == "Español" else "This assistant will be an invaluable tool for your daily life, facilitating organization, learning, and handling your responsibilities. With intuitive interfaces accessible from various platforms, this assistant will always be available to help you at any time and place. Its implementation will not only improve your efficiency but also provide you with constant and personalized support.\n\n"
290
  return informe
291
 
292
+ def enviar_correo(resumen):
293
+ remitente = "tucorreo@gmail.com"
294
+ destinatario = "josedcape@gmail.com"
295
+ asunto = "Resumen de la Encuesta"
296
+ cuerpo = resumen
297
+
298
+ mensaje = MIMEMultipart()
299
+ mensaje['From'] = remitente
300
+ mensaje['To'] = destinatario
301
+ mensaje['Subject'] = asunto
302
+
303
+ mensaje.attach(MIMEText(cuerpo, 'plain'))
304
+
305
+ # Iniciar la sesión SMTP
306
+ servidor = smtplib.SMTP('smtp.gmail.com', 587)
307
+ servidor.starttls()
308
+ servidor.login(remitente, os.getenv("EMAIL_PASSWORD"))
309
+ texto = mensaje.as_string()
310
+ servidor.sendmail(remitente, destinatario, texto)
311
+ servidor.quit()
312
+
313
  # Función para incrustar video en la página principal
314
  def incrustar_video_principal():
315
  video_url = "https://www.youtube.com/watch?v=uGzZe1LxVPk" # Reemplaza con el enlace correcto
 
409
  elif page == "asistente":
410
  pagina_asistente()
411
 
 
 
 
 
 
 
 
 
412
  if __name__ == "__main__":
413
  main()