View a markdown version of this page

Analyze Lending ワークフローの使用 - Amazon Textract

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

Analyze Lending ワークフローの使用

ローン分析ワークフローを使用して、複数ページのローンドキュメント内のテキストを検出または分析するには、以下を実行します。

  1. Amazon SNS トピックと Amazon SQS キューを作成します。

  2. トピックをキューにサブスクライブします。

  3. キューにメッセージを送信するアクセス許可をトピックに付与します。

  4. ドキュメントの処理を開始します。呼び出しStartLendingAnalysisオペレーション。

  5. 完了ステータスを Amazon SQS キューから取得します。サンプルコードは、 Startオペレーションによって返されるジョブ識別子 (JobId) を追跡します。サンプルコードは、完了ステータスから読み取られた一致するジョブ識別子の結果のみを取得します。これは、他のアプリケーションが同じキューとトピックを使用している場合に重要です。わかりやすくするために、サンプルコードは一致しないジョブを削除します。詳細な調査のために、削除されたジョブを Amazon SQS デッドレターキューに追加することを検討してください。

    StartLendingAnalysis オペレーションの結果は、OutputConfig 機能を使用して、選択した Amazon S3 バケットに送信できます。この機能を使用する場合は、ユーザーロールとサービスロールの追加設定が必要になる場合があります。Amazon Textract が暗号化されたドキュメントを Amazon S3 バケットに送信できるようにする方法については、「」を参照してください出力設定のアクセス許可

  6. GetLendingAnalysis オペレーションまたは GetLendingAnalysisSummaryオペレーションを呼び出して、処理結果を取得して表示します。

  7. ドキュメントの処理が完了したら、Amazon SNS トピックと Amazon SQS キューを削除してください。追加のドキュメントを処理する必要がある場合は、Amazon SNS トピックと Amazon SQS キューをそのまま残し、他のドキュメントに再利用できます。

非同期融資分析の実行

この手順のサンプルコードは、Python と で提供されています AWS CLI。開始する前に、適切な AWS SDK をインストールします。詳細については、「ステップ 2: AWS CLI と AWS SDKs」を参照してください。

  1. Amazon Textract へのユーザーアクセスを設定し、Amazon SNS への Amazon Textract アクセスを設定します。詳細については、「非同期オペレーション用の Amazon Textract の設定」を参照してください。この手順を完了するには、PDF 形式の複数ページのドキュメントファイルが必要です。サンプルコードは Amazon SNS トピックと Amazon SQS キューを作成して設定するため、設定手順のステップ 3~6 をスキップできます。CLI の例を完了する場合、SQS キューを設定する必要はありません。

  2. PDF または TIFF 形式の複数ページのドキュメントファイルを Amazon S3 バケットにアップロードします (JPEG、PNG、TIFF、または PDF 形式で単一ページのドキュメントを処理することもできます)。手順については、Amazon Simple Storage Service ユーザーガイドの「Amazon Amazon S3へのオブジェクトのアップロード」を参照してください。

  3. 次の AWS SDK for Python (Boto3) または AWS CLI コードを使用して、複数ページの融資ドキュメント内のテキストを分析します。メイン関数の場合:

    • の値をroleArn、Amazon Amazon SNSトピックへの Amazon Textract アクセスの付与で保存した IAM ロール ARN に置き換えます

    • bucket と の値を、前のステップ 2 で指定したバケットとドキュメントのファイル名documentに置き換えます。

    • ProcessDocument 関数typeの入力パラメータの値を、使用する処理のタイプに置き換えます。たとえば、 ProcessType.DETECTIONを使用してテキストを検出したり、 を使用してテキストを分析しProcessType.ANALYSISたりします。

    • Python の例では、 の値を、クライアントregion_nameが運用しているリージョンに置き換えます。

    今後の AWS CLI サンプルコードについては、以下を実行します。

    • StartLendingAnalysis オペレーションを呼び出すときは、 の値を S3 バケットの名前bucket-nameに置き換え、 をステップ 2 で指定したファイルの名前FileNameに置き換えます。をリージョンの名前region-nameに置き換えて、バケットのリージョンを指定します。CLI の例は SQS を使用しないことに注意してください。

    • GetLendingAnalysis オペレーションまたは GetLendingAnalysisSummary オペレーションを呼び出す場合は、 を StartLendingAnalysis によってjobId返された jobId に置き換えます。をリージョンの名前region-nameに置き換えて、バケットのリージョンを指定します。

  4. 選択した SDK または CLI AWS のコードを実行します。

    オペレーションの完了までに時間がかかる場合があります。完了すると、検出または分析されたテキストのブロックのリストが次の例に表示されます。

    AWS CLI

    レンディングドキュメント分析を開始するには、次の CLI コマンドを使用します。分割されたドキュメントを表示するには、 output-config引数を使用します。それ以外の場合は削除できます。

    aws textract start-lending-analysis \ --document-location '{"S3Object":{"Bucket":"S3Bucket","Name":"FileName"}}' \ --output-config '{"S3Bucket": "S3Bucket", "S3Prefix": "S3Prefix"}' \ --kms-key-id '1234abcd-12ab-34cd-56ef-1234567890ab' \ --region 'region-name'

    レンディングドキュメント分析の結果を取得するには、次の CLI コマンドを使用します。max-results 引数はオプションであり、返される結果の数を制限しない場合は削除できます。

    aws textract get-lending-analysis \ --job-id 'jobId' \ --region 'us-west-2' \ --max-results 30

    結果の概要を取得するには:

    aws textract get-lending-analysis-summary \ --job-id 'jobId' \ --region 'us-west-2'
    Python
    import boto3 import json import sys import time class DocumentProcessor: def __init__(self, role, bucket, document, region): self.roleArn = role self.bucket = bucket self.document = document self.region_name = region self.textract = boto3.client('textract', region_name=self.region_name) self.sqs = boto3.client('sqs') self.sns = boto3.client('sns') def ProcessDocument(self): jobFound = False response = self.textract.start_lending_analysis( DocumentLocation={'S3Object': {'Bucket': self.bucket, 'Name': self.document}}, NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn}) print('Processing type: Analysis') print('Start Job Id: ' + response['JobId']) dotLine = 0 while jobFound == False: sqsResponse = self.sqs.receive_message(QueueUrl=self.sqsQueueUrl, MessageAttributeNames=['ALL'], MaxNumberOfMessages=10) if sqsResponse: if 'Messages' not in sqsResponse: if dotLine < 40: print('.', end='') dotLine = dotLine + 1 else: print() dotLine = 0 sys.stdout.flush() time.sleep(5) continue for message in sqsResponse['Messages']: notification = json.loads(message['Body']) textMessage = json.loads(notification['Message']) print(textMessage['JobId']) print(textMessage['Status']) if str(textMessage['JobId']) == response['JobId']: print('Matching Job Found:' + textMessage['JobId']) jobFound = True self.GetResults(textMessage['JobId']) self.GetSummary(textMessage['JobId']) self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) else: print("Job didn't match:" + str(textMessage['JobId']) + ' : ' + str(response['JobId'])) # Delete the unknown message. Consider sending to dead letter queue self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) print('Done!') def CreateTopicandQueue(self): millis = str(int(round(time.time() * 1000))) # Create SNS topic snsTopicName = "AmazonTextractTopic" + millis topicResponse = self.sns.create_topic(Name=snsTopicName) self.snsTopicArn = topicResponse['TopicArn'] # create SQS queue sqsQueueName = "AmazonTextractQueue" + millis self.sqs.create_queue(QueueName=sqsQueueName) self.sqsQueueUrl = self.sqs.get_queue_url(QueueName=sqsQueueName)['QueueUrl'] attribs = self.sqs.get_queue_attributes(QueueUrl=self.sqsQueueUrl, AttributeNames=['QueueArn'])['Attributes'] sqsQueueArn = attribs['QueueArn'] # Subscribe SQS queue to SNS topic self.sns.subscribe( TopicArn=self.snsTopicArn, Protocol='sqs', Endpoint=sqsQueueArn) # Authorize SNS to write SQS queue policy = """{{ "Version":"2012-10-17", "Statement":[ {{ "Sid":"MyPolicy", "Effect":"Allow", "Principal" : {{"AWS" : "*"}}, "Action":"sqs:*", "Resource": "{}", "Condition":{{ "ArnEquals":{{ "aws:SourceArn": "{}" }} }} }} ] }}""".format(sqsQueueArn, self.snsTopicArn) response = self.sqs.set_queue_attributes( QueueUrl=self.sqsQueueUrl, Attributes={ 'Policy': policy }) def DeleteTopicandQueue(self): self.sqs.delete_queue(QueueUrl=self.sqsQueueUrl) self.sns.delete_topic(TopicArn=self.snsTopicArn) # Display information about a block def DisplayExtractInfo(self, response): results = response['Results'] for page in results: print("Page Classification: {}".format(page["PageClassification"]["PageType"])) print("Page Number: {}".format(page["Page"])) for extract in page["Extractions"]: for fields, vals in extract['LendingDocument'].items(): for val in vals: print("Document Type: {}".format(val['Type'])) detections = val['ValueDetections'] for i in detections: print(i['Text']) print('Geometry') print('\tBounding Box: {}'.format(i['Geometry']['BoundingBox'])) print('\tPolygon: {}'.format(i['Geometry']['Polygon'])) def GetSummary(self, jobId): maxResults = 1000 response = self.textract.get_lending_analysis_summary(JobId=jobId, MaxResults=maxResults) doc_groups = response['DocumentGroups'] print("Summary info:") for group in doc_groups: print("Document type: " + group['Type']) split_docs = group['SplitDocuments'] for doc in split_docs: print(doc) for idx, page in doc.items(): print(str(idx) + " - " + str(page)) def GetResults(self, jobId): maxResults = 1000 paginationToken = None finished = False while finished == False: response = None if paginationToken == None: response = self.textract.get_lending_analysis(JobId=jobId, MaxResults=maxResults) else: response = self.textract.get_lending_analysis(JobId=jobId, MaxResults=maxResults, NextToken=paginationToken) print('Detected Document Text') print('Pages: {}'.format(response['DocumentMetadata']['Pages'])) self.DisplayExtractInfo(response) if 'NextToken' in response: paginationToken = response['NextToken'] else: finished = True def main(): roleArn = '' bucket = '' document = '' region_name = '' analyzer = DocumentProcessor(roleArn, bucket, document, region_name) analyzer.CreateTopicandQueue() analyzer.ProcessDocument() analyzer.DeleteTopicandQueue() if __name__ == "__main__": main()