Comment utiliser le logiciel OCR IronOCR 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 la reconnaissance optique de caractères (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 compartiment 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.
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
Commencez à utiliser IronOCR dans votre projet 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 Namespace
Avant 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 PDF, qui est transmis à 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. Comme base, 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 de sortie d'exécution : Tué .
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. Pour en savoir plus sur la publication d'une Lambda, visitez le site AWS.
Essayez-le!
Vous pouvez activer la fonction Lambda soit via la console Lambda soit via Visual Studio.
Questions Fréquemment Posées
Comment puis-je effectuer des OCR sur des documents dans AWS en utilisant C# ?
Vous pouvez utiliser IronOCR pour effectuer des OCR sur des documents stockés dans les buckets Amazon S3 en l'intégrant à AWS Lambda. Cela implique de créer une fonction Lambda en C# qui récupère des documents depuis S3, les traite avec IronOCR, puis télécharge les résultats de nouveau sur S3.
Quelles étapes sont impliquées dans la configuration de OCR sur AWS Lambda avec C# ?
Pour configurer OCR sur AWS Lambda en utilisant C#, vous devez télécharger la bibliothèque IronOCR, créer un projet AWS Lambda dans Visual Studio, configurer votre gestionnaire de fonction pour utiliser IronOCR pour le traitement et déployer votre fonction. Cette configuration vous permet de convertir des images en PDF consultables.
Quelle est la configuration recommandée pour exécuter OCR dans AWS Lambda ?
Pour une performance optimale lors de l'exécution d'OCR avec IronOCR dans AWS Lambda, il est recommandé de définir une allocation mémoire d'au moins 512 Mo et une période de timeout de 300 secondes. Ces paramètres aident à gérer le traitement de documents volumineux ou multiples.
Comment gérer 'Runtime exited with error: signal: killed' dans AWS Lambda ?
Cette erreur indique souvent que votre fonction Lambda a épuisé sa mémoire allouée. Augmenter l'allocation de mémoire dans la configuration de la fonction Lambda peut résoudre ce problème, surtout lors du traitement de documents volumineux avec IronOCR.
Puis-je tester ma fonction OCR AWS Lambda localement avant le déploiement ?
Oui, vous pouvez tester votre fonction OCR AWS Lambda localement en utilisant le AWS Toolkit pour Visual Studio. Cet outil fournit un environnement local pour simuler les exécutions Lambda, vous permettant de déboguer et d'affiner votre fonction avant le déploiement.
Quel est le but d'un Dockerfile dans un projet AWS Lambda ?
Un Dockerfile dans un projet AWS Lambda est utilisé pour créer une image de conteneur qui définit l'environnement d'exécution et les dépendances de votre fonction Lambda. Cela garantit que votre fonction dispose de tous les composants nécessaires pour fonctionner correctement dans AWS.
Ai-je besoin de dépendances supplémentaires pour utiliser IronOCR dans .NET 8 sur AWS Lambda ?
Aucune dépendance supplémentaire n'est nécessaire au-delà de la bibliothèque IronOCR et des packages AWS SDK nécessaires lors de l'utilisation de .NET 8 sur AWS Lambda. Cela simplifie le processus d'intégration pour exécuter des tâches OCR.
Quelles sont les conditions préalables pour intégrer le OCR C# avec AWS Lambda ?
Avant d'intégrer le OCR C# avec AWS Lambda, vous devez installer le AWS SDK pour S3, la bibliothèque IronOCR, et AWS Toolkit pour Visual Studio. Vous aurez également besoin d'un bucket S3 configuré pour stocker et récupérer des documents.

