在 Spring Boot 中使用 Amazon Textract 從圖像中提取文本
1. 概述
企業通常需要從各種類型的影像中提取有意義的數據,例如處理費用追蹤的發票或收據、KYC(了解您的客戶)流程的身份文件或從表單中自動輸入資料。然而,手動從圖像中提取文字是一個耗時且昂貴的過程。
Amazon Textract提供自動化解決方案,使用機器學習從文件中提取列印文字和手寫資料。
在本教程中,我們將探討如何在 Spring Boot 應用程式中使用 Amazon Textract 從圖像中提取文字。我們將逐步完成必要的配置並實現從本地圖像檔案和 Amazon S3 中儲存的圖像中提取文字的功能。
2. 設定項目
在開始從圖像中提取文字之前,我們需要包含 SDK 依賴項並正確配置我們的應用程式。
2.1.依賴關係
首先,我們將Amazon Textract 相依性新增至專案的pom.xml
檔案:
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>textract</artifactId>
<version>2.27.5</version>
</dependency>
此相依性為我們提供了TextractClient
和其他相關類,我們將使用它們與 Textract 服務進行互動。
2.2.定義 AWS 配置屬性
現在,為了與 Textract 服務互動並從圖像中提取文本,**我們需要配置用於身份驗證的 AWS 憑證以及我們想要使用該服務的AWS 區域**。
我們將這些屬性儲存在專案的application.yaml
檔案中,並使用@ConfigurationProperties
將值對應到 POJO,我們的服務層在與 Textract 互動時引用該 POJO:
@Validated
@ConfigurationProperties(prefix = "com.baeldung.aws")
class AwsConfigurationProperties {
@NotBlank
private String region;
@NotBlank
private String accessKey;
@NotBlank
private String secretKey;
// standard setters and getters
}
我們還添加了驗證註釋,以確保正確配置所有必需的屬性。如果任何定義的驗證失敗,Spring ApplicationContext
將無法啟動。這使我們能夠遵守快速失敗原則。
以下是application.yaml
檔案的片段,它定義了將自動對應到我們的AwsConfigurationProperties
類別的所需屬性:
com:
baeldung:
aws:
region: ${AWS_REGION}
access-key: ${AWS_ACCESS_KEY}
secret-key: ${AWS_SECRET_KEY}
我們使用${}
屬性佔位符從環境變數載入屬性值。
因此,此設定允許我們外部化 AWS 屬性並在我們的應用程式中輕鬆存取它們。
2.3.聲明TextractClient
Bean
現在我們已經配置了屬性,讓我們引用它們來定義我們的TextractClient
bean:
@Bean
public TextractClient textractClient() {
String region = awsConfigurationProperties.getRegion();
String accessKey = awsConfigurationProperties.getAccessKey();
String secretKey = awsConfigurationProperties.getSecretKey();
AwsBasicCredentials awsCredentials = AwsBasicCredentials.create(accessKey, secretKey);
return TextractClient.builder()
.region(Region.of(region))
.credentialsProvider(StaticCredentialsProvider.create(awsCredentials))
.build();
}
TextractClient
類別是與 Textract 服務互動的主要入口點。我們將在服務層中自動組裝它,並發送請求以從圖像檔案中提取文字。
3. 從圖像中提取文本
現在我們已經定義了TextractClient
bean,讓我們建立一個TextExtractor
類別並引用它來實現我們預期的功能:
public String extract(@ValidFileType MultipartFile image) {
byte[] imageBytes = image.getBytes();
DetectDocumentTextResponse response = textractClient.detectDocumentText(request -> request
.document(document -> document
.bytes(SdkBytes.fromByteArray(imageBytes))
.build())
.build());
return transformTextDetectionResponse(response);
}
private String transformTextDetectionResponse(DetectDocumentTextResponse response) {
return response.blocks()
.stream()
.filter(block -> block.blockType().equals(BlockType.LINE))
.map(Block::text)
.collect(Collectors.joining(" "));
}
在extract()
方法中,我們將MultipartFile
轉換為位元組數組,並將其作為Document
傳遞給detectDocumentText()
方法。
Amazon Textract 目前僅支援 PNG、JPEG、TIFF 和 PDF 文件格式。我們建立一個自訂驗證註解@ValidFileType
以確保上傳的檔案採用這些支援的格式之一。
對於我們的演示,在我們的輔助方法transformTextDetectionResponse()
中,我們透過連接每個block
的文字內容將DetectDocumentTextResponse
轉換為簡單的String
。但是,可以根據業務需求自訂轉換邏輯。
除了從應用程式傳遞圖像之外,我們還可以從儲存在 S3 儲存桶中的圖像中提取文字:
public String extract(String bucketName, String objectKey) {
textractClient.detectDocumentText(request -> request
.document(document -> document
.s3Object(s3Object -> s3Object
.bucket(bucketName)
.name(objectKey)
.build())
.build())
.build());
return transformTextDetectionResponse(response);
}
在我們重載的extract()
方法中,我們將 S3 儲存桶名稱和物件鍵作為參數,允許我們指定映像在 S3 中的位置。
值得注意的是,我們呼叫TextractClient
bean 的detectDocumentText()
方法,這是一個用於處理單頁文件的同步操作。**但是,為了處理多頁文檔,Amazon Textract 提供了非同步操作**。
4.IAM權限
最後,為了讓我們的應用程式正常運行,我們需要為我們在應用程式中配置的IAM用戶配置一些權限:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowTextractDocumentDetection",
"Effect": "Allow",
"Action": "textract:DetectDocumentText",
"Resource": "*"
},
{
"Sid": "AllowS3ReadAccessToSourceBucket",
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::bucket-name/*"
}
]
}
在我們的 IAM 策略中, AllowTextractDocumentDetection
語句可讓我們呼叫DetectDocumentText
API 從圖片中擷取文字。
如果我們從儲存在 S3 中的映像中提取文本,我們還需要包含AllowS3ReadAccessToSourceBucket
語句以允許對 S3 儲存桶進行讀取存取。
我們的 IAM 策略符合最小權限原則,僅授予我們的應用程式正常運作所需的必要權限。
5. 結論
在本文中,我們探索了使用 Amazon Textract 和 Spring Boot 從圖像中提取文字。
我們討論瞭如何從本機圖像檔案以及 Amazon S3 中儲存的圖像中提取文字。
Amazon Textract 是一項功能強大的服務,廣泛應用於金融科技和健康科技產業,有助於自動執行處理發票或從醫療表格中提取病患資料等任務。
與往常一樣,本文中使用的所有程式碼範例都可以在 GitHub 上找到。