Tutorial: nozioni di base sull'uso dell'API di Amazon A2I - Amazon SageMaker

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Tutorial: nozioni di base sull'uso dell'API di Amazon A2I

Questo tutorial spiega le operazioni API che è possibile utilizzare per iniziare a usare Amazon A2I.

Per utilizzare un Jupyter Notebook per eseguire queste operazioni, seleziona un Jupyter Notebook da Casi d'uso ed esempi con Amazon A2I e usalo Usa un'istanza SageMaker Notebook con Amazon A2I Jupyter Notebook per imparare a usarlo in un'istanza di notebook. SageMaker

Per ulteriori informazioni sulle operazioni API che è possibile utilizzare con Amazon A2I, consulta Utilizzo di API in IA aumentata Amazon.

Creare di una team di lavoro privato

È possibile creare un team di lavoro privato e aggiungersi come worker in modo da visualizzare in anteprima Amazon A2I.

Se non conosci Amazon Cognito, ti consigliamo di utilizzare la SageMaker console per creare una forza lavoro privata e aggiungerti come lavoratore privato. Per istruzioni, consulta Fase 1: creare un team di lavoro.

Se conosci Amazon Cognito, puoi utilizzare le seguenti istruzioni per creare un team di lavoro privato utilizzando l' SageMaker API. Dopo aver creato un team di lavoro, annota l'ARN del team di lavoro (WorkteamArn).

Per ulteriori informazioni sulla forza lavoro privata e su altre configurazioni disponibili, consulta Utilizzo di una forza lavoro privata.

Creazione di una forza lavoro privata

Se non hai creato una forza lavoro privata, puoi farlo utilizzando un pool di utenti Amazon Cognito. Assicurati di esserti aggiunto a questo pool di utenti. Puoi creare un team di lavoro privato utilizzando la AWS SDK for Python (Boto3) create_workforce funzione. Per gli SDK specifici per altre lingue, consulta l'elenco in. CreateWorkforce

response = client.create_workforce( CognitoConfig={ "UserPool": "Pool_ID", "ClientId": "app-client-id" }, WorkforceName="workforce-name" )
Creare una forza lavoro privata

Dopo aver creato una forza lavoro privata nella AWS Regione per configurare e avviare il ciclo umano, puoi creare un team di lavoro privato utilizzando questa funzione. AWS SDK for Python (Boto3) create_workteam Per gli SDK specifici in altre lingue, consulta l'elenco in 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" }, } ] )

Accedi all'ARN del team di lavoro come segue:

workteamArn = response["WorkteamArn"]
Elenca i team di lavoro privati nel tuo account

Se hai già creato un team di lavoro privato, puoi elencare tutti i team di lavoro di una determinata AWS regione nel tuo account utilizzando la AWS SDK for Python (Boto3) list_workteams funzione. Per gli SDK specifici in altre lingue, consulta l'elenco in ListWorkteams.

response = client.list_workteams()

Se nel tuo account sono presenti numerosi team di lavoro, potresti voler utilizzare MaxResults, SortBy e NameContains per filtrare i risultati.

Creare un flusso di lavoro di revisione umana

È possibile creare un flusso di lavoro di revisione umana utilizzando l'operazione Amazon A2I CreateFlowDefinition. Prima di creare il flusso di lavoro di revisione umana, crea un'interfaccia utente delle attività umane. È possibile farlo con l'operazione CreateHumanTaskUi.

Se utilizzi Amazon A2I con le integrazioni Amazon Textract o Amazon Rekognition, puoi specificare le condizioni di attivazione utilizzando un JSON.

Creazione di un'interfaccia utente per attività umana

Se stai creando un flusso di lavoro di revisione umana da utilizzare con le integrazioni Amazon Textract o Amazon Rekognition, devi utilizzare e modificare un modello di attività del worker predefinito. Per tutte le integrazioni personalizzate, è possibile utilizzare il proprio modello di attività del worker personalizzato. Utilizza la tabella seguente per scoprire come creare un'interfaccia utente per attività umane utilizzando un modello di attività del worker per le due integrazioni incorporate. Sostituisci il modello con il tuo per personalizzare questa richiesta.

Amazon Textract – Key-value pair extraction

Per ulteriori informazioni sui modelli, vedere Esempio di modello personalizzato per 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

Per ulteriori informazioni sui modelli, vedere Esempio di modello personalizzato per 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

Di seguito è riportato un modello di esempio che può essere utilizzato in un'integrazione personalizzata. Questo modello viene utilizzato in questo notebook e dimostra un'integrazione personalizzata con 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> """

Utilizzando il modello sopra specificato, è possibile creare un modello utilizzando la AWS SDK for Python (Boto3) create_human_task_ui funzione. Per gli SDK specifici in altre lingue, consulta l'elenco in CreateHumanTaskUi.

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

Questo elemento di risposta contiene l'ARN dell'interfaccia utente dell'attività umana. Salva questo come segue:

humanTaskUiArn = response["HumanTaskUiArn"]

Crea JSON per specificare le condizioni di attivazione

Per le integrazioni incorporate di Amazon Textract e Amazon Rekognition, è possibile salvare le condizioni di attivazione in un oggetto JSON e utilizzarle nella propria richiesta CreateFlowDefinition.

Successivamente, seleziona una scheda per visualizzare esempi di condizioni di attivazione che puoi utilizzare per queste integrazioni incorporate. Per maggiori informazioni sulle opzioni di condizione attivazione, vedere Schema JSON per condizioni attivazione del ciclo umano in Amazon Augmented AI.

Amazon Textract – Key-value pair extraction

Questo esempio specifica le condizioni per chiavi specifiche (ad esempio Mail address) del documento. Se l'attendibilità di Amazon Textract non supera le soglie stabilite qui, il documento viene inviato a un operatore per la revisione, con le chiavi specifiche che hanno avviato il ciclo umano richieste al worker.

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

Le condizioni di attivazione del ciclo umano qui utilizzate sono personalizzate per la moderazione dei contenuti di Amazon Rekognition e si basano sulle soglie di l'attendibilità delle etichette di moderazione Suggestive Female 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 } } ] } ] } )

Creare un flusso di lavoro di revisione umana

Questa sezione fornisce un esempio della CreateFlowDefinition AWS SDK for Python (Boto3) richiesta che utilizza le risorse create nelle sezioni precedenti. Per gli SDK specifici per altre lingue, consulta l'elenco in Definizione. CreateFlow Utilizza le schede nella tabella seguente per visualizzare le richieste di creazione di un flusso di lavoro di revisione umana delle integrazioni incorporate di Amazon Textract e Amazon Rekognition.

Amazon Textract – Key-value pair extraction

Se utilizzi l'integrazione incorporata con Amazon Textract, devi specificare "AWS/Textract/AnalyzeDocument/Forms/V1" per "AwsManagedHumanLoopRequestSource" in HumanLoopRequestSource.

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://DOC-EXAMPLE-BUCKET/prefix/", }, RoleArn="arn:aws:iam::<account-number>:role/<role-name>", Tags=[ { "Key": "string", "Value": "string" }, ] )
Amazon Rekognition – Image moderation

Se utilizzi l'integrazione incorporata con Amazon Rekognition, devi specificare "AWS/Rekognition/DetectModerationLabels/Image/V3" per "AwsManagedHumanLoopRequestSource" in HumanLoopRequestSource.

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://DOC-EXAMPLE-BUCKET/prefix/", }, RoleArn="arn:aws:iam::<account-number>:role/<role-name>", Tags=[ { "Key": "string", "Value": "string" }, ] )
Custom Integration

Se utilizzi un'integrazione personalizzata, escludi i seguenti parametri: 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://DOC-EXAMPLE-BUCKET/prefix/", }, RoleArn="arn:aws:iam::<account-number>:role/<role-name>", Tags=[ { "Key": "string", "Value": "string" }, ] )

Dopo aver creato un flusso di lavoro di revisione umana, è possibile recuperare l'ARN della definizione del flusso dalla risposta:

humanReviewWorkflowArn = response["FlowDefinitionArn"]

Creazione di un ciclo umano

L'operazione API utilizzata per avviare un ciclo umano dipende dall'integrazione Amazon A2I utilizzata.

Seleziona il tipo di attività nella tabella seguente per visualizzare esempi di richieste per Amazon Textract e Amazon Rekognition utilizzando il AWS SDK for Python (Boto3).

Amazon Textract – Key-value pair extraction

L'esempio seguente utilizza AWS SDK for Python (Boto3) to call analyze_document us-west-2. Sostituisci il testo in rosso in corsivo con le tue risorse. Includi il parametro DataAttributes solo se utilizzi la forza lavoro di Amazon Mechanical Turk. Per ulteriori informazioni, consulta la documentazione analyze_document in API Reference AWS SDK for Python (Boto) .

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"] )

I cicli umani vengono creati solo se l'attendibilità di Amazon Textract per l'attività di analisi dei documenti soddisfa le condizioni di attivazione specificate nel flusso di lavoro di revisione umana. È possibile controllare l'elemento response per determinare se è stato creato un ciclo umano. Per vedere tutto ciò che è incluso in questa risposta, consulta 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

L'esempio seguente utilizza AWS SDK for Python (Boto3) to call detect_moderation_labels us-west-2. Sostituisci il testo in rosso in corsivo con le tue risorse. Includi il parametro DataAttributes solo se utilizzi la forza lavoro di Amazon Mechanical Turk. Per ulteriori informazioni, consulta la documentazione detect_moderation_labels in API Reference AWS SDK for Python (Boto) .

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"]} } )

I cicli umani vengono creati solo se l'attendibilità di Amazon Rekognition per un'attività di moderazione delle immagini soddisfa le condizioni di attivazione specificate nel flusso di lavoro della revisione umana. È possibile controllare l'elemento response per determinare se è stato creato un ciclo umano. Per vedere tutto ciò che è incluso in questa risposta, consulta 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

L'esempio seguente utilizza AWS SDK for Python (Boto3) to call start_human_loop us-west-2. Sostituisci il testo in rosso in corsivo con le tue risorse. Includi il parametro DataAttributes solo se utilizzi la forza lavoro di Amazon Mechanical Turk. Per ulteriori informazioni, consulta la documentazione start_human_loop in AWS SDK for Python (Boto) API Reference.

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"]} )

Questo esempio memorizza il contenuto di input nella variabile inputContentJson. Supponiamo che il contenuto di input contenga due elementi: un blurb di testo e un sentiment (come Positive,Negative o Neutral) e che sia formattato come segue:

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

Le chiavi initialValue e taskObject devono corrispondere alle chiavi utilizzate negli elementi liquidi del modello di attività del worker. Fai riferimento al modello personalizzato in Creazione di un'interfaccia utente per attività umana per vedere un esempio.

Per creare un inputContentJson, procedere come descritto qui di seguito:

import json inputContentJson = json.dumps(inputContent)

Ogni volta che chiami start_human_loop si avvia un ciclo umano. Per controllare lo stato del tuo ciclo umano, usa descrivi_ciclo_umano:

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