

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à.

# Trasformazione dei file manifest multietichetta di SageMaker AI Ground Truth
<a name="md-gt-cl-transform"></a>

Questo argomento mostra come trasformare un file manifest multietichetta di Amazon SageMaker AI Ground Truth in un file manifest in formato Amazon Rekognition Custom Labels. 

SageMaker I file manifest AI Ground Truth per lavori con più etichette sono formattati in modo diverso rispetto ai file manifest in formato Amazon Rekognition Custom Labels. La classificazione multietichetta si verifica quando un'immagine viene classificata in un insieme di classi, ma può appartenere a più di una contemporaneamente. In questo caso, l'immagine può potenzialmente avere più etichette (etichetta multipla), come *calcio* e *palla*.

Per informazioni sui lavori multietichetta di SageMaker AI Ground Truth, vedi [Image Classification (Multi-label](https://docs.aws.amazon.com/sagemaker/latest/dg/sms-image-classification-multilabel.html)). Per informazioni sui file manifest di Amazon Rekognition Custom Labels in formato multietichetta, consultare [Aggiungere più etichette a livello di immagine a un'immagine](md-create-manifest-file-classification.md#md-dataset-purpose-classification-multiple-labels).

## Ottenere il file manifest per un lavoro SageMaker AI Ground Truth
<a name="md-get-gt-manifest"></a>

La procedura seguente mostra come ottenere il file manifest di output (`output.manifest`) per un job Amazon SageMaker AI Ground Truth. Usare `output.manifest` come input per la prossima procedura.

**Per scaricare un file di manifesto del lavoro di SageMaker AI Ground Truth**

1. Apri la [https://console.aws.amazon.com/sagemaker/](https://console.aws.amazon.com/sagemaker/). 

1. Nel riquadro di navigazione, scegliere **Ground Truth**, quindi scegli **Labeling Jobs**. 

1. Selezionare il processo di etichettatura che contiene il file manifest da utilizzare.

1. Nella pagina dei dettagli, scegliere il collegamento in **Posizione del set di dati di output**. La console Amazon S3 si apre nella posizione del set di dati. 

1. Scegliere `Manifests`, `output` e poi `output.manifest`.

1. Per scaricare il file manifest, scegliere **Azioni oggetto** e poi **Scaricare**.

## Trasformazione di un file manifest SageMaker AI multietichetta
<a name="md-transform-ml-gt"></a>

La procedura seguente crea un file manifest Amazon Rekognition Custom Labels in formato multietichetta da un file manifest AI in formato multietichetta esistente. SageMaker GroundTruth

**Nota**  
Per eseguire il codice, è necessaria la versione 3 di Python o quella successiva.<a name="md-procedure-multi-label-transform"></a>

**Per trasformare un file manifest AI multietichetta SageMaker**

1. Utilizzare il seguente codice Python. Specificare il nome del file manifest creato [Ottenere il file manifest per un lavoro SageMaker AI Ground Truth](#md-get-gt-manifest) come argomento della riga di 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. Annotare il nome del nuovo file manifesto visualizzato dallo script. Verrà usato nel prossimo passaggio.

1. [Carica i file manifest](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html) nel bucket Amazon S3 che si desidera utilizzare per archiviare il file manifest.
**Nota**  
Assicurarsi che Amazon Rekognition Custom Labels abbia accesso al bucket Amazon S3 a cui si fa riferimento nel campo `source-ref` delle righe JSON del file manifest. Per ulteriori informazioni, consulta [Accesso a bucket Amazon S3 esterni](su-console-policy.md#su-external-buckets). Se il lavoro Ground Truth memorizza immagini nel bucket della console Amazon Rekognition Custom Labels, non è necessario aggiungere autorizzazioni.

1. Seguire le istruzioni riportate in [Creazione di un set di dati con un file manifest SageMaker AI Ground Truth (Console)](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-console) per creare un set di dati con il file manifest caricato. Per il passaggio 8, in **posizione del file.manifest**, inserire l'URL di Amazon S3 per la posizione del file manifest. Se si usa l' AWS SDK, fare [Creazione di un set di dati con un file manifest SageMaker AI Ground Truth (SDK)](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-sdk).