Usando Textract para OCR localmente
Quero extrair texto de imagens usando Python. (Tessaract lib não funciona para mim porque requer instalação).
Eu encontrei boto3 lib e Textract, mas estou tendo problemas para trabalhar com eles. Eu ainda sou novo nisso. Você pode me dizer o que preciso fazer para executar meu script corretamente.
Este é o meu código:
import cv2
import boto3
import textract
#img = cv2.imread('slika2.jpg') #this is jpg file
with open('slika2.pdf', 'rb') as document:
img = bytearray(document.read())
textract = boto3.client('textract',region_name='us-west-2')
response = textract.detect_document_text(Document={'Bytes': img}). #gives me error
print(response)
Quando executo este código, obtenho:
botocore.exceptions.ClientError: An error occurred (InvalidSignatureException) when calling the DetectDocumentText operation: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Eu também tentei isso:
# Document
documentName = "slika2.jpg"
# Read document content
with open(documentName, 'rb') as document:
imageBytes = bytearray(document.read())
# Amazon Textract client
textract = boto3.client('textract',region_name='us-west-2')
# Call Amazon Textract
response = textract.detect_document_text(Document={'Bytes': imageBytes}) #ERROR
#print(response)
# Print detected text
for item in response["Blocks"]:
if item["BlockType"] == "LINE":
print ('\033[94m' + item["Text"] + '\033[0m')
Mas recebo este erro:
botocore.exceptions.ClientError: An error occurred (InvalidSignatureException) when calling the DetectDocumentText operation: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Eu sou noob nisso, então qualquer ajuda seria boa. Como posso ler o texto da minha imagem ou arquivo pdf?
Também adicionei este bloco de código, mas o erro ainda é Unable to locate credentials.
session = boto3.Session(
aws_access_key_id='xxxxxxxxxxxx',
aws_secret_access_key='yyyyyyyyyyyyyyyyyyyyy'
)
Respostas
Há um problema ao passar credenciais para boto3. Você tem que passar as credenciais ao criar o cliente boto3.
import boto3
# boto3 client
client = boto3.client(
'textract',
region_name='us-west-2',
aws_access_key_id='xxxxxxx',
aws_secret_access_key='xxxxxxx'
)
# Read image
with open('slika2.png', 'rb') as document:
img = bytearray(document.read())
# Call Amazon Textract
response = client.detect_document_text(
Document={'Bytes': img}
)
# Print detected text
for item in response["Blocks"]:
if item["BlockType"] == "LINE":
print ('\033[94m' + item["Text"] + '\033[0m')
Observe que não é recomendável codificar as chaves AWS no código. Consulte a seguir este documento
https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/configuration.html