翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
接続エラーの処理
Amazon Textract オペレーションは、1 秒あたりのトランザクション (TPS) の最大数を超えた場合、サービスによってアプリケーションがスロットリングされた場合、または接続が切断された場合に失敗する可能性があります。例えば、短時間に Amazon Textract オペレーションを呼び出す回数が多すぎると、呼び出しがスロットリングされ、オペレーションレスポンスにProvisionedThroughputExceededExceptionエラーが送信されます。Amazon Textract TPS クォータの詳細については、「Amazon Textract Quotas」を参照してください。制限を変更するには、 Service Quotas コンソールで Amazon Textract オプションにアクセスできます。
オペレーションを自動的に再試行することで、スロットリング接続とドロップ接続を管理できます。Amazon Textract クライアントの作成時に Configパラメータを含めることで、再試行回数を指定できます。再試行回数は 5 にすることをお勧めします。 AWS SDK は、例外に失敗してスローする前に、指定された回数だけオペレーションを再試行します。詳細については、AWS でのエラーの再試行とエクスポネンシャルバックオフを参照してください。
次の例は、複数のドキュメントを処理するときに Amazon Textract オペレーションを自動的に再試行する方法を示しています。
オペレーションを自動的に再試行するには
-
S3 バケットに複数のドキュメントイメージをアップロードして、同期例を実行します。マルチページドキュメントを S3 バケットにアップロードし、そのバケットStartDocumentTextDetectionで を実行して非同期の例を実行します。
手順については、Amazon Simple Storage Service ユーザーガイドの「Amazon S3 へのオブジェクトのアップロード」を参照してください。
-
次の例は、 Configパラメータを使用して オペレーションを自動的に再試行する方法を示しています。同期例では DetectDocumentTextオペレーションを呼び出し、非同期例では GetDocumentTextDetectionオペレーションを呼び出します。
- Sync Example
-
次の例を使用して、Amazon S3 バケット内のドキュメントに対して DetectDocumentTextオペレーションを呼び出します。でmain、 の値を S3 バケットに変更bucketします。の値を、ステップ 2 でアップロードしたドキュメントイメージの名前documentsに変更します。
import boto3
from botocore.client import Config
# Documents
def process_multiple_documents(bucket, documents):
config = Config(retries = dict(max_attempts = 5))
# Amazon Textract client
textract = boto3.client('textract', config=config)
for documentName in documents:
print("\nProcessing: {}\n==========================================".format(documentName))
# Call Amazon Textract
response = textract.detect_document_text(
Document={
'S3Object': {
'Bucket': bucket,
'Name': documentName
}
})
# Print detected text
for item in response["Blocks"]:
if item["BlockType"] == "LINE":
print ('\033[94m' + item["Text"] + '\033[0m')
def main():
bucket = ""
documents = ["document-image-1.png",
"document-image-2.png", "document-image-3.png",
"document-image-4.png", "document-image-5.png" ]
process_multiple_documents(bucket, documents)
if __name__ == "__main__":
main()
- Async Example
-
以下の例を使用して、GetDocumentTextDetection オペレーションを呼び出します。Amazon S3 バケット内のドキュメントStartDocumentTextDetectionで を呼び出し、 を取得済みであることを前提としていますJobId。でmain、 の値を S3 バケットbucketに変更し、 の値を Textract ロールに割り当てられた roleArn Arn に変更します。また、 の値を Amazon S3 バケット内の複数ページドキュメントdocumentの名前に変更する必要があります。最後に、 の値をリージョンregion_nameの名前に置き換え、GetResults関数に の名前を指定しますjobId。
import boto3
from botocore.client import Config
class DocumentProcessor:
jobId = ''
region_name = ''
roleArn = ''
bucket = ''
document = ''
sqsQueueUrl = ''
snsTopicArn = ''
processType = ''
def __init__(self, role, bucket, document, region):
self.roleArn = role
self.bucket = bucket
self.document = document
self.region_name = region
self.config = Config(retries = dict(max_attempts = 5))
self.textract = boto3.client('textract', region_name=self.region_name, config=self.config)
self.sqs = boto3.client('sqs')
self.sns = boto3.client('sns')
# Display information about a block
def DisplayBlockInfo(self, block):
print("Block Id: " + block['Id'])
print("Type: " + block['BlockType'])
if 'EntityTypes' in block:
print('EntityTypes: {}'.format(block['EntityTypes']))
if 'Text' in block:
print("Text: " + block['Text'])
if block['BlockType'] != 'PAGE':
print("Confidence: " + "{:.2f}".format(block['Confidence']) + "%")
print('Page: {}'.format(block['Page']))
if block['BlockType'] == 'CELL':
print('Cell Information')
print('\tColumn: {} '.format(block['ColumnIndex']))
print('\tRow: {}'.format(block['RowIndex']))
print('\tColumn span: {} '.format(block['ColumnSpan']))
print('\tRow span: {}'.format(block['RowSpan']))
if 'Relationships' in block:
print('\tRelationships: {}'.format(block['Relationships']))
print('Geometry')
print('\tBounding Box: {}'.format(block['Geometry']['BoundingBox']))
print('\tPolygon: {}'.format(block['Geometry']['Polygon']))
if block['BlockType'] == 'SELECTION_ELEMENT':
print(' Selection element detected: ', end='')
if block['SelectionStatus'] == 'SELECTED':
print('Selected')
else:
print('Not selected')
def GetResults(self, jobId):
maxResults = 1000
paginationToken = None
finished = False
while finished == False:
response = None
if paginationToken == None:
response = self.textract.get_document_text_detection(JobId=jobId,
MaxResults=maxResults)
else:
response = self.textract.get_document_text_detection(JobId=jobId,
MaxResults=maxResults,
NextToken=paginationToken)
blocks = response['Blocks']
print('Detected Document Text')
print('Pages: {}'.format(response['DocumentMetadata']['Pages']))
# Display block information
for block in blocks:
self.DisplayBlockInfo(block)
print()
print()
if 'NextToken' in response:
paginationToken = response['NextToken']
else:
finished = True
def main():
roleArn = 'role-arn'
bucket = 'bucket-name'
document = 'document-name'
region_name = 'region-name'
analyzer = DocumentProcessor(roleArn, bucket, document, region_name)
analyzer.GetResults("job-id")
if __name__ == "__main__":
main()