Como Converter Imagem em Texto e Realizar OCR no AWS Lambda
Este artigo de instruções fornece um guia passo a passo para configurar uma função AWS Lambda usando o IronOCR. Seguindo este guia, você aprenderá como configurar o IronOCR para converter imagem em texto e ler documentos armazenados em um bucket S3 de forma eficiente.
Como realizar OCR em documentos no AWS Lambda
- Baixar uma biblioteca C# para realizar OCR em documentos
- Crie e escolha o modelo de projeto
- Modifique o código do FunctionHandler.
- Configure e implemente o projeto
- Invoque a função e verifique os resultados no S3.
Instalação
Este artigo utilizará um bucket S3, portanto, o pacote AWSSDK.S3 é necessário.
Se você estiver usando o IronOCR ZIP, é essencial definir a pasta temporária.
// Set temporary folder path and log file path for IronOCR.
var awsTmpPath = @"/tmp/";
IronOcr.Installation.InstallationPath = awsTmpPath;
IronOcr.Installation.LogFilePath = awsTmpPath;
// Set temporary folder path and log file path for IronOCR.
var awsTmpPath = @"/tmp/";
IronOcr.Installation.InstallationPath = awsTmpPath;
IronOcr.Installation.LogFilePath = awsTmpPath;
' Set temporary folder path and log file path for IronOCR.
Dim awsTmpPath = "/tmp/"
IronOcr.Installation.InstallationPath = awsTmpPath
IronOcr.Installation.LogFilePath = awsTmpPath
!{--010011000100100101000010010100100100000101010010010110010101111101010011010101000100000101010010010101000101111101010001010010010010010010100000101001100010111110100001001001100010011110100001101001011--}
Criar um projeto AWS Lambda
Com o Visual Studio, criar uma instância AWS Lambda em contêiner é um processo fácil:
- Instale o AWS Toolkit para Visual Studio.
- Selecione um 'Projeto AWS Lambda (.NET Core - C#)'.
- Selecione um modelo ' .NET 8 (Imagem de Contêiner)' e, em seguida, selecione 'Concluir'.

Adicionar dependências de pacotes
Usar a biblioteca IronOCR no .NET 8 não requer dependências adicionais para ser usada no AWS Lambda. Modifique o Dockerfile do projeto com o seguinte:
FROM public.ecr.aws/lambda/dotnet:8
# Update all installed packages
RUN dnf update -y
WORKDIR /var/task
# Copy build artifacts from the host machine into the Docker image
COPY "bin/Release/lambda-publish" .
Modifique o código do manipulador de funções.
Este exemplo recupera uma imagem de um bucket S3, processa e salva um PDF pesquisável de volta no mesmo bucket. Definir a pasta temporária é essencial ao usar o IronOCR ZIP, pois a biblioteca exige permissões de gravação para copiar a pasta de runtime dos DLLs.
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronOcr;
using System;
using System.IO;
using System.Threading.Tasks;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace IronOcrZipAwsLambda
{
public class Function
{
// Initialize the S3 client with a specific region endpoint
private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);
/// <summary>
/// Function handler to process OCR on the PDF stored in S3.
/// </summary>
/// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
public async Task FunctionHandler(ILambdaContext context)
{
// Set up necessary paths for IronOCR
var awsTmpPath = @"/tmp/";
IronOcr.Installation.InstallationPath = awsTmpPath;
IronOcr.Installation.LogFilePath = awsTmpPath;
// Set license key for IronOCR
IronOcr.License.LicenseKey = "IRONOCR-MYLICENSE-KEY-1EF01";
string bucketName = "deploymenttestbucket"; // Your bucket name
string pdfName = "sample";
string objectKey = $"IronPdfZip/{pdfName}.pdf";
string objectKeyForSearchablePdf = $"IronPdfZip/{pdfName}-SearchablePdf.pdf";
try
{
// Retrieve the PDF file from S3
var pdfData = await GetPdfFromS3Async(bucketName, objectKey);
// Initialize IronTesseract for OCR processing
IronTesseract ironTesseract = new IronTesseract();
OcrInput ocrInput = new OcrInput();
ocrInput.LoadPdf(pdfData);
OcrResult result = ironTesseract.Read(ocrInput);
// Log the OCR result
context.Logger.LogLine($"OCR result: {result.Text}");
// Upload the searchable PDF to S3
await UploadPdfToS3Async(bucketName, objectKeyForSearchablePdf, result.SaveAsSearchablePdfBytes());
context.Logger.LogLine($"PDF uploaded successfully to {bucketName}/{objectKeyForSearchablePdf}");
}
catch (Exception e)
{
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
}
}
/// <summary>
/// Retrieves a PDF from S3 and returns it as a byte array.
/// </summary>
private async Task<byte[]> GetPdfFromS3Async(string bucketName, string objectKey)
{
var request = new GetObjectRequest
{
BucketName = bucketName,
Key = objectKey
};
using (var response = await _s3Client.GetObjectAsync(request))
using (var memoryStream = new MemoryStream())
{
await response.ResponseStream.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
}
/// <summary>
/// Uploads the generated searchable PDF back to S3.
/// </summary>
private async Task UploadPdfToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
{
using (var memoryStream = new MemoryStream(pdfBytes))
{
var request = new PutObjectRequest
{
BucketName = bucketName,
Key = objectKey,
InputStream = memoryStream,
ContentType = "application/pdf"
};
await _s3Client.PutObjectAsync(request);
}
}
}
}
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronOcr;
using System;
using System.IO;
using System.Threading.Tasks;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace IronOcrZipAwsLambda
{
public class Function
{
// Initialize the S3 client with a specific region endpoint
private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);
/// <summary>
/// Function handler to process OCR on the PDF stored in S3.
/// </summary>
/// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
public async Task FunctionHandler(ILambdaContext context)
{
// Set up necessary paths for IronOCR
var awsTmpPath = @"/tmp/";
IronOcr.Installation.InstallationPath = awsTmpPath;
IronOcr.Installation.LogFilePath = awsTmpPath;
// Set license key for IronOCR
IronOcr.License.LicenseKey = "IRONOCR-MYLICENSE-KEY-1EF01";
string bucketName = "deploymenttestbucket"; // Your bucket name
string pdfName = "sample";
string objectKey = $"IronPdfZip/{pdfName}.pdf";
string objectKeyForSearchablePdf = $"IronPdfZip/{pdfName}-SearchablePdf.pdf";
try
{
// Retrieve the PDF file from S3
var pdfData = await GetPdfFromS3Async(bucketName, objectKey);
// Initialize IronTesseract for OCR processing
IronTesseract ironTesseract = new IronTesseract();
OcrInput ocrInput = new OcrInput();
ocrInput.LoadPdf(pdfData);
OcrResult result = ironTesseract.Read(ocrInput);
// Log the OCR result
context.Logger.LogLine($"OCR result: {result.Text}");
// Upload the searchable PDF to S3
await UploadPdfToS3Async(bucketName, objectKeyForSearchablePdf, result.SaveAsSearchablePdfBytes());
context.Logger.LogLine($"PDF uploaded successfully to {bucketName}/{objectKeyForSearchablePdf}");
}
catch (Exception e)
{
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
}
}
/// <summary>
/// Retrieves a PDF from S3 and returns it as a byte array.
/// </summary>
private async Task<byte[]> GetPdfFromS3Async(string bucketName, string objectKey)
{
var request = new GetObjectRequest
{
BucketName = bucketName,
Key = objectKey
};
using (var response = await _s3Client.GetObjectAsync(request))
using (var memoryStream = new MemoryStream())
{
await response.ResponseStream.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
}
/// <summary>
/// Uploads the generated searchable PDF back to S3.
/// </summary>
private async Task UploadPdfToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
{
using (var memoryStream = new MemoryStream(pdfBytes))
{
var request = new PutObjectRequest
{
BucketName = bucketName,
Key = objectKey,
InputStream = memoryStream,
ContentType = "application/pdf"
};
await _s3Client.PutObjectAsync(request);
}
}
}
}
Imports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronOcr
Imports System
Imports System.IO
Imports System.Threading.Tasks
' Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
<Assembly: LambdaSerializer(GetType(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))>
Namespace IronOcrZipAwsLambda
Public Class [Function]
' Initialize the S3 client with a specific region endpoint
Private Shared ReadOnly _s3Client As IAmazonS3 = New AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1)
''' <summary>
''' Function handler to process OCR on the PDF stored in S3.
''' </summary>
''' <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
Public Async Function FunctionHandler(ByVal context As ILambdaContext) As Task
' Set up necessary paths for IronOCR
Dim awsTmpPath = "/tmp/"
IronOcr.Installation.InstallationPath = awsTmpPath
IronOcr.Installation.LogFilePath = awsTmpPath
' Set license key for IronOCR
IronOcr.License.LicenseKey = "IRONOCR-MYLICENSE-KEY-1EF01"
Dim bucketName As String = "deploymenttestbucket" ' Your bucket name
Dim pdfName As String = "sample"
Dim objectKey As String = $"IronPdfZip/{pdfName}.pdf"
Dim objectKeyForSearchablePdf As String = $"IronPdfZip/{pdfName}-SearchablePdf.pdf"
Try
' Retrieve the PDF file from S3
Dim pdfData = Await GetPdfFromS3Async(bucketName, objectKey)
' Initialize IronTesseract for OCR processing
Dim ironTesseract As New IronTesseract()
Dim ocrInput As New OcrInput()
ocrInput.LoadPdf(pdfData)
Dim result As OcrResult = ironTesseract.Read(ocrInput)
' Log the OCR result
context.Logger.LogLine($"OCR result: {result.Text}")
' Upload the searchable PDF to S3
Await UploadPdfToS3Async(bucketName, objectKeyForSearchablePdf, result.SaveAsSearchablePdfBytes())
context.Logger.LogLine($"PDF uploaded successfully to {bucketName}/{objectKeyForSearchablePdf}")
Catch e As Exception
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}")
End Try
End Function
''' <summary>
''' Retrieves a PDF from S3 and returns it as a byte array.
''' </summary>
Private Async Function GetPdfFromS3Async(ByVal bucketName As String, ByVal objectKey As String) As Task(Of Byte())
Dim request = New GetObjectRequest With {
.BucketName = bucketName,
.Key = objectKey
}
Using response = Await _s3Client.GetObjectAsync(request)
Using memoryStream As New MemoryStream()
Await response.ResponseStream.CopyToAsync(memoryStream)
Return memoryStream.ToArray()
End Using
End Using
End Function
''' <summary>
''' Uploads the generated searchable PDF back to S3.
''' </summary>
Private Async Function UploadPdfToS3Async(ByVal bucketName As String, ByVal objectKey As String, ByVal pdfBytes() As Byte) As Task
Using memoryStream As New MemoryStream(pdfBytes)
Dim request = New PutObjectRequest With {
.BucketName = bucketName,
.Key = objectKey,
.InputStream = memoryStream,
.ContentType = "application/pdf"
}
Await _s3Client.PutObjectAsync(request)
End Using
End Function
End Class
End Namespace
Antes do bloco try, o arquivo 'sample.pdf' é especificado para leitura no diretório IronPdfZip. O método GetPdfFromS3Async é então usado para recuperar o byte do PDF, que é passado para o método LoadPdf.
Aumentar a memória e o tempo limite
A quantidade de memória alocada na função Lambda irá variar com base no tamanho dos documentos sendo processados e o número de documentos processados simultaneamente. Como linha de base, defina a memória para 512 MB e o tempo limite para 300 segundos em aws-lambda-tools-defaults.json.
{
"function-memory-size": 512,
"function-timeout": 300
}
Quando a memória é insuficiente, o programa lançará o erro: 'Runtime exited with error: signal: killed.' Aumentar o tamanho da memória pode resolver esse problema. Para mais detalhes, consulte o artigo de resolução de problemas: AWS Lambda - Runtime Exited Signal: Killed.
Publicar
Para publicar no Visual Studio, clique com o botão direito no projeto e selecione 'Publish to AWS Lambda...', então configure as configurações necessárias. Você pode ler mais sobre a publicação de um Lambda no site da AWS.
Experimente!
Você pode ativar a função Lambda através do console do Lambda ou através do Visual Studio.
Perguntas frequentes
Como posso realizar OCR em documentos na AWS usando C#?
Você pode usar o IronOCR para realizar OCR em documentos armazenados em buckets do Amazon S3, integrando-o ao AWS Lambda. Isso envolve a criação de uma função Lambda em C# que recupera os documentos do S3, os processa com o IronOCR e, em seguida, envia os resultados de volta para o S3.
Quais são os passos envolvidos na configuração de OCR no AWS Lambda com C#?
Para configurar o OCR no AWS Lambda usando C#, você precisa baixar a biblioteca IronOCR, criar um projeto AWS Lambda no Visual Studio, configurar o manipulador da sua função para usar o IronOCR no processamento e implantar a função. Essa configuração permite converter imagens em PDFs pesquisáveis.
Qual é a configuração recomendada para executar OCR no AWS Lambda?
Para obter o melhor desempenho ao executar OCR com o IronOCR no AWS Lambda, recomenda-se alocar pelo menos 512 MB de memória e definir um tempo limite de 300 segundos. Essas configurações ajudam a gerenciar o processamento de documentos grandes ou múltiplos.
Como lidar com o erro 'Runtime exited with error: signal: killed' no AWS Lambda?
Esse erro geralmente indica que sua função Lambda esgotou a memória alocada. Aumentar a alocação de memória na configuração da função Lambda pode resolver esse problema, especialmente ao processar documentos grandes com o IronOCR.
Posso testar minha função OCR do AWS Lambda localmente antes da implantação?
Sim, você pode testar sua função OCR do AWS Lambda localmente usando o AWS Toolkit para Visual Studio. Esse conjunto de ferramentas fornece um ambiente local para simular execuções do Lambda, permitindo depurar e aprimorar sua função antes da implantação.
Qual é a finalidade de um Dockerfile em um projeto AWS Lambda?
Um Dockerfile em um projeto AWS Lambda é usado para criar uma imagem de contêiner que define o ambiente de execução e as dependências da sua função Lambda. Isso garante que sua função tenha todos os componentes necessários para ser executada corretamente na AWS.
Preciso de alguma dependência adicional para usar o IronOCR no .NET 8 no AWS Lambda?
Ao usar o .NET 8 no AWS Lambda, não são necessárias dependências adicionais além da biblioteca IronOCR e dos pacotes do SDK da AWS necessários. Isso simplifica o processo de integração para a execução de tarefas de OCR.
Quais são os pré-requisitos para integrar o OCR em C# com o AWS Lambda?
Antes de integrar o OCR em C# com o AWS Lambda, você precisa instalar o AWS SDK para S3, a biblioteca IronOCR e o AWS Toolkit para Visual Studio. Você também precisará de um bucket S3 configurado para armazenar e recuperar documentos.

