쿠키 기본 설정 선택

당사는 사이트와 서비스를 제공하는 데 필요한 필수 쿠키 및 유사한 도구를 사용합니다. 고객이 사이트를 어떻게 사용하는지 파악하고 개선할 수 있도록 성능 쿠키를 사용해 익명의 통계를 수집합니다. 필수 쿠키는 비활성화할 수 없지만 '사용자 지정' 또는 ‘거부’를 클릭하여 성능 쿠키를 거부할 수 있습니다.

사용자가 동의하는 경우 AWS와 승인된 제3자도 쿠키를 사용하여 유용한 사이트 기능을 제공하고, 사용자의 기본 설정을 기억하고, 관련 광고를 비롯한 관련 콘텐츠를 표시합니다. 필수가 아닌 모든 쿠키를 수락하거나 거부하려면 ‘수락’ 또는 ‘거부’를 클릭하세요. 더 자세한 내용을 선택하려면 ‘사용자 정의’를 클릭하세요.

SDK for Python (Boto3)을 사용한 Amazon Textract 예제 - AWS SDK 코드 예제

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. AWS

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. AWS

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

SDK for Python (Boto3)을 사용한 Amazon Textract 예제

다음 코드 예제에서는 Amazon Textract와 AWS SDK for Python (Boto3) 함께를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 관련 시나리오의 컨텍스트에 따라 표시되며, 개별 서비스 함수를 직접적으로 호출하는 방법을 보여줍니다.

시나리오는 동일한 서비스 내에서 또는 다른 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를 참조하십시오.

다음 코드 예시에서는 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를 참조하십시오.

다음 코드 예시에서는 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를 참조하십시오.

다음 코드 예시에서는 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를 참조하십시오.

다음 코드 예시에서는 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

다음 코드 예시에서는 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

시나리오

다음 코드 예제는 대화형 애플리케이션을 통해 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 S3

  • Amazon SNS

  • Amazon SQS

  • Amazon Textract

다음 코드 예제는 대화형 애플리케이션을 통해 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 S3

  • Amazon SNS

  • Amazon SQS

  • Amazon Textract

다음 코드 예제에서는 Amazon Comprehend를 사용하여 Amazon S3에 저장된 이미지에서 Amazon Textract를 통해 추출한 텍스트의 엔터티를 감지하는 방법을 보여줍니다.

SDK for Python(Boto3)

Jupyter 노트북 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

다음 코드 예제에서는 Amazon Comprehend를 사용하여 Amazon S3에 저장된 이미지에서 Amazon Textract를 통해 추출한 텍스트의 엔터티를 감지하는 방법을 보여줍니다.

SDK for Python(Boto3)

Jupyter 노트북 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

프라이버시사이트 이용 약관쿠키 기본 설정
© 2025, Amazon Web Services, Inc. 또는 계열사. All rights reserved.