Comment effectuer une reconnaissance optique de caractères (OCR) sur AWS Lambda
Cet article pratique fournit un guide étape par étape pour configurer une fonction AWS Lambda à l'aide d'IronOCR. En suivant ce guide, vous apprendrez à configurer IronOCR et à lire efficacement les documents stockés dans un compartiment S3.
Comment effectuer une reconnaissance optique de caractères (OCR) sur AWS Lambda
- Téléchargez une bibliothèque C# pour effectuer l'OCR sur des documents
- Créer et choisir le modèle de projet
- Modifier le code du FunctionHandler
- Configurer et déployer le projet
- Invoquer la fonction et vérifier les résultats dans S3
Installation
Cet article utilisera un bucket S3, donc le package AWSSDK.S3 est requis.
Si vous utilisez IronOCR ZIP, il est essentiel de définir le dossier temporaire.
// 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 As String = "/tmp/"
IronOcr.Installation.InstallationPath = awsTmpPath
IronOcr.Installation.LogFilePath = awsTmpPath' Set temporary folder path and log file path for IronOCR.
Dim awsTmpPath As String = "/tmp/"
IronOcr.Installation.InstallationPath = awsTmpPath
IronOcr.Installation.LogFilePath = awsTmpPathCommencez à utiliser IronOCR dans votre projet dès aujourd'hui avec un essai gratuit.
Créer un projet AWS Lambda
Avec Visual Studio, créer un AWS Lambda containerisé est un processus simple :
- Installez le kit d'outils AWS pour Visual Studio.
- Sélectionnez un « Projet AWS Lambda (.NET Core - C#) ».
- Sélectionnez un modèle '.NET 8 (Image de Conteneur)', puis sélectionnez 'Terminer'.

Ajouter des dépendances de package
L'utilisation de la bibliothèque IronOCR dans .NET 8 ne nécessite pas l'installation de dépendances supplémentaires pour une utilisation sur AWS Lambda. Modifiez le fichier Dockerfile du projet comme suit :
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" .
Modifier le code de FunctionHandler
Cet exemple récupère une image depuis un compartiment S3, la traite et enregistre un PDF consultable dans le même compartiment. La configuration du dossier temporaire est essentielle lors de l'utilisation d'IronOCR ZIP, car la bibliothèque nécessite des autorisations d'écriture pour copier le dossier d'exécution à partir des DLL.
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 NamespaceImports 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 NamespaceAvant le bloc try, le fichier 'sample.pdf' est spécifié pour être lu depuis le répertoire IronPDFZip. La méthode GetPdfFromS3Async est ensuite utilisée pour récupérer l'octet du PDF, qui est passé à la méthode LoadPdf.
Augmenter la mémoire et le délai d'expiration
La quantité de mémoire allouée dans la fonction Lambda variera en fonction de la taille des documents traités et du nombre de documents traités simultanément. À titre de référence, définissez la mémoire à 512 Mo et le délai d'attente à 300 secondes dans aws-lambda-tools-defaults.json.
{
"function-memory-size": 512,
"function-timeout": 300
}
Lorsque la mémoire est insuffisante, le programme génère l'erreur : 'Runtime exited with error: signal: killed.' Augmenter la taille de la mémoire peut résoudre ce problème. Pour plus de détails, consultez l'article de dépannage : AWS Lambda - Signal sorti du runtime : Killed.
Publier
Pour publier dans Visual Studio, cliquez avec le bouton droit sur le projet et sélectionnez 'Publier sur AWS Lambda...', puis configurez les paramètres nécessaires. Vous pouvez en lire plus sur la publication d'une Lambda sur le site Web AWS.
Essayez-le!
Vous pouvez activer la fonction Lambda soit par la console Lambda soit par Visual Studio.
Questions fréquemment posées
Comment puis-je intégrer IronOCR avec AWS dans un projet C# ?
Pour intégrer IronOCR avec AWS dans un projet C#, vous devez configurer une fonction AWS Lambda. Suivez le guide pas-à-pas fourni dans le tutoriel pour configurer IronOCR et lire efficacement les documents stockés dans un bucket S3.
Quelles sont les conditions préalables pour utiliser IronOCR sur AWS Lambda ?
Avant d'utiliser IronOCR sur AWS Lambda, vous devez avoir installé AWS Toolkit for Visual Studio, configuré un projet AWS Lambda en .NET Core et le package AWSSDK.S3 pour gérer les opérations S3.
Comment gérer le traitement OCR dans une fonction Lambda utilisant IronOCR ?
Dans une fonction AWS Lambda, IronOCR peut traiter des images en les récupérant d'un bucket S3, en utilisant IronTesseract pour lire le contenu, et en enregistrant les résultats sous forme de PDF consultables dans le bucket S3.
Pourquoi est-il important de définir le dossier temporaire lors de l'utilisation de IronOCR ZIP ?
Définir le chemin du dossier temporaire est crucial lors de l'utilisation de IronOCR ZIP car cela nécessite des permissions d'écriture pour copier le dossier runtime depuis les DLLs. Cette configuration permet à IronOCR de fonctionner correctement dans l'environnement Lambda.
Que dois-je faire si je rencontre une erreur 'signal: killed' en utilisant IronOCR sur AWS Lambda ?
Si vous rencontrez une erreur 'Runtime exited with error: signal: killed', cela peut être dû à une allocation de mémoire insuffisante pour votre fonction Lambda. Augmenter la taille de la mémoire et les paramètres de délai d'expiration dans le fichier aws-lambda-tools-defaults.json peut résoudre ce problème.
Comment puis-je publier mon projet AWS Lambda en utilisant Visual Studio ?
Pour publier un projet AWS Lambda depuis Visual Studio, faites un clic droit sur votre projet, sélectionnez 'Publish to AWS Lambda...', et configurez les paramètres nécessaires en suivant la documentation AWS sur la publication des fonctions Lambda.
Quelle est la configuration recommandée de mémoire et de délai d'expiration pour traiter de grands documents avec IronOCR sur AWS Lambda ?
Pour traiter de grands documents, il est recommandé d'allouer au moins 512 Mo de mémoire et de définir un délai d'expiration de 300 secondes pour garantir que la fonction Lambda s'exécute sans erreurs.
IronOCR peut-il traiter directement les PDF dans AWS Lambda ?
Oui, IronOCR peut traiter directement les PDF dans AWS Lambda en utilisant la classe IronTesseract pour lire les PDF chargés depuis un bucket S3 et retourner des PDF consultables dans le bucket.
Comment enregistrer les résultats OCR dans une fonction AWS Lambda en utilisant IronOCR ?
Dans votre fonction AWS Lambda, utilisez la méthode Logger.LogLine du contexte Lambda pour enregistrer les résultats de l'OCR. Cela vous permet de suivre et de vérifier la sortie OCR traitée par IronOCR.
Est-il nécessaire d'installer des dépendances supplémentaires pour IronOCR dans .NET 8 lors du déploiement sur AWS Lambda ?
Aucune dépendance supplémentaire n'est requise pour utiliser la bibliothèque IronOCR dans un projet .NET 8 AWS Lambda, hormis la définition des chemins corrects et la configuration des packages nécessaires comme AWSSDK.S3 pour les opérations S3.
Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes et créer des manuels bien structurés et visuellement attrayants.