

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

# Creare un file manifest da CSV
<a name="ex-csv-manifest"></a>

Questo esempio di script Python semplifica la creazione di un file manifest utilizzando un file CSV (Comma Separated Values) per etichettare le immagini. Creare il file CSV. Il file manifest è adatto per la [classificazione di immagini multietichetta](getting-started.md#gs-multi-label-image-classification-example) o [Classificazione delle immagini multietichetta](getting-started.md#gs-multi-label-image-classification-example). Per ulteriori informazioni, consulta [Trova oggetti, scene e concetti](understanding-custom-labels.md#tm-classification). 

**Nota**  
Questo script non crea un file manifest adatto alla ricerca di [posizioni di oggetti](understanding-custom-labels.md#tm-object-localization) o di [posizione marchi](understanding-custom-labels.md#tm-brand-detection-localization).

Un file manifest descrive le immagini utilizzate per addestrare un modello. Ad esempio, le posizioni delle immagini e le etichette assegnate alle immagini. Un file manifest è costituito da una o più righe JSON. Ogni riga JSON descrive una singola immagine. Per ulteriori informazioni, consulta [Importazione di etichette a livello di immagine nei file manifest](md-create-manifest-file-classification.md).

Un file CSV rappresenta dati tabulari su più righe in un file di testo. I campi in una riga sono separati da una virgola. Per ulteriori informazioni, consulta [valori separati da virgola](https://en.wikipedia.org/wiki/Comma-separated_values). Per questo script, ogni riga del file CSV rappresenta una singola immagine ed è mappata a una riga JSON nel file manifest. Per creare un file CSV per un file manifest che supporti la [classificazione delle immagini multietichetta](getting-started.md#gs-multi-label-image-classification-example), aggiungere una o più etichette a livello di immagine in ciascuna riga. Per creare un file manifest adatto a [Classificazione delle immagini](getting-started.md#gs-image-classification-example), aggiungere una singola etichetta a livello di immagine in ciascuna riga.

Ad esempio, il seguente file CSV descrive le immagini del progetto [Classificazione delle immagini multietichetta](getting-started.md#gs-multi-label-image-classification-example) (Flowers) *Getting started*. 

```
camellia1.jpg,camellia,with_leaves
camellia2.jpg,camellia,with_leaves
camellia3.jpg,camellia,without_leaves
helleborus1.jpg,helleborus,without_leaves,not_fully_grown
helleborus2.jpg,helleborus,with_leaves,fully_grown
helleborus3.jpg,helleborus,with_leaves,fully_grown
jonquil1.jpg,jonquil,with_leaves
jonquil2.jpg,jonquil,with_leaves
jonquil3.jpg,jonquil,with_leaves
jonquil4.jpg,jonquil,without_leaves
mauve_honey_myrtle1.jpg,mauve_honey_myrtle,without_leaves
mauve_honey_myrtle2.jpg,mauve_honey_myrtle,with_leaves
mauve_honey_myrtle3.jpg,mauve_honey_myrtle,with_leaves
mediterranean_spurge1.jpg,mediterranean_spurge,with_leaves
mediterranean_spurge2.jpg,mediterranean_spurge,without_leaves
```

Lo script genera righe JSON per ogni riga. Ad esempio, quanto segue è una riga JSON per la prima riga (`camellia1.jpg,camellia,with_leaves`).

```
{"source-ref": "s3://bucket/flowers/train/camellia1.jpg","camellia": 1,"camellia-metadata":{"confidence": 1,"job-name": "labeling-job/camellia","class-name": "camellia","human-annotated": "yes","creation-date": "2022-01-21T14:21:05","type": "groundtruth/image-classification"},"with_leaves": 1,"with_leaves-metadata":{"confidence": 1,"job-name": "labeling-job/with_leaves","class-name": "with_leaves","human-annotated": "yes","creation-date": "2022-01-21T14:21:05","type": "groundtruth/image-classification"}}
```

Nell'esempio CSV, il percorso di Amazon S3 per l'immagine non è presente. Se il file CSV non include il percorso Amazon S3 per le immagini, usare l'argomento `--s3_path` della riga di comando per specificare il percorso Amazon S3 dell'immagine. 

Lo script registra la prima voce per ogni immagine in un file CSV di immagine deduplicato. Il file CSV di immagine deduplicata contiene una singola istanza di ogni immagine trovata nel file CSV di input. Le ulteriori occorrenze di un'immagine nel file CSV di input vengono registrate in un file CSV di immagine duplicato. Se lo script trova immagini duplicate, rivedere il file CSV di immagini duplicate e se necessario, aggiornarlo. Eseguire nuovamente lo script con il file deduplicato. Se non vengono trovati duplicati nel file CSV di input, lo script elimina il file CSV dell'immagine deduplicata e l'immagine duplicata, poiché sono vuoti. CSVfile 

 In questa procedura, creare il file CSV ed eseguire lo script Python per creare il file manifest. 

**Creare un file manifest da un file CSV**

1. Crea un file CSV con i seguenti campi in ogni riga (una riga per immagine). Non aggiungere una riga di intestazione al file CSV.    
[See the AWS documentation website for more details](http://docs.aws.amazon.com/it_it/rekognition/latest/customlabels-dg/ex-csv-manifest.html)

   Ad esempio, `camellia1.jpg,camellia,with_leaves` o `s3://my-bucket/flowers/train/camellia1.jpg,camellia,with_leaves` 

1. Salvare il file CSV.

1. Eseguire il seguente Python script. Fornire gli argomenti seguenti:
   + `csv_file`: il file CVS che si è creato nella fase 1. 
   + `manifest_file`: il nome del file manifest che si desidera creare.
   + (Facoltativo)`--s3_path {{s3://path_to_folder/}}`: il percorso Amazon S3 da aggiungere ai nomi dei file immagine (campo 1). Utilizzare `--s3_path` se le immagini nel campo 1 non contengono già un percorso S3.

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier:  Apache-2.0
   
   from datetime import datetime, timezone
   import argparse
   import logging
   import csv
   import os
   import json
   
   """
   Purpose
   Amazon Rekognition Custom Labels model example used in the service documentation.
   Shows how to create an image-level (classification) manifest file from a CSV file.
   You can specify multiple image level labels per image.
   CSV file format is
   image,label,label,..
   If necessary, use the bucket argument to specify the S3 bucket folder for the images.
   https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/md-gt-cl-transform.html
   """
   
   logger = logging.getLogger(__name__)
   
   
   def check_duplicates(csv_file, deduplicated_file, duplicates_file):
       """
       Checks for duplicate images in a CSV file. If duplicate images
       are found, deduplicated_file is the deduplicated CSV file - only the first
       occurence of a duplicate is recorded. Other duplicates are recorded in duplicates_file.
       :param csv_file: The source CSV file.
       :param deduplicated_file: The deduplicated CSV file to create. If no duplicates are found
       this file is removed.
       :param duplicates_file: The duplicate images CSV file to create. If no duplicates are found
       this file is removed.
       :return: True if duplicates are found, otherwise false.
       """
   
       logger.info("Deduplicating %s", csv_file)
   
       duplicates_found = False
   
       # Find duplicates.
       with open(csv_file, 'r', newline='', encoding="UTF-8") as f,\
               open(deduplicated_file, 'w', encoding="UTF-8") as dedup,\
               open(duplicates_file, 'w', encoding="UTF-8") as duplicates:
   
           reader = csv.reader(f, delimiter=',')
           dedup_writer = csv.writer(dedup)
           duplicates_writer = csv.writer(duplicates)
   
           entries = set()
           for row in reader:
               # Skip empty lines.
               if not ''.join(row).strip():
                   continue
   
               key = row[0]
               if key not in entries:
                   dedup_writer.writerow(row)
                   entries.add(key)
               else:
                   duplicates_writer.writerow(row)
                   duplicates_found = True
   
       if duplicates_found:
           logger.info("Duplicates found check %s", duplicates_file)
   
       else:
           os.remove(duplicates_file)
           os.remove(deduplicated_file)
   
       return duplicates_found
   
   
   def create_manifest_file(csv_file, manifest_file, s3_path):
       """
       Reads a CSV file and creates a Custom Labels classification manifest file.
       :param csv_file: The source CSV file.
       :param manifest_file: The name of the manifest file to create.
       :param s3_path: The S3 path to the folder that contains the images.
       """
       logger.info("Processing CSV file %s", csv_file)
   
       image_count = 0
       label_count = 0
   
       with open(csv_file, newline='', encoding="UTF-8") as csvfile,\
               open(manifest_file, "w", encoding="UTF-8") as output_file:
   
           image_classifications = csv.reader(
               csvfile, delimiter=',', quotechar='|')
   
           # Process each row (image) in CSV file.
           for row in image_classifications:
               source_ref = str(s3_path)+row[0]
   
               image_count += 1
   
               # Create JSON for image source ref.
               json_line = {}
               json_line['source-ref'] = source_ref
   
               # Process each image level label.
               for index in range(1, len(row)):
                   image_level_label = row[index]
   
                   # Skip empty columns.
                   if image_level_label == '':
                       continue
                   label_count += 1
   
                  # Create the JSON line metadata.
                   json_line[image_level_label] = 1
                   metadata = {}
                   metadata['confidence'] = 1
                   metadata['job-name'] = 'labeling-job/' + image_level_label
                   metadata['class-name'] = image_level_label
                   metadata['human-annotated'] = "yes"
                   metadata['creation-date'] = \
                       datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')
                   metadata['type'] = "groundtruth/image-classification"
   
                   json_line[f'{image_level_label}-metadata'] = metadata
   
                   # Write the image JSON Line.
               output_file.write(json.dumps(json_line))
               output_file.write('\n')
   
       output_file.close()
       logger.info("Finished creating manifest file %s\nImages: %s\nLabels: %s",
                   manifest_file, image_count, label_count)
   
       return image_count, label_count
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "csv_file", help="The CSV file that you want to process."
       )
   
       parser.add_argument(
           "--s3_path", help="The S3 bucket and folder path for the images."
           " If not supplied, column 1 is assumed to include the S3 path.", required=False
       )
   
   
   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()
   
           s3_path = args.s3_path
           if s3_path is None:
               s3_path = ''
   
           # Create file names.
           csv_file = args.csv_file
           file_name = os.path.splitext(csv_file)[0]
           manifest_file = f'{file_name}.manifest'
           duplicates_file = f'{file_name}-duplicates.csv'
           deduplicated_file = f'{file_name}-deduplicated.csv'
   
           # Create manifest file, if there are no duplicate images.
           if check_duplicates(csv_file, deduplicated_file, duplicates_file):
               print(f"Duplicates found. Use {duplicates_file} to view duplicates "
                     f"and then update {deduplicated_file}. ")
               print(f"{deduplicated_file} contains the first occurence of a duplicate. "
                     "Update as necessary with the correct label information.")
               print(f"Re-run the script with {deduplicated_file}")
           else:
               print("No duplicates found. Creating manifest file.")
   
               image_count, label_count = create_manifest_file(csv_file,
                                                               manifest_file,
                                                               s3_path)
   
               print(f"Finished creating manifest file: {manifest_file} \n"
                     f"Images: {image_count}\nLabels: {label_count}")
   
       except FileNotFoundError as err:
           logger.exception("File not found: %s", err)
           print(f"File not found: {err}. Check your input CSV file.")
   
   
   if __name__ == "__main__":
       main()
   ```

1. Se si vuole utilizzare un set di dati di test, ripetere i passaggi da 1 a 3 per creare un file manifest per il set di dati di test.

1. Se necessario, copiare le immagini nel percorso del bucket Amazon S3 specificato nella colonna 1 del file CSV (o specificato nella riga di comando `--s3_path`). Utilizzare il seguente comando AWS S3.

   ```
   aws s3 cp --recursive {{your-local-folder}} {{s3://your-target-S3-location}}
   ```

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