Spaces:
Sleeping
Sleeping
aap.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import subprocess
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
import tempfile
|
6 |
+
import shlex
|
7 |
+
from gradio_pdf import PDF
|
8 |
+
|
9 |
+
# Configuraci贸n de logs
|
10 |
+
logger = logging.getLogger(__name__)
|
11 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
12 |
+
|
13 |
+
def ejecutar_comando(comando):
|
14 |
+
"""Ejecuta un comando de shell y maneja errores."""
|
15 |
+
try:
|
16 |
+
resultado = subprocess.run(comando, shell=True, check=True, capture_output=True, text=True)
|
17 |
+
logger.info(f"Comando ejecutado: {comando}\nSalida:\n{resultado.stdout}")
|
18 |
+
return resultado.stdout
|
19 |
+
except subprocess.CalledProcessError as e:
|
20 |
+
error_message = f"Error al ejecutar el comando: {comando}\nError: {e}\nSalida de error:\n{e.stderr}"
|
21 |
+
logger.error(error_message)
|
22 |
+
raise RuntimeError(error_message)
|
23 |
+
|
24 |
+
def reparar_pdf(input_pdf, output_pdf):
|
25 |
+
"""Repara un PDF usando qpdf."""
|
26 |
+
comando = f"qpdf --linearize {shlex.quote(input_pdf)} {shlex.quote(output_pdf)}"
|
27 |
+
ejecutar_comando(comando)
|
28 |
+
|
29 |
+
def simplificar_pdf(input_pdf, output_pdf):
|
30 |
+
"""Simplifica un PDF usando Ghostscript."""
|
31 |
+
comando = f"gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH -sOutputFile={shlex.quote(output_pdf)} {shlex.quote(input_pdf)}"
|
32 |
+
ejecutar_comando(comando)
|
33 |
+
|
34 |
+
def crear_pdf_con_texto_incrustado(pdf_original, archivo_salida, idioma="spa"):
|
35 |
+
"""Procesa un PDF con OCR usando OCRmyPDF."""
|
36 |
+
comando = f"ocrmypdf -l {idioma} --force-ocr --deskew --output-type pdf {shlex.quote(pdf_original)} {shlex.quote(archivo_salida)}"
|
37 |
+
ejecutar_comando(comando)
|
38 |
+
|
39 |
+
def flujo_principal(pdf_file, idioma="spa"):
|
40 |
+
"""Procesa un PDF subido con reparaci贸n, simplificaci贸n y OCR."""
|
41 |
+
if not pdf_file:
|
42 |
+
raise gr.Error("No se subi贸 ning煤n archivo.")
|
43 |
+
|
44 |
+
reparado_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
|
45 |
+
simplificado_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
|
46 |
+
output_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
|
47 |
+
|
48 |
+
try:
|
49 |
+
# Reparar el PDF
|
50 |
+
reparar_pdf(pdf_file, reparado_pdf)
|
51 |
+
|
52 |
+
# Simplificar el PDF
|
53 |
+
simplificar_pdf(reparado_pdf, simplificado_pdf)
|
54 |
+
|
55 |
+
# Procesar con OCR
|
56 |
+
crear_pdf_con_texto_incrustado(simplificado_pdf, output_pdf, idioma)
|
57 |
+
|
58 |
+
return output_pdf # Devolver el PDF final con OCR
|
59 |
+
|
60 |
+
except Exception as e:
|
61 |
+
logger.error(f"Error durante el procesamiento del PDF: {str(e)}")
|
62 |
+
raise gr.Error(f"Error al procesar el PDF: {str(e)}")
|
63 |
+
|
64 |
+
# Interfaz Gradio
|
65 |
+
with gr.Blocks() as interfaz:
|
66 |
+
gr.Markdown("## Procesador de PDFs con OCR")
|
67 |
+
|
68 |
+
with gr.Row():
|
69 |
+
archivo_pdf = PDF(label="Sube tu archivo PDF") # Entrada usando PDF
|
70 |
+
idioma_ocr = gr.Dropdown(["spa", "eng", "fra", "deu"], label="Idioma OCR", value="spa")
|
71 |
+
boton_procesar = gr.Button("Procesar OCR")
|
72 |
+
|
73 |
+
with gr.Row():
|
74 |
+
pdf_vista = PDF(label="Visor PDF procesado", interactive=False) # Salida usando PDF para visualizaci贸n
|
75 |
+
boton_procesar.click(
|
76 |
+
fn=flujo_principal,
|
77 |
+
inputs=[archivo_pdf, idioma_ocr],
|
78 |
+
outputs=[pdf_vista],
|
79 |
+
)
|
80 |
+
|
81 |
+
with gr.Row():
|
82 |
+
gr.Markdown("### Descargar PDF procesado con OCR")
|
83 |
+
pdf_descarga = gr.File(label="Descargar PDF con OCR", interactive=False)
|
84 |
+
boton_procesar.click(
|
85 |
+
fn=lambda x: x,
|
86 |
+
inputs=[pdf_vista],
|
87 |
+
outputs=[pdf_descarga]
|
88 |
+
)
|
89 |
+
|
90 |
+
if __name__ == "__main__":
|
91 |
+
interfaz.launch()
|