

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Membuat file manifes dari file CSV
<a name="ex-csv-manifest"></a>

Contoh skrip Python ini menyederhanakan pembuatan file manifes dengan menggunakan file Comma Separated Values (CSV) untuk memberi label gambar. Anda membuat file CSV. File manifes cocok untuk [klasifikasi gambar Multi-label](getting-started.md#gs-multi-label-image-classification-example) atau[Klasifikasi gambar multi-label](getting-started.md#gs-multi-label-image-classification-example). Untuk informasi selengkapnya, lihat [Temukan objek, adegan, dan konsep](understanding-custom-labels.md#tm-classification). 

**catatan**  
Skrip ini tidak membuat file manifes yang cocok untuk menemukan [lokasi objek](understanding-custom-labels.md#tm-object-localization) atau untuk menemukan [lokasi merek](understanding-custom-labels.md#tm-brand-detection-localization).

File manifes menjelaskan gambar yang digunakan untuk melatih model. Misalnya, lokasi gambar dan label yang ditetapkan untuk gambar. File manifes terdiri dari satu atau lebih baris JSON. Setiap baris JSON menggambarkan satu gambar. Untuk informasi selengkapnya, lihat [Mengimpor label tingkat gambar dalam file manifes](md-create-manifest-file-classification.md).

File CSV mewakili data tabular di beberapa baris dalam file teks. Bidang pada baris dipisahkan dengan koma. Untuk informasi selengkapnya, lihat [nilai yang dipisahkan koma](https://en.wikipedia.org/wiki/Comma-separated_values). Untuk skrip ini, setiap baris dalam file CSV Anda mewakili satu gambar dan memetakan ke Baris JSON dalam file manifes. Untuk membuat file CSV untuk file manifes yang mendukung [klasifikasi gambar Multi-label](getting-started.md#gs-multi-label-image-classification-example), Anda menambahkan satu atau beberapa label tingkat gambar ke setiap baris. Untuk membuat file manifes yang cocok[Klasifikasi gambar](getting-started.md#gs-image-classification-example), Anda menambahkan satu label tingkat gambar ke setiap baris.

Misalnya, File CSV berikut menjelaskan gambar dalam proyek [Klasifikasi gambar multi-label](getting-started.md#gs-multi-label-image-classification-example) (Bunga) *Memulai*. 

```
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
```

Script menghasilkan JSON Lines untuk setiap baris. Sebagai contoh, berikut ini adalah JSON Line untuk baris pertama (`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"}}
```

Dalam contoh CSV, jalur Amazon S3 ke gambar tidak ada. Jika file CSV Anda tidak menyertakan jalur Amazon S3 untuk gambar, gunakan `--s3_path` argumen baris perintah untuk menentukan jalur Amazon S3 ke gambar. 

Skrip merekam entri pertama untuk setiap gambar dalam file CSV gambar yang tidak digandakan. File CSV gambar yang dideduplikasi berisi satu contoh dari setiap gambar yang ditemukan dalam file CSV input. Kemunculan lebih lanjut dari gambar dalam file CSV input direkam dalam file CSV gambar duplikat. Jika skrip menemukan gambar duplikat, tinjau file CSV gambar duplikat dan perbarui file CSV gambar yang tidak digandakan seperlunya. Jalankan kembali skrip dengan file deduplikat. Jika tidak ada duplikat yang ditemukan dalam file CSV input, skrip menghapus file CSV gambar yang tidak digandakan dan gambar duplikat, karena kosong. CSVfile 

 Dalam prosedur ini, Anda membuat file CSV dan menjalankan skrip Python untuk membuat file manifes. 

**Untuk membuat file manifes dari file CSV**

1. Buat file CSV dengan bidang berikut di setiap baris (satu baris per gambar). Jangan menambahkan baris header ke file CSV.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/rekognition/latest/customlabels-dg/ex-csv-manifest.html)

   Misalnya `camellia1.jpg,camellia,with_leaves` atau `s3://my-bucket/flowers/train/camellia1.jpg,camellia,with_leaves` 

1. Simpan file CSV.

1. Jalankan skrip Python berikut. Berikan argumen berikut:
   + `csv_file`— File CSV yang Anda buat di langkah 1. 
   + `manifest_file`— Nama file manifes yang ingin Anda buat.
   + (Opsional) `--s3_path s3://path_to_folder/` - Jalur Amazon S3 untuk ditambahkan ke nama file gambar (bidang 1). Gunakan `--s3_path` jika gambar di bidang 1 belum berisi jalur 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. Jika Anda berencana menggunakan kumpulan data pengujian, ulangi langkah 1-3 untuk membuat file manifes untuk kumpulan data pengujian Anda.

1. Jika perlu, salin gambar ke jalur bucket Amazon S3 yang Anda tentukan di kolom 1 file CSV (atau ditentukan dalam `--s3_path` baris perintah). Anda dapat menggunakan perintah AWS S3 berikut.

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

1. [Unggah file manifes Anda](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html) ke bucket Amazon S3 yang ingin Anda gunakan untuk menyimpan file manifes.
**catatan**  
Pastikan Label Kustom Amazon Rekognition memiliki akses ke bucket Amazon S3 yang direferensikan di bidang baris JSON file `source-ref` manifes. Untuk informasi selengkapnya, lihat [Mengakses Bucket Amazon S3 eksternal](su-console-policy.md#su-external-buckets). Jika lowongan Ground Truth menyimpan gambar di Bucket Konsol Label Kustom Amazon Rekognition, Anda tidak perlu menambahkan izin.

1. Ikuti petunjuk di [Membuat kumpulan data dengan file manifes SageMaker AI Ground Truth (Console)](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-console) untuk membuat kumpulan data dengan file manifes yang diunggah. Untuk langkah 8, di **lokasi file.manifest**, masukkan URL Amazon S3 untuk lokasi file manifes. Jika Anda menggunakan AWS SDK, lakukan[Membuat kumpulan data dengan file manifes SageMaker AI Ground Truth (SDK)](md-create-dataset-ground-truth.md#md-create-dataset-ground-truth-sdk).