Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pytesseract
|
3 |
+
from PIL import Image
|
4 |
+
import os
|
5 |
+
from pdf2image import convert_from_bytes
|
6 |
+
import io
|
7 |
+
|
8 |
+
# Configurar Tesseract para usar el modelo entrenado en Hugging Face Spaces
|
9 |
+
tessdata_dir = "/home/user/.apt/usr/share/tesseract-ocr/4.00/tessdata"
|
10 |
+
if os.path.exists(tessdata_dir):
|
11 |
+
pytesseract.pytesseract.tesseract_cmd = '/home/user/.apt/usr/bin/tesseract'
|
12 |
+
os.environ["TESSDATA_PREFIX"] = tessdata_dir
|
13 |
+
|
14 |
+
def perform_ocr(file):
|
15 |
+
if file is None:
|
16 |
+
return "Por favor, sube un archivo."
|
17 |
+
|
18 |
+
# Verificar si el archivo es un PDF
|
19 |
+
if file.name.lower().endswith('.pdf'):
|
20 |
+
# Convertir PDF a imágenes
|
21 |
+
images = convert_from_bytes(file.read())
|
22 |
+
text = ""
|
23 |
+
for image in images:
|
24 |
+
text += pytesseract.image_to_string(image) + "\n\n"
|
25 |
+
else:
|
26 |
+
# Procesar como imagen
|
27 |
+
image = Image.open(file)
|
28 |
+
text = pytesseract.image_to_string(image)
|
29 |
+
|
30 |
+
return text
|
31 |
+
|
32 |
+
# Crear la interfaz de Gradio
|
33 |
+
iface = gr.Interface(
|
34 |
+
fn=perform_ocr,
|
35 |
+
inputs=gr.File(label="Sube una imagen o PDF"),
|
36 |
+
outputs="text",
|
37 |
+
title="Tesseract OCR para Imágenes y PDFs",
|
38 |
+
description="Sube una imagen o un archivo PDF para extraer texto usando Tesseract OCR."
|
39 |
+
)
|
40 |
+
|
41 |
+
# Lanzar la interfaz
|
42 |
+
iface.launch()
|