AWS Lambda'da Belgeler Nasıl OCR Yapılır

This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to AWS Lambda'da Belgeler Nasıl OCR Yapılır

Bu nasıl yapılır makalesi, IronOCR kullanarak AWS Lambda fonksiyonunun nasıl ayarlanacağına dair adım adım bir kılavuz sunar. Bu kılavuzu takip ederek, IronOCR'yi nasıl yapılandıracağınızı ve bir S3 kovasında depolanan belgeleri nasıl verimli okuyacağınızı öğreneceksiniz.

Kurulum

Bu makale bir S3 kovası kullanacak, bu nedenle AWSSDK.S3 paketi gereklidir.

IronOCR ZIP kullanıyorsanız, geçici klasörü ayarlamanız önemlidir.

// 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
$vbLabelText   $csharpLabel

!{--0100110001001001010000100101001001000001010100100101100101011111--}

Bir AWS Lambda Projesi Oluşturun

Visual Studio ile bir kaplamalı AWS Lambda oluşturmak kolay bir süreçtir:

  • AWS Toolkit for Visual Studio kurulumunu gerçekleştirin.
  • 'AWS Lambda Projesi (.NET Core - C#)' seçin.
  • '.NET 8 (Container Image)' şablonunu seçin, ardından 'Finish' ile tamamlayın.

Konteyner görüntüsünü seçin

Paket Bağımlılıklarını Ekleyin

.NET 8 içinde IronOCR kütüphanesini AWS Lambda üzerinde kullanmak için ek bir bağımlılık kurulumu gerektirmez. Projenin Dockerfile'ını aşağıdaki ile 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 Değiştirin

Bu örnek, bir S3 kovasından bir resmi alır, işler ve aynı kovada aranabilir bir PDF olarak kaydeder. IronOCR ZIP'i kullanırken geçici klasörü ayarlamak önemlidir çünkü kütüphane DLL'lerden çalışma zamanı klasörünü kopyalamak için yazma izinlerine ihtiyaç duyar.

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
$vbLabelText   $csharpLabel

Deneme bloğundan önce, 'sample.pdf' dosyası IronPdfZip dizininden okunması için belirtilir. GetPdfFromS3Async yöntemi, PDF baytını almak için kullanılır, daha sonra LoadPdf yöntemine iletilir.

Bellek ve Zaman Aşımı Artırın

Lambda işlevinde ayrılan bellek miktarı, işlenen belgelerin boyutuna ve aynı anda işlenen belge sayısına bağlı olarak değişir. Başlangıç noktası olarak, belleği 512 MB ve zaman aşımını 300 saniyeye ayarlayın aws-lambda-tools-defaults.json.

{
    "function-memory-size": 512,
    "function-timeout": 300
}

Bellek yetersiz kaldığında program, 'Çalışma zamanı hata ile çıktı: sinyal: durduruldu.' şeklinde hata fırlatacaktır. Bellek boyutunu artırmak bu sorunu çözebilir. Daha fazla ayrıntı için çözüm makalesine bakın: AWS Lambda - Çalışma Zamanı Çıkışı Sinyal: Killed.

Yayınla

Visual Studio'da yayınlamak için projeye sağ tıklayın ve 'AWS Lambda'ya Yayınla...' seçeneğini seçin, ardından gerekli ayarları yapılandırın. AWS web sitesinde Lambda yayınlama hakkında daha fazla okuyabilirsiniz: AWS web sitesi.

Dene!

Lambda işlevini ya Lambda konsolu ya da Visual Studio aracılığıyla etkinleştirebilirsiniz.

Sıkça Sorulan Sorular

C# kullanarak AWS üzerinde belgelerde OCR'ı nasıl yapabilirim?

IronOCR'u, Amazon S3 sepetlerindeki belgelerde OCR gerçekleştirmek için AWS Lambda ile entegre edebilirsiniz. Bu, belgeleri S3'ten alan, IronOCR ile işleyen ve sonuçları tekrar S3'e yükleyen bir C# Lambda fonksiyonu oluşturmaktan geçer.

C# ile AWS Lambda'da OCR kurulumunda hangi adımlar yer alır?

C# kullanarak AWS Lambda üzerinde OCR kurmak için IronOCR kütüphanesini indirmeniz, Visual Studio'da bir AWS Lambda projesi oluşturmanız, fonksiyon işleyicinizi IronOCR'u kullanarak işlemek için yapılandırmanız ve fonksiyonunuzu dağıtmanız gerekir. Bu kurulum, görüntüleri aranabilir PDF'lere dönüştürmenizi sağlar.

AWS Lambda üzerinde OCR çalıştırmak için önerilen yapılandırma nedir?

AWS Lambda üzerinde IronOCR ile OCR çalıştırırken optimal performans için en az 512 MB bellek tahsis edilmesi ve 300 saniye zaman aşımı süresi ayarlanması önerilir. Bu ayarlar, büyük veya birden fazla belgenin işlenmesini yönetmeye yardımcı olur.

AWS Lambda üzerinde 'Çalışma zamanı hata ile sonlandı: sinyal: öldürüldü' hatasını nasıl ele alırım?

Bu hata genellikle Lambda fonksiyonunuzun ayrılan belleğini bitirdiğini gösterir. Özellikle IronOCR ile büyük belgeleri işlerken, Lambda fonksiyonunun yapılandırmasında bellek tahsisini artırmak bu sorunu çözebilir.

AWS Lambda OCR fonksiyonumu dağıtmadan önce yerel olarak test edebilir miyim?

Evet, AWS Lambda OCR fonksiyonunuzu Visual Studio için AWS Araç Seti'ni kullanarak yerel olarak test edebilirsiniz. Bu araç seti, dağıtmadan önce Lambda çalıştırmalarını simüle etmek, fonksiyonunuzu hata ayıklamak ve iyileştirmek için bir yerel ortam sağlar.

AWS Lambda projesinde Dockerfile’ın amacı nedir?

Bir AWS Lambda projesinde Dockerfile, Lambda fonksiyonunuz için çalışma ortamını ve bağımlılıkları tanımlayan bir konteyner görüntüsü oluşturmak için kullanılır. Bu, fonksiyonunuzun AWS'de düzgün çalışması için gerekli tüm bileşenlerin bulunmasını sağlar.

.NET 8 üzerinde AWS Lambda'da IronOCR kullanmak için ek bir bağımlılığa ihtiyaçım var mı?

.NET 8 üzerinde AWS Lambda'da kullanırken IronOCR kütüphanesi ve gerekli AWS SDK paketleri dışında başka ek bağımlılığa ihtiyaçınız yoktur. Bu, OCR görevlerini yürütme sürecini basitleştirir.

C# OCR'u AWS Lambda ile entegre etmek için ön koşullar nelerdir?

C# OCR'u AWS Lambda ile entegre etmeden önce, S3 için AWS SDK, IronOCR kütüphanesi ve Visual Studio için AWS Araç Seti'ni yüklemeniz gerekmektedir. Belgeleri depolamak ve geri almak için yapılandırılmış bir S3 sepetine de ihtiyaçınız olacak.

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında lisans derecesine sahiptir (Carleton Üniversitesi) ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirme üzerine uzmanlaşmıştır. Kullanıcı dostu ve estetik açıdan hoş arayüzler tasarlamaya tutkuyla bağlı olan Curtis, modern çerç...

Daha Fazlasını Oku
Başlamaya Hazır mısınız?
Nuget İndirmeler 5,585,834 | Sürüm: 2026.4 just released
Still Scrolling Icon

Hala Kaydiriyor musunuz?

Hızlı bir kanit mi istiyorsunuz? PM > Install-Package IronOcr
örnekleri çalıştır resminizin aranabilir metne donuşünü izleyin.