File size: 3,504 Bytes
eec7f0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import gradio as gr
import subprocess
import logging
import os
import tempfile
import shlex
from gradio_pdf import PDF

# Configuraci贸n de logs
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

def ejecutar_comando(comando):
    """Ejecuta un comando de shell y maneja errores."""
    try:
        resultado = subprocess.run(comando, shell=True, check=True, capture_output=True, text=True)
        logger.info(f"Comando ejecutado: {comando}\nSalida:\n{resultado.stdout}")
        return resultado.stdout
    except subprocess.CalledProcessError as e:
        error_message = f"Error al ejecutar el comando: {comando}\nError: {e}\nSalida de error:\n{e.stderr}"
        logger.error(error_message)
        raise RuntimeError(error_message)

def reparar_pdf(input_pdf, output_pdf):
    """Repara un PDF usando qpdf."""
    comando = f"qpdf --linearize {shlex.quote(input_pdf)} {shlex.quote(output_pdf)}"
    ejecutar_comando(comando)

def simplificar_pdf(input_pdf, output_pdf):
    """Simplifica un PDF usando Ghostscript."""
    comando = f"gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH -sOutputFile={shlex.quote(output_pdf)} {shlex.quote(input_pdf)}"
    ejecutar_comando(comando)

def crear_pdf_con_texto_incrustado(pdf_original, archivo_salida, idioma="spa"):
    """Procesa un PDF con OCR usando OCRmyPDF."""
    comando = f"ocrmypdf -l {idioma} --force-ocr --deskew --output-type pdf {shlex.quote(pdf_original)} {shlex.quote(archivo_salida)}"
    ejecutar_comando(comando)

def flujo_principal(pdf_file, idioma="spa"):
    """Procesa un PDF subido con reparaci贸n, simplificaci贸n y OCR."""
    if not pdf_file:
        raise gr.Error("No se subi贸 ning煤n archivo.")

    reparado_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
    simplificado_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
    output_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name

    try:
        # Reparar el PDF
        reparar_pdf(pdf_file, reparado_pdf)

        # Simplificar el PDF
        simplificar_pdf(reparado_pdf, simplificado_pdf)

        # Procesar con OCR
        crear_pdf_con_texto_incrustado(simplificado_pdf, output_pdf, idioma)

        return output_pdf  # Devolver el PDF final con OCR

    except Exception as e:
        logger.error(f"Error durante el procesamiento del PDF: {str(e)}")
        raise gr.Error(f"Error al procesar el PDF: {str(e)}")

# Interfaz Gradio
with gr.Blocks() as interfaz:
    gr.Markdown("## Procesador de PDFs con OCR")

    with gr.Row():
        archivo_pdf = PDF(label="Sube tu archivo PDF")  # Entrada usando PDF
        idioma_ocr = gr.Dropdown(["spa", "eng", "fra", "deu"], label="Idioma OCR", value="spa")
        boton_procesar = gr.Button("Procesar OCR")

    with gr.Row():
        pdf_vista = PDF(label="Visor PDF procesado", interactive=False)  # Salida usando PDF para visualizaci贸n
        boton_procesar.click(
            fn=flujo_principal,
            inputs=[archivo_pdf, idioma_ocr],
            outputs=[pdf_vista],
        )

    with gr.Row():
        gr.Markdown("### Descargar PDF procesado con OCR")
        pdf_descarga = gr.File(label="Descargar PDF con OCR", interactive=False)
        boton_procesar.click(
            fn=lambda x: x,
            inputs=[pdf_vista],
            outputs=[pdf_descarga]
        )

if __name__ == "__main__":
    interfaz.launch()