enpaiva commited on
Commit
11c47fb
verified
1 Parent(s): 50c82fe

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +321 -0
app.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from fpdf import FPDF
3
+ from PIL import Image
4
+ from groq import Groq
5
+ from datetime import datetime, timezone
6
+ import base64
7
+ from io import BytesIO
8
+ import time, os
9
+
10
+ max_texts_rows = 5
11
+ max_texts_elements = 10
12
+ max_img_desc_rows = 5
13
+
14
+ init_texts_rows_state = 1
15
+ init_img_desc_rows_state = 0
16
+
17
+ test_mode = True
18
+
19
+ custom_css = """
20
+ html {
21
+ height: 100%;
22
+ margin: 0;
23
+ display: flex;
24
+ justify-content: center;
25
+ align-items: center;
26
+ }
27
+ body {
28
+ min-height: 50vh;
29
+ aspect-ratio: 1 / 1.414; /* A4 aspect ratio */
30
+ width: 100%; /* Full width */
31
+ max-width: 210mm; /* Max width for A4 */
32
+ max-height: 297mm; /* Max height for A4 */
33
+ padding: 10px; /* Optional padding */
34
+ box-sizing: border-box;
35
+ margin: 0 auto; /* Center the block */
36
+ overflow: auto; /* Ensure content is scrollable if it exceeds the block size */
37
+ gap: 10px; /* Add gap between elements */
38
+ }
39
+ .gradio-container{
40
+ background-color: white;
41
+
42
+ }
43
+ #logo-upload {
44
+ min-height: 100px;
45
+ max-height: 100px;
46
+ }
47
+ #text-empresa {
48
+ min-height: 100px;
49
+ max-height: 100px;
50
+ }
51
+ .text-box {
52
+ }
53
+ .image-upload{
54
+ min-height: 300px;
55
+ max-height: 300px;
56
+ }
57
+ img {
58
+ object-fit: contain;
59
+ }
60
+ .description {
61
+ min-height: 300px;
62
+ max-height: 300px;
63
+ }
64
+ h1, h2, h3 {
65
+ color: rgb(60, 60, 60);
66
+ }
67
+ """
68
+
69
+ client = Groq(
70
+ api_key=os.environ.get("GROQ_API_KEY"),
71
+ )
72
+
73
+ with gr.Blocks(css=custom_css) as demo:
74
+
75
+ gr.Markdown("# Plataforma de Generaci贸n de Informes de ViLAB", elem_id="title")
76
+
77
+ gr.Markdown("### Ingrese el nombre de su empresa y su logo [opcional].", elem_id="subtitle")
78
+
79
+ header_items = []
80
+
81
+ with gr.Row(equal_height=True):
82
+ with gr.Column(scale=1, min_width=160):
83
+ nombre_empresa = gr.Textbox("Dra. Veterinaria Bel茅n Colm谩n" if test_mode else "Nombre de la Empresa", label=None, visible = True, container = False, elem_id="text-empresa", interactive=True)
84
+ header_items.append(nombre_empresa)
85
+ with gr.Column(scale=1, min_width=160):
86
+ logo = gr.Image(Image.open("/content/file.jpg") if test_mode else None,label="Logo", elem_id="logo-upload", visible=True, interactive=True, mirror_webcam=False, sources="upload")
87
+ header_items.append(logo)
88
+
89
+ gr.Markdown("---")
90
+
91
+ # -----------------------------------------------------------------------------------------------------
92
+
93
+ gr.Markdown("## Plantilla de Informes")
94
+
95
+ gr.Markdown("### Ingrese los datos para el informe.")
96
+ gr.Markdown("### (Agregue campos con el bot贸n '+', remueva campos con el bot贸n '-')")
97
+
98
+ texts_state = gr.State(2)
99
+
100
+ textboxes = []
101
+
102
+ for i in range(max_texts_rows):
103
+ with gr.Row():
104
+ with gr.Column(scale=1, min_width=160):
105
+ textbox_l = gr.Textbox("T铆tulo: Descripci贸n", show_label=False, elem_classes="text-box", visible = (i<init_texts_rows_state), interactive=True )
106
+ textboxes.append(textbox_l)
107
+ with gr.Column(scale=1, min_width=160):
108
+ if i == 0:
109
+ textbox_r = gr.Textbox("Fecha: " + datetime.now().strftime("%d/%m/%Y"), show_label=False, elem_classes="text-box", visible = (i<init_texts_rows_state), interactive=False )
110
+ else:
111
+ textbox_r = gr.Textbox("T铆tulo: Descripci贸n", show_label=False, elem_classes="text-box", visible = (i<init_texts_rows_state), interactive=True )
112
+ textboxes.append(textbox_r)
113
+
114
+ with gr.Row():
115
+ with gr.Column(scale=1, min_width=160):
116
+ plus_button = gr.Button("+")
117
+ with gr.Column(scale=1, min_width=160):
118
+ minus_button = gr.Button("-")
119
+
120
+ def variable_outputs_plus(k):
121
+ k = int(k)
122
+ k = min(max_texts_elements, k + 1)
123
+ return [gr.Textbox(visible=True)]*(k) + [gr.Textbox(visible=False)]*(max_texts_elements-k) + [k]
124
+
125
+ def variable_outputs_minus(k):
126
+ k = int(k)
127
+ k = max(1, k - 1)
128
+ return [gr.Textbox(visible=True)]*(k) + [gr.Textbox(visible=False)]*(max_texts_elements-k) + [k]
129
+
130
+ plus_button.click(variable_outputs_plus, texts_state, textboxes + [texts_state])
131
+ minus_button.click(variable_outputs_minus, texts_state, textboxes + [texts_state])
132
+
133
+ gr.Markdown("---")
134
+
135
+ # -----------------------------------------------------------------------------------------------------
136
+
137
+ gr.Markdown("## Plantilla de Resultados")
138
+
139
+ gr.Markdown("### Ingrese los resultados con imagen y descripci贸n.")
140
+ gr.Markdown("### (Agregue campos con el bot贸n '+', remueva campos con el bot贸n '-')")
141
+
142
+ images_description_state = gr.State(0)
143
+
144
+ img_desc_boxes = []
145
+
146
+ for i in range(max_img_desc_rows):
147
+ with gr.Row():
148
+ with gr.Column(scale=1, min_width=160):
149
+ image = gr.Image(label=f"Imagen {i}", interactive=True, mirror_webcam=False, sources="upload", elem_classes="image-upload", container = True, visible = (i<init_img_desc_rows_state))
150
+ img_desc_boxes.append(image)
151
+ with gr.Column(scale=1, min_width=160):
152
+ description = gr.TextArea("Describa su muestra ... ", label=f"Descripci贸n", visible=(i<init_img_desc_rows_state), elem_classes="description", interactive=True, max_lines=10 )
153
+ img_desc_boxes.append(description)
154
+
155
+ with gr.Row():
156
+ with gr.Column(scale=1, min_width=160):
157
+ plus_img_desc_button = gr.Button("+")
158
+ with gr.Column(scale=1, min_width=160):
159
+ minus_img_desc_button = gr.Button("-")
160
+
161
+
162
+ def variable_outputs_plus_img_desc(k):
163
+ k = int(k)
164
+ k = min(max_img_desc_rows, k + 1)
165
+ return [gr.Image(visible=True), gr.TextArea(visible=True)]*k + [gr.Image(visible=False), gr.TextArea(visible=False)]*(max_img_desc_rows-k) + [k]
166
+
167
+ def variable_outputs_minus_img_desc(k):
168
+ k = int(k)
169
+ k = max(0, k - 1)
170
+ return [gr.TextArea(visible=True)]*(2*k) + [gr.TextArea(visible=False)]*(2*(max_texts_rows-k)) + [k]
171
+
172
+ plus_img_desc_button.click(variable_outputs_plus_img_desc, images_description_state, img_desc_boxes + [images_description_state])
173
+ minus_img_desc_button.click(variable_outputs_minus_img_desc, images_description_state, img_desc_boxes + [images_description_state])
174
+
175
+ gr.Markdown("---")
176
+
177
+ # -----------------------------------------------------------------------------------------------------
178
+
179
+ state_data = gr.State([])
180
+
181
+ with gr.Row():
182
+ submit_button = gr.DownloadButton (label="Generar Reporte")
183
+
184
+ # Funci贸n para mantener la relaci贸n de aspecto de la imagen
185
+ def get_aspect_ratio_image_size(img, max_width, max_height):
186
+ width, height = img.size
187
+ aspect_ratio = width / height
188
+ if width > max_width or height > max_height:
189
+ if width / max_width > height / max_height:
190
+ width = max_width
191
+ height = width / aspect_ratio
192
+ else:
193
+ height = max_height
194
+ width = height * aspect_ratio
195
+ return width, height
196
+
197
+ class PDF(FPDF):
198
+
199
+ def __init__(self, datos, *args, **kwargs):
200
+ super().__init__(*args, **kwargs)
201
+ self.datos = datos
202
+
203
+ def set_text(self, datos):
204
+ self.datos = datos
205
+
206
+ def footer(self):
207
+ self.set_y(-15)
208
+ self.set_font('Helvetica', '', 8)
209
+ self.cell(0, 10, 'P谩gina %s' % self.page_no(), 0, new_x='RIGHT', new_y='TOP', align='C')
210
+
211
+ def body(self):
212
+
213
+ # Datos de la Empresa
214
+ nombre_empresa = "Nombre de la Empresa: " + self.datos[0][0]
215
+ logo_path = self.datos[0][1]
216
+ if logo_path is not None:
217
+ image = Image.fromarray(logo_path)
218
+ logo_width, logo_height = get_aspect_ratio_image_size(image, 30, 30)
219
+ self.image(image, 10, self.get_y(), logo_width, logo_height)
220
+ self.ln(logo_height + 5)
221
+ self.set_font('Helvetica', '', 12)
222
+ self.cell(0, 10, nombre_empresa, 0, new_x='LMARGIN', new_y='NEXT', align='L')
223
+
224
+ # L铆nea horizontal divisoria
225
+ self.line(10, self.get_y(), self.w - 10, self.get_y())
226
+ self.ln(5)
227
+
228
+ # Datos del Informe
229
+ self.set_font('Helvetica', '', 11)
230
+ for i in range(len(self.datos[1])):
231
+ if i%2 != 0:
232
+ if self.datos[1][i] != "T铆tulo: Descripci贸n":
233
+ self.cell(self.w / 2 - 10, 10, self.datos[1][i], 0, new_x='LMARGIN', new_y='NEXT', align='L')
234
+ if i%2 == 0:
235
+ if self.datos[1][i] != "T铆tulo: Descripci贸n":
236
+ self.cell(self.w / 2 - 10, 10, self.datos[1][i], 0, new_x='RIGHT', new_y='TOP', align='L')
237
+
238
+ # L铆nea horizontal divisoria
239
+ self.ln(10)
240
+ self.line(10, self.get_y(), self.w - 10, self.get_y())
241
+ self.ln(5)
242
+
243
+ # Datos del Resultado
244
+ for i in range(len(self.datos[2])):
245
+ if self.datos[2][i] is not None:
246
+ image = Image.fromarray(self.datos[2][i])
247
+ img_width, img_height = get_aspect_ratio_image_size(image, self.w / 2 - 20, 100)
248
+ if self.get_y() + img_height + 10 > self.h - 30:
249
+ self.add_page()
250
+ self.image(image, 10, self.get_y(), img_width, img_height)
251
+ if self.datos[3][i] != "Describa su muestra ... ":
252
+ self.set_font('Helvetica', '', 10)
253
+ self.set_xy(self.w / 2 + 10, self.get_y())
254
+ self.multi_cell(self.w / 2 - 20, None, self.datos[3][i])
255
+ self.ln(img_height + 5)
256
+ else:
257
+ if self.datos[3][i] != "Describa su muestra ... ":
258
+ self.set_font('Helvetica', '', 10)
259
+ if self.get_y() + 10 > self.h - 30:
260
+ self.add_page()
261
+ self.set_xy(self.w / 2 + 10, self.get_y())
262
+ self.multi_cell(self.w / 2 - 20, None, self.datos[3][i])
263
+
264
+ # Resumen del Informe
265
+ self.set_font('Helvetica', '', 10)
266
+ self.ln(10) # A帽adir espacio antes del resumen
267
+ self.multi_cell(0, 6, "Resumen - Historial Cl铆nico: " + self.datos[4], 0, 'L')
268
+
269
+
270
+ def get_values(*args):
271
+ n_args = len(args)
272
+
273
+ data = [
274
+ list(args[0:2]),
275
+ list(args[2:2+max_texts_elements-1]),
276
+ list(args[2+max_texts_elements:n_args:2]),
277
+ list(args[2+max_texts_elements+1:n_args+1:2])
278
+ ]
279
+
280
+ nombre_empresa = data[0][0]
281
+ datos_informe = [i for i in data[1] if i != "T铆tulo: Descripci贸n"]
282
+ resultados_informe = [i for i in data[3] if i != "Describa su muestra ... "]
283
+
284
+ prompt = f"""Eres un narrador del historial cl铆nico en espa帽ol basado en el siguiente contexto:
285
+ -------------------------------
286
+ Nombre de la empresa: {nombre_empresa}
287
+ {' - '.join(datos_informe)}
288
+ Descripciones seg煤n las im谩genes digitalizadas con ViLAB desde el microscopio: {' - '.join(resultados_informe)}
289
+ -------------------------------
290
+ - Nunca generes informaci贸n extra fuera del contexto.
291
+ - A帽ade informaciones 煤tiles
292
+
293
+ Solo presenta el resumen del historial cl铆nico en un p谩rrafo.
294
+ Resumen:"""
295
+
296
+ chat_completion = client.chat.completions.create(
297
+ messages=[
298
+ {
299
+ "role": "user",
300
+ "content": prompt,
301
+ }
302
+ ],
303
+ model="llama3-70b-8192",
304
+ )
305
+
306
+ data.append(chat_completion.choices[0].message.content)
307
+
308
+ # Crear PDF
309
+ pdf = PDF(data)
310
+ pdf.add_page()
311
+ pdf.body()
312
+ pdf_path = "./documento_generado.pdf"
313
+ pdf.output(pdf_path)
314
+
315
+ return pdf_path
316
+
317
+ submit_button.click(get_values, header_items + textboxes + img_desc_boxes, [submit_button])
318
+
319
+ if __name__ == "__main__":
320
+
321
+ demo.launch()