Update utils/data_manager.py
Browse files- utils/data_manager.py +29 -73
utils/data_manager.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
|
| 2 |
import tempfile
|
| 3 |
import openai
|
| 4 |
from dotenv import load_dotenv
|
|
@@ -9,6 +9,7 @@ from nltk.corpus import stopwords
|
|
| 9 |
from nltk.stem import SnowballStemmer
|
| 10 |
import pandas as pd
|
| 11 |
from fpdf import FPDF
|
|
|
|
| 12 |
import requests
|
| 13 |
from google.cloud import texttospeech
|
| 14 |
|
|
@@ -23,12 +24,12 @@ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
|
|
| 23 |
|
| 24 |
# Verifica que las claves API est谩n configuradas
|
| 25 |
if not openai_api_key:
|
| 26 |
-
|
| 27 |
else:
|
| 28 |
openai.api_key = openai_api_key
|
| 29 |
|
| 30 |
if not brevo_api_key:
|
| 31 |
-
|
| 32 |
|
| 33 |
def extraer_texto_pdf(archivo):
|
| 34 |
texto = ""
|
|
@@ -42,7 +43,7 @@ def extraer_texto_pdf(archivo):
|
|
| 42 |
for page in range(len(reader.pages)):
|
| 43 |
texto += reader.pages[page].extract_text()
|
| 44 |
except Exception as e:
|
| 45 |
-
|
| 46 |
finally:
|
| 47 |
os.unlink(temp_file_path)
|
| 48 |
return texto
|
|
@@ -88,10 +89,12 @@ def obtener_respuesta(pregunta, texto_preprocesado, modelo, temperatura=0.5, ass
|
|
| 88 |
return respuesta
|
| 89 |
|
| 90 |
except openai.OpenAIError as e:
|
| 91 |
-
|
|
|
|
| 92 |
|
| 93 |
except Exception as e:
|
| 94 |
-
|
|
|
|
| 95 |
|
| 96 |
def guardar_en_txt(nombre_archivo, datos):
|
| 97 |
carpeta = "datos_guardados"
|
|
@@ -101,7 +104,7 @@ def guardar_en_txt(nombre_archivo, datos):
|
|
| 101 |
with open(ruta_archivo, 'a', encoding='utf-8') as archivo: # Append mode
|
| 102 |
archivo.write(datos + "\n")
|
| 103 |
except Exception as e:
|
| 104 |
-
|
| 105 |
return ruta_archivo
|
| 106 |
|
| 107 |
def cargar_desde_txt(nombre_archivo):
|
|
@@ -112,9 +115,11 @@ def cargar_desde_txt(nombre_archivo):
|
|
| 112 |
with open(ruta_archivo, 'r', encoding='utf-8') as archivo:
|
| 113 |
return archivo.read()
|
| 114 |
else:
|
| 115 |
-
|
|
|
|
| 116 |
except Exception as e:
|
| 117 |
-
|
|
|
|
| 118 |
|
| 119 |
def listar_archivos_txt():
|
| 120 |
carpeta = "datos_guardados"
|
|
@@ -125,7 +130,8 @@ def listar_archivos_txt():
|
|
| 125 |
archivos_ordenados = sorted(archivos, key=lambda x: os.path.getctime(os.path.join(carpeta, x)), reverse=True)
|
| 126 |
return archivos_ordenados
|
| 127 |
except Exception as e:
|
| 128 |
-
|
|
|
|
| 129 |
|
| 130 |
def generar_pdf(dataframe, titulo, filename):
|
| 131 |
pdf = FPDF()
|
|
@@ -142,7 +148,8 @@ def generar_pdf(dataframe, titulo, filename):
|
|
| 142 |
pdf.output(tmp_file.name)
|
| 143 |
return tmp_file.name
|
| 144 |
except Exception as e:
|
| 145 |
-
|
|
|
|
| 146 |
|
| 147 |
def enviar_correo(destinatario, asunto, contenido):
|
| 148 |
url = "https://api.brevo.com/v3/smtp/email"
|
|
@@ -162,9 +169,9 @@ def enviar_correo(destinatario, asunto, contenido):
|
|
| 162 |
if response.status_code == 201:
|
| 163 |
st.success(f"Correo enviado a {destinatario}")
|
| 164 |
else:
|
| 165 |
-
|
| 166 |
except Exception as e:
|
| 167 |
-
|
| 168 |
|
| 169 |
def enviar_whatsapp(numero, mensaje):
|
| 170 |
url = "https://api.brevo.com/v3/whatsapp/send"
|
|
@@ -183,9 +190,9 @@ def enviar_whatsapp(numero, mensaje):
|
|
| 183 |
if response.status_code == 201:
|
| 184 |
st.success(f"Mensaje de WhatsApp enviado a {numero}")
|
| 185 |
else:
|
| 186 |
-
|
| 187 |
except Exception as e:
|
| 188 |
-
|
| 189 |
|
| 190 |
def flujo_laboratorio():
|
| 191 |
st.title("馃Ψ Gesti贸n de Trabajos de Laboratorio")
|
|
@@ -346,7 +353,7 @@ def mostrar_datos_como_texto(datos):
|
|
| 346 |
|
| 347 |
def flujo_presupuestos():
|
| 348 |
st.title("馃挵 Asistente de Presupuestos")
|
| 349 |
-
st.markdown("Hola Dr. cu茅nteme en
|
| 350 |
|
| 351 |
lista_precios = {
|
| 352 |
"Restauraciones en resina de una superficie": 75000,
|
|
@@ -374,64 +381,13 @@ def flujo_presupuestos():
|
|
| 374 |
"Endodoncia de premolares superiores": 480000,
|
| 375 |
}
|
| 376 |
|
| 377 |
-
if 'presupuesto' not in st.session_state:
|
| 378 |
-
st.session_state['presupuesto'] = []
|
| 379 |
-
|
| 380 |
-
# Mostrar lista de precios en un men煤 desplegable
|
| 381 |
-
with st.expander("Mostrar Lista de Precios"):
|
| 382 |
-
st.markdown("### Lista de Precios")
|
| 383 |
-
for tratamiento, precio in lista_precios.items():
|
| 384 |
-
st.markdown(f"**{tratamiento}:** {precio} COP")
|
| 385 |
-
|
| 386 |
-
# Selecci贸n de tratamientos y cantidad
|
| 387 |
tratamiento = st.selectbox("Selecciona el tratamiento", list(lista_precios.keys()))
|
| 388 |
cantidad = st.number_input("Cantidad", min_value=1, step=1)
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
st.success(f"Agregado: {cantidad} {tratamiento} - Total: {precio_total} COP")
|
| 395 |
-
|
| 396 |
-
# Mostrar servicios seleccionados y total
|
| 397 |
-
if st.session_state['presupuesto']:
|
| 398 |
-
st.write("### Servicios Seleccionados")
|
| 399 |
-
total_presupuesto = sum(item['precio_total'] for item in st.session_state['presupuesto'])
|
| 400 |
-
for item in st.session_state['presupuesto']:
|
| 401 |
-
st.write(f"{item['cantidad']} x {item['tratamiento']} - {item['precio_total']} COP")
|
| 402 |
-
st.write(f"**Total: {total_presupuesto} COP**")
|
| 403 |
-
|
| 404 |
-
# Transferir presupuesto al chat del asistente
|
| 405 |
-
if st.button("Transferir Presupuesto al Chat del Asistente"):
|
| 406 |
-
servicios = "\n".join([f"{item['cantidad']} x {item['tratamiento']} - {item['precio_total']} COP" for item in st.session_state['presupuesto']])
|
| 407 |
-
total = f"**Total: {total_presupuesto} COP**"
|
| 408 |
-
st.session_state['presupuesto_texto'] = f"{servicios}\n{total}"
|
| 409 |
-
st.success("Presupuesto transferido al chat del asistente.")
|
| 410 |
-
|
| 411 |
-
# Mostrar chat del asistente
|
| 412 |
-
if 'mostrar_chat' not in st.session_state:
|
| 413 |
-
st.session_state['mostrar_chat'] = False
|
| 414 |
-
|
| 415 |
-
def mostrar_chat():
|
| 416 |
-
st.session_state['mostrar_chat'] = not st.session_state['mostrar_chat']
|
| 417 |
-
|
| 418 |
-
if st.button("Mostrar Chat", key="assistant_button"):
|
| 419 |
-
mostrar_chat()
|
| 420 |
-
|
| 421 |
-
if st.session_state['mostrar_chat']:
|
| 422 |
-
st.markdown("<div id='assistant_chat'></div>", unsafe_allow_html=True)
|
| 423 |
-
st.markdown("### Chat con Asistente")
|
| 424 |
-
|
| 425 |
-
pregunta_usuario = st.text_input("Escribe tu pregunta aqu铆:", value=st.session_state.get('presupuesto_texto', ''))
|
| 426 |
-
if st.button("Enviar Pregunta"):
|
| 427 |
-
respuesta = obtener_respuesta(
|
| 428 |
-
pregunta_usuario,
|
| 429 |
-
"", # No se necesita texto preprocesado en este caso
|
| 430 |
-
st.session_state['modelo'],
|
| 431 |
-
st.session_state['temperatura'],
|
| 432 |
-
st.session_state.get('assistant_id', 'asst_KngkX6sbRccg5a6fcnDHO06R')
|
| 433 |
-
)
|
| 434 |
-
st.markdown(f"**Asistente**: {respuesta}")
|
| 435 |
|
| 436 |
def flujo_radiografias():
|
| 437 |
st.title("馃摳 Registro de Radiograf铆as")
|
|
@@ -470,4 +426,4 @@ def flujo_radiografias():
|
|
| 470 |
data=open(pdf_file, 'rb').read(),
|
| 471 |
file_name="radiografias.pdf",
|
| 472 |
mime="application/pdf"
|
| 473 |
-
)
|
|
|
|
| 1 |
+
mport os
|
| 2 |
import tempfile
|
| 3 |
import openai
|
| 4 |
from dotenv import load_dotenv
|
|
|
|
| 9 |
from nltk.stem import SnowballStemmer
|
| 10 |
import pandas as pd
|
| 11 |
from fpdf import FPDF
|
| 12 |
+
import streamlit as st
|
| 13 |
import requests
|
| 14 |
from google.cloud import texttospeech
|
| 15 |
|
|
|
|
| 24 |
|
| 25 |
# Verifica que las claves API est谩n configuradas
|
| 26 |
if not openai_api_key:
|
| 27 |
+
st.error("No API key provided for OpenAI. Please set your API key in the .env file.")
|
| 28 |
else:
|
| 29 |
openai.api_key = openai_api_key
|
| 30 |
|
| 31 |
if not brevo_api_key:
|
| 32 |
+
st.error("No API key provided for Brevo. Please set your API key in the .env file.")
|
| 33 |
|
| 34 |
def extraer_texto_pdf(archivo):
|
| 35 |
texto = ""
|
|
|
|
| 43 |
for page in range(len(reader.pages)):
|
| 44 |
texto += reader.pages[page].extract_text()
|
| 45 |
except Exception as e:
|
| 46 |
+
st.error(f"Error al extraer texto del PDF: {e}")
|
| 47 |
finally:
|
| 48 |
os.unlink(temp_file_path)
|
| 49 |
return texto
|
|
|
|
| 89 |
return respuesta
|
| 90 |
|
| 91 |
except openai.OpenAIError as e:
|
| 92 |
+
st.error(f"Error al comunicarse con OpenAI: {e}")
|
| 93 |
+
return "Lo siento, no puedo procesar tu solicitud en este momento."
|
| 94 |
|
| 95 |
except Exception as e:
|
| 96 |
+
st.error(f"Error al generar la respuesta y el audio: {e}")
|
| 97 |
+
return "Lo siento, ocurri贸 un error al procesar tu solicitud."
|
| 98 |
|
| 99 |
def guardar_en_txt(nombre_archivo, datos):
|
| 100 |
carpeta = "datos_guardados"
|
|
|
|
| 104 |
with open(ruta_archivo, 'a', encoding='utf-8') as archivo: # Append mode
|
| 105 |
archivo.write(datos + "\n")
|
| 106 |
except Exception as e:
|
| 107 |
+
st.error(f"Error al guardar datos en el archivo: {e}")
|
| 108 |
return ruta_archivo
|
| 109 |
|
| 110 |
def cargar_desde_txt(nombre_archivo):
|
|
|
|
| 115 |
with open(ruta_archivo, 'r', encoding='utf-8') as archivo:
|
| 116 |
return archivo.read()
|
| 117 |
else:
|
| 118 |
+
st.warning("Archivo no encontrado.")
|
| 119 |
+
return ""
|
| 120 |
except Exception as e:
|
| 121 |
+
st.error(f"Error al cargar datos desde el archivo: {e}")
|
| 122 |
+
return ""
|
| 123 |
|
| 124 |
def listar_archivos_txt():
|
| 125 |
carpeta = "datos_guardados"
|
|
|
|
| 130 |
archivos_ordenados = sorted(archivos, key=lambda x: os.path.getctime(os.path.join(carpeta, x)), reverse=True)
|
| 131 |
return archivos_ordenados
|
| 132 |
except Exception as e:
|
| 133 |
+
st.error(f"Error al listar archivos: {e}")
|
| 134 |
+
return []
|
| 135 |
|
| 136 |
def generar_pdf(dataframe, titulo, filename):
|
| 137 |
pdf = FPDF()
|
|
|
|
| 148 |
pdf.output(tmp_file.name)
|
| 149 |
return tmp_file.name
|
| 150 |
except Exception as e:
|
| 151 |
+
st.error(f"Error al generar PDF: {e}")
|
| 152 |
+
return None
|
| 153 |
|
| 154 |
def enviar_correo(destinatario, asunto, contenido):
|
| 155 |
url = "https://api.brevo.com/v3/smtp/email"
|
|
|
|
| 169 |
if response.status_code == 201:
|
| 170 |
st.success(f"Correo enviado a {destinatario}")
|
| 171 |
else:
|
| 172 |
+
st.error(f"Error al enviar el correo: {response.text}")
|
| 173 |
except Exception as e:
|
| 174 |
+
st.error(f"Error al enviar el correo: {e}")
|
| 175 |
|
| 176 |
def enviar_whatsapp(numero, mensaje):
|
| 177 |
url = "https://api.brevo.com/v3/whatsapp/send"
|
|
|
|
| 190 |
if response.status_code == 201:
|
| 191 |
st.success(f"Mensaje de WhatsApp enviado a {numero}")
|
| 192 |
else:
|
| 193 |
+
st.error(f"Error al enviar el mensaje de WhatsApp: {response.text}")
|
| 194 |
except Exception as e:
|
| 195 |
+
st.error(f"Error al enviar el mensaje de WhatsApp: {e}")
|
| 196 |
|
| 197 |
def flujo_laboratorio():
|
| 198 |
st.title("馃Ψ Gesti贸n de Trabajos de Laboratorio")
|
|
|
|
| 353 |
|
| 354 |
def flujo_presupuestos():
|
| 355 |
st.title("馃挵 Asistente de Presupuestos")
|
| 356 |
+
st.markdown("Hola Dr. cu茅nteme en que puedo ayudarle?")
|
| 357 |
|
| 358 |
lista_precios = {
|
| 359 |
"Restauraciones en resina de una superficie": 75000,
|
|
|
|
| 381 |
"Endodoncia de premolares superiores": 480000,
|
| 382 |
}
|
| 383 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
tratamiento = st.selectbox("Selecciona el tratamiento", list(lista_precios.keys()))
|
| 385 |
cantidad = st.number_input("Cantidad", min_value=1, step=1)
|
| 386 |
+
|
| 387 |
+
if st.button("Calcular Presupuesto"):
|
| 388 |
+
if tratamiento and cantidad:
|
| 389 |
+
precio_total = lista_precios[tratamiento] * cantidad
|
| 390 |
+
st.success(f"El precio total para {cantidad} {tratamiento} es: {precio_total} COP")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
|
| 392 |
def flujo_radiografias():
|
| 393 |
st.title("馃摳 Registro de Radiograf铆as")
|
|
|
|
| 426 |
data=open(pdf_file, 'rb').read(),
|
| 427 |
file_name="radiografias.pdf",
|
| 428 |
mime="application/pdf"
|
| 429 |
+
)
|