Spaces:
Build error
Build error
app.py
CHANGED
@@ -1,31 +1,97 @@
|
|
1 |
import gradio as gr
|
|
|
|
|
2 |
from PyPDF2 import PdfReader
|
|
|
|
|
3 |
|
4 |
-
#
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import subprocess
|
3 |
+
import logging
|
4 |
from PyPDF2 import PdfReader
|
5 |
+
import tempfile
|
6 |
+
import os
|
7 |
|
8 |
+
# Configuraci贸n de logs (mejor usar un logger)
|
9 |
+
logger = logging.getLogger(__name__)
|
10 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
11 |
+
|
12 |
+
def ejecutar_comando(comando):
|
13 |
+
"""Ejecuta un comando de shell y maneja errores."""
|
14 |
+
try:
|
15 |
+
resultado = subprocess.run(comando, shell=True, check=True, capture_output=True, text=True)
|
16 |
+
logger.info(f"Comando ejecutado: {comando}\nSalida:\n{resultado.stdout}")
|
17 |
+
return resultado.stdout
|
18 |
+
except subprocess.CalledProcessError as e:
|
19 |
+
error_message = f"Error al ejecutar el comando: {comando}\nError: {e}\nSalida de error:\n{e.stderr}"
|
20 |
+
logger.error(error_message)
|
21 |
+
raise RuntimeError(error_message)
|
22 |
+
|
23 |
+
def crear_pdf_con_texto_incrustado(pdf_original, archivo_salida, idioma="spa"):
|
24 |
+
"""Procesa un PDF con OCR usando OCRmyPDF."""
|
25 |
+
try:
|
26 |
+
ejecutar_comando(
|
27 |
+
f"ocrmypdf -l {idioma} --force-ocr --deskew --clean --output-type pdf {pdf_original} {archivo_salida}"
|
28 |
+
)
|
29 |
+
except RuntimeError as e: # Capturar el error espec铆fico
|
30 |
+
raise gr.Error(str(e)) # Mostrar el error en la interfaz de Gradio
|
31 |
+
|
32 |
+
|
33 |
+
def leer_pdf(pdf_path):
|
34 |
+
"""Extrae texto de un archivo PDF."""
|
35 |
+
try:
|
36 |
+
reader = PdfReader(pdf_path)
|
37 |
+
texto = ""
|
38 |
+
for pagina in reader.pages:
|
39 |
+
texto += pagina.extract_text() + "\n"
|
40 |
+
return texto.strip() or "No se pudo extraer texto del PDF."
|
41 |
+
except Exception as e:
|
42 |
+
return f"Error al leer el PDF: {e}"
|
43 |
+
|
44 |
+
def flujo_principal(pdf_file, idioma="spa"):
|
45 |
+
"""Procesa un PDF subido, realiza OCR y extrae texto."""
|
46 |
+
if not pdf_file:
|
47 |
+
raise gr.Error("No se subi贸 ning煤n archivo.")
|
48 |
+
|
49 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_input:
|
50 |
+
temp_input.write(pdf_file.read())
|
51 |
+
input_pdf = temp_input.name
|
52 |
+
|
53 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_output:
|
54 |
+
output_pdf = temp_output.name
|
55 |
+
|
56 |
+
texto_original = leer_pdf(input_pdf)
|
57 |
+
|
58 |
+
try:
|
59 |
+
crear_pdf_con_texto_incrustado(input_pdf, output_pdf, idioma)
|
60 |
+
texto_ocr = leer_pdf(output_pdf)
|
61 |
+
return gr.File(input_pdf, label="PDF Original"), texto_original, gr.File(output_pdf, label="PDF con OCR"), texto_ocr
|
62 |
+
except gr.Error as e:
|
63 |
+
# Limpieza en caso de error
|
64 |
+
os.remove(input_pdf)
|
65 |
+
if os.path.exists(output_pdf):
|
66 |
+
os.remove(output_pdf)
|
67 |
+
raise e # Re-lanzar la excepci贸n para que Gradio la maneje
|
68 |
+
finally: # Limpieza, incluso si hay excepciones
|
69 |
+
if os.path.exists(input_pdf): os.remove(input_pdf)
|
70 |
+
if os.path.exists(output_pdf): os.remove(output_pdf)
|
71 |
+
|
72 |
+
|
73 |
+
|
74 |
+
# Interfaz Gradio
|
75 |
+
with gr.Blocks() as interfaz:
|
76 |
+
gr.Markdown("## Procesador OCR para PDFs")
|
77 |
+
|
78 |
+
with gr.Row():
|
79 |
+
archivo_pdf = gr.File(label="Sube tu archivo PDF")
|
80 |
+
idioma_ocr = gr.Dropdown(["spa", "eng", "fra", "deu"], label="Idioma OCR", value="spa")
|
81 |
+
boton_procesar = gr.Button("Procesar OCR")
|
82 |
+
|
83 |
+
with gr.Row():
|
84 |
+
texto_original = gr.Textbox(label="Texto Original", lines=10, interactive=False)
|
85 |
+
texto_ocr = gr.Textbox(label="Texto con OCR", lines=10, interactive=False)
|
86 |
+
|
87 |
+
with gr.Row():
|
88 |
+
pdf_original_vista = gr.File(label="Descargar PDF Original", interactive=False)
|
89 |
+
pdf_ocr_vista = gr.File(label="Descargar PDF con OCR", interactive=False)
|
90 |
+
|
91 |
+
boton_procesar.click(
|
92 |
+
fn=flujo_principal,
|
93 |
+
inputs=[archivo_pdf, idioma_ocr],
|
94 |
+
outputs=[pdf_original_vista, texto_original, pdf_ocr_vista, texto_ocr]
|
95 |
+
)
|
96 |
+
|
97 |
+
interfaz.launch(share=True)
|