Skip to content

Instantly share code, notes, and snippets.

@josezambrana
Last active October 9, 2023 21:52
Show Gist options
  • Save josezambrana/7451d84e9d5868c6dbffec6ed8063897 to your computer and use it in GitHub Desktop.
Save josezambrana/7451d84e9d5868c6dbffec6ed8063897 to your computer and use it in GitHub Desktop.
import pytesseract
import boto3
from PIL import Image
import os
import json
import hashlib
import datetime
os.environ.setdefault('AWS_DEFAULT_REGION', 'us-east-1')
os.environ.setdefault('AWS_ACCESS_KEY_ID', '')
os.environ.setdefault('AWS_SECRET_ACCESS_KEY', '')
def create_hash_id(filename):
# Crear el objeto hash SHA-1
sha1 = hashlib.sha1()
# Convertir el nombre del archivo a bytes y actualizar el objeto hash
sha1.update(filename.encode())
# Devolver el hash id como una cadena hexadecimal
return sha1.hexdigest()
def extract_text_from_image(image_path):
# Configura el cliente de Textract
client = boto3.client('textract')
# Lee el archivo de imagen en bytes
with open(image_path, 'rb') as image:
img_bytes = image.read()
# Llama al API de Textract para extraer el texto
response = client.detect_document_text(Document={'Bytes': img_bytes})
# Extrae el texto encontrado en la imagen
text = ""
for item in response["Blocks"]:
if item["BlockType"] == "LINE":
text += item["Text"] + "\n"
# Devuelve el texto encontrado
return text.strip()
def list_images(directory):
# Lista de extensiones de archivo de imagen
extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.gif')
# Lista de paths absolutos de las imágenes
image_paths = []
# Recorrer todos los archivos en el directorio
for root, dirs, files in os.walk(directory):
for filename in files:
# Comprobar si la extensión del archivo corresponde a una imagen
if filename.lower().endswith(extensions) and 'checkpoint' not in filename:
# Agregar el path absoluto del archivo a la lista de imágenes
image_path = os.path.join(root, filename)
image_paths.append(os.path.abspath(image_path))
return sorted(image_paths)
def crear_ruta_directorios(path):
"""
Crea todos los directorios en la ruta especificada si no existen.
"""
# Divide la ruta en una lista de nombres de directorios
directorios = path.split(os.path.sep)
# Inicializa la ruta actual como la raíz
ruta_actual = os.path.sep
# Recorre cada directorio en la ruta
for directorio in directorios:
# Concatena el directorio actual con el siguiente en la ruta
ruta_actual = os.path.join(ruta_actual, directorio)
# Comprueba si el directorio ya existe
if not os.path.exists(ruta_actual):
# Si no existe, crea el directorio
os.mkdir(ruta_actual)
def image2text(source, target):
crear_ruta_directorios(target)
images = list_images(source)
results = []
for image in images:
content = extract_text_from_image(image)
results.append(content)
output = os.path.join(target, os.path.basename(image) + '.txt')
with open(output, 'w') as f:
print("Almacenando content en %s " % output)
f.write(content)
ROOT_PATH = os.getcwd()
INPUT = os.path.join(ROOT_PATH, 'images')
OUTPUT = os.path.join(ROOT_PATH, 'text')
image2text(INPUT, OUTPUT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment