haryde commited on
Commit
32b0a3f
·
verified ·
1 Parent(s): ddb1cd6

Update app.py

Browse files

fixed open md error

Files changed (1) hide show
  1. app.py +39 -36
app.py CHANGED
@@ -25,26 +25,26 @@ def procesar_pdf(pdf_file=None, url_pdf=None, formatos=[], verbose="auto"):
25
  os.makedirs(output_base, exist_ok=True)
26
  start_time = time.time()
27
 
28
- # Verificar marker_single
 
29
  try:
30
  subprocess.run(["marker_single", "--help"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
31
  except FileNotFoundError:
32
- yield "Error: el comando 'marker_single' no está disponible.", None, None, None
33
  return
34
 
35
  if not formatos:
36
- yield "⚠️ Selecciona al menos un formato de salida.", None, None, None
37
  return
38
 
39
  try:
40
- # Obtener el archivo
41
  if url_pdf:
42
  parsed = urlparse(url_pdf)
43
  nombre_pdf = parsed.path.split("/")[-1] or "documento"
44
  ruta_pdf = obtener_ruta_segura(output_base, nombre_pdf)
45
  response = requests.get(url_pdf)
46
  if response.status_code != 200:
47
- yield "No se pudo descargar correctamente el PDF desde la URL.", None, None, None
48
  return
49
  with open(ruta_pdf, "wb") as f:
50
  f.write(response.content)
@@ -53,17 +53,16 @@ def procesar_pdf(pdf_file=None, url_pdf=None, formatos=[], verbose="auto"):
53
  ruta_pdf = obtener_ruta_segura(output_base, nombre_pdf)
54
  shutil.copyfile(pdf_file.name, ruta_pdf)
55
  else:
56
- yield "⚠️ No se proporcionó archivo ni URL.", None, None, None
57
  return
58
 
59
- # Verificar cabecera PDF
60
  with open(ruta_pdf, "rb") as f:
61
  if f.read(4) != b"%PDF":
62
- yield "El archivo no es un PDF válido (no comienza por %PDF).", None, None, None
63
  return
64
 
65
  if os.path.getsize(ruta_pdf) > 3 * 1024 * 1024:
66
- yield "⚠️ Aviso: el PDF es grande y puede tardar más de lo normal.", None, None, None
67
 
68
  nombre_sin_ext = os.path.splitext(os.path.basename(ruta_pdf))[0]
69
  carpeta_salida = os.path.join(output_base, nombre_sin_ext)
@@ -71,9 +70,11 @@ def procesar_pdf(pdf_file=None, url_pdf=None, formatos=[], verbose="auto"):
71
  shutil.rmtree(carpeta_salida)
72
  os.makedirs(carpeta_salida, exist_ok=True)
73
 
74
- # Procesar cada formato
75
  for fmt in formatos:
76
- tiempo_parcial = round(time.time() - start_time, 1)
 
 
 
77
  if fmt == "md":
78
  cmd = ["marker_single", ruta_pdf, "--output_format", "markdown", "--disable_ocr", "--output_dir", carpeta_salida]
79
  elif fmt == "md + ocr":
@@ -81,54 +82,56 @@ def procesar_pdf(pdf_file=None, url_pdf=None, formatos=[], verbose="auto"):
81
  else:
82
  cmd = ["marker_single", ruta_pdf, "--output_format", fmt, "--output_dir", carpeta_salida]
83
 
84
- yield f"⏳ Procesando formato '{fmt}'... (tiempo: {tiempo_parcial} s)", None, None, None
85
-
86
  for intento in range(1, 4):
87
  try:
88
  result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=900)
89
  if result.returncode == 0:
90
  break
91
  elif intento == 3:
92
- yield f"Error en marker_single:\n{result.stderr}", None, None, None
 
93
  return
94
  time.sleep(2)
95
  except Exception as e:
96
- yield f"Error inesperado:\n{str(e)}", None, None, None
 
97
  return
98
 
99
- # Leer contenido Markdown
100
  md_path = os.path.join(carpeta_salida, f"{nombre_sin_ext}.md")
101
- md_content = ""
102
- if os.path.exists(md_path):
103
- with open(md_path, "r", encoding="utf-8") as f:
104
- md_content = f.read()
 
 
 
105
 
106
  tiempo_total = round(time.time() - start_time, 1)
107
  palabras = len(md_content.split())
108
  caracteres = len(md_content)
109
  figuras = len([f for f in os.listdir(carpeta_salida) if f.lower().endswith(".jpeg")])
110
  tablas = len(os.listdir(os.path.join(carpeta_salida, "tables"))) if os.path.exists(os.path.join(carpeta_salida, "tables")) else 0
111
- tamaño_kb = os.path.getsize(md_path) / 1024 if os.path.exists(md_path) else 0
112
 
113
- resumen = "\n\n---\nResumen del procesamiento\n"
114
- resumen += f"- Palabras detectadas: {palabras}\n"
115
- resumen += f"- Caracteres totales: {caracteres}\n"
116
- resumen += f"- Tamaño del archivo Markdown: {tamaño_kb:.2f} KB\n"
117
  resumen += f"- Imágenes extraídas: {figuras}\n"
118
  resumen += f"- Tablas detectadas: {tablas}\n"
119
- resumen += f"- Tiempo total: {tiempo_total} segundos"
120
 
121
  zip_path = os.path.join(output_base, f"{nombre_sin_ext}.zip")
122
  shutil.make_archive(base_name=zip_path.replace(".zip", ""), format="zip", root_dir=carpeta_salida)
123
 
124
- estado_final = f"Procesamiento completado correctamente (tiempo total: {tiempo_total} segundos)"
125
- salida_md = md_content + resumen if md_content else resumen
126
- yield estado_final, gr.update(value=md_path, visible=True), gr.update(value=zip_path, visible=True), salida_md
127
 
128
  except Exception as e:
129
- yield f"Error general inesperado: {str(e)}", None, None, None
 
130
 
131
- # Interfaz con 4 salidas
132
  demo = gr.Interface(
133
  fn=procesar_pdf,
134
  inputs=[
@@ -141,13 +144,13 @@ demo = gr.Interface(
141
  )
142
  ],
143
  outputs=[
144
- gr.Textbox(label="Estado del procesamiento", lines=5),
145
- gr.File(label="Descargar Markdown", visible=False),
146
- gr.File(label="Descargar ZIP completo", visible=False),
147
- gr.Textbox(label="Contenido extraído en Markdown", lines=25, visible=False)
148
  ],
149
  title="Marker PDF",
150
- description="Convierte PDFs científicos en Markdown, HTML o JSON. Incluye OCR opcional y resumen completo.",
151
  flagging_mode="never"
152
  )
153
 
 
25
  os.makedirs(output_base, exist_ok=True)
26
  start_time = time.time()
27
 
28
+ estado = ""
29
+
30
  try:
31
  subprocess.run(["marker_single", "--help"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
32
  except FileNotFoundError:
33
+ yield "Error: el comando 'marker_single' no está disponible.\nVerifica que marker-pdf esté en requirements.txt", "", None, None
34
  return
35
 
36
  if not formatos:
37
+ yield "Debes seleccionar al menos un formato de salida.", "", None, None
38
  return
39
 
40
  try:
 
41
  if url_pdf:
42
  parsed = urlparse(url_pdf)
43
  nombre_pdf = parsed.path.split("/")[-1] or "documento"
44
  ruta_pdf = obtener_ruta_segura(output_base, nombre_pdf)
45
  response = requests.get(url_pdf)
46
  if response.status_code != 200:
47
+ yield "No se pudo descargar el PDF desde la URL proporcionada.", "", None, None
48
  return
49
  with open(ruta_pdf, "wb") as f:
50
  f.write(response.content)
 
53
  ruta_pdf = obtener_ruta_segura(output_base, nombre_pdf)
54
  shutil.copyfile(pdf_file.name, ruta_pdf)
55
  else:
56
+ yield "No se proporcionó ni archivo ni URL.", "", None, None
57
  return
58
 
 
59
  with open(ruta_pdf, "rb") as f:
60
  if f.read(4) != b"%PDF":
61
+ yield "El archivo proporcionado no es un PDF válido.", "", None, None
62
  return
63
 
64
  if os.path.getsize(ruta_pdf) > 3 * 1024 * 1024:
65
+ estado += "Aviso: el PDF es grande y puede tardar más de lo normal.\n"
66
 
67
  nombre_sin_ext = os.path.splitext(os.path.basename(ruta_pdf))[0]
68
  carpeta_salida = os.path.join(output_base, nombre_sin_ext)
 
70
  shutil.rmtree(carpeta_salida)
71
  os.makedirs(carpeta_salida, exist_ok=True)
72
 
 
73
  for fmt in formatos:
74
+ tiempo = round(time.time() - start_time, 1)
75
+ estado += f"Procesando formato '{fmt}'... (tiempo: {tiempo} s)\n"
76
+ yield estado, f"{tiempo} s", None, None
77
+
78
  if fmt == "md":
79
  cmd = ["marker_single", ruta_pdf, "--output_format", "markdown", "--disable_ocr", "--output_dir", carpeta_salida]
80
  elif fmt == "md + ocr":
 
82
  else:
83
  cmd = ["marker_single", ruta_pdf, "--output_format", fmt, "--output_dir", carpeta_salida]
84
 
 
 
85
  for intento in range(1, 4):
86
  try:
87
  result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=900)
88
  if result.returncode == 0:
89
  break
90
  elif intento == 3:
91
+ estado += f"Error ejecutando marker_single (intento {intento}):\n{result.stderr}\n"
92
+ yield estado, "", None, None
93
  return
94
  time.sleep(2)
95
  except Exception as e:
96
+ estado += f"Error inesperado durante el intento {intento}: {str(e)}\n"
97
+ yield estado, "", None, None
98
  return
99
 
 
100
  md_path = os.path.join(carpeta_salida, f"{nombre_sin_ext}.md")
101
+ if not os.path.exists(md_path):
102
+ estado += "No se generó el archivo Markdown. Puede que el PDF no contenga texto reconocible.\n"
103
+ yield estado, "", None, None
104
+ return
105
+
106
+ with open(md_path, "r", encoding="utf-8") as f:
107
+ md_content = f.read()
108
 
109
  tiempo_total = round(time.time() - start_time, 1)
110
  palabras = len(md_content.split())
111
  caracteres = len(md_content)
112
  figuras = len([f for f in os.listdir(carpeta_salida) if f.lower().endswith(".jpeg")])
113
  tablas = len(os.listdir(os.path.join(carpeta_salida, "tables"))) if os.path.exists(os.path.join(carpeta_salida, "tables")) else 0
114
+ tamaño_kb = os.path.getsize(md_path) / 1024
115
 
116
+ resumen = f"\n---\nResumen del procesamiento:\n"
117
+ resumen += f"- Palabras: {palabras}\n"
118
+ resumen += f"- Caracteres: {caracteres}\n"
119
+ resumen += f"- Tamaño Markdown: {tamaño_kb:.2f} KB\n"
120
  resumen += f"- Imágenes extraídas: {figuras}\n"
121
  resumen += f"- Tablas detectadas: {tablas}\n"
122
+ resumen += f"- Tiempo total: {tiempo_total} s"
123
 
124
  zip_path = os.path.join(output_base, f"{nombre_sin_ext}.zip")
125
  shutil.make_archive(base_name=zip_path.replace(".zip", ""), format="zip", root_dir=carpeta_salida)
126
 
127
+ estado += f"Procesamiento finalizado correctamente. Tiempo total: {tiempo_total} s"
128
+ yield estado + resumen, f"{tiempo_total} s", gr.update(value=md_path, visible=True), gr.update(value=zip_path, visible=True)
 
129
 
130
  except Exception as e:
131
+ estado += f"Error general inesperado: {str(e)}"
132
+ yield estado, "", None, None
133
 
134
+ # Interfaz 4 salidas (estado + tiempo + 2 archivos)
135
  demo = gr.Interface(
136
  fn=procesar_pdf,
137
  inputs=[
 
144
  )
145
  ],
146
  outputs=[
147
+ gr.Textbox(label="Estado del procesamiento", lines=12),
148
+ gr.Textbox(label="Tiempo transcurrido", interactive=False),
149
+ gr.File(label="Descargar Markdown (.md)", visible=False),
150
+ gr.File(label="Descargar ZIP completo", visible=False)
151
  ],
152
  title="Marker PDF",
153
+ description="Convierte artículos científicos en Markdown, HTML o JSON. Incluye OCR opcional y resumen detallado del contenido.",
154
  flagging_mode="never"
155
  )
156