File size: 3,124 Bytes
1b10823
30cca7c
 
1b10823
30cca7c
 
d473fc1
1b10823
d473fc1
30cca7c
d473fc1
30cca7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d473fc1
 
 
 
30cca7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7666f21
 
 
30cca7c
271e5ba
 
 
30cca7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7666f21
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
import gradio as gr
import subprocess
import logging
from PyPDF2 import PdfReader
import tempfile
import os
import shlex  # Importa para manejar nombres de archivo con espacios

# 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 crear_pdf_con_texto_incrustado(pdf_original, archivo_salida, idioma="spa"):
    """Procesa un PDF con OCR usando OCRmyPDF."""
    try:
        # Usa shlex.quote para manejar espacios en los nombres de archivo
        comando = f"ocrmypdf -l {idioma} --force-ocr --deskew --clean --output-type pdf {shlex.quote(pdf_original)} {shlex.quote(archivo_salida)}"
        ejecutar_comando(comando)
    except RuntimeError as e:
        raise gr.Error(str(e))  # Mostrar el error en la interfaz de Gradio

def leer_pdf(pdf_path):
    """Extrae texto de un archivo PDF."""
    try:
        reader = PdfReader(pdf_path)
        texto = ""
        for pagina in reader.pages:
            texto += pagina.extract_text() + "\n"
        return texto.strip() or "No se pudo extraer texto del PDF."
    except Exception as e:
        return f"Error al leer el PDF: {e}"

def flujo_principal(pdf_file, idioma="spa"):
    """Procesa un PDF subido, realiza OCR y extrae texto."""
    if not pdf_file:
        raise gr.Error("No se subió ningún archivo.")

    # Guardar el archivo subido en el directorio /tmp
    temp_dir = tempfile.mkdtemp()
    input_pdf_path = os.path.join(temp_dir, pdf_file.name)

    # Usar pdf_file.name para acceder al contenido del archivo
    with open(input_pdf_path, "wb") as f:
        f.write(open(pdf_file.name, "rb").read()) 

# Interfaz Gradio
with gr.Blocks() as interfaz:
    gr.Markdown("## Procesador OCR para PDFs")
    with gr.Row():
        archivo_pdf = gr.File(label="Sube tu archivo PDF")
        idioma_ocr = gr.Dropdown(["spa", "eng", "fra", "deu"], label="Idioma OCR", value="spa")
        boton_procesar = gr.Button("Procesar OCR")
    with gr.Row():
        texto_original = gr.Textbox(label="Texto Original", lines=10, interactive=False)
        texto_ocr = gr.Textbox(label="Texto con OCR", lines=10, interactive=False)
    with gr.Row():
        pdf_original_vista = gr.File(label="Descargar PDF Original", interactive=False)
        pdf_ocr_vista = gr.File(label="Descargar PDF con OCR", interactive=False)
    boton_procesar.click(
        fn=flujo_principal,
        inputs=[archivo_pdf, idioma_ocr],
        outputs=[pdf_original_vista, texto_original, pdf_ocr_vista, texto_ocr]
    )

interfaz.launch()