AWS Lambda Üzerinde Belgeleri OCR Yapma Yöntemleri
Bu nasıl yapılır makalesi, IronOCR kullanarak bir AWS Lambda işlevinin kurulumu için adım adım bir rehber sunar. Bu rehberi izleyerek, IronOCR'yi yapılandırmayı ve S3 kovasında saklanan belgeleri etkili bir şekilde okumayı öğreneceksiniz.
AWS Lambda'da Belgeleri OCR Yapma Yöntemleri
- Belgelerde OCR yapmak için bir C# kütüphanesi indirin
- Proje şablonunu oluşturun ve seçin
- FunctionHandler kodunu düzenleyin
- Projeyi yapılandırın ve dağıtın
- İşlevi çalıştırın ve sonuçları S3'te kontrol edin
Kurulum
Bu makalede bir S3 bucket kullanılacak, bu yüzden AWSSDK.S3 paketi gereklidir.
IronOCR ZIP kullanıyorsanız, geçici klasörü ayarlamak zorunludur.
// 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 = awsTmpPathIronOCR'u projenizde kullanmaya bugün ücretsiz deneme sürümüyle başlayın.
Bir AWS Lambda Projesi Oluşturun
Visual Studio ile, kapsayıcılaştırılmış bir AWS Lambda oluşturmak kolay bir işlemdir:
- Visual Studio için AWS Toolkit'i yükleyin.
- 'AWS Lambda Projesi (.NET Core - C#)' seçeneğini seçin.
- '.NET 8 (Kapsayıcı Görüntü)' şablonunu seçin, ardından 'Bitir' seçin.

Paket Bağımlılıklarını Ekleyin
.NET 8'de IronOCR kütüphanesini AWS Lambda üzerinde kullanmak için ek bir bağımlılık yüklemeye gerek yoktur. Projenin Dockerfile dosyasını aşağıdakiyle değiştirin:
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" .
FunctionHandler Kodunu Düzenleyin
Bu örnek, bir görüntüyü bir S3 kovasından alır, işlemler ve aranabilir bir PDF olarak aynı kovaya geri kaydeder. IronOCR ZIP kullanırken geçici klasörün ayarlanması zorunludur, çünkü kütüphane, DLL'lerden çalışma zamanı klasörünü kopyalamak için yazma izinleri gerektirir.
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 NamespaceTry bloğundan önce, IronPdfZip dizininde 'sample.pdf' dosyasının okuma işlemi için ayarlandığından emin olun. GetPdfFromS3Async metodu, PDF baytını almak için kullanılır ve bu bayt, LoadPdf metoduna geçirilir.
Bellek ve Zaman Aşımını Artırın
Lambda fonksiyonunda tahsis edilen bellek miktarı, işlenen belgelerin boyutuna ve aynı anda işlenen belge sayısına bağlı olarak değişecektir. Temel olarak, aws-lambda-tools-defaults.json içinde belleği 512 MB'a ve zaman aşımını 300 saniyeye ayarlayın.
{
"function-memory-size": 512,
"function-timeout": 300
}
Bellek yetersiz olduğunda, program 'Çalışma zamanı hatayla çıktı: sinyal: öldürüldü.' hatasını verecektir. Bellek boyutunu artırmak bu sorunu çözebilir. Daha fazla detay için sorun giderme makalesine bakın: AWS Lambda - Çalışma İstem Çıkışı: Öldürüldü.
Yayınla
Visual Studio'da yayınlamak için, proje üzerine sağ tıklayın ve 'AWS Lambda'ya Yayınla...' seçin, ardından gerekli ayarları yapılandırın. Bir Lambda'yı yayınlama hakkında daha fazla bilgi için AWS web sitesini okuyabilirsiniz.
Deneyin!
Lambda işlevini ya Lambda konsolu ya da Visual Studio üzerinden etkinleştirebilirsiniz.
Sıkça Sorulan Sorular
C# projesinde IronOCR ile AWS entegrasyonunu nasıl yapabilirim?
IronOCR'yi bir C# projesinde AWS ile entegre etmek için bir AWS Lambda işlevi kurmanız gerekir. Eğiticideki adım adım kılavuzu izleyerek IronOCR'yi yapılandırabilir ve belgeleri S3 bucket'ında etkili bir şekilde okuyabilirsiniz.
IronOCR'yi AWS Lambda üzerinde kullanmak için ön koşullar nelerdir?
IronOCR'yi AWS Lambda üzerinde kullanmadan önce, Visual Studio için AWS Araç Seti'ni yüklemiş olmanız, .NET Core'da bir AWS Lambda projesi ayarlamış olmanız ve S3 işlemlerini yönetmek için AWSSDK.S3 paketine sahip olmanız gerekir.
IronOCR kullanarak bir Lambda işlevinde OCR işlemesini nasıl yaparım?
Bir AWS Lambda işlevinde, IronOCR S3 bucket'ından görüntüleri alarak, IronTesseract kullanarak içerikleri okuyarak ve sonuçları aranabilir PDF'ler olarak S3 bucket'ına geri kaydederek işleyebilir.
IronOCR ZIP kullanırken geçici klasörü ayarlamak neden önemlidir?
IronOCR ZIP kullanırken geçici klasör yolunu ayarlamak kritik öneme sahiptir çünkü çalışma zamanını DLL'lerden kopyalamak için yazma iznine ihtiyaç vardır. Bu yapılandırma, IronOCR'nin Lambda ortamında düzgün çalışmasını sağlar.
AWS Lambda üzerinde IronOCR kullanırken 'signal: killed' hatasıyla karşılaşırsam ne yapmalıyım?
Lambda işlevinizde 'Çalışma zamanı hata ile sona erdi: sinyal: öldürüldü' hatasıyla karşılaşırsanız, bu, Lambda işleviniz için yetersiz bellek tahsisinden kaynaklanıyor olabilir. Bu sorunu çözmek için aws-lambda-tools-defaults.json dosyasındaki bellek büyüklüğü ve zaman aşımı ayarlarını artırabilirsiniz.
AWS Lambda projemi Visual Studio kullanarak nasıl yayınlayabilirim?
Visual Studio'dan bir AWS Lambda projesi yayınlamak için projenize sağ tıklayın, 'Publish to AWS Lambda...' seçeneğini seçin ve AWS belgelerindeki Lambda işlevlerini yayınlama yönergelerini izleyerek gerekli ayarları yapılandırın.
IronOCR'yi AWS Lambda üzerinde büyük belgeleri işlerken önerilen bellek ve zaman aşımı ayarları nelerdir?
Büyük belgeleri işlerken sorunsuz bir şekilde çalışmak için en az 512 MB bellek ayırmak ve 300 saniye zaman aşımı ayarlamak önerilir.
IronOCR, AWS Lambda'da PDF dosyalarını doğrudan işleyebilir mi?
Evet, IronOCR, S3 bucket'ından yüklenen PDF'leri okuyup aranabilir PDF'ler olarak geri döndürmek için IronTesseract sınıfını kullanarak PDF dosyalarını doğrudan AWS Lambda'da işleyebilir.
IronOCR kullanarak AWS Lambda işlevinde OCR sonuçlarını nasıl kaydederim?
AWS Lambda işlevinizde, Lambda bağlamının Logger.LogLine yöntemini kullanarak OCR sonuçlarını kaydedin. Bu, IronOCR tarafından işlenen OCR çıktısını izlemenizi ve doğrulamanızı sağlar.
.NET 8 üzerinde AWS Lambda'ya dağıtım yaparken IronOCR için ek bağımlılıkları yüklemek gerekli mi?
IronOCR kütüphanesini bir .NET 8 AWS Lambda projesinde kullanmak için, S3 işlemleri için AWSSDK.S3 gibi gerekli paketleri yapılandırma ve doğru yolları ayarlama dışında ek bağımlılık gerekli değildir.
Curtis Chau, Bilgisayar Bilimleri alanında Lisans Derecesine (Carleton Üniversitesi) sahip ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirmeyle ilgileniyor. Sezgisel ve estetik açıdan hoş kullanıcı arayüzleri oluşturma tutkunu, Curtis modern çerçevelerle çalışmayı ve iyi yapılandırılmış, görsel olarak çekici kılavuzlar oluşturmayı seviyor.