File size: 1,274 Bytes
0b83885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pytesseract
from PIL import Image
import os
from pdf2image import convert_from_bytes
import io

# Configurar Tesseract para usar el modelo entrenado en Hugging Face Spaces
tessdata_dir = "/home/user/.apt/usr/share/tesseract-ocr/4.00/tessdata"
if os.path.exists(tessdata_dir):
    pytesseract.pytesseract.tesseract_cmd = '/home/user/.apt/usr/bin/tesseract'
    os.environ["TESSDATA_PREFIX"] = tessdata_dir

def perform_ocr(file):
    if file is None:
        return "Por favor, sube un archivo."
    
    # Verificar si el archivo es un PDF
    if file.name.lower().endswith('.pdf'):
        # Convertir PDF a imágenes
        images = convert_from_bytes(file.read())
        text = ""
        for image in images:
            text += pytesseract.image_to_string(image) + "\n\n"
    else:
        # Procesar como imagen
        image = Image.open(file)
        text = pytesseract.image_to_string(image)
    
    return text

# Crear la interfaz de Gradio
iface = gr.Interface(
    fn=perform_ocr,
    inputs=gr.File(label="Sube una imagen o PDF"),
    outputs="text",
    title="Tesseract OCR para Imágenes y PDFs",
    description="Sube una imagen o un archivo PDF para extraer texto usando Tesseract OCR."
)

# Lanzar la interfaz
iface.launch()