DaniFera commited on
Commit
cfdd571
·
verified ·
1 Parent(s): acc9131

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -58
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # Versión 2.5: App con Ciclo de Vida de Seguridad (Auto-borrado)
2
  import gradio as gr
3
  import pandas as pd
4
  import config
@@ -9,37 +9,63 @@ from core import PDFEngine
9
 
10
  engine = PDFEngine()
11
 
12
- # --- SEGURIDAD: HILO DE LIMPIEZA AUTOMÁTICA ---
13
  def cleanup_cron():
14
  """
15
- Se ejecuta en segundo plano.
16
- Revisa la carpeta temporal cada 5 minutos y borra archivos
17
  """
18
  while True:
19
  try:
 
20
  time.sleep(60)
 
 
 
 
 
21
  now = time.time()
22
- cutoff = now - 300
 
 
23
 
24
  if os.path.exists(config.TEMP_DIR):
25
- for filename in os.listdir(config.TEMP_DIR):
 
 
 
 
26
  filepath = os.path.join(config.TEMP_DIR, filename)
27
- # Verificar si es un archivo y si es viejo
28
  if os.path.isfile(filepath):
29
- t_mod = os.path.getmtime(filepath)
30
- if t_mod < cutoff:
 
 
 
 
 
 
 
 
31
  try:
32
  os.remove(filepath)
33
- print(f"[SEGURIDAD] Archivo expirado eliminado: {filename}")
34
  except Exception as e:
35
- print(f"[ERROR] No se pudo borrar {filename}: {e}")
 
 
 
 
 
36
  except Exception as e:
37
- print(f"[ERROR CRÍTICO] Fallo en el hilo de limpieza: {e}")
38
 
39
- # Iniciar el conserje en un hilo separado (Daemon para que muera si la app muere)
40
  threading.Thread(target=cleanup_cron, daemon=True).start()
41
 
42
- # --- WRAPPERS ---
 
43
  def update_file_list(files):
44
  if not files: return pd.DataFrame(), ""
45
  data = [[i, f.split("/")[-1]] for i, f in enumerate(files)]
@@ -73,7 +99,6 @@ def process_reorder(f, o):
73
  try: return engine.reorder_pages(f, o)
74
  except Exception as e: raise gr.Error(str(e))
75
 
76
- # CAMBIO AQUÍ: Llamamos a compare_pdfs_text en lugar de visual
77
  def process_compare(fa, fb):
78
  if not fa or not fb: return None
79
  try: return engine.compare_pdfs_text(fa, fb)
@@ -141,10 +166,23 @@ def process_i2p(fs):
141
  except Exception as e: raise gr.Error(str(e))
142
 
143
 
144
- # --- UI ---
145
  with gr.Blocks(title=config.APP_TITLE, theme=gr.themes.Soft()) as demo:
 
146
  gr.Markdown(f"# {config.APP_TITLE}")
147
- gr.Markdown(config.APP_DESCRIPTION)
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  with gr.Tabs():
150
 
@@ -155,33 +193,40 @@ with gr.Blocks(title=config.APP_TITLE, theme=gr.themes.Soft()) as demo:
155
  m_files = gr.File(file_count="multiple", label="Archivos", file_types=[".pdf"])
156
  with gr.Column(scale=2):
157
  m_tbl = gr.Dataframe(headers=["ID", "Archivo"], interactive=False)
158
- m_ord = gr.Textbox(label="Orden de los archivos según su ID", placeholder="Ej: 0, 2, 1")
159
  m_btn = gr.Button("Unir", variant="primary")
160
  m_out = gr.File(label="Resultado")
161
  m_files.change(update_file_list, m_files, [m_tbl, m_ord])
162
  m_btn.click(process_merge, [m_files, m_ord], m_out)
163
 
164
- # 2. DIVIDIR
165
  with gr.TabItem("Dividir / Reordenar"):
166
- with gr.Row():
167
- with gr.Column():
168
- dr_f = gr.File(label="PDF Origen", file_types=[".pdf"])
169
- dr_inf = gr.Markdown("")
170
- dr_pg = gr.State(0)
171
- with gr.Column():
172
- with gr.Tab("Extraer"):
173
- s_rng = gr.Textbox(label="Rangos de división", placeholder="1-3, 5")
174
- s_prv = gr.Button("Previsualización")
175
- s_btn = gr.Button("Dividir", variant="primary")
176
- s_gal = gr.Gallery(height=150, columns=4)
177
- s_out = gr.File()
178
- s_prv.click(update_split_preview, [dr_f, s_rng, dr_pg], s_gal)
179
- s_btn.click(process_split, [dr_f, s_rng], s_out)
180
- with gr.Tab("Reordenar"):
181
- r_ord = gr.Textbox(label="Nuevo Orden", placeholder="3, 1, 2")
182
- r_btn = gr.Button("Reordenar", variant="primary")
183
- r_out = gr.File()
184
- r_btn.click(process_reorder, [dr_f, r_ord], r_out)
 
 
 
 
 
 
 
185
  dr_f.change(load_info, dr_f, [dr_inf, dr_pg, s_out])
186
 
187
  # 3. COMPRIMIR
@@ -189,10 +234,10 @@ with gr.Blocks(title=config.APP_TITLE, theme=gr.themes.Soft()) as demo:
189
  with gr.Row():
190
  with gr.Column():
191
  c_f = gr.File(label="PDF Original", file_types=[".pdf"])
192
- c_l = gr.Radio(["Baja (Máxima calidad)", "Media (Recomendado)", "Alta (Pantalla - 72dpi)"], label="Nivel de compresión", value="Media (Recomendado - eBook)")
193
  c_b = gr.Button("Comprimir", variant="primary")
194
  with gr.Column():
195
- c_out = gr.File(label="Resultado")
196
  c_b.click(process_compress, [c_f, c_l], c_out)
197
 
198
  # 4. CONVERTIR
@@ -203,48 +248,48 @@ with gr.Blocks(title=config.APP_TITLE, theme=gr.themes.Soft()) as demo:
203
  gr.Markdown("### A Word")
204
  w_f = gr.File(label="PDF")
205
  w_b = gr.Button("Convertir")
206
- w_o = gr.File()
207
  w_b.click(process_word, w_f, w_o)
208
  with gr.Column():
209
  gr.Markdown("### A Excel")
210
  x_f = gr.File(label="PDF")
211
  x_b = gr.Button("Convertir")
212
- x_o = gr.File()
213
  x_b.click(process_excel, x_f, x_o)
214
  with gr.Column():
215
  gr.Markdown("### A PowerPoint")
216
  p_f = gr.File(label="PDF")
217
  p_b = gr.Button("Convertir")
218
- p_o = gr.File()
219
  p_b.click(process_pptx, p_f, p_o)
220
  with gr.Tab("A Imágenes"):
221
  with gr.Row():
222
  with gr.Column():
223
  p2i_f = gr.File(label="PDF")
224
  p2i_b = gr.Button("Extraer ZIP")
225
- p2i_o = gr.File()
226
  p2i_b.click(process_p2i, p2i_f, p2i_o)
227
  with gr.Column():
228
  i2p_f = gr.File(label="Imágenes", file_count="multiple")
229
  i2p_b = gr.Button("Crear PDF")
230
- i2p_o = gr.File()
231
  i2p_b.click(process_i2p, i2p_f, i2p_o)
232
 
233
- # 5. COMPARAR (Actualizado)
234
  with gr.TabItem("Comparar"):
235
- gr.Markdown("Compara el **texto** de dos versiones. Descarga un informe con lo añadido (Verde) y borrado (Rojo).")
236
  with gr.Row():
237
  with gr.Column():
238
  ca = gr.File(label="Versión A (Original)", file_types=[".pdf"])
239
  with gr.Column():
240
  cb = gr.File(label="Versión B (Modificada)", file_types=[".pdf"])
241
- cb_btn = gr.Button("Generar Informe de Cambios", variant="primary")
242
  co = gr.File(label="Informe PDF")
243
  cb_btn.click(process_compare, [ca, cb], co)
244
 
245
  # 6. EXTRAS
246
- with gr.TabItem("Extras (Rotar,proteger,metadatos)"):
247
- with gr.Tab("Rotar pdf"):
248
  with gr.Row():
249
  with gr.Column():
250
  rf = gr.File(label="PDF")
@@ -252,35 +297,39 @@ with gr.Blocks(title=config.APP_TITLE, theme=gr.themes.Soft()) as demo:
252
  rb = gr.Button("Rotar", variant="primary")
253
  with gr.Column():
254
  rp = gr.Image(label="Preview")
255
- ro = gr.File()
256
  rf.change(update_rot_preview, [rf, ra], rp)
257
  ra.change(update_rot_preview, [rf, ra], rp)
258
  rb.click(process_rotate, [rf, ra], ro)
259
 
260
- with gr.Tab("Proteger con contraseña"):
261
  with gr.Row():
262
  with gr.Column():
263
  pf = gr.File(label="PDF")
264
- pp = gr.Textbox(type="password", label="password")
265
  pb = gr.Button("Encriptar", variant="primary")
266
  with gr.Column():
267
- po = gr.File()
268
  pb.click(process_protect, [pf, pp], po)
269
 
270
- with gr.Tab("Extraer texto/Modificar Metadatos"):
271
  with gr.Row():
272
  with gr.Column():
273
  tf = gr.File(label="PDF")
274
- tb = gr.Button("Extraer Texto en .txt")
275
  to = gr.File()
276
  tb.click(process_text, tf, to)
277
  with gr.Column():
278
  mt = gr.Textbox(label="Título")
279
  ma = gr.Textbox(label="Autor")
280
  ms = gr.Textbox(label="Asunto")
281
- mb = gr.Button("Modificar Metadatos")
282
  mo = gr.File()
283
  mb.click(process_meta, [tf, mt, ma, ms], mo)
284
 
285
  if __name__ == "__main__":
286
- demo.launch()
 
 
 
 
 
1
+ # Versión 3.1: App Pública con Logs de Seguridad en Consola
2
  import gradio as gr
3
  import pandas as pd
4
  import config
 
9
 
10
  engine = PDFEngine()
11
 
12
+ # --- SEGURIDAD: GARBAGE COLLECTOR CON LOGS (VERBOSE) ---
13
  def cleanup_cron():
14
  """
15
+ Revisa cada minuto y borra archivos mayores a 5 minutos.
16
+ Muestra el estado en la consola de Hugging Face.
17
  """
18
  while True:
19
  try:
20
+ # 1. Esperar 1 minuto entre revisiones
21
  time.sleep(60)
22
+
23
+ # 2. Configurar umbral de 5 minutos (300 segundos)
24
+ LIMIT_MINUTES = 5
25
+ limit_seconds = LIMIT_MINUTES * 60
26
+
27
  now = time.time()
28
+ cutoff = now - limit_seconds
29
+
30
+ print(f"\n--- [SEGURIDAD] Ronda de limpieza: {time.strftime('%H:%M:%S')} ---")
31
 
32
  if os.path.exists(config.TEMP_DIR):
33
+ files = os.listdir(config.TEMP_DIR)
34
+ if not files:
35
+ print("[ESTADO] Carpeta temporal vacía (0 archivos).")
36
+
37
+ for filename in files:
38
  filepath = os.path.join(config.TEMP_DIR, filename)
39
+
40
  if os.path.isfile(filepath):
41
+ # Calcular edad del archivo
42
+ creation_time = os.path.getmtime(filepath)
43
+ age_seconds = now - creation_time
44
+ age_minutes = int(age_seconds // 60)
45
+ age_secs_remainder = int(age_seconds % 60)
46
+
47
+ file_age_str = f"{age_minutes}m {age_secs_remainder}s"
48
+
49
+ # Decidir si borrar o mantener
50
+ if creation_time < cutoff:
51
  try:
52
  os.remove(filepath)
53
+ print(f"[BORRADO] {filename} | Edad: {file_age_str} (> {LIMIT_MINUTES}m)")
54
  except Exception as e:
55
+ print(f"⚠️ [ERROR] Fallo al borrar {filename}: {e}")
56
+ else:
57
+ print(f"✅ [VIGENTE] {filename} | Edad: {file_age_str}")
58
+ else:
59
+ print("[INFO] La carpeta temporal aún no existe.")
60
+
61
  except Exception as e:
62
+ print(f"[CRITICAL] El hilo de limpieza ha fallado: {e}")
63
 
64
+ # Iniciar el hilo "chivato"
65
  threading.Thread(target=cleanup_cron, daemon=True).start()
66
 
67
+ # --- WRAPPERS (Lógica de enlace UI -> Core) ---
68
+ # (Idénticos a versiones anteriores)
69
  def update_file_list(files):
70
  if not files: return pd.DataFrame(), ""
71
  data = [[i, f.split("/")[-1]] for i, f in enumerate(files)]
 
99
  try: return engine.reorder_pages(f, o)
100
  except Exception as e: raise gr.Error(str(e))
101
 
 
102
  def process_compare(fa, fb):
103
  if not fa or not fb: return None
104
  try: return engine.compare_pdfs_text(fa, fb)
 
166
  except Exception as e: raise gr.Error(str(e))
167
 
168
 
169
+ # --- UI LAYOUT ---
170
  with gr.Blocks(title=config.APP_TITLE, theme=gr.themes.Soft()) as demo:
171
+
172
  gr.Markdown(f"# {config.APP_TITLE}")
173
+ gr.Markdown("""
174
+ ### 🛡️ Suite PDF: Libre, Gratuita y Privada
175
+ Los archivos se procesan en memoria y se **autodestruyen tras 5 minutos**.
176
+ """)
177
+
178
+ gr.HTML("""
179
+ <div style="display: flex; gap: 10px; margin-bottom: 20px;">
180
+ <a href="https://huggingface.co/spaces/TU_USUARIO/TU_SPACE?duplicate=true">
181
+ <img src="https://huggingface.co/datasets/huggingface/badges/raw/main/duplicate-this-space-sm.svg" alt="Duplicate Space">
182
+ </a>
183
+ <span>⚡ ¿Va lento? Duplica este espacio para tener tu propia instancia privada y rápida.</span>
184
+ </div>
185
+ """)
186
 
187
  with gr.Tabs():
188
 
 
193
  m_files = gr.File(file_count="multiple", label="Archivos", file_types=[".pdf"])
194
  with gr.Column(scale=2):
195
  m_tbl = gr.Dataframe(headers=["ID", "Archivo"], interactive=False)
196
+ m_ord = gr.Textbox(label="Orden", placeholder="Ej: 0, 2, 1")
197
  m_btn = gr.Button("Unir", variant="primary")
198
  m_out = gr.File(label="Resultado")
199
  m_files.change(update_file_list, m_files, [m_tbl, m_ord])
200
  m_btn.click(process_merge, [m_files, m_ord], m_out)
201
 
202
+ # 2. DIVIDIR / REORDENAR
203
  with gr.TabItem("Dividir / Reordenar"):
204
+ dr_f = gr.File(label="PDF Origen", file_types=[".pdf"])
205
+ dr_inf = gr.Markdown("")
206
+ dr_pg = gr.State(0)
207
+ with gr.Tabs():
208
+ with gr.Tab("Extraer"):
209
+ gr.Markdown("Separa páginas en un ZIP.")
210
+ with gr.Row():
211
+ with gr.Column():
212
+ s_rng = gr.Textbox(label="Rango", placeholder="Ej: 1-3, 5")
213
+ with gr.Row():
214
+ s_prv = gr.Button("Preview")
215
+ s_btn = gr.Button("Dividir (ZIP)", variant="primary")
216
+ with gr.Column():
217
+ s_gal = gr.Gallery(height=160, columns=4, object_fit="contain", label="Vista Previa")
218
+ s_out = gr.File(label="ZIP")
219
+ s_prv.click(update_split_preview, [dr_f, s_rng, dr_pg], s_gal)
220
+ s_btn.click(process_split, [dr_f, s_rng], s_out)
221
+ with gr.Tab("Reordenar"):
222
+ gr.Markdown("Crea un PDF con nuevo orden.")
223
+ with gr.Row():
224
+ with gr.Column():
225
+ r_ord = gr.Textbox(label="Nuevo Orden", placeholder="Ej: 3, 1, 2, 4-10")
226
+ r_btn = gr.Button("Reordenar", variant="primary")
227
+ with gr.Column():
228
+ r_out = gr.File(label="PDF Reordenado")
229
+ r_btn.click(process_reorder, [dr_f, r_ord], r_out)
230
  dr_f.change(load_info, dr_f, [dr_inf, dr_pg, s_out])
231
 
232
  # 3. COMPRIMIR
 
234
  with gr.Row():
235
  with gr.Column():
236
  c_f = gr.File(label="PDF Original", file_types=[".pdf"])
237
+ c_l = gr.Radio(["Baja (Máxima calidad)", "Media (Recomendado - eBook)", "Alta (Pantalla - 72dpi)"], label="Nivel", value="Media (Recomendado - eBook)")
238
  c_b = gr.Button("Comprimir", variant="primary")
239
  with gr.Column():
240
+ c_out = gr.File(label="PDF Comprimido")
241
  c_b.click(process_compress, [c_f, c_l], c_out)
242
 
243
  # 4. CONVERTIR
 
248
  gr.Markdown("### A Word")
249
  w_f = gr.File(label="PDF")
250
  w_b = gr.Button("Convertir")
251
+ w_o = gr.File(label="DOCX")
252
  w_b.click(process_word, w_f, w_o)
253
  with gr.Column():
254
  gr.Markdown("### A Excel")
255
  x_f = gr.File(label="PDF")
256
  x_b = gr.Button("Convertir")
257
+ x_o = gr.File(label="XLSX")
258
  x_b.click(process_excel, x_f, x_o)
259
  with gr.Column():
260
  gr.Markdown("### A PowerPoint")
261
  p_f = gr.File(label="PDF")
262
  p_b = gr.Button("Convertir")
263
+ p_o = gr.File(label="PPTX")
264
  p_b.click(process_pptx, p_f, p_o)
265
  with gr.Tab("A Imágenes"):
266
  with gr.Row():
267
  with gr.Column():
268
  p2i_f = gr.File(label="PDF")
269
  p2i_b = gr.Button("Extraer ZIP")
270
+ p2i_o = gr.File(label="ZIP")
271
  p2i_b.click(process_p2i, p2i_f, p2i_o)
272
  with gr.Column():
273
  i2p_f = gr.File(label="Imágenes", file_count="multiple")
274
  i2p_b = gr.Button("Crear PDF")
275
+ i2p_o = gr.File(label="PDF")
276
  i2p_b.click(process_i2p, i2p_f, i2p_o)
277
 
278
+ # 5. COMPARAR
279
  with gr.TabItem("Comparar"):
280
+ gr.Markdown("Compara el **texto** de dos versiones. Descarga un informe con cambios.")
281
  with gr.Row():
282
  with gr.Column():
283
  ca = gr.File(label="Versión A (Original)", file_types=[".pdf"])
284
  with gr.Column():
285
  cb = gr.File(label="Versión B (Modificada)", file_types=[".pdf"])
286
+ cb_btn = gr.Button("Generar Informe", variant="primary")
287
  co = gr.File(label="Informe PDF")
288
  cb_btn.click(process_compare, [ca, cb], co)
289
 
290
  # 6. EXTRAS
291
+ with gr.TabItem("Extras"):
292
+ with gr.Tab("Rotar"):
293
  with gr.Row():
294
  with gr.Column():
295
  rf = gr.File(label="PDF")
 
297
  rb = gr.Button("Rotar", variant="primary")
298
  with gr.Column():
299
  rp = gr.Image(label="Preview")
300
+ ro = gr.File(label="PDF Rotado")
301
  rf.change(update_rot_preview, [rf, ra], rp)
302
  ra.change(update_rot_preview, [rf, ra], rp)
303
  rb.click(process_rotate, [rf, ra], ro)
304
 
305
+ with gr.Tab("Proteger"):
306
  with gr.Row():
307
  with gr.Column():
308
  pf = gr.File(label="PDF")
309
+ pp = gr.Textbox(type="password", label="Pass")
310
  pb = gr.Button("Encriptar", variant="primary")
311
  with gr.Column():
312
+ po = gr.File(label="Protegido")
313
  pb.click(process_protect, [pf, pp], po)
314
 
315
+ with gr.Tab("Info/Texto"):
316
  with gr.Row():
317
  with gr.Column():
318
  tf = gr.File(label="PDF")
319
+ tb = gr.Button("Extraer Texto")
320
  to = gr.File()
321
  tb.click(process_text, tf, to)
322
  with gr.Column():
323
  mt = gr.Textbox(label="Título")
324
  ma = gr.Textbox(label="Autor")
325
  ms = gr.Textbox(label="Asunto")
326
+ mb = gr.Button("Actualizar Meta")
327
  mo = gr.File()
328
  mb.click(process_meta, [tf, mt, ma, ms], mo)
329
 
330
  if __name__ == "__main__":
331
+ # CONFIGURACIÓN PÚBLICA
332
+ demo.queue(default_concurrency_limit=2).launch(
333
+ server_name="0.0.0.0",
334
+ server_port=7860
335
+ )