如何在 AWS Lambda 上識別文件 OCR
本文提供了使用 IronOCR 設定 AWS Lambda 函數的逐步指南。 透過本指南,您將學習如何配置 IronOCR 並有效率地讀取儲存在 S3 儲存桶中的文件。
如何在 AWS Lambda 上識別文件 OCR
- 下載一個 C# 函式庫,用於對文件執行 OCR 識別。
- 創建並選擇項目模板
- 修改 FunctionHandler 代碼
- 配置並部署項目
- 調用函數並檢查 S3 中的結果
安裝
本文將使用 S3 儲存桶,因此需要AWSSDK.S3包。
如果您使用的是 IronOCR ZIP,則必須設定臨時資料夾。
// 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;立即開始在您的專案中使用 IronOCR,享受免費試用。
建立 AWS Lambda 項目
使用 Visual Studio,建立容器化的 AWS Lambda 函數非常簡單:
- 安裝適用於 Visual Studio 的 AWS 工具包。
- 選擇"AWS Lambda 專案(.NET Core - C#)"。
- 選擇".NET 8(容器映像)"藍圖,然後選擇"完成"。
新增包依賴項
在 .NET 8 中使用 IronOCR 程式庫不需要安裝額外的相依性即可在 AWS Lambda 上使用。 修改專案的 Dockerfile 文件,新增以下內容:
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" .修改函數處理程序程式碼
此範例從 S3 儲存桶中檢索影像,對其進行處理,並將可搜尋的 PDF 保存回同一個儲存桶。 使用 IronOCR ZIP 時,設定臨時資料夾至關重要,因為該程式庫需要寫入權限才能從 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);
}
}
}
}在 try 程式碼區塊之前,指定要從 IronPdfZip 目錄讀取的檔案為"sample.pdf"。 然後使用GetPdfFromS3Async方法檢索 PDF 位元組,並將其傳遞給LoadPdf方法。
增加記憶體和超時
Lambda 函數中分配的記憶體量將根據正在處理的文件的大小和同時處理的文件數量而變化。 作為基準,在aws-lambda-tools-defaults.json中將記憶體設為 512 MB,逾時設為 300 秒。
{
"function-memory-size": 512,
"function-timeout": 300
}當記憶體不足時,程式會拋出錯誤:"運行時錯誤退出:訊號:終止"。增加記憶體大小可以解決此問題。 如需更多詳細信息,請參閱故障排除文章: AWS Lambda - 運行時退出訊號:已終止。
發布
若要在 Visual Studio 中發布,請右鍵按一下專案並選擇"發佈到 AWS Lambda...",然後配置必要的設定。 您可以在AWS 網站上閱讀更多關於發布 Lambda 函數的資訊。
試試看!
您可以透過Lambda 控制台或 Visual Studio 啟動 Lambda 函數。
常見問題解答
如何使用 C# 在 AWS 中對文件進行 OCR 識別?
您可以將 IronOCR 與 AWS Lambda 集成,從而對儲存在 Amazon S3 儲存桶中的文件執行 OCR 識別。這需要用 C# 建立一個 Lambda 函數,該函數從 S3 中檢索文檔,使用 IronOCR 處理文檔,然後將結果上傳回 S3。
使用 C# 在 AWS Lambda 上設定 OCR 需要哪些步驟?
若要使用 C# 在 AWS Lambda 上設定 OCR,您需要下載 IronOCR 庫,在 Visual Studio 中建立 AWS Lambda 項目,配置函數處理程序以使用 IronOCR 進行處理,然後部署函數。此設定可讓您將影像轉換為可搜尋的 PDF。
在 AWS Lambda 中執行 OCR 的建議配置是什麼?
為了在 AWS Lambda 中使用 IronOCR 運行 OCR 時獲得最佳效能,建議設定至少 512 MB 的記憶體分配和 300 秒的逾時時間。這些設定有助於管理大型文件或多個文件的處理。
如何在 AWS Lambda 中處理「運行時因錯誤而退出:訊號:已終止」的情況?
此錯誤通常表示您的 Lambda 函數已耗盡其分配的記憶體。增加 Lambda 函數配置中的記憶體分配可以解決此問題,尤其是在使用 IronOCR 處理大型文件時。
我可以在部署前在本地測試我的 AWS Lambda OCR 函數嗎?
是的,您可以使用適用於 Visual Studio 的 AWS 工具包在本機上測試您的 AWS Lambda OCR 函數。該工具包提供了一個用於模擬 Lambda 執行的本地環境,使您能夠在部署之前調試和優化您的函數。
AWS Lambda 專案中 Dockerfile 的用途是什麼?
AWS Lambda 專案中的 Dockerfile 用於建立容器映像,該映像定義了 Lambda 函數的執行環境和相依性。這確保您的函數擁有在 AWS 中經常運行所需的所有元件。
在 AWS Lambda 上使用 .NET 8 中的 IronOCR 是否需要任何額外的依賴項?
在 AWS Lambda 上使用 .NET 8 時,除了 IronOCR 庫和必要的 AWS SDK 套件之外,無需其他相依性。這簡化了執行 OCR 任務的整合過程。
將 C# OCR 與 AWS Lambda 整合有哪些先決條件?
在將 C# OCR 與 AWS Lambda 整合之前,您需要安裝適用於 S3 的 AWS 開發工具包、IronOCR 程式庫和適用於 Visual Studio 的 AWS 工具包。您還需要一個已配置好的 S3 儲存桶,用於儲存和檢索文件。






