Update utils/data_manager.py
Browse files- utils/data_manager.py +95 -47
utils/data_manager.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
import os
|
| 2 |
import tempfile
|
| 3 |
-
import openai
|
| 4 |
import PyPDF2
|
| 5 |
import nltk
|
| 6 |
from nltk.tokenize import word_tokenize
|
|
@@ -8,29 +7,13 @@ from nltk.corpus import stopwords
|
|
| 8 |
from nltk.stem import SnowballStemmer
|
| 9 |
import pandas as pd
|
| 10 |
from fpdf import FPDF
|
|
|
|
| 11 |
import requests
|
| 12 |
from google.cloud import texttospeech
|
| 13 |
-
from dotenv import load_dotenv
|
| 14 |
-
import streamlit as st
|
| 15 |
|
| 16 |
nltk.download('punkt', quiet=True)
|
| 17 |
nltk.download('stopwords', quiet=True)
|
| 18 |
|
| 19 |
-
# Cargar las claves API desde el archivo .env
|
| 20 |
-
load_dotenv()
|
| 21 |
-
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 22 |
-
brevo_api_key = os.getenv("BREVO_API_KEY")
|
| 23 |
-
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "service_account.json"
|
| 24 |
-
|
| 25 |
-
# Verifica que las claves API est谩n configuradas
|
| 26 |
-
if not openai_api_key:
|
| 27 |
-
raise ValueError("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 |
-
raise ValueError("No API key provided for Brevo. Please set your API key in the .env file.")
|
| 33 |
-
|
| 34 |
def extraer_texto_pdf(archivo):
|
| 35 |
texto = ""
|
| 36 |
if archivo:
|
|
@@ -43,7 +26,7 @@ def extraer_texto_pdf(archivo):
|
|
| 43 |
for page in range(len(reader.pages)):
|
| 44 |
texto += reader.pages[page].extract_text()
|
| 45 |
except Exception as e:
|
| 46 |
-
|
| 47 |
finally:
|
| 48 |
os.unlink(temp_file_path)
|
| 49 |
return texto
|
|
@@ -84,23 +67,27 @@ def obtener_respuesta(pregunta, texto_preprocesado, modelo, temperatura=0.5, ass
|
|
| 84 |
input=input_text, voice=voice, audio_config=audio_config
|
| 85 |
)
|
| 86 |
|
|
|
|
|
|
|
| 87 |
return respuesta
|
| 88 |
|
| 89 |
except openai.OpenAIError as e:
|
| 90 |
-
|
|
|
|
| 91 |
|
| 92 |
except Exception as e:
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
def guardar_en_txt(nombre_archivo, datos):
|
| 96 |
carpeta = "datos_guardados"
|
| 97 |
-
os.makedirs(carpeta,
|
| 98 |
ruta_archivo = os.path.join(carpeta, nombre_archivo)
|
| 99 |
try:
|
| 100 |
with open(ruta_archivo, 'a', encoding='utf-8') as archivo: # Append mode
|
| 101 |
archivo.write(datos + "\n")
|
| 102 |
except Exception as e:
|
| 103 |
-
|
| 104 |
return ruta_archivo
|
| 105 |
|
| 106 |
def cargar_desde_txt(nombre_archivo):
|
|
@@ -111,9 +98,11 @@ def cargar_desde_txt(nombre_archivo):
|
|
| 111 |
with open(ruta_archivo, 'r', encoding='utf-8') as archivo:
|
| 112 |
return archivo.read()
|
| 113 |
else:
|
|
|
|
| 114 |
return ""
|
| 115 |
except Exception as e:
|
| 116 |
-
|
|
|
|
| 117 |
|
| 118 |
def listar_archivos_txt():
|
| 119 |
carpeta = "datos_guardados"
|
|
@@ -124,7 +113,8 @@ def listar_archivos_txt():
|
|
| 124 |
archivos_ordenados = sorted(archivos, key=lambda x: os.path.getctime(os.path.join(carpeta, x)), reverse=True)
|
| 125 |
return archivos_ordenados
|
| 126 |
except Exception as e:
|
| 127 |
-
|
|
|
|
| 128 |
|
| 129 |
def generar_pdf(dataframe, titulo, filename):
|
| 130 |
pdf = FPDF()
|
|
@@ -141,7 +131,8 @@ def generar_pdf(dataframe, titulo, filename):
|
|
| 141 |
pdf.output(tmp_file.name)
|
| 142 |
return tmp_file.name
|
| 143 |
except Exception as e:
|
| 144 |
-
|
|
|
|
| 145 |
|
| 146 |
def enviar_correo(destinatario, asunto, contenido):
|
| 147 |
url = "https://api.brevo.com/v3/smtp/email"
|
|
@@ -159,11 +150,11 @@ def enviar_correo(destinatario, asunto, contenido):
|
|
| 159 |
try:
|
| 160 |
response = requests.post(url, json=payload, headers=headers)
|
| 161 |
if response.status_code == 201:
|
| 162 |
-
|
| 163 |
else:
|
| 164 |
-
|
| 165 |
except Exception as e:
|
| 166 |
-
|
| 167 |
|
| 168 |
def enviar_whatsapp(numero, mensaje):
|
| 169 |
url = "https://api.brevo.com/v3/whatsapp/send"
|
|
@@ -180,26 +171,11 @@ def enviar_whatsapp(numero, mensaje):
|
|
| 180 |
try:
|
| 181 |
response = requests.post(url, json=payload, headers=headers)
|
| 182 |
if response.status_code == 201:
|
| 183 |
-
|
| 184 |
else:
|
| 185 |
-
|
| 186 |
except Exception as e:
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
def mostrar_datos_como_texto(datos):
|
| 190 |
-
texto = ""
|
| 191 |
-
if isinstance(datos, dict):
|
| 192 |
-
for key, value in datos.items():
|
| 193 |
-
texto += f"{key}: {value}\n"
|
| 194 |
-
elif isinstance(datos, list):
|
| 195 |
-
for item in datos:
|
| 196 |
-
if isinstance(item, dict):
|
| 197 |
-
for key, value in item.items():
|
| 198 |
-
texto += f"{key}: {value}\n"
|
| 199 |
-
texto += "\n"
|
| 200 |
-
else:
|
| 201 |
-
texto += f"{item}\n"
|
| 202 |
-
return texto
|
| 203 |
|
| 204 |
def flujo_laboratorio():
|
| 205 |
st.title("馃Ψ Gesti贸n de Trabajos de Laboratorio")
|
|
@@ -286,6 +262,78 @@ def flujo_insumos():
|
|
| 286 |
mime="application/pdf"
|
| 287 |
)
|
| 288 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
def flujo_presupuestos():
|
| 290 |
st.title("馃挵 Asistente de Presupuestos")
|
| 291 |
st.markdown("Hola Dr. cu茅nteme en qu茅 puedo ayudarle?")
|
|
|
|
| 1 |
import os
|
| 2 |
import tempfile
|
|
|
|
| 3 |
import PyPDF2
|
| 4 |
import nltk
|
| 5 |
from nltk.tokenize import word_tokenize
|
|
|
|
| 7 |
from nltk.stem import SnowballStemmer
|
| 8 |
import pandas as pd
|
| 9 |
from fpdf import FPDF
|
| 10 |
+
import streamlit as st
|
| 11 |
import requests
|
| 12 |
from google.cloud import texttospeech
|
|
|
|
|
|
|
| 13 |
|
| 14 |
nltk.download('punkt', quiet=True)
|
| 15 |
nltk.download('stopwords', quiet=True)
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
def extraer_texto_pdf(archivo):
|
| 18 |
texto = ""
|
| 19 |
if archivo:
|
|
|
|
| 26 |
for page in range(len(reader.pages)):
|
| 27 |
texto += reader.pages[page].extract_text()
|
| 28 |
except Exception as e:
|
| 29 |
+
st.error(f"Error al extraer texto del PDF: {e}")
|
| 30 |
finally:
|
| 31 |
os.unlink(temp_file_path)
|
| 32 |
return texto
|
|
|
|
| 67 |
input=input_text, voice=voice, audio_config=audio_config
|
| 68 |
)
|
| 69 |
|
| 70 |
+
# Reproduce el audio en Streamlit
|
| 71 |
+
st.audio(response.audio_content, format="audio/mp3")
|
| 72 |
return respuesta
|
| 73 |
|
| 74 |
except openai.OpenAIError as e:
|
| 75 |
+
st.error(f"Error al comunicarse con OpenAI: {e}")
|
| 76 |
+
return "Lo siento, no puedo procesar tu solicitud en este momento."
|
| 77 |
|
| 78 |
except Exception as e:
|
| 79 |
+
st.error(f"Error al generar la respuesta y el audio: {e}")
|
| 80 |
+
return "Lo siento, ocurri贸 un error al procesar tu solicitud."
|
| 81 |
|
| 82 |
def guardar_en_txt(nombre_archivo, datos):
|
| 83 |
carpeta = "datos_guardados"
|
| 84 |
+
os.makedirs(carpeta, existo_ok=True)
|
| 85 |
ruta_archivo = os.path.join(carpeta, nombre_archivo)
|
| 86 |
try:
|
| 87 |
with open(ruta_archivo, 'a', encoding='utf-8') as archivo: # Append mode
|
| 88 |
archivo.write(datos + "\n")
|
| 89 |
except Exception as e:
|
| 90 |
+
st.error(f"Error al guardar datos en el archivo: {e}")
|
| 91 |
return ruta_archivo
|
| 92 |
|
| 93 |
def cargar_desde_txt(nombre_archivo):
|
|
|
|
| 98 |
with open(ruta_archivo, 'r', encoding='utf-8') as archivo:
|
| 99 |
return archivo.read()
|
| 100 |
else:
|
| 101 |
+
st.warning("Archivo no encontrado.")
|
| 102 |
return ""
|
| 103 |
except Exception as e:
|
| 104 |
+
st.error(f"Error al cargar datos desde el archivo: {e}")
|
| 105 |
+
return ""
|
| 106 |
|
| 107 |
def listar_archivos_txt():
|
| 108 |
carpeta = "datos_guardados"
|
|
|
|
| 113 |
archivos_ordenados = sorted(archivos, key=lambda x: os.path.getctime(os.path.join(carpeta, x)), reverse=True)
|
| 114 |
return archivos_ordenados
|
| 115 |
except Exception as e:
|
| 116 |
+
st.error(f"Error al listar archivos: {e}")
|
| 117 |
+
return []
|
| 118 |
|
| 119 |
def generar_pdf(dataframe, titulo, filename):
|
| 120 |
pdf = FPDF()
|
|
|
|
| 131 |
pdf.output(tmp_file.name)
|
| 132 |
return tmp_file.name
|
| 133 |
except Exception as e:
|
| 134 |
+
st.error(f"Error al generar PDF: {e}")
|
| 135 |
+
return None
|
| 136 |
|
| 137 |
def enviar_correo(destinatario, asunto, contenido):
|
| 138 |
url = "https://api.brevo.com/v3/smtp/email"
|
|
|
|
| 150 |
try:
|
| 151 |
response = requests.post(url, json=payload, headers=headers)
|
| 152 |
if response.status_code == 201:
|
| 153 |
+
st.success(f"Correo enviado a {destinatario}")
|
| 154 |
else:
|
| 155 |
+
st.error(f"Error al enviar el correo: {response.text}")
|
| 156 |
except Exception as e:
|
| 157 |
+
st.error(f"Error al enviar el correo: {e}")
|
| 158 |
|
| 159 |
def enviar_whatsapp(numero, mensaje):
|
| 160 |
url = "https://api.brevo.com/v3/whatsapp/send"
|
|
|
|
| 171 |
try:
|
| 172 |
response = requests.post(url, json=payload, headers=headers)
|
| 173 |
if response.status_code == 201:
|
| 174 |
+
st.success(f"Mensaje de WhatsApp enviado a {numero}")
|
| 175 |
else:
|
| 176 |
+
st.error(f"Error al enviar el mensaje de WhatsApp: {response.text}")
|
| 177 |
except Exception as e:
|
| 178 |
+
st.error(f"Error al enviar el mensaje de WhatsApp: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
def flujo_laboratorio():
|
| 181 |
st.title("馃Ψ Gesti贸n de Trabajos de Laboratorio")
|
|
|
|
| 262 |
mime="application/pdf"
|
| 263 |
)
|
| 264 |
|
| 265 |
+
def buscar_datos_guardados():
|
| 266 |
+
st.title("馃攳 Buscar Datos Guardados")
|
| 267 |
+
|
| 268 |
+
carpeta = "datos_guardados"
|
| 269 |
+
if not os.path.exists(carpeta):
|
| 270 |
+
st.info("No se encontraron archivos de datos guardados.")
|
| 271 |
+
return
|
| 272 |
+
|
| 273 |
+
archivos = listar_archivos_txt()
|
| 274 |
+
|
| 275 |
+
if archivos:
|
| 276 |
+
archivo_seleccionado = st.selectbox("Selecciona un archivo para ver:", archivos)
|
| 277 |
+
|
| 278 |
+
if archivo_seleccionado:
|
| 279 |
+
datos = cargar_desde_txt(os.path.join(carpeta, archivo_seleccionado))
|
| 280 |
+
if datos:
|
| 281 |
+
st.write(f"### Datos del archivo {archivo_seleccionado}")
|
| 282 |
+
st.text_area("Datos", datos, height=300)
|
| 283 |
+
|
| 284 |
+
# Link to download the file
|
| 285 |
+
try:
|
| 286 |
+
with open(os.path.join(carpeta, archivo_seleccionado), 'rb') as file:
|
| 287 |
+
st.download_button(
|
| 288 |
+
label="馃摜 Descargar Archivo TXT",
|
| 289 |
+
data=file,
|
| 290 |
+
file_name=archivo_seleccionado,
|
| 291 |
+
mime="text/plain"
|
| 292 |
+
)
|
| 293 |
+
except Exception as e:
|
| 294 |
+
st.error(f"Error al preparar la descarga: {e}")
|
| 295 |
+
|
| 296 |
+
# Enviar el archivo seleccionado por correo
|
| 297 |
+
if st.button("Enviar por correo"):
|
| 298 |
+
contenido = f"Datos del archivo {archivo_seleccionado}:\n\n{datos}"
|
| 299 |
+
enviar_correo("josedcape@gmail.com", f"Datos del archivo {archivo_seleccionado}", contenido)
|
| 300 |
+
|
| 301 |
+
# Enviar el archivo seleccionado por WhatsApp
|
| 302 |
+
if st.button("Enviar por WhatsApp"):
|
| 303 |
+
mensaje = f"Datos del archivo {archivo_seleccionado}:\n\n{datos}"
|
| 304 |
+
enviar_whatsapp("3114329322", mensaje)
|
| 305 |
+
|
| 306 |
+
else:
|
| 307 |
+
st.warning(f"No se encontraron datos en el archivo {archivo_seleccionado}")
|
| 308 |
+
else:
|
| 309 |
+
st.info("No se encontraron archivos de datos guardados.")
|
| 310 |
+
|
| 311 |
+
def generar_notificaciones_pendientes():
|
| 312 |
+
if 'laboratorio' not in st.session_state or not st.session_state.laboratorio:
|
| 313 |
+
st.info("No hay trabajos pendientes.")
|
| 314 |
+
return
|
| 315 |
+
|
| 316 |
+
pendientes = [trabajo for trabajo in st.session_state.laboratorio if trabajo["estado"] == "pendiente"]
|
| 317 |
+
if pendientes:
|
| 318 |
+
st.write("### Notificaciones de Trabajos Pendientes")
|
| 319 |
+
for trabajo in pendientes:
|
| 320 |
+
st.info(f"Pendiente: {trabajo['tipo_trabajo']} - {trabajo['numero_orden']} para {trabajo['doctor']}. Enviado a {trabajo['laboratorio']} el {trabajo['fecha_envio']}.")
|
| 321 |
+
|
| 322 |
+
def mostrar_datos_como_texto(datos):
|
| 323 |
+
texto = ""
|
| 324 |
+
if isinstance(datos, dict):
|
| 325 |
+
for key, value in datos.items():
|
| 326 |
+
texto += f"{key}: {value}\n"
|
| 327 |
+
elif isinstance(datos, list):
|
| 328 |
+
for item in datos:
|
| 329 |
+
if isinstance(item, dict):
|
| 330 |
+
for key, value in item.items():
|
| 331 |
+
texto += f"{key}: {value}\n"
|
| 332 |
+
texto += "\n"
|
| 333 |
+
else:
|
| 334 |
+
texto += f"{item}\n"
|
| 335 |
+
return texto
|
| 336 |
+
|
| 337 |
def flujo_presupuestos():
|
| 338 |
st.title("馃挵 Asistente de Presupuestos")
|
| 339 |
st.markdown("Hola Dr. cu茅nteme en qu茅 puedo ayudarle?")
|