튜토리얼: Amazon A2I 사용 시작하기 API - 아마존 SageMaker

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

튜토리얼: Amazon A2I 사용 시작하기 API

이 자습서에서는 Amazon A2I 사용을 시작하는 데 사용할 수 있는 API 작업을 설명합니다.

Jupyter Notebook을 사용하여 이러한 작업을 실행하려면 에서 Jupyter Notebook을 선택하고 Amazon A2I Jupyter 노트북과 함께 SageMaker 노트북 인스턴스 사용 이를 사용하여 노트북 인스턴스에서 Amazon A2I를 사용한 사용 사례 및 예제 사용하는 방법을 알아보십시오. SageMaker

Amazon A2I에서 사용할 수 있는 API 작업에 대한 자세한 내용은 을 참조하십시오. Amazon Augmented AI에서 API 사용

프라이빗 작업 인력 생성

프라이빗 작업 팀을 만들고 자신을 작업자로 추가하여 Amazon A2I를 미리 볼 수 있습니다.

Amazon Cognito에 익숙하지 않은 경우 SageMaker 콘솔을 사용하여 개인 인력을 생성하고 자신을 개인 작업자로 추가하는 것이 좋습니다. 지침은 1단계: 작업 팀 생성 단원을 참조하십시오.

Amazon Cognito에 익숙하다면 다음 지침에 따라 를 사용하여 프라이빗 작업 팀을 만들 수 있습니다. SageMaker API 작업 팀을 만든 후에는 작업 팀 ARN (WorkteamArn) 을 기록해 둡니다.

프라이빗 작업 인력 및 기타 사용 가능한 구성에 대한 자세한 정보는 프라이빗 작업 인력 사용 섹션을 참조하세요.

프라이빗 작업 인력 생성

프라이빗 작업 인력을 생성하지 않은 경우 Amazon Cognito 사용자 풀을 사용하여 생성할 수 있습니다. 이 사용자 풀에 자신을 추가해야 합니다. AWS SDK for Python (Boto3) create_workforce함수를 사용하여 비공개 작업팀을 만들 수 있습니다. 다른 언어별 SDKs 정보는 의 목록을 참조하십시오. CreateWorkforce

response = client.create_workforce( CognitoConfig={ "UserPool": "Pool_ID", "ClientId": "app-client-id" }, WorkforceName="workforce-name" )
프라이빗 작업 팀 생성

AWS 지역에 휴먼 루프를 구성하고 시작할 수 있는 개인 인력을 만든 후 함수를 사용하여 개인 작업 팀을 만들 수 있습니다. AWS SDK for Python (Boto3) create_workteam 다른 언어별 SDKs 정보는 의 목록을 참조하십시오. CreateWorkteam

response = client.create_workteam( WorkteamName="work-team-name", WorkforceName= "workforce-name", MemberDefinitions=[ { "CognitoMemberDefinition": { "UserPool": "<aws-region>_ID", "UserGroup": "user-group", "ClientId": "app-client-id" }, } ] )

ARN다음과 같이 작업 팀에 액세스하십시오.

workteamArn = response["WorkteamArn"]
계정의 프라이빗 작업 팀을 나열하세요.

이미 비공개 작업팀을 만든 경우 AWS SDK for Python (Boto3) list_workteams 함수를 사용하여 계정의 특정 AWS 지역에 있는 모든 작업팀을 나열할 수 있습니다. 다른 언어별 SDKs 정보는 의 목록을 참조하십시오. ListWorkteams

response = client.list_workteams()

계정에 작업 팀이 많으면 MaxResults, SortByNameContains를 사용하여 결과를 필터링하는 것이 좋습니다.

인적 검토 워크플로 생성

Amazon A2I CreateFlowDefinition 작업을 사용하여 인적 검토 워크플로를 생성할 수 있습니다. 인적 검토 워크플로를 생성하려면 먼저 인적 태스크 UI를 생성해야 합니다. CreateHumanTaskUi 작업을 사용하면 됩니다.

Amazon Textract 또는 Amazon Rekognition 통합과 함께 Amazon A2I를 사용하는 경우 a를 사용하여 활성화 조건을 지정할 수 있습니다. JSON

인적 태스크 UI 생성

Amazon Textract 또는 Amazon Rekognition 통합과 함께 사용할 인적 검토 워크플로를 생성하는 경우 미리 만들어진 작업자 태스크 템플릿을 사용하고 수정해야 합니다. 모든 사용자 지정 통합에는 자체 사용자 지정 작업자 태스크 템플릿을 사용할 수 있습니다. 다음 테이블을 참조하여 두 가지 내장된 통합을 위한 작업자 태스크 템플릿을 사용하여 인적 태스크 UI를 만드는 방법을 알아보세요. 템플릿을 자체 템플릿으로 교체하여 이 요청을 사용자 지정하세요.

Amazon Textract – Key-value pair extraction

이 템플릿에 대한 자세한 내용은 Amazon Textract에 사용되는 사용자 지정 템플릿 예제 섹션을 참조하세요.

template = r""" <script src="https://assets.crowd.aws/crowd-html-elements.js"></script> {% capture s3_uri %}http://s3.amazonaws.com/{{ task.input.aiServiceRequest.document.s3Object.bucket }}/{{ task.input.aiServiceRequest.document.s3Object.name }}{% endcapture %} <crowd-form> <crowd-textract-analyze-document src="{{ s3_uri | grant_read_access }}" initial-value="{{ task.input.selectedAiServiceResponse.blocks }}" header="Review the key-value pairs listed on the right and correct them if they don"t match the following document." no-key-edit="" no-geometry-edit="" keys="{{ task.input.humanLoopContext.importantFormKeys }}" block-types='["KEY_VALUE_SET"]'> <short-instructions header="Instructions"> <p>Click on a key-value block to highlight the corresponding key-value pair in the document. </p><p><br></p> <p>If it is a valid key-value pair, review the content for the value. If the content is incorrect, correct it. </p><p><br></p> <p>The text of the value is incorrect, correct it.</p> <p><img src="https://assets.crowd.aws/images/a2i-console/correct-value-text.png"> </p><p><br></p> <p>A wrong value is identified, correct it.</p> <p><img src="https://assets.crowd.aws/images/a2i-console/correct-value.png"> </p><p><br></p> <p>If it is not a valid key-value relationship, choose No.</p> <p><img src="https://assets.crowd.aws/images/a2i-console/not-a-key-value-pair.png"> </p><p><br></p> <p>If you can’t find the key in the document, choose Key not found.</p> <p><img src="https://assets.crowd.aws/images/a2i-console/key-is-not-found.png"> </p><p><br></p> <p>If the content of a field is empty, choose Value is blank.</p> <p><img src="https://assets.crowd.aws/images/a2i-console/value-is-blank.png"> </p><p><br></p> <p><strong>Examples</strong></p> <p>Key and value are often displayed next or below to each other. </p><p><br></p> <p>Key and value displayed in one line.</p> <p><img src="https://assets.crowd.aws/images/a2i-console/sample-key-value-pair-1.png"> </p><p><br></p> <p>Key and value displayed in two lines.</p> <p><img src="https://assets.crowd.aws/images/a2i-console/sample-key-value-pair-2.png"> </p><p><br></p> <p>If the content of the value has multiple lines, enter all the text without line break. Include all value text even if it extends beyond the highlight box.</p> <p><img src="https://assets.crowd.aws/images/a2i-console/multiple-lines.png"></p> </short-instructions> <full-instructions header="Instructions"></full-instructions> </crowd-textract-analyze-document> </crowd-form> """
Amazon Rekognition – Image moderation

이 템플릿에 대한 자세한 내용은 Amazon Rekognition에 사용되는 사용자 지정 템플릿 예제 섹션을 참조하세요.

template = r""" <script src="https://assets.crowd.aws/crowd-html-elements.js"></script> {% capture s3_uri %}http://s3.amazonaws.com/{{ task.input.aiServiceRequest.image.s3Object.bucket }}/{{ task.input.aiServiceRequest.image.s3Object.name }}{% endcapture %} <crowd-form> <crowd-rekognition-detect-moderation-labels categories='[ {% for label in task.input.selectedAiServiceResponse.moderationLabels %} { name: "{{ label.name }}", parentName: "{{ label.parentName }}", }, {% endfor %} ]' src="{{ s3_uri | grant_read_access }}" header="Review the image and choose all applicable categories." > <short-instructions header="Instructions"> <style> .instructions { white-space: pre-wrap; } </style> <p class="instructions">Review the image and choose all applicable categories. If no categories apply, choose None. <b>Nudity</b> Visuals depicting nude male or female person or persons <b>Partial Nudity</b> Visuals depicting covered up nudity, for example using hands or pose <b>Revealing Clothes</b> Visuals depicting revealing clothes and poses <b>Physical Violence</b> Visuals depicting violent physical assault, such as kicking or punching <b>Weapon Violence</b> Visuals depicting violence using weapons like firearms or blades, such as shooting <b>Weapons</b> Visuals depicting weapons like firearms and blades </short-instructions> <full-instructions header="Instructions"></full-instructions> </crowd-rekognition-detect-moderation-labels> </crowd-form>"""
Custom Integration

다음은 사용자 지정 통합에 사용할 수 있는 예제 템플릿입니다. 이 템플릿은 이 노트북에서 사용되며, Amazon Comprehend와의 사용자 지정 통합을 보여줍니다.

template = r""" <script src="https://assets.crowd.aws/crowd-html-elements.js"></script> <crowd-form> <crowd-classifier name="sentiment" categories='["Positive", "Negative", "Neutral", "Mixed"]' initial-value="{{ task.input.initialValue }}" header="What sentiment does this text convey?" > <classification-target> {{ task.input.taskObject }} </classification-target> <full-instructions header="Sentiment Analysis Instructions"> <p><strong>Positive</strong> sentiment include: joy, excitement, delight</p> <p><strong>Negative</strong> sentiment include: anger, sarcasm, anxiety</p> <p><strong>Neutral</strong>: neither positive or negative, such as stating a fact</p> <p><strong>Mixed</strong>: when the sentiment is mixed</p> </full-instructions> <short-instructions> Choose the primary sentiment that is expressed by the text. </short-instructions> </crowd-classifier> </crowd-form> """

위에 지정된 템플릿을 사용하여 함수를 사용하여 템플릿을 생성할 수 있습니다. AWS SDK for Python (Boto3) create_human_task_ui 다른 언어별 SDKs 정보는 의 목록을 참조하십시오. CreateHumanTaskUi

response = client.create_human_task_ui( HumanTaskUiName="human-task-ui-name", UiTemplate={ "Content": template } )

이 응답 요소에는 휴먼 태스크 UI가 포함되어 있습니다. ARN 다음과 같이 저장합니다.

humanTaskUiArn = response["HumanTaskUiArn"]

JSON생성하여 활성화 조건을 지정합니다.

Amazon Textract와 Amazon Rekognition 빌트인 통합의 경우 활성화 조건을 객체에 저장하여 요청에 사용할 수 있습니다. JSON CreateFlowDefinition

그런 다음 탭을 선택하여 이러한 내장 통합에 사용할 수 있는 예제 활성화 조건을 확인하세요. 활성화 조건 옵션에 대한 추가 정보는 Amazon 증강 AI의 인적 루프 활성화 조건에 대한 JSON 스키마 섹션을 참조하세요.

Amazon Textract – Key-value pair extraction

이 예제에서는 문서의 특정 키(예: Mail address)에 대한 조건을 지정합니다. Amazon Textract의 신뢰도가 여기에 설정된 임곗값을 벗어나는 경우, 문서는 인적 검토를 위해 전송되고 인적 루프를 시작한 특정 키가 작업자에게 전달됩니다.

import json humanLoopActivationConditions = json.dumps( { "Conditions": [ { "Or": [ { "ConditionType": "ImportantFormKeyConfidenceCheck", "ConditionParameters": { "ImportantFormKey": "Mail address", "ImportantFormKeyAliases": ["Mail Address:","Mail address:", "Mailing Add:","Mailing Addresses"], "KeyValueBlockConfidenceLessThan": 100, "WordBlockConfidenceLessThan": 100 } }, { "ConditionType": "MissingImportantFormKey", "ConditionParameters": { "ImportantFormKey": "Mail address", "ImportantFormKeyAliases": ["Mail Address:","Mail address:","Mailing Add:","Mailing Addresses"] } }, { "ConditionType": "ImportantFormKeyConfidenceCheck", "ConditionParameters": { "ImportantFormKey": "Phone Number", "ImportantFormKeyAliases": ["Phone number:", "Phone No.:", "Number:"], "KeyValueBlockConfidenceLessThan": 100, "WordBlockConfidenceLessThan": 100 } }, { "ConditionType": "ImportantFormKeyConfidenceCheck", "ConditionParameters": { "ImportantFormKey": "*", "KeyValueBlockConfidenceLessThan": 100, "WordBlockConfidenceLessThan": 100 } }, { "ConditionType": "ImportantFormKeyConfidenceCheck", "ConditionParameters": { "ImportantFormKey": "*", "KeyValueBlockConfidenceGreaterThan": 0, "WordBlockConfidenceGreaterThan": 0 } } ] } ] } )
Amazon Rekognition – Image moderation

여기에 사용되는 인적 루프 활성화 조건은 Amazon Rekognition 콘텐츠 조절에 맞게 조정되었습니다. 이 조건은 SuggestiveFemale Swimwear Or Underwear 조절 레이블의 신뢰도 임곗값을 기반으로 합니다.

import json humanLoopActivationConditions = json.dumps( { "Conditions": [ { "Or": [ { "ConditionType": "ModerationLabelConfidenceCheck", "ConditionParameters": { "ModerationLabelName": "Suggestive", "ConfidenceLessThan": 98 } }, { "ConditionType": "ModerationLabelConfidenceCheck", "ConditionParameters": { "ModerationLabelName": "Female Swimwear Or Underwear", "ConfidenceGreaterThan": 98 } } ] } ] } )

인적 검토 워크플로 생성

이 섹션에서는 이전 섹션에서 생성한 리소스를 사용한 CreateFlowDefinition AWS SDK for Python (Boto3) 요청의 예를 제공합니다. 다른 언어별 SDKs 정보는 의 목록을 참조하십시오. CreateFlowDefinition 다음 표의 탭을 사용하여 Amazon Textract와 Amazon Rekognition의 내장 통합을 위한 인적 검토 워크플로를 생성하기 위한 요청을 확인하세요.

Amazon Textract – Key-value pair extraction

Amazon Textract와의 내장 통합을 사용하는 경우 HumanLoopRequestSource에서 "AwsManagedHumanLoopRequestSource"에 대해 "AWS/Textract/AnalyzeDocument/Forms/V1"을 지정해야 합니다.

response = client.create_flow_definition( FlowDefinitionName="human-review-workflow-name", HumanLoopRequestSource={ "AwsManagedHumanLoopRequestSource": "AWS/Textract/AnalyzeDocument/Forms/V1" }, HumanLoopActivationConfig={ "HumanLoopActivationConditionsConfig": { "HumanLoopActivationConditions": humanLoopActivationConditions } }, HumanLoopConfig={ "WorkteamArn": workteamArn, "HumanTaskUiArn": humanTaskUiArn, "TaskTitle": "Document entry review", "TaskDescription": "Review the document and instructions. Complete the task", "TaskCount": 1, "TaskAvailabilityLifetimeInSeconds": 43200, "TaskTimeLimitInSeconds": 3600, "TaskKeywords": [ "document review", ], }, OutputConfig={ "S3OutputPath": "s3://amzn-s3-demo-bucket/prefix/", }, RoleArn="arn:aws:iam::<account-number>:role/<role-name>", Tags=[ { "Key": "string", "Value": "string" }, ] )
Amazon Rekognition – Image moderation

Amazon Rekognition과의 내장 통합을 사용하는 경우 HumanLoopRequestSource에서 "AwsManagedHumanLoopRequestSource"에 대해 "AWS/Rekognition/DetectModerationLabels/Image/V3"를 지정해야 합니다.

response = client.create_flow_definition( FlowDefinitionName="human-review-workflow-name", HumanLoopRequestSource={ "AwsManagedHumanLoopRequestSource": "AWS/Rekognition/DetectModerationLabels/Image/V3" }, HumanLoopActivationConfig={ "HumanLoopActivationConditionsConfig": { "HumanLoopActivationConditions": humanLoopActivationConditions } }, HumanLoopConfig={ "WorkteamArn": workteamArn, "HumanTaskUiArn": humanTaskUiArn, "TaskTitle": "Image content moderation", "TaskDescription": "Review the image and instructions. Complete the task", "TaskCount": 1, "TaskAvailabilityLifetimeInSeconds": 43200, "TaskTimeLimitInSeconds": 3600, "TaskKeywords": [ "content moderation", ], }, OutputConfig={ "S3OutputPath": "s3://amzn-s3-demo-bucket/prefix/", }, RoleArn="arn:aws:iam::<account-number>:role/<role-name>", Tags=[ { "Key": "string", "Value": "string" }, ] )
Custom Integration

사용자 지정 통합을 사용하는 경우, HumanLoopRequestSource, HumanLoopActivationConfig 파라미터를 제외하세요.

response = client.create_flow_definition( FlowDefinitionName="human-review-workflow-name", HumanLoopConfig={ "WorkteamArn": workteamArn, "HumanTaskUiArn": humanTaskUiArn, "TaskTitle": "Image content moderation", "TaskDescription": "Review the image and instructions. Complete the task", "TaskCount": 1, "TaskAvailabilityLifetimeInSeconds": 43200, "TaskTimeLimitInSeconds": 3600, "TaskKeywords": [ "content moderation", ], }, OutputConfig={ "S3OutputPath": "s3://amzn-s3-demo-bucket/prefix/", }, RoleArn="arn:aws:iam::<account-number>:role/<role-name>", Tags=[ { "Key": "string", "Value": "string" }, ] )

휴먼 리뷰 워크플로를 만든 후 ARN 응답에서 흐름 정의를 검색할 수 있습니다.

humanReviewWorkflowArn = response["FlowDefinitionArn"]

인적 루프 생성

휴먼 루프를 시작하는 데 사용하는 API 작업은 사용하는 Amazon A2I 통합에 따라 다릅니다.

  • Amazon Textract의 내장된 통합을 사용하는 경우 작업을 사용합니다. AnalyzeDocument

  • Amazon Rekognition의 내장된 통합 기능을 사용하는 경우 작업을 사용합니다. DetectModerationLabels

  • 사용자 지정 통합을 사용하는 경우 작업을 사용합니다. StartHumanLoop

다음 테이블에서 태스크 유형을 선택하면 AWS SDK for Python (Boto3)을 사용하는 Amazon Textract와 Amazon Rekognition에 대한 요청 예시를 볼 수 있습니다.

Amazon Textract – Key-value pair extraction

다음 analyze_document 예제에서는 AWS SDK for Python (Boto3) us-west-2를 호출하는 데 를 사용합니다. 기울임꼴로 표시된 빨간색 텍스트를 귀사의 리소스로 바꾸세요. Amazon Mechanical Turk 인력을 사용하는 경우 DataAttributes 파라미터를 포함하세요. 자세한 내용은 레퍼런스의 analyze_document 설명서를 참조하십시오.AWS SDK for Python (Boto) API

response = client.analyze_document( Document={"S3Object": {"Bucket": "AWSDOC-EXAMPLE-BUCKET", "Name": "document-name.pdf"}, HumanLoopConfig={ "FlowDefinitionArn":"arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name", "HumanLoopName":"human-loop-name", "DataAttributes" : {ContentClassifiers:["FreeOfPersonallyIdentifiableInformation"|"FreeOfAdultContent"]} } FeatureTypes=["FORMS"] )

인적 루프는 문서 분석 태스크에 대한 Amazon Textract의 신뢰도가 인적 검토 워크플로에 지정된 활성화 조건을 충족하는 경우에만 생성됩니다. response 요소를 검사하여 인적 루프가 생성되었는지 확인할 수 있습니다. 이 응답에 포함된 모든 내용을 보려면 HumanLoopActivationOutput 섹션을 참조하세요.

if "HumanLoopArn" in analyzeDocumentResponse["HumanLoopActivationOutput"]: # A human loop has been started! print(f"A human loop has been started with ARN: {analyzeDocumentResponse["HumanLoopActivationOutput"]["HumanLoopArn"]}"
Amazon Rekognition – Image moderation

다음 detect_moderation_labels 예제에서는 AWS SDK for Python (Boto3) us-west-2를 호출하는 데 를 사용합니다. 기울임꼴로 표시된 빨간색 텍스트를 귀사의 리소스로 바꾸세요. Amazon Mechanical Turk 인력을 사용하는 경우 DataAttributes 파라미터를 포함하세요. 자세한 내용은 레퍼런스의 detect_moderation_labels 문서를 참조하십시오.AWS SDK for Python (Boto) API

response = client.detect_moderation_labels( Image={"S3Object":{"Bucket": "AWSDOC-EXAMPLE-BUCKET", "Name": "image-name.png"}}, HumanLoopConfig={ "FlowDefinitionArn":"arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name", "HumanLoopName":"human-loop-name", "DataAttributes":{ContentClassifiers:["FreeOfPersonallyIdentifiableInformation"|"FreeOfAdultContent"]} } )

인적 루프는 이미지 조절 태스크에 대한 Amazon Rekognition의 신뢰도가 인적 검토 워크플로에 지정된 활성화 조건을 충족하는 경우에만 생성됩니다. response 요소를 검사하여 인적 루프가 생성되었는지 확인할 수 있습니다. 이 응답에 포함된 모든 내용을 보려면 HumanLoopActivationOutput 섹션을 참조하세요.

if "HumanLoopArn" in response["HumanLoopActivationOutput"]: # A human loop has been started! print(f"A human loop has been started with ARN: {response["HumanLoopActivationOutput"]["HumanLoopArn"]}")
Custom Integration

다음 start_human_loop 예제에서는 AWS SDK for Python (Boto3) us-west-2를 호출하는 데 를 사용합니다. 기울임꼴로 표시된 빨간색 텍스트를 귀사의 리소스로 바꾸세요. Amazon Mechanical Turk 인력을 사용하는 경우 DataAttributes 파라미터를 포함하세요. 자세한 내용은 레퍼런스의 start_human_loop 문서를 참조하십시오.AWS SDK for Python (Boto) API

response = client.start_human_loop( HumanLoopName= "human-loop-name", FlowDefinitionArn= "arn:aws:sagemaker:us-west-2:111122223333:flow-definition/flow-definition-name", HumanLoopInput={"InputContent": inputContentJson}, DataAttributes={"ContentClassifiers":["FreeOfPersonallyIdentifiableInformation"|"FreeOfAdultContent"]} )

이 예제에서는 입력 내용을 변수에 저장합니다.inputContentJson. 입력 콘텐츠에 텍스트 안내문과 센티멘트 (예: PositiveNegative, 또는Neutral) 라는 두 요소가 포함되어 있고 형식이 다음과 같다고 가정해 보겠습니다.

inputContent = { "initialValue": sentiment, "taskObject": blurb }

initialValuetaskObject 키는 작업자 태스크 템플릿의 리퀴드 요소에 사용되는 키와 일치해야 합니다. 예를 보려면 인적 태스크 UI 생성의 사용자 지정 템플릿을 참조하세요.

inputContentJson을 생성하려면 다음을 수행합니다.

import json inputContentJson = json.dumps(inputContent)

start_human_loop를 호출할 때마다 인적 루프가 시작됩니다. 인적 루프의 상태를 확인하려면 describe_human_loop를 사용하세요.

human_loop_info = a2i.describe_human_loop(HumanLoopName="human_loop_name") print(f"HumanLoop Status: {resp["HumanLoopStatus"]}") print(f"HumanLoop Output Destination: {resp["HumanLoopOutput"]}")