Josedcape commited on
Commit
51bb2d0
·
verified ·
1 Parent(s): 6249ca5

Update utils/data_manager.py

Browse files
Files changed (1) hide show
  1. utils/data_manager.py +85 -163
utils/data_manager.py CHANGED
@@ -1,185 +1,107 @@
1
- import openai
2
  import os
 
 
3
  import tempfile
4
- import PyPDF2
5
- from dotenv import load_dotenv
6
- from google.cloud import texttospeech
7
- import nltk
8
- from nltk.tokenize import word_tokenize
9
- from nltk.corpus import stopwords
10
- from nltk.stem import SnowballStemmer
11
  import streamlit as st
12
- import requests
13
 
14
- nltk.download('punkt', quiet=True)
15
- nltk.download('stopwords', quiet=True)
16
-
17
- # Cargar las claves API desde el archivo .env
18
- load_dotenv()
19
- openai_api_key = os.getenv("OPENAI_API_KEY")
20
- brevo_api_key = os.getenv("BREVO_API_KEY")
21
- os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "botidinamix-g.json"
22
-
23
- # Verifica que las claves API están configuradas
24
- if not openai_api_key:
25
- st.error("No API key provided for OpenAI. Please set your API key in the .env file.")
26
- else:
27
- openai.api_key = openai_api_key
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- if not brevo_api_key:
30
- st.error("No API key provided for Brevo. Please set your API key in the .env file.")
31
 
32
- def extraer_texto_pdf(archivo):
33
  texto = ""
34
- if archivo:
35
- with tempfile.NamedTemporaryFile(delete=False) as temp_file:
36
- temp_file.write(archivo.read())
37
- temp_file_path = temp_file.name
38
- try:
39
- with open(temp_file_path, 'rb') as file:
40
- reader = PyPDF2.PdfReader(file)
41
- for page in range(len(reader.pages)):
42
- texto += reader.pages[page].extract_text()
43
- except Exception as e:
44
- st.error(f"Error al extraer texto del PDF: {e}")
45
- finally:
46
- os.unlink(temp_file_path)
47
  return texto
48
 
49
- def preprocesar_texto(texto):
50
- tokens = word_tokenize(texto, language='spanish')
51
- tokens = [word.lower() for word in tokens if word.isalpha()]
52
- stopwords_es = set(stopwords.words('spanish'))
53
- tokens = [word for word in tokens if word not in stopwords_es]
54
- stemmer = SnowballStemmer('spanish')
55
- tokens = [stemmer.stem(word) for word in tokens]
56
- return " ".join(tokens)
57
-
58
- client = texttospeech.TextToSpeechClient()
59
-
60
- def obtener_respuesta(pregunta, texto_preprocesado, modelo, temperatura=0.5, assistant_id=None):
61
- try:
62
- messages = [
63
- {"role": "system", "content": "Actua como Galatea la asistente de la clinica Odontologica OMARDENT y resuelve las inquietudes"},
64
- {"role": "user", "content": f"{pregunta}\n\nContexto: {texto_preprocesado}"}
65
- ]
66
-
67
- if assistant_id:
68
- response = openai.Completion.create(
69
- model=assistant_id,
70
- prompt=f"{messages}",
71
- temperature=temperatura
72
- )
73
- respuesta = response.choices[0].text.strip()
74
- else:
75
- response = openai.ChatCompletion.create(
76
- model=modelo,
77
- messages=messages,
78
- temperature=temperatura
79
- )
80
- respuesta = response.choices[0].message['content'].strip()
81
-
82
- input_text = texttospeech.SynthesisInput(text=respuesta)
83
- voice = texttospeech.VoiceSelectionParams(
84
- language_code="es-ES", ssml_gender=texttospeech.SsmlVoiceGender.FEMALE
85
- )
86
- audio_config = texttospeech.AudioConfig(
87
- audio_encoding=texttospeech.AudioEncoding.MP3
88
- )
89
-
90
- response = client.synthesize_speech(
91
- input=input_text, voice=voice, audio_config=audio_config
92
- )
93
-
94
- st.audio(response.audio_content, format="audio/mp3")
95
- return respuesta
96
-
97
- except openai.OpenAIError as e:
98
- st.error(f"Error al comunicarse con OpenAI: {e}")
99
- return "Lo siento, no puedo procesar tu solicitud en este momento."
100
-
101
- except Exception as e:
102
- st.error(f"Error al generar la respuesta y el audio: {e}")
103
- return "Lo siento, ocurrió un error al procesar tu solicitud."
104
-
105
  def guardar_en_txt(nombre_archivo, datos):
106
  carpeta = "datos_guardados"
107
  os.makedirs(carpeta, exist_ok=True)
108
  ruta_archivo = os.path.join(carpeta, nombre_archivo)
109
  try:
110
- with open(ruta_archivo, 'a', encoding='utf-8') as archivo:
111
  archivo.write(datos + "\n")
112
  except Exception as e:
113
  st.error(f"Error al guardar datos en el archivo: {e}")
114
  return ruta_archivo
115
 
116
- def cargar_desde_txt(nombre_archivo):
117
- carpeta = "datos_guardados"
118
- ruta_archivo = os.path.join(carpeta, nombre_archivo)
119
- try:
120
- if os.path.exists(ruta_archivo):
121
- with open(ruta_archivo, 'r', encoding='utf-8') as archivo:
122
- return archivo.read()
123
- else:
124
- st.warning("Archivo no encontrado.")
125
- return ""
126
- except Exception as e:
127
- st.error(f"Error al cargar datos desde el archivo: {e}")
128
- return ""
129
-
130
- def listar_archivos_txt():
131
- carpeta = "datos_guardados"
132
- try:
133
- if not os.path.exists(carpeta):
134
- return []
135
- archivos = [f for f in os.listdir(carpeta) if f.endswith('.txt')]
136
- archivos_ordenados = sorted(archivos, key=lambda x: os.path.getctime(os.path.join(carpeta, x)), reverse=True)
137
- return archivos_ordenados
138
- except Exception as e:
139
- st.error(f"Error al listar archivos: {e}")
140
- return []
141
 
142
- def enviar_correo(destinatario, asunto, contenido):
143
- url = "https://api.brevo.com/v3/smtp/email"
144
- headers = {
145
- "accept": "application/json",
146
- "api-key": brevo_api_key,
147
- "content-type": "application/json"
148
- }
149
- payload = {
150
- "sender": {"email": "tu_correo@dominio.com"},
151
- "to": [{"email": destinatario}],
152
- "subject": asunto,
153
- "htmlContent": contenido
154
- }
155
  try:
156
- response = requests.post(url, json=payload, headers=headers)
157
- if response.status_code == 201:
158
- st.success(f"Correo enviado a {destinatario}")
159
- else:
160
- st.error(f"Error al enviar el correo: {response.text}")
161
  except Exception as e:
162
- st.error(f"Error al enviar el correo: {e}")
163
-
164
- def enviar_whatsapp(numero, mensaje):
165
- url = "https://api.brevo.com/v3/whatsapp/send"
166
- headers = {
167
- "accept": "application/json",
168
- "api-key": brevo_api_key,
169
- "content-type": "application/json"
170
- }
171
- payload = {
172
- "recipient": {"number": numero},
173
- "sender": {"number": "tu_numero_whatsapp"},
174
- "content": mensaje
175
- }
176
- try:
177
- response = requests.post(url, json=payload, headers=headers)
178
- if response.status_code == 201:
179
- st.success(f"Mensaje de WhatsApp enviado a {numero}")
180
- else:
181
- st.error(f"Error al enviar el mensaje de WhatsApp: {response.text}")
182
- except Exception as e:
183
- st.error(f"Error al enviar el mensaje de WhatsApp: {e}")
184
-
185
- # Añadir funciones para buscar datos guardados, generar notificaciones y mostrar datos como texto si es necesario
 
 
1
  import os
2
+ import pandas as pd
3
+ from fpdf import FPDF
4
  import tempfile
 
 
 
 
 
 
 
5
  import streamlit as st
 
6
 
7
+ # Aquí irían otras importaciones y funciones...
8
+
9
+ def flujo_laboratorio():
10
+ st.title("🦷 Gestión de Trabajos de Laboratorio")
11
+
12
+ if 'laboratorio' not in st.session_state:
13
+ st.session_state.laboratorio = []
14
+
15
+ with st.form("laboratorio_form"):
16
+ tipo_trabajo = st.selectbox("Tipo de trabajo:", [
17
+ "Protesis total", "Protesis removible metal-acrilico", "Parcialita acrilico",
18
+ "Placa de blanqueamiento", "Placa de bruxismo", "Corona de acrilico",
19
+ "Corona en zirconio", "Protesis flexible", "Acker flexible"
20
+ ])
21
+ doctor = st.selectbox("Doctor que requiere el trabajo:", ["Dr. Jose Daniel C", "Dr. Jose Omar C"])
22
+ fecha_entrega = st.date_input("Fecha de entrega:")
23
+ fecha_envio = st.date_input("Fecha de envío:")
24
+ laboratorio = st.selectbox("Laboratorio dental:", ["Ernesto Correa lab", "Formando Sonrisas"])
25
+ nombre_paciente = st.text_input("Nombre paciente:")
26
+ observaciones = st.text_input("Observaciones:")
27
+ numero_orden = st.text_input("Número de orden:")
28
+ cantidad = st.number_input("Cantidad:", min_value=1, step=1)
29
+
30
+ submitted = st.form_submit_button("Registrar Trabajo")
31
+
32
+ if submitted:
33
+ trabajo = {
34
+ "tipo_trabajo": tipo_trabajo,
35
+ "doctor": doctor,
36
+ "fecha_entrega": str(fecha_entrega),
37
+ "fecha_envio": str(fecha_envio),
38
+ "laboratorio": laboratorio,
39
+ "nombre_paciente": nombre_paciente,
40
+ "observaciones": observaciones,
41
+ "numero_orden": numero_orden,
42
+ "cantidad": cantidad,
43
+ "estado": "pendiente"
44
+ }
45
+ st.session_state.laboratorio.append(trabajo)
46
+ datos_guardados = mostrar_datos_como_texto([trabajo]) # Append only the new entry
47
+ guardar_en_txt('trabajos_laboratorio.txt', datos_guardados)
48
+ st.success("Trabajo registrado con éxito.")
49
+
50
+ if st.session_state.laboratorio:
51
+ st.write("### Trabajos Registrados")
52
+ df_trabajos = pd.DataFrame(st.session_state.laboratorio)
53
+ st.write(df_trabajos)
54
+
55
+ pdf_file = generar_pdf(df_trabajos, "Registro de Trabajos de Laboratorio", "trabajos_laboratorio.pdf")
56
+ st.download_button(
57
+ label="📥 Descargar PDF",
58
+ data=open(pdf_file, 'rb').read(),
59
+ file_name="trabajos_laboratorio.pdf",
60
+ mime="application/pdf"
61
+ )
62
 
63
+ # Aquí pueden ir otras funciones...
 
64
 
65
+ def mostrar_datos_como_texto(datos):
66
  texto = ""
67
+ if isinstance(datos, dict):
68
+ for key, value in datos.items():
69
+ texto += f"{key}: {value}\n"
70
+ elif isinstance(datos, list):
71
+ for item in datos:
72
+ if isinstance(item, dict):
73
+ for key, value in item.items():
74
+ texto += f"{key}: {value}\n"
75
+ texto += "\n"
76
+ else:
77
+ texto += f"{item}\n"
 
 
78
  return texto
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  def guardar_en_txt(nombre_archivo, datos):
81
  carpeta = "datos_guardados"
82
  os.makedirs(carpeta, exist_ok=True)
83
  ruta_archivo = os.path.join(carpeta, nombre_archivo)
84
  try:
85
+ with open(ruta_archivo, 'a', encoding='utf-8') as archivo: # Append mode
86
  archivo.write(datos + "\n")
87
  except Exception as e:
88
  st.error(f"Error al guardar datos en el archivo: {e}")
89
  return ruta_archivo
90
 
91
+ def generar_pdf(dataframe, titulo, filename):
92
+ pdf = FPDF()
93
+ pdf.add_page()
94
+ pdf.set_font("Arial", size=12)
95
+ pdf.cell(200, 10, txt=titulo, ln=True, align='C')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ for i, row in dataframe.iterrows():
98
+ row_text = ", ".join(f"{col}: {val}" for col, val in row.items())
99
+ pdf.cell(200, 10, txt=row_text, ln=True)
100
+
 
 
 
 
 
 
 
 
 
101
  try:
102
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
103
+ pdf.output(tmp_file.name)
104
+ return tmp_file.name
 
 
105
  except Exception as e:
106
+ st.error(f"Error al generar PDF: {e}")
107
+ return None