AWS Doc SDK Examples
SDK for Python (Boto3) を使用する Amazon Textract の例
次のコード例は、Amazon Textract で AWS SDK for Python (Boto3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。
アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。
シナリオは、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。
各例には、完全なソースコードへのリンクが含まれており、そこからコンテキストにおけるコードの設定方法と実行方法についての手順を確認できます。
アクション
次のコード例は、AnalyzeDocument を使用する方法を示しています。
- SDK for Python (Boto3)
-
注記
GitHub には、その他のリソースもあります。AWS コード例リポジトリ
で完全な例を見つけて、設定と実行の方法を確認してください。 class TextractWrapper: """Encapsulates Textract functions.""" def __init__(self, textract_client, s3_resource, sqs_resource): """ :param textract_client: A Boto3 Textract client. :param s3_resource: A Boto3 Amazon S3 resource. :param sqs_resource: A Boto3 Amazon SQS resource. """ self.textract_client = textract_client self.s3_resource = s3_resource self.sqs_resource = sqs_resource def analyze_file( self, feature_types, *, document_file_name=None, document_bytes=None ): """ Detects text and additional elements, such as forms or tables, in a local image file or from in-memory byte data. The image must be in PNG or JPG format. :param feature_types: The types of additional document features to detect. :param document_file_name: The name of a document image file. :param document_bytes: In-memory byte data of a document image. :return: The response from Amazon Textract, including a list of blocks that describe elements detected in the image. """ if document_file_name is not None: with open(document_file_name, "rb") as document_file: document_bytes = document_file.read() try: response = self.textract_client.analyze_document( Document={"Bytes": document_bytes}, FeatureTypes=feature_types ) logger.info("Detected %s blocks.", len(response["Blocks"])) except ClientError: logger.exception("Couldn't detect text.") raise else: return response-
API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「AnalyzeDocument」を参照してください。
-
次のコード例は、DetectDocumentText を使用する方法を示しています。
- SDK for Python (Boto3)
-
注記
GitHub には、その他のリソースもあります。AWS コード例リポジトリ
で完全な例を見つけて、設定と実行の方法を確認してください。 class TextractWrapper: """Encapsulates Textract functions.""" def __init__(self, textract_client, s3_resource, sqs_resource): """ :param textract_client: A Boto3 Textract client. :param s3_resource: A Boto3 Amazon S3 resource. :param sqs_resource: A Boto3 Amazon SQS resource. """ self.textract_client = textract_client self.s3_resource = s3_resource self.sqs_resource = sqs_resource def detect_file_text(self, *, document_file_name=None, document_bytes=None): """ Detects text elements in a local image file or from in-memory byte data. The image must be in PNG or JPG format. :param document_file_name: The name of a document image file. :param document_bytes: In-memory byte data of a document image. :return: The response from Amazon Textract, including a list of blocks that describe elements detected in the image. """ if document_file_name is not None: with open(document_file_name, "rb") as document_file: document_bytes = document_file.read() try: response = self.textract_client.detect_document_text( Document={"Bytes": document_bytes} ) logger.info("Detected %s blocks.", len(response["Blocks"])) except ClientError: logger.exception("Couldn't detect text.") raise else: return response-
API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「DetectDocumentText」を参照してください。
-
次のコード例は、GetDocumentAnalysis を使用する方法を示しています。
- SDK for Python (Boto3)
-
注記
GitHub には、その他のリソースもあります。AWS コード例リポジトリ
で完全な例を見つけて、設定と実行の方法を確認してください。 class TextractWrapper: """Encapsulates Textract functions.""" def __init__(self, textract_client, s3_resource, sqs_resource): """ :param textract_client: A Boto3 Textract client. :param s3_resource: A Boto3 Amazon S3 resource. :param sqs_resource: A Boto3 Amazon SQS resource. """ self.textract_client = textract_client self.s3_resource = s3_resource self.sqs_resource = sqs_resource def get_analysis_job(self, job_id): """ Gets data for a previously started detection job that includes additional elements. :param job_id: The ID of the job to retrieve. :return: The job data, including a list of blocks that describe elements detected in the image. """ try: response = self.textract_client.get_document_analysis(JobId=job_id) job_status = response["JobStatus"] logger.info("Job %s status is %s.", job_id, job_status) except ClientError: logger.exception("Couldn't get data for job %s.", job_id) raise else: return response-
API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「GetDocumentAnalysis」を参照してください。
-
次のコード例は、StartDocumentAnalysis を使用する方法を示しています。
- SDK for Python (Boto3)
-
注記
GitHub には、その他のリソースもあります。AWS コード例リポジトリ
で完全な例を見つけて、設定と実行の方法を確認してください。 非同期ジョブを開始してドキュメントを分析します。
class TextractWrapper: """Encapsulates Textract functions.""" def __init__(self, textract_client, s3_resource, sqs_resource): """ :param textract_client: A Boto3 Textract client. :param s3_resource: A Boto3 Amazon S3 resource. :param sqs_resource: A Boto3 Amazon SQS resource. """ self.textract_client = textract_client self.s3_resource = s3_resource self.sqs_resource = sqs_resource def start_analysis_job( self, bucket_name, document_file_name, feature_types, sns_topic_arn, sns_role_arn, ): """ Starts an asynchronous job to detect text and additional elements, such as forms or tables, in an image stored in an Amazon S3 bucket. Textract publishes a notification to the specified Amazon SNS topic when the job completes. The image must be in PNG, JPG, or PDF format. :param bucket_name: The name of the Amazon S3 bucket that contains the image. :param document_file_name: The name of the document image stored in Amazon S3. :param feature_types: The types of additional document features to detect. :param sns_topic_arn: The Amazon Resource Name (ARN) of an Amazon SNS topic where job completion notification is published. :param sns_role_arn: The ARN of an AWS Identity and Access Management (IAM) role that can be assumed by Textract and grants permission to publish to the Amazon SNS topic. :return: The ID of the job. """ try: response = self.textract_client.start_document_analysis( DocumentLocation={ "S3Object": {"Bucket": bucket_name, "Name": document_file_name} }, NotificationChannel={ "SNSTopicArn": sns_topic_arn, "RoleArn": sns_role_arn, }, FeatureTypes=feature_types, ) job_id = response["JobId"] logger.info( "Started text analysis job %s on %s.", job_id, document_file_name ) except ClientError: logger.exception("Couldn't analyze text in %s.", document_file_name) raise else: return job_id-
API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「StartDocumentAnalysis」を参照してください。
-
次のコード例は、StartDocumentTextDetection を使用する方法を示しています。
- SDK for Python (Boto3)
-
注記
GitHub には、その他のリソースもあります。AWS コード例リポジトリ
で完全な例を見つけて、設定と実行の方法を確認してください。 ドキュメント内のテキストを検出する非同期ジョブを開始します。
class TextractWrapper: """Encapsulates Textract functions.""" def __init__(self, textract_client, s3_resource, sqs_resource): """ :param textract_client: A Boto3 Textract client. :param s3_resource: A Boto3 Amazon S3 resource. :param sqs_resource: A Boto3 Amazon SQS resource. """ self.textract_client = textract_client self.s3_resource = s3_resource self.sqs_resource = sqs_resource def start_detection_job( self, bucket_name, document_file_name, sns_topic_arn, sns_role_arn ): """ Starts an asynchronous job to detect text elements in an image stored in an Amazon S3 bucket. Textract publishes a notification to the specified Amazon SNS topic when the job completes. The image must be in PNG, JPG, or PDF format. :param bucket_name: The name of the Amazon S3 bucket that contains the image. :param document_file_name: The name of the document image stored in Amazon S3. :param sns_topic_arn: The Amazon Resource Name (ARN) of an Amazon SNS topic where the job completion notification is published. :param sns_role_arn: The ARN of an AWS Identity and Access Management (IAM) role that can be assumed by Textract and grants permission to publish to the Amazon SNS topic. :return: The ID of the job. """ try: response = self.textract_client.start_document_text_detection( DocumentLocation={ "S3Object": {"Bucket": bucket_name, "Name": document_file_name} }, NotificationChannel={ "SNSTopicArn": sns_topic_arn, "RoleArn": sns_role_arn, }, ) job_id = response["JobId"] logger.info( "Started text detection job %s on %s.", job_id, document_file_name ) except ClientError: logger.exception("Couldn't detect text in %s.", document_file_name) raise else: return job_id-
API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「StartDocumentTextDetection」を参照してください。
-
シナリオ
次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。
- SDK for Python (Boto3)
-
Amazon Textract で AWS SDK for Python (Boto3) を使用して、ドキュメントイメージ内のテキスト、フォーム、および表要素を検出する方法を示します。入力イメージと Amazon Textract 出力は、検出された要素を探索できる Tkinter アプリケーションに表示されます。
Amazon Textract にドキュメントイメージを送信し、検出された要素の出力を調べます。
Amazon Textract に直接イメージを送信するか、Amazon Simple Storage Service (Amazon S3) バケットを通じてイメージを送信します。
非同期 API を使用して、ジョブの完了時に Amazon Simple Notification Service (Amazon SNS) トピックに通知を発行するジョブを開始します。
Amazon Simple Queue Service (Amazon SQS) キューにジョブ完了メッセージについてポーリングし、結果を表示します。
完全なソースコードとセットアップおよび実行の手順については、GitHub
で完全な例を参照してください。 この例で使用されているサービス
Amazon Cognito ID
Amazon S3
Amazon SNS
Amazon SQS
Amazon Textract
次のコード例は、Amazon Comprehend を使用して、Amazon S3 に格納されている画像から Amazon Textract によって抽出されたテキスト内のエンティティを検出する方法を示しています。
- SDK for Python (Boto3)
-
Jupyter Notebook で AWS SDK for Python (Boto3) を使用して、画像から抽出されたテキスト内のエンティティを検出する方法を示しています。この例では、Amazon Textract を使用して Amazon Simple Storage Service (Amazon S3) に保存されている画像からテキストを抽出し、Amazon Comprehend を使用して、抽出されたテキスト内のエンティティを検出します。
この例は Jupyter Notebook であり、ノートブックをホストできる環境で実行する必要があります。Amazon SageMaker AI を使用してサンプルを実行する方法については、「TextractAndComprehendNotebook.ipynb
」の手順を参照してください。 完全なソースコードとセットアップおよび実行の手順については、GitHub
で完全な例を参照してください。 この例で使用されているサービス
Amazon Comprehend
Amazon S3
Amazon Textract