Spaces:
Sleeping
Sleeping
app.py
CHANGED
@@ -5,7 +5,7 @@ from PyPDF2 import PdfReader
|
|
5 |
import tempfile
|
6 |
import os
|
7 |
import shlex
|
8 |
-
from
|
9 |
|
10 |
# Configuraci贸n de logs
|
11 |
logger = logging.getLogger(__name__)
|
@@ -22,78 +22,65 @@ def ejecutar_comando(comando):
|
|
22 |
logger.error(error_message)
|
23 |
raise RuntimeError(error_message)
|
24 |
|
25 |
-
def reparar_pdf(input_pdf, output_pdf):
|
26 |
-
"""Repara un PDF usando qpdf."""
|
27 |
-
comando = f"qpdf --linearize {shlex.quote(input_pdf)} {shlex.quote(output_pdf)}"
|
28 |
-
try:
|
29 |
-
ejecutar_comando(comando)
|
30 |
-
except RuntimeError as e:
|
31 |
-
raise gr.Error(f"Error al reparar el PDF: {e}")
|
32 |
-
|
33 |
-
def simplificar_pdf(input_pdf, output_pdf):
|
34 |
-
"""Simplifica un PDF usando Ghostscript."""
|
35 |
-
comando = f"gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH -sOutputFile={shlex.quote(output_pdf)} {shlex.quote(input_pdf)}"
|
36 |
-
try:
|
37 |
-
ejecutar_comando(comando)
|
38 |
-
except RuntimeError as e:
|
39 |
-
raise gr.Error(f"Error al simplificar el PDF: {e}")
|
40 |
-
|
41 |
def crear_pdf_con_texto_incrustado(pdf_original, archivo_salida, idioma="spa"):
|
42 |
"""Procesa un PDF con OCR usando OCRmyPDF."""
|
43 |
comando = f"ocrmypdf -l {idioma} --force-ocr --deskew --output-type pdf {shlex.quote(pdf_original)} {shlex.quote(archivo_salida)}"
|
44 |
-
|
45 |
-
ejecutar_comando(comando)
|
46 |
-
except RuntimeError as e:
|
47 |
-
raise gr.Error(f"Error al procesar el archivo con OCR: {e}")
|
48 |
|
49 |
def flujo_principal(pdf_file, idioma="spa"):
|
50 |
-
"""Procesa un PDF subido con
|
51 |
if not pdf_file:
|
52 |
raise gr.Error("No se subi贸 ning煤n archivo.")
|
53 |
|
54 |
input_pdf = pdf_file
|
55 |
-
reparado_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
|
56 |
-
simplificado_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
|
57 |
output_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
|
58 |
|
59 |
try:
|
60 |
-
# Reparar el PDF
|
61 |
-
reparar_pdf(input_pdf, reparado_pdf)
|
62 |
-
|
63 |
-
# Simplificar el PDF
|
64 |
-
simplificar_pdf(reparado_pdf, simplificado_pdf)
|
65 |
-
|
66 |
# Procesar con OCR
|
67 |
-
crear_pdf_con_texto_incrustado(
|
68 |
-
|
69 |
-
return input_pdf, output_pdf
|
70 |
except gr.Error as e:
|
71 |
logger.error("Error durante el procesamiento del PDF.")
|
72 |
raise e
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
# Interfaz Gradio mejorada
|
80 |
with gr.Blocks() as interfaz:
|
81 |
gr.Markdown("## Visualizador de PDFs con OCR")
|
82 |
|
83 |
with gr.Row():
|
84 |
-
archivo_pdf =
|
85 |
idioma_ocr = gr.Dropdown(["spa", "eng", "fra", "deu"], label="Idioma OCR", value="spa")
|
86 |
boton_procesar = gr.Button("Procesar OCR")
|
87 |
|
88 |
with gr.Row():
|
89 |
-
|
90 |
-
|
|
|
|
|
|
|
91 |
|
92 |
boton_procesar.click(
|
93 |
fn=flujo_principal,
|
94 |
inputs=[archivo_pdf, idioma_ocr],
|
95 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
)
|
97 |
|
98 |
if __name__ == "__main__":
|
99 |
-
interfaz.launch()
|
|
|
|
5 |
import tempfile
|
6 |
import os
|
7 |
import shlex
|
8 |
+
from pdf2image import convert_from_path
|
9 |
|
10 |
# Configuraci贸n de logs
|
11 |
logger = logging.getLogger(__name__)
|
|
|
22 |
logger.error(error_message)
|
23 |
raise RuntimeError(error_message)
|
24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
def crear_pdf_con_texto_incrustado(pdf_original, archivo_salida, idioma="spa"):
|
26 |
"""Procesa un PDF con OCR usando OCRmyPDF."""
|
27 |
comando = f"ocrmypdf -l {idioma} --force-ocr --deskew --output-type pdf {shlex.quote(pdf_original)} {shlex.quote(archivo_salida)}"
|
28 |
+
ejecutar_comando(comando)
|
|
|
|
|
|
|
29 |
|
30 |
def flujo_principal(pdf_file, idioma="spa"):
|
31 |
+
"""Procesa un PDF subido con OCR."""
|
32 |
if not pdf_file:
|
33 |
raise gr.Error("No se subi贸 ning煤n archivo.")
|
34 |
|
35 |
input_pdf = pdf_file
|
|
|
|
|
36 |
output_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
|
37 |
|
38 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
# Procesar con OCR
|
40 |
+
crear_pdf_con_texto_incrustado(input_pdf, output_pdf, idioma)
|
41 |
+
return f"/pdfs/{os.path.basename(input_pdf)}", f"/pdfs/{os.path.basename(output_pdf)}"
|
|
|
42 |
except gr.Error as e:
|
43 |
logger.error("Error durante el procesamiento del PDF.")
|
44 |
raise e
|
45 |
+
|
46 |
+
def mostrar_paginas(pdf_path):
|
47 |
+
"""Genera im谩genes por p谩gina de un PDF."""
|
48 |
+
pages = convert_from_path(pdf_path, dpi=150)
|
49 |
+
temp_images = []
|
50 |
+
for page in pages:
|
51 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
52 |
+
page.save(temp_file.name, "PNG")
|
53 |
+
temp_images.append(temp_file.name)
|
54 |
+
return temp_images
|
55 |
|
56 |
# Interfaz Gradio mejorada
|
57 |
with gr.Blocks() as interfaz:
|
58 |
gr.Markdown("## Visualizador de PDFs con OCR")
|
59 |
|
60 |
with gr.Row():
|
61 |
+
archivo_pdf = gr.File(label="Sube tu archivo PDF")
|
62 |
idioma_ocr = gr.Dropdown(["spa", "eng", "fra", "deu"], label="Idioma OCR", value="spa")
|
63 |
boton_procesar = gr.Button("Procesar OCR")
|
64 |
|
65 |
with gr.Row():
|
66 |
+
pdf_original = gr.HTML(label="Visualizaci贸n PDF Original")
|
67 |
+
pdf_procesado = gr.HTML(label="Visualizaci贸n PDF Procesado")
|
68 |
+
|
69 |
+
with gr.Row():
|
70 |
+
imagenes_pdf = gr.Gallery(label="P谩ginas del PDF")
|
71 |
|
72 |
boton_procesar.click(
|
73 |
fn=flujo_principal,
|
74 |
inputs=[archivo_pdf, idioma_ocr],
|
75 |
+
outputs=[pdf_original, pdf_procesado]
|
76 |
+
)
|
77 |
+
|
78 |
+
boton_procesar.click(
|
79 |
+
fn=mostrar_paginas,
|
80 |
+
inputs=[archivo_pdf],
|
81 |
+
outputs=[imagenes_pdf]
|
82 |
)
|
83 |
|
84 |
if __name__ == "__main__":
|
85 |
+
interfaz.launch()
|
86 |
+
|