

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Transformando arquivos de manifesto com vários rótulos do SageMaker AI Ground Truth
<a name="md-gt-cl-transform"></a>

Este tópico mostra como transformar um arquivo de manifesto com vários rótulos do Amazon SageMaker AI Ground Truth em um arquivo de manifesto no formato Amazon Rekognition Custom Labels. 

SageMaker Os arquivos de manifesto do AI Ground Truth para trabalhos com vários rótulos são formatados de forma diferente dos arquivos de manifesto no formato Amazon Rekognition Custom Labels. A classificação com vários rótulos ocorre quando uma imagem é classificada em um conjunto de classes, mas pode pertencer a várias classes ao mesmo tempo. Neste caso, a imagem pode ter potencialmente vários rótulos (vários rótulos), como *futebol* e *bola*.

Para obter informações sobre trabalhos com vários rótulos do SageMaker AI Ground Truth, consulte [Classificação de imagens (vários rótulos](https://docs.aws.amazon.com/sagemaker/latest/dg/sms-image-classification-multilabel.html)). Para obter informações sobre os arquivos de manifesto do Amazon Rekognition Custom Labels em formato de vários rótulos, consulte [Como adicionar vários rótulos em nível de imagem a uma imagem](md-create-manifest-file-classification.md#md-dataset-purpose-classification-multiple-labels).

## Obtendo o arquivo de manifesto para um trabalho do SageMaker AI Ground Truth
<a name="md-get-gt-manifest"></a>

O procedimento a seguir mostra como obter o arquivo manifesto de saída (`output.manifest`) para um trabalho do Amazon SageMaker AI Ground Truth. `output.manifest` será usado como entrada para o próximo procedimento.

**Para baixar um arquivo de manifesto de trabalho do SageMaker AI Ground Truth**

1. Abra a [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/). 

1. No painel de navegação, escolha **Ground Truth** e escolha **Labeling Jobs**. 

1. Escolha o trabalho de rotulagem que contém o arquivo de manifesto que você deseja usar.

1. Na página de detalhes, escolha o link em **Local do conjunto de dados de saída**. O console do Amazon S3 é aberto no local do conjunto de dados. 

1. Escolha `Manifests`, `output` e depois `output.manifest`.

1. Escolha **Ações de objeto** e escolha **Download** para baixar o arquivo de manifesto.

## Transformação de um arquivo de manifesto de SageMaker IA com vários rótulos
<a name="md-transform-ml-gt"></a>

O procedimento a seguir cria um arquivo de manifesto Amazon Rekognition Custom Labels no formato de vários rótulos a partir de um arquivo de manifesto AI existente no formato de vários rótulos. SageMaker GroundTruth

**nota**  
Para executar o código, você precisa do Python versão 3 ou superior.<a name="md-procedure-multi-label-transform"></a>

**Para transformar um arquivo de manifesto de SageMaker IA com vários rótulos**

1. Execute o código em Python a seguir. Forneça o nome do arquivo de manifesto criado em [Obtendo o arquivo de manifesto para um trabalho do SageMaker AI Ground Truth](#md-get-gt-manifest) como um argumento da linha de comando.

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier:  Apache-2.0
   """
   Purpose
   Shows how to create and Amazon Rekognition Custom Labels format
   manifest file from an Amazon SageMaker Ground Truth Image
   Classification (Multi-label) format manifest file.
   """
   import json
   import logging
   import argparse
   import os.path
   
   logger = logging.getLogger(__name__)
   
   def create_manifest_file(ground_truth_manifest_file):
       """
       Creates an Amazon Rekognition Custom Labels format manifest file from
       an Amazon SageMaker Ground Truth Image Classification (Multi-label) format
       manifest file.
       :param: ground_truth_manifest_file: The name of the Ground Truth manifest file,
       including the relative path.
       :return: The name of the new Custom Labels manifest file.
       """
   
       logger.info('Creating manifest file from %s', ground_truth_manifest_file)
       new_manifest_file = f'custom_labels_{os.path.basename(ground_truth_manifest_file)}'
   
       # Read the SageMaker Ground Truth manifest file into memory.
       with open(ground_truth_manifest_file) as gt_file:
           lines = gt_file.readlines()
   
       #Iterate through the lines one at a time to generate the
       #new lines for the Custom Labels manifest file.
       with open(new_manifest_file, 'w') as the_new_file:
           for line in lines:
               #job_name - The of the Amazon Sagemaker Ground Truth job.
               job_name = ''
               # Load in the old json item from the Ground Truth manifest file
               old_json = json.loads(line)
   
               # Get the job name
               keys = old_json.keys()
               for key in keys:
                   if 'source-ref' not in key and '-metadata' not in key:
                       job_name = key
   
               new_json = {}
               # Set the location of the image
               new_json['source-ref'] = old_json['source-ref']
   
               # Temporarily store the list of labels
               labels = old_json[job_name]
   
               # Iterate through the labels and reformat to Custom Labels format
               for index, label in enumerate(labels):
                   new_json[f'{job_name}{index}'] = index
                   metadata = {}
                   metadata['class-name'] = old_json[f'{job_name}-metadata']['class-map'][str(label)]
                   metadata['confidence'] = old_json[f'{job_name}-metadata']['confidence-map'][str(label)]
                   metadata['type'] = 'groundtruth/image-classification'
                   metadata['job-name'] = old_json[f'{job_name}-metadata']['job-name']
                   metadata['human-annotated'] = old_json[f'{job_name}-metadata']['human-annotated']
                   metadata['creation-date'] = old_json[f'{job_name}-metadata']['creation-date']
                   # Add the metadata to new json line
                   new_json[f'{job_name}{index}-metadata'] = metadata
               # Write the current line to the json file
               the_new_file.write(json.dumps(new_json))
               the_new_file.write('\n')
   
       logger.info('Created %s', new_manifest_file)
       return  new_manifest_file
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "manifest_file", help="The Amazon SageMaker Ground Truth manifest file"
           "that you want to use."
       )
   
   
   def main():
       logging.basicConfig(level=logging.INFO,
                           format="%(levelname)s: %(message)s")
       try:
           # get command line arguments
           parser = argparse.ArgumentParser(usage=argparse.SUPPRESS)
           add_arguments(parser)
           args = parser.parse_args()
           # Create the manifest file
           manifest_file = create_manifest_file(args.manifest_file)
           print(f'Manifest file created: {manifest_file}')
       except FileNotFoundError as err:
           logger.exception('File not found: %s', err)
           print(f'File not found: {err}. Check your manifest file.')
   
   if __name__ == "__main__":
       main()
   ```

1. Observe o nome do novo arquivo de manifesto exibido pelo script. Ele será usado na próxima etapa.

1. [Faça upload dos arquivos de manifesto](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html) para o bucket do Amazon S3 que você deseja usar para armazenar o arquivo de manifesto.
**nota**  
Certifique-se de que o Amazon Rekognition Custom Labels tenha acesso ao bucket do Amazon S3 referenciado no campo `source-ref` das linhas JSON do arquivo de manifesto. Para obter mais informações, consulte [Como acessar os buckets externos do Amazon S3](su-console-policy.md#su-external-buckets). Se seu trabalho do Ground Truth armazena imagens no bucket do console do Amazon Rekognition Custom Labels, você não precisa adicionar permissões.

1. Siga as instruções em [Criação de um conjunto de dados com um arquivo de manifesto do SageMaker AI Ground Truth (console)](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-console) para criar um conjunto de dados com o arquivo de manifesto carregado. Para a etapa 8, na **localização do arquivo .manifest**, insira a URL do Amazon S3 para a localização do arquivo de manifesto. Se estiver usando o AWS SDK, use [Criação de um conjunto de dados com um arquivo de manifesto (SDK) do SageMaker AI Ground Truth](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-sdk).