

# Managing an Amazon Rekognition Custom Labels model
Managing a model

An Amazon Rekognition Custom Labels model is a mathematical model that predicts the presence of objects, scenes, and concepts in new images. It does this by finding patterns in images used to train the model. This section shows you how to train a model, evaluate its performance, and make improvements. It also shows you how to make a model available for use and how to delete a model when you no longer need it. 

**Topics**
+ [

# Deleting an Amazon Rekognition Custom Labels model
](tm-delete-model.md)
+ [

# Tagging a model
](tm-tagging-model.md)
+ [

# Describing a model (SDK)
](md-describing-model-sdk.md)
+ [

# Copying an Amazon Rekognition Custom Labels model (SDK)
](md-copy-model-overview.md)

# Deleting an Amazon Rekognition Custom Labels model
Deleting a model

You can delete a model by using the Amazon Rekognition Custom Labels console or by using the [DeleteProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteProjectVersion) API. You can't delete a model if it is running or if it is training. To stop a running model, use the [StopProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) API. For more information, see [Stopping an Amazon Rekognition Custom Labels model (SDK)](rm-stop.md#rm-stop-sdk). If a model is training, wait until it finishes before you delete the model.

A deleted model can't be undeleted.

**Topics**
+ [

## Deleting an Amazon Rekognition Custom Labels model (Console)
](#tm-delete-model-console)
+ [

## Deleting an Amazon Rekognition Custom Labels model (SDK)
](#tm-delete-model-sdk)

## Deleting an Amazon Rekognition Custom Labels model (Console)
Deleting a model (Console)

The following procedure shows how to delete a model from a project details page. You can also delete a model from a model's detail page. 

**To delete a model (console)**

1. Open the Amazon Rekognition console at [https://console.aws.amazon.com/rekognition/](https://console.aws.amazon.com/rekognition/).

1. Choose **Use Custom Labels**.

1. Choose **Get started**. 

1. In the left navigation pane, choose **Projects**.

1. Choose the project that contains the model that you want to delete. The project details page opens.

1. In the **Models** section, select the models that you want to delete.
**Note**  
If the model can't be selected, the model is either running or is training, and can't be deleted. Check the **Status** field and try again after stopping the running model, or wait until training finishes. 

1. Choose **Delete model** and the **Delete model dialog box is shown**.

1. Enter **delete** to confirm deletion. 

1. Choose **Delete** to delete the model. Deleting the model might take a while to complete.
**Note**  
If you **Close** the dialog box during model deletion, the models are still deleted.

## Deleting an Amazon Rekognition Custom Labels model (SDK)
Deleting a model (SDK)

You delete an Amazon Rekognition Custom Labels model by calling [DeleteProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteProjectVersion) and supplying the Amazon Resource Name (ARN) of the model that you want to delete. You can get the model ARN from the **Use your model** section of the model details page in the Amazon Rekognition Custom Labels console. Alternatively, call [DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions) and supply the following.
+ The ARN of the project (`ProjectArn`) that the model is associated with.
+ The version name (`VersionNames`) of the model. 

The model ARN is the `ProjectVersionArn` field in the [ProjectVersionDescription](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProjectVersionDescription) object, from the `DescribeProjectVersions` response.

You can't delete a model if it is running or is training. To determine if the model is running or training, call [DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeProjectVersions) and check the `Status` field of the model's [ProjectVersionDescription](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ProjectVersionDescription) object. To stop a running model, use the [StopProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) API. For more information, see [Stopping an Amazon Rekognition Custom Labels model (SDK)](rm-stop.md#rm-stop-sdk). You have to wait for a model to finishing training before you can delete it. 

**To delete a model (SDK)**

1. If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 4: Set up the AWS CLI and AWS SDKs](su-awscli-sdk.md).

1. Use the following code to delete a model. 

------
#### [ AWS CLI ]

   Change the value of `project-version-arn` to the name of the project that you want to delete.

   ```
   aws rekognition delete-project-version --project-version-arn model_arn \
     --profile custom-labels-access
   ```

------
#### [ Python ]

   Supply the following command line parameters
   + `project_arn` – the ARN of the project that contains the model that you want to delete.
   + `model_arn` – the ARN of the model version that you want to delete.

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Shows how to delete an existing Amazon Rekognition Custom Labels model.
   """
   
   
   import argparse
   import logging
   import time
   import boto3
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   
   def find_forward_slash(input_string, n):
       """
       Returns the location of '/' after n number of occurences. 
       :param input_string: The string you want to search
       : n: the occurence that you want to find.
       """
       position = input_string.find('/')
       while position >= 0 and n > 1:
           position = input_string.find('/', position + 1)
           n -= 1
       return position
   
   
   def delete_model(rek_client, project_arn, model_arn):
       """
       Deletes an Amazon Rekognition Custom Labels model.
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param model_arn: The ARN of the model version that you want to delete.
       """
   
       try:
           # Delete the model
           logger.info("Deleting dataset: {%s}", model_arn)
   
           rek_client.delete_project_version(ProjectVersionArn=model_arn)
   
           # Get the model version name
           start = find_forward_slash(model_arn, 3) + 1
           end = find_forward_slash(model_arn, 4)
           version_name = model_arn[start:end]
   
           deleted = False
   
           # model might not be deleted yet, so wait deletion finishes.
           while deleted is False:
               describe_response = rek_client.describe_project_versions(ProjectArn=project_arn,
                                                                        VersionNames=[version_name])
               if len(describe_response['ProjectVersionDescriptions']) == 0:
                   deleted = True
               else:
                   logger.info("Waiting for model deletion %s", model_arn)
                   time.sleep(5)
   
           logger.info("model deleted: %s", model_arn)
   
           return True
   
       except ClientError as err:
           logger.exception("Couldn't delete model - %s: %s",
                            model_arn, err.response['Error']['Message'])
           raise
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "project_arn", help="The ARN of the project that contains the model that you want to delete."
       )
   
       parser.add_argument(
           "model_arn", help="The ARN of the model version that you want to delete."
       )
   
   
   def confirm_model_deletion(model_arn):
       """
       Confirms deletion of the model. Returns True if delete entered.
       :param model_arn: The ARN of the model that you want to delete.
       """
       print(f"Are you sure you wany to delete model {model_arn} ?\n", model_arn)
   
       start = input("Enter delete to delete your model: ")
       if start == "delete":
           return True
       else:
           return 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()
   
           if confirm_model_deletion(args.model_arn) is True:
               print(f"Deleting model: {args.model_arn}")
   
               # Delete the model.
               session = boto3.Session(profile_name='custom-labels-access')
               rekognition_client = session.client("rekognition")
   
               delete_model(rekognition_client,
                            args.project_arn,
                            args.model_arn)
   
               print(f"Finished deleting model: {args.model_arn}")
           else:
               print(f"Not deleting model {args.model_arn}")
   
       except ClientError as err:
           print(f"Problem deleting model: {err}")
   
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Java V2 ]
   + `project_arn` – the ARN of the project that contains the model that you want to delete.
   + `model_arn` – the ARN of the model version that you want to delete.

   ```
   //Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-custom-labels-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import java.net.URI;
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   
   import software.amazon.awssdk.services.rekognition.model.DeleteProjectVersionRequest;
   import software.amazon.awssdk.services.rekognition.model.DeleteProjectVersionResponse;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsRequest;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   
   public class DeleteModel {
   
       public static final Logger logger = Logger.getLogger(DeleteModel.class.getName());
   
       public static int findForwardSlash(String modelArn, int n) {
   
           int start = modelArn.indexOf('/');
           while (start >= 0 && n > 1) {
               start = modelArn.indexOf('/', start + 1);
               n -= 1;
           }
           return start;
   
       }
   
       public static void deleteMyModel(RekognitionClient rekClient, String projectArn, String modelArn)
               throws InterruptedException {
   
           try {
   
               logger.log(Level.INFO, "Deleting model: {0}", projectArn);
   
               // Delete the model
   
               DeleteProjectVersionRequest deleteProjectVersionRequest = DeleteProjectVersionRequest.builder()
                       .projectVersionArn(modelArn).build();
   
               DeleteProjectVersionResponse response =
                       rekClient.deleteProjectVersion(deleteProjectVersionRequest);
   
               logger.log(Level.INFO, "Status: {0}", response.status());
   
               // Get the model version
   
               int start = findForwardSlash(modelArn, 3) + 1;
               int end = findForwardSlash(modelArn, 4);
   
               String versionName = modelArn.substring(start, end);
   
               Boolean deleted = false;
   
               DescribeProjectVersionsRequest describeProjectVersionsRequest = DescribeProjectVersionsRequest.builder()
                       .projectArn(projectArn).versionNames(versionName).build();
   
               // Wait until model is deleted.
   
               do {
   
                   DescribeProjectVersionsResponse describeProjectVersionsResponse = rekClient
                           .describeProjectVersions(describeProjectVersionsRequest);
   
                   if (describeProjectVersionsResponse.projectVersionDescriptions().size()==0) {
                       logger.log(Level.INFO, "Waiting for model deletion: {0}", modelArn);
                       Thread.sleep(5000);
                   } else {
                       deleted = true;
                       logger.log(Level.INFO, "Model deleted: {0}", modelArn);
                   }
                   
               } while (Boolean.FALSE.equals(deleted));
   
               logger.log(Level.INFO, "Model deleted: {0}", modelArn);
   
           } catch (
   
           RekognitionException e) {
               logger.log(Level.SEVERE, "Client error occurred: {0}", e.getMessage());
               throw e;
           }
   
       }
   
       public static void main(String args[]) {
   
           final String USAGE = "\n" + "Usage: " + "<project_arn> <model_arn>\n\n" + "Where:\n"
                   + "   project_arn - The ARN of the project that contains the model that you want to delete.\n\n"
                   + "   model_version - The ARN of the model that you want to delete.\n\n";
   
           if (args.length != 2) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           String projectArn = args[0];
           String modelVersion = args[1];
   
           try {
   
               RekognitionClient rekClient = RekognitionClient.builder().build();
   
               // Delete the model
               deleteMyModel(rekClient, projectArn, modelVersion);
   
               System.out.println(String.format("model deleted: %s", modelVersion));
   
               rekClient.close();
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               System.exit(1);
           }
   
           catch (InterruptedException intError) {
               logger.log(Level.SEVERE, "Exception while sleeping: {0}", intError.getMessage());
               System.exit(1);
           }
   
       }
   
   }
   ```

------

# Tagging a model


You can identify, organize, search for, and filter your Amazon Rekognition models by using tags. Each tag is a label consisting of a user-defined key and value. For example, to help determine billing for your models, tag your models with a `Cost center` key and add the appropriate cost center number as a value. For more information, see [Tagging AWS resources](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html).

Use tags to:
+ Track billing for a model by using cost allocation tags. For more information, see [Using Cost Allocation Tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html).
+ Control access to a model by using Identity and Access Management (IAM). For more information, see [Controlling access to AWS resources using resource tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html).
+ Automate model management. For example, you can run automated start or stop scripts that turn off development models during non-business hours to reduce costs. For more information, see [Running a trained Amazon Rekognition Custom Labels model](running-model.md). 

You can tag models by using the Amazon Rekognition console or by using the AWS SDKs. 

**Topics**
+ [

## Tagging models (console)
](#tm-tagging-model-console)
+ [

## Viewing model tags
](#tm-tagging-model-viewing-console)
+ [

## Tagging models (SDK)
](#tm-tagging-model-sdk)

## Tagging models (console)


You can use the Rekognition console to add tags to models, view the tags attached to a model, and remove tags. 

### Adding or removing tags


This procedure explains how to add tags to, or remove tags from, an existing model. You can also add tags to a new model when it is trained. For more information, see [Training an Amazon Rekognition Custom Labels model](training-model.md). 

**To add tags to, or remove tags from, an existing model using the console**

1. Open the Amazon Rekognition console at [ https://console.aws.amazon.com/rekognition/]( https://console.aws.amazon.com/rekognition/).

1. Choose **Get started**. 

1. In the navigation pane, choose **Projects**.

1. On the **Projects** resources page, choose the project that contains the model that you want to tag.

1. In the navigation pane, under the project you previously chose, choose **Models**.

1. In the **Models** section, choose the model that you want to add a tag to. 

1. On the model's details page, choose the **Tags** tab. 

1. In the **Tags** section, choose **Manage tags**.

1. On the **Manage tags** page, choose **Add new tag**.

1. Enter a key and a value.

   1. For **Key**, enter a name for the key.

   1. For **Value**, enter a value.

1. To add more tags, repeat steps 9 and 10.

1. (Optional) To remove a tag, choose **Remove** next to the tag that you want to remove. If you are removing a previously saved tag, it is removed when you save your changes. 

1. Choose **Save changes** to save your changes.

## Viewing model tags


You can use the Amazon Rekognition console to view the tags attached to a model.

To view the tags attached to *all models within a project*, you must use the AWS SDK. For more information, see [Listing model tags](#listing-model-tags-sdk).

**To view the tags attached to a model**

1. Open the Amazon Rekognition console at [ https://console.aws.amazon.com/rekognition/]( https://console.aws.amazon.com/rekognition/).

1. Choose **Get started**. 

1. In the navigation pane, choose **Projects**.

1. On the **Projects** resources page, choose the project that contains the model whose tag you want to view.

1. In the navigation pane, under the project you previously chose, choose **Models**.

1. In the **Models** section, choose the model whose tag you want to view. 

1. On the model's details page, choose the **Tags** tab. The tags are shown in **Tags** section.

## Tagging models (SDK)


You can use the AWS SDK to:
+ Add tags to a new model
+ Add tags to an existing model
+ List the tags attached to a model 
+ Remove tags from a model 

The tags in the following AWS CLI examples are in the following format.

```
--tags '{"key1":"value1","key2":"value2"}' 
```

Alternatively, you can use this format.

```
--tags key1=value1,key2=value2
```

If you haven't installed the AWS CLI, see [Step 4: Set up the AWS CLI and AWS SDKs](su-awscli-sdk.md).

### Adding tags to a new model


You can add tags to a model when you create it using the [CreateProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateProjectVersion.html) operation. Specify one or more tags in the `Tags` array input parameter. 

```
aws rekognition create-project-version --project-arn project arn \
  --version-name version_name \
  --output-config '{ "S3Location": { "Bucket": "output bucket", "Prefix":  "output folder" } }' \
  --tags '{"key1":"value1","key2":"value2"}' \
  --profile custom-labels-access
```

For information about creating and training a model, see [Training a model (SDK)](training-model.md#tm-sdk).

### Adding tags to an existing model


To add one or more tags to an existing model, use the [TagResource](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_TagResource) operation. Specify the model's Amazon Resource Name (ARN) (`ResourceArn`) and the tags (`Tags`) that you want to add. The following example shows how to add two tags.

```
aws rekognition tag-resource --resource-arn resource-arn \
  --tags '{"key1":"value1","key2":"value2"}' \
  --profile custom-labels-access
```

You can get the ARN for a model by calling [CreateProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateProjectVersion).

### Listing model tags


To list the tags attached to a model, use the [ListTagsForResource](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListTagsForResource) operation and specify the ARN of the model (`ResourceArn`). The response is a map of tag keys and values that are attached to the specified model.

```
aws rekognition list-tags-for-resource --resource-arn resource-arn \
  --profile custom-labels-access
```

The output displays a list of the tags attached to the model.

```
{
    "Tags": {
        "Dept": "Engineering",
        "Name": "Ana Silva Carolina",
        "Role": "Developer"
    }
}
```

To see which models in a project have a specific tag, call `DescribeProjectVersions` to get a list of models. Then call `ListTagsForResource` for each model in the response from `DescribeProjectVersions`. Inspect the response from `ListTagsForResource` to see if the required tag is present. 

The following Python 3 example shows you how search all your projects for a specific tag key and value. The output includes the project ARN and the model ARN where a matching key is found.

**To search for a tag value**

1. Save the following code to a file named `find_tag.py`.

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   """
   Purpose
   Shows how to find a tag value that's associated with models within
   your Amazon Rekognition Custom Labels projects.
   """
   import logging
   import argparse
   import boto3
   
   from botocore.exceptions import ClientError
   
   
   logger = logging.getLogger(__name__)
   
   
   def find_tag_in_projects(rekognition_client, key, value):
       """
       Finds Amazon Rekognition Custom Label models tagged with the supplied key and key value.
       :param rekognition_client: An Amazon Rekognition boto3 client.
       :param key: The tag key to find.
       :param value: The value of the tag that you want to find.
       return: A list of matching model versions (and model projects) that were found.
       """
       try:
   
           found_tags = []
           found = False
   
           projects = rekognition_client.describe_projects()
           # Iterate through each project and models within a project.
           for project in projects["ProjectDescriptions"]:
               logger.info("Searching project: %s ...", project["ProjectArn"])
   
               models = rekognition_client.describe_project_versions(
                   ProjectArn=(project["ProjectArn"])
               )
   
               for model in models["ProjectVersionDescriptions"]:
                   logger.info("Searching model %s", model["ProjectVersionArn"])
   
                   tags = rekognition_client.list_tags_for_resource(
                       ResourceArn=model["ProjectVersionArn"]
                   )
   
                   logger.info(
                       "\tSearching model: %s for tag: %s value: %s.",
                       model["ProjectVersionArn"],
                       key,
                       value,
                   )
                   # Check if tag exists.
   
                   if key in tags["Tags"]:
                       if tags["Tags"][key] == value:
                           found = True
                           logger.info(
                               "\t\tMATCH: Project: %s: model version %s",
                               project["ProjectArn"],
                               model["ProjectVersionArn"],
                           )
                           found_tags.append(
                               {
                                   "Project": project["ProjectArn"],
                                   "ModelVersion": model["ProjectVersionArn"],
                               }
                           )
   
           if found is False:
               logger.info("No match for Tag %s with value %s.", key, value)
           return found_tags
       except ClientError as err:
           logger.info("Problem finding tags: %s. ", format(err))
           raise
   
   
   def main():
       """
       Entry point for example.
       """
       logging.basicConfig(level=logging.INFO,
                           format="%(levelname)s: %(message)s")
   
       # Set up command line arguments.
       parser = argparse.ArgumentParser(usage=argparse.SUPPRESS)
   
       parser.add_argument("tag", help="The tag that you want to find.")
       parser.add_argument("value", help="The tag value that you want to find.")
   
       args = parser.parse_args()
       key = args.tag
       value = args.value
   
       print(f"Searching your models for tag: {key} with value: {value}.")
   
   
       session = boto3.Session(profile_name='custom-labels-access')
       rekognition_client = session.client("rekognition")
   
       # Get tagged models for all projects.
       tagged_models = find_tag_in_projects(rekognition_client, key, value)
   
       print("Matched models\n--------------")
       if len(tagged_models) > 0:
           for model in tagged_models:
               print(
                   "Project: {project}\nModel version: {version}\n".format(
                       project=model["Project"], version=model["ModelVersion"]
                   )
               )
   
       else:
           print("No matches found.")
   
       print("Done.")
   
   
   if __name__ == "__main__":
       main()
   ```

1. At the command prompt, enter the following. Replace *key* and *value* with the key name and the key value that you want to find.

   ```
   python find_tag.py key value
   ```

### Deleting tags from a model


To remove one or more tags from a model, use the [UntagResource](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_UntagResource) operation. Specify the ARN of the model (`ResourceArn`) and the tag keys (`Tag-Keys`) that you want to remove. 

```
aws rekognition untag-resource --resource-arn resource-arn \
  --tag-keys '["key1","key2"]' \
  --profile custom-labels-access
```

Alternatively, you can specify `tag-keys` in this format.

```
--tag-keys key1,key2 
```

# Describing a model (SDK)


You can use the `DescribeProjectVersions` API to get information about a version of a model. If you don't specify `VersionName`, `DescribeProjectVersions` returns descriptions for all model versions in the project.

**To describe a model (SDK)**

1. If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 4: Set up the AWS CLI and AWS SDKs](su-awscli-sdk.md).

1. Use the following example code to describe a version of a model.

------
#### [ AWS CLI ]

   Change the value of `project-arn` to the ARN of the project that you want to describe. Change the value of `version-name` to the version of the model that you want to describe.

   ```
   aws rekognition describe-project-versions --project-arn project_arn \
     --version-names version_name \
     --profile custom-labels-access
   ```

------
#### [ Python ]

   Use the following code. Supply the following command line parameters:
   + project\$1arn — the ARN of the model that you want to describe. 
   + model\$1version — the version of the model that you want to describe. 

   For example: `python describe_model.py project_arn model_version `

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Shows how to describe an Amazon Rekognition Custom Labels model.
   """
   import argparse
   import logging
   import boto3
   
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   
   def describe_model(rek_client, project_arn, version_name):
       """
       Describes an Amazon Rekognition Custom Labels model.
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param project_arn: The ARN of the prject that contains the model.
       :param version_name: The version name of the model that you want to describe.
       """
   
       try:
           # Describe the model
           logger.info("Describing model: %s for project %s",
                       version_name, project_arn)
   
           describe_response = rek_client.describe_project_versions(ProjectArn=project_arn,
                                                                    VersionNames=[version_name])
           for model in describe_response['ProjectVersionDescriptions']:
               print(f"Created: {str(model['CreationTimestamp'])} ")
               print(f"ARN: {str(model['ProjectVersionArn'])} ")
               if 'BillableTrainingTimeInSeconds' in model:
                   print(
                       f"Billing training time (minutes): {str(model['BillableTrainingTimeInSeconds']/60)} ")
               print("Evaluation results: ")
               if 'EvaluationResult' in model:
                   evaluation_results = model['EvaluationResult']
                   print(f"\tF1 score: {str(evaluation_results['F1Score'])}")
                   print(
                       f"\tSummary location: s3://{evaluation_results['Summary']['S3Object']['Bucket']}/{evaluation_results['Summary']['S3Object']['Name']}")
   
               if 'ManifestSummary' in model:
                   print(
                       f"Manifest summary location: s3://{model['ManifestSummary']['S3Object']['Bucket']}/{model['ManifestSummary']['S3Object']['Name']}")
               if 'OutputConfig' in model:
                   print(
                       f"Training output location: s3://{model['OutputConfig']['S3Bucket']}/{model['OutputConfig']['S3KeyPrefix']}")
               if 'MinInferenceUnits' in model:
                   print(
                       f"Minimum inference units: {str(model['MinInferenceUnits'])}")
               if 'MaxInferenceUnits' in model:
                   print(
                       f"Maximum Inference units: {str(model['MaxInferenceUnits'])}")
   
               print("Status: " + model['Status'])
               print("Message: " + model['StatusMessage'])
   
       except ClientError as err:
           logger.exception(
               "Couldn't describe model: %s", err.response['Error']['Message'])
           raise
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "project_arn", help="The ARN of the project in which the model resides."
       )
       parser.add_argument(
           "version_name", help="The version of the model that you want to describe."
       )
   
   
   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()
   
           print(
               f"Describing model: {args.version_name} for project {args.project_arn}.")
   
           # Describe the model.
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
   
           describe_model(rekognition_client, args.project_arn,
                          args.version_name)
   
           print(
               f"Finished describing model: {args.version_name} for project {args.project_arn}.")
   
       except ClientError as err:
           error_message = f"Problem describing model: {err}"
           logger.exception(error_message)
           print(error_message)
       except Exception as err:
           error_message = f"Problem describing model: {err}"
           logger.exception(error_message)
           print(error_message)
   
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Java V2 ]

   Use the following code. Supply the following command line parameters:
   + project\$1arn — the ARN of the model that you want to describe. 
   + model\$1version — the version of the model that you want to describe. 

   ```
   /*
      Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
      SPDX-License-Identifier: Apache-2.0
   */
   
   package com.example.rekognition;
   
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsRequest;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsResponse;
   import software.amazon.awssdk.services.rekognition.model.EvaluationResult;
   import software.amazon.awssdk.services.rekognition.model.GroundTruthManifest;
   import software.amazon.awssdk.services.rekognition.model.OutputConfig;
   import software.amazon.awssdk.services.rekognition.model.ProjectVersionDescription;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   public class DescribeModel {
   
       public static final Logger logger = Logger.getLogger(DescribeModel.class.getName());
   
       public static void describeMyModel(RekognitionClient rekClient, String projectArn, String versionName) {
   
           try {
   
               // If a single version name is supplied, build request argument
   
               DescribeProjectVersionsRequest describeProjectVersionsRequest = null;
   
               if (versionName == null) {
                   describeProjectVersionsRequest = DescribeProjectVersionsRequest.builder().projectArn(projectArn)
                           .build();
               } else {
                   describeProjectVersionsRequest = DescribeProjectVersionsRequest.builder().projectArn(projectArn)
                           .versionNames(versionName).build();
               }
   
               DescribeProjectVersionsResponse describeProjectVersionsResponse = rekClient
                       .describeProjectVersions(describeProjectVersionsRequest);
   
               for (ProjectVersionDescription projectVersionDescription : describeProjectVersionsResponse
                       .projectVersionDescriptions()) {
   
                   System.out.println("ARN: " + projectVersionDescription.projectVersionArn());
                   System.out.println("Status: " + projectVersionDescription.statusAsString());
                   System.out.println("Message: " + projectVersionDescription.statusMessage());
   
                   if (projectVersionDescription.billableTrainingTimeInSeconds() != null) {
                       System.out.println(
                               "Billable minutes: " + (projectVersionDescription.billableTrainingTimeInSeconds() / 60));
                   }
   
                   if (projectVersionDescription.evaluationResult() != null) {
                       EvaluationResult evaluationResult = projectVersionDescription.evaluationResult();
   
                       System.out.println("F1 Score: " + evaluationResult.f1Score());
                       System.out.println("Summary location: s3://" + evaluationResult.summary().s3Object().bucket() + "/"
                               + evaluationResult.summary().s3Object().name());
                   }
   
                   if (projectVersionDescription.manifestSummary() != null) {
                       GroundTruthManifest manifestSummary = projectVersionDescription.manifestSummary();
                       System.out.println("Manifest summary location: s3://" + manifestSummary.s3Object().bucket() + "/"
                               + manifestSummary.s3Object().name());
   
                   }
   
                   if (projectVersionDescription.outputConfig() != null) {
                       OutputConfig outputConfig = projectVersionDescription.outputConfig();
                       System.out.println(
                               "Training output: s3://" + outputConfig.s3Bucket() + "/" + outputConfig.s3KeyPrefix());
                   }
   
                   if (projectVersionDescription.minInferenceUnits() != null) {
                       System.out.println("Min inference units: " + projectVersionDescription.minInferenceUnits());
                   }
   
                   System.out.println();
   
               }
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               throw rekError;
           }
   
       }
   
       public static void main(String args[]) {
   
           String projectArn = null;
           String versionName = null;
   
           final String USAGE = "\n" + "Usage: " + "<project_arn> <version_name>\n\n" + "Where:\n"
                   + "   project_arn - The ARN of the project that contains the models you want to describe.\n\n"
                   + "   version_name - (optional) The version name of the model that you want to describe. \n\n"
                   + "                  If you don't specify a value, all model versions are described.\n\n";
   
           if (args.length > 2 || args.length == 0) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           projectArn = args[0];
   
           if (args.length == 2) {
               versionName = args[1];
           }
   
           try {
   
               // Get the Rekognition client.
               RekognitionClient rekClient = RekognitionClient.builder()
               .credentialsProvider(ProfileCredentialsProvider.create("custom-labels-access"))
               .region(Region.US_WEST_2)
               .build();
   
                // Describe the model
               describeMyModel(rekClient, projectArn, versionName);
   
               rekClient.close();
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               System.exit(1);
           }
   
       }
   
   }
   ```

------

# Copying an Amazon Rekognition Custom Labels model (SDK)
Copying a model (SDK)

You can use the [CopyProjectVersion](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CopyProjectVersion) operation to copy an Amazon Rekognition Custom Labels model version from a source Amazon Rekognition Custom Labels project to a destination project. The destination project can be in a different AWS account, or in the same AWS account. A typical scenario is copying a tested model from a development AWS account to a production AWS account. 



Alternatively, you can train the model in the destination account with the source dataset. Using the `CopyProjectVersion` operation has the following advantages.
+ Model behavior is consistent. Model training is non-deterministic and two models trained with same dataset aren't guaranteed to make the same predictions. Copying the model with `CopyProjectVersion` helps make sure that the behavior of the copied model is consistent with the source model and you won't need to re-test the model. 
+ Model training isn't required. This saves you money as you are charged for each successful training of a model. 

To copy a model to a different AWS account, you must have an Amazon Rekognition Custom Labels project in the destination AWS account. For information about creating a project, see [Creating a project](mp-create-project.md). Be sure to create the project in the destination AWS account.

A [project policy](md-create-project-policy-document.md) is a resource-based policy that sets copy permissions for the model version that you want to copy. You will need to use a [project policy](md-create-project-policy-document.md) when the destination project is in a different AWS account from the source project.

You do not need to use a [project policy](md-create-project-policy-document.md), when copying model versions within the same account. However, you can choose to use a [project policy](md-create-project-policy-document.md) on inter-account projects if you would like more control over these resources.

You attach the project policy to the source project by calling the [PutProjectPolicy](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_PutProjectPolicy) operation.

You can't use `CopyProjectVersion` to copy a model to a project in a different AWS Region. Also, you can't copy a model with the Amazon Rekognition Custom Labels console. In these cases, you can train the model in the destination project with the datasets used to train the source model. For more information, see [Training an Amazon Rekognition Custom Labels model](training-model.md). 

To copy a model from a source project to a destination project, do the following:

**To copy a model**

1. [Create a project policy document](md-create-project-policy-document.md).

1. [Attach the project policy to the source project](md-attach-project-policy.md).

1. [Copy the model with the `CopyProjectVersion` operation](md-copy-model-sdk.md).

To remove a project policy from a project, call [DeleteProjectPolicy](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteProjectPolicy). To get a list of project policies attached to a project, call [ListProjectPolicies](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListProjectPolicies). 

**Topics**
+ [

# Creating a project policy document
](md-create-project-policy-document.md)
+ [

# Attaching a project policy (SDK)
](md-attach-project-policy.md)
+ [

# Copying a model (SDK)
](md-copy-model-sdk.md)
+ [

# Listing project policies (SDK)
](md-list-project-policies.md)
+ [

# Deleting a project policy (SDK)
](md-delete-project-policy.title.md)

# Creating a project policy document


Rekognition Custom Labels uses a resource-based policy, known as *project policy*, to manage copy permissions for a model version. A project policy is a JSON format document.

A project policy allows or denies a [principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) permission to copy a model version from a source project to a destination project. You need a project policy if the destination project is in a different AWS account. That's also true if the destination project is in the same AWS account as the source project and you want to restrict access to specific model versions. For example, you might want to deny copy permissions to a specific IAM role within an AWS account.

The following example allows the principal `arn:aws:iam::111111111111:role/Admin` to copy the model version `arn:aws:rekognition:us-east-1:123456789012:project/my_project/version/test_1/1627045542080`. 

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement":[
    {
      "Effect":"Allow",
      "Principal":{
        "AWS":"arn:aws:iam::111111111111:role/Admin"
      },
      "Action":"rekognition:CopyProjectVersion",
      "Resource":"arn:aws:rekognition:us-east-1:111111111111:project/my_project/version/test_1/1627045542080"
    }
  ]
}
```

------

**Note**  
`Action`, `Resource`, `Principal`, and `Effect` are required fields in a project policy document.  
The only supported `action` is `rekognition:CopyProjectVersion`.  
`NotAction`, `NotResource`, and `NotPrincipal` are prohibited fields and must not be present in the project policy document.

If you don't specify a project policy, a principal in the same AWS account as the source project can still copy a model, if the principal has an Identity-based policy, such as ` AmazonRekognitionCustomLabelsFullAccess`, that gives permission to call `CopyProjectVersion`.

The following procedure creates a project policy document file that you can use with the Python example in [Attaching a project policy (SDK)](md-attach-project-policy.md). If you are using the `put-project-policy` AWS CLI command, you supply the project policy as a JSON string. 

**To create a project policy document**

1. In a text editor, create the following document. Change the following values:
   + Effect – Specify `ALLOW` to grant copy permission. Specify `DENY` to deny copy permission. 
   + Principal – To the principal that you want to allow or deny access to the model versions that you specify in `Resource`. For example you can specify the [AWS account principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html#principal-accounts) for a different AWS account. We don't restrict the principals that you can use. For more information, see [Specifying a principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html#Principal_specifying).
   + Resource – The Amazon Resource Name (ARN) of the model version for which you want to specify copy permissions. If you want to grant permissions to all model versions within the source project, use the following format `arn:aws:rekognition:region:account:project/source project/version/* `

1. Save the project policy to your computer.

1. Attach the project policy to the source project by following the instructions at [Attaching a project policy (SDK)](md-attach-project-policy.md).

# Attaching a project policy (SDK)


You attach a project policy to an Amazon Rekognition Custom Labels project by calling the [PutProjectpolicy](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_PutProjectPolicy) operation. 

Attach multiple project policies to a project by calling `PutProjectPolicy` for each project policy that you want to add. You can attach up to five project project policies to a project. If you need to attach more project policies, you can request a [limit](limits.md) increase.

When you first attach a unique project policy to a project, don't specify a revision ID in the `PolicyRevisionId` input parameter. The response from `PutProjectPolicy` is a revision ID for the project policy that Amazon Rekognition Custom Labels creates for you. You can use the revision ID to update or delete the latest revision of a project policy. Amazon Rekognition Custom Labels only keeps the latest revision of a project policy. If you try to update or delete a previous revision of a project policy, you get an `InvalidPolicyRevisionIdException` error.

To update an existing project policy, specify the revision ID of the project policy in the `PolicyRevisionId` input parameter. You can get the revision IDs for project policies in a project by calling [ListProjectPolicies](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListProjectPolicies).

After you attach a project policy to a source project, you can copy the model from the source project to the destination project. For more information, see [Copying a model (SDK)](md-copy-model-sdk.md). 

To remove a project policy from a project, call [DeleteProjectPolicy](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteProjectPolicy). To get a list of project policies attached to a project, call [ListProjectPolicies](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListProjectPolicies). 

**To attach a project policy to a project (SDK)**

1. If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 4: Set up the AWS CLI and AWS SDKs](su-awscli-sdk.md).

1. [Create a project policy document](md-create-project-policy-document.md).

1. Use the following code to attach the project policy to the project, in the trusting AWS account, that contains the model version that you want to copy. To get the project ARN, call [DescribeProjects](https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/md-describing-project-sdk.html). To get the model version ARN call [DescribeProjectVersions](https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/md-describing-model-sdk.html). 

------
#### [ AWS CLI ]

   Change the following values:
   + `project-arn` to the ARN of the source project in the trusting AWS account that contains the model version that you want to copy. 
   + `policy-name` to a policy name that you choose. 
   + `principal` To the principal that you want to allow or deny access to the model versions that you specify in `Model version ARN`. 
   + `project-version-arn` to the ARN of the model version that you want to copy.

   If you want to update an existing project policy, specify the `policy-revision-id` parameter and supply the revision ID of the desired project policy. 

   ```
   aws rekognition put-project-policy \
     --project-arn project-arn \
     --policy-name policy-name \
     --policy-document '{ "Version": "2012-10-17",		 	 	  "Statement":[{ "Effect":"ALLOW or DENY", "Principal":{ "AWS":"principal" }, "Action":"rekognition:CopyProjectVersion", "Resource":"project-version-arn" }]}' \
     --profile custom-labels-access
   ```

------
#### [ Python ]

   Use the following code. Supply the following command line parameters:
   + `project_arn` – The ARN of the source project that you want to attach the project policy to. 
   + `policy_name` – A policy name that you choose. 
   + `project_policy` – The file that contains the project policy document,.
   + `policy_revision_id` – (Optional). If you want to update an existing revision of a project policy, specify the revision ID of the project policy.

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Amazon Rekognition Custom Labels model example used in the service documentation:
   https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/md-copy-model-sdk.html
   Shows how to attach a project policy to an Amazon Rekognition Custom Labels project.
   """
   
   import boto3
   import argparse
   import logging
   import json
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   
   def put_project_policy(rek_client, project_arn, policy_name, policy_document_file, policy_revision_id=None):
       """
       Attaches a project policy to an Amazon Rekognition Custom Labels project.
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param policy_name: A name for the project policy.
       :param project_arn: The Amazon Resource Name (ARN) of the source project
       that you want to attach the project policy to.
       :param policy_document_file: The JSON project policy document to
       attach to the source project.
       :param policy_revision_id: (Optional) The revision of an existing policy to update.
       Pass None to attach new policy.
       :return The revision ID for the project policy.
       """
   
       try:
   
           policy_document_json = ""
           response = None
   
           with open(policy_document_file, 'r') as policy_document:
               policy_document_json = json.dumps(json.load(policy_document))
   
           logger.info(
               "Attaching %s project_policy to project %s.", 
               policy_name, project_arn)
   
           if policy_revision_id is None:
               response = rek_client.put_project_policy(ProjectArn=project_arn,
                                                        PolicyName=policy_name,
                                                        PolicyDocument=policy_document_json)
   
           else:
               response = rek_client.put_project_policy(ProjectArn=project_arn,
                                                        PolicyName=policy_name,
                                                        PolicyDocument=policy_document_json,
                                                        PolicyRevisionId=policy_revision_id)
   
           new_revision_id = response['PolicyRevisionId']
   
           logger.info(
               "Finished creating project policy %s. Revision ID: %s",
               policy_name, new_revision_id)
   
           return new_revision_id
   
       except ClientError as err:
           logger.exception(
               "Couldn't attach %s project policy to project %s: %s }",
               policy_name, project_arn, err.response['Error']['Message'] )
           raise
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "project_arn",  help="The Amazon Resource Name (ARN) of the project "
           "that you want to attach the project policy to."
       )
       parser.add_argument(
           "policy_name",  help="A name for the project policy."
   
       )
   
       parser.add_argument(
           "project_policy",  help="The file containing the project policy JSON"
       )
   
       parser.add_argument(
           "--policy_revision_id",  help="The revision of an existing policy to update. "
           "If you don't supply a value, a new project policy is created.",
           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()
   
           print(f"Attaching policy to {args.project_arn}")
   
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
   
   
           # Attach a new policy or update an existing policy.
   
           response = put_project_policy(rekognition_client,
                                         args.project_arn,
                                         args.policy_name,
                                         args.project_policy,
                                         args.policy_revision_id)
   
           print(
               f"project policy {args.policy_name} attached to project {args.project_arn}")
           print(f"Revision ID: {response}")
   
       except ClientError as err:
           print("Problem attaching project policy: %s", err)
   
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Java V2 ]

   Use the following code. Supply the following command line parameters:
   + `project_arn` – The ARN of the source project that you want to attach the project policy to. 
   + `project_policy_name` – A policy name that you choose. 
   + `project_policy_document` – The file that contains the project policy document.
   + `project_policy_revision_id` – (Optional). If you want to update an existing revision of a project policy, specify the revision ID of the project policy.

   ```
   /*
      Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
      SPDX-License-Identifier: Apache-2.0
   */
   
   package com.example.rekognition;
   
   import java.io.IOException;
   import java.nio.file.Files;
   import java.nio.file.Path;
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.PutProjectPolicyRequest;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   
   public class PutProjectPolicy {
   
       public static final Logger logger = Logger.getLogger(PutProjectPolicy.class.getName());
   
       public static void putMyProjectPolicy(RekognitionClient rekClient, String projectArn, String projectPolicyName,
                String projectPolicyFileName, String projectPolicyRevisionId) throws IOException {
   
           try {
   
               Path filePath = Path.of(projectPolicyFileName);
   
               
   
               String policyDocument = Files.readString(filePath);
   
               String[] logArguments = new String[] { projectPolicyFileName, projectPolicyName };
   
               PutProjectPolicyRequest putProjectPolicyRequest = null;
   
               logger.log(Level.INFO, "Attaching Project policy: {0} to project: {1}", logArguments);
   
               // Attach the project policy.
   
               if (projectPolicyRevisionId == null) {
                   putProjectPolicyRequest = PutProjectPolicyRequest.builder().projectArn(projectArn)
                           .policyName(projectPolicyName).policyDocument(policyDocument).build();
               } else {
                   putProjectPolicyRequest = PutProjectPolicyRequest.builder().projectArn(projectArn)
                           .policyName(projectPolicyName).policyRevisionId(projectPolicyRevisionId)
                           .policyDocument(policyDocument)
   
                           .build();
               }
   
               rekClient.putProjectPolicy(putProjectPolicyRequest);
   
               logger.log(Level.INFO, "Attached Project policy: {0} to project: {1}", logArguments);
   
           } catch (
   
           RekognitionException e) {
               logger.log(Level.SEVERE, "Client error occurred: {0}", e.getMessage());
               throw e;
           }
   
       }
   
       public static void main(String args[]) {
   
           final String USAGE = "\n" + "Usage: "
                   + "<project_arn> <project_policy_name> <policy_document> <project_policy_revision_id>\n\n" + "Where:\n"
                   + "   project_arn - The ARN of the project that you want to attach the project policy to.\n\n"
                   + "   project_policy_name - A name for the project policy.\n\n"
                   + "   project_policy_document - The file name of the project policy.\n\n"
                   + "   project_policy_revision_id - (Optional) The revision ID of the project policy that you want to update.\n\n";
   
           if (args.length < 3 || args.length > 4) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           String projectArn = args[0];
           String projectPolicyName = args[1];
           String projectPolicyDocument = args[2];
           String projectPolicyRevisionId = null;
   
           if (args.length == 4) {
               projectPolicyRevisionId = args[3];
           }
   
           try {
   
               RekognitionClient rekClient = RekognitionClient.builder()
               .credentialsProvider(ProfileCredentialsProvider.create("custom-labels-access"))
               .region(Region.US_WEST_2)
               .build();
   
           
               // Attach the project policy.
               putMyProjectPolicy(rekClient, projectArn, projectPolicyName, projectPolicyDocument,
                       projectPolicyRevisionId);
   
               System.out.println(
                       String.format("project policy %s: attached to project: %s", projectPolicyName, projectArn));
   
               rekClient.close();
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               System.exit(1);
           }
   
           catch (IOException intError) {
               logger.log(Level.SEVERE, "Exception while reading policy document: {0}", intError.getMessage());
               System.exit(1);
           }
   
       }
   
   }
   ```

------

1. Copy the model version by following the instructions at [Copying a model (SDK)](md-copy-model-sdk.md). 

# Copying a model (SDK)


You can use the `CopyProjectVersion` API to copy a model version from a source project to a destination project. The destination project can be in a different AWS account but must be the same AWS Region. If the destination project is in a different AWS account (or if you want to grant specific permissions for a model version copied within an AWS account), you must attach a project policy to the source project. For more information, see [Creating a project policy document](md-create-project-policy-document.md). The `CopyProjectVersion` API requires access to your Amazon S3 bucket. 

The copied model includes the training results for the source model, but doesn't include the source datasets.

The source AWS account has no ownership over the model copied into a destination account, unless you set up appropriate permissions.

**To copy a model (SDK)**

1. If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 4: Set up the AWS CLI and AWS SDKs](su-awscli-sdk.md).

1. Attach a project policy to the source project by following the instructions at [Attaching a project policy (SDK)](md-attach-project-policy.md). 

1. If you are copying the model to a different AWS account, make sure that you have a project in the destination AWS account. 

1. Use the following code to copy the model version to a destination project.

------
#### [ AWS CLI ]

   Change the following values:
   + `source-project-arn` to the ARN of the source project that contains the model version that you want to copy. 
   + `source-project-version-arn` to the ARN of the model version that that you want to copy. 
   + `destination-project-arn` to the ARN of the destination project that you want to copy the model to. 
   + `version-name` to a version name for the model in the destination project. 
   + `bucket` to the S3 bucket that you want the training results for the source model copied to. 
   + `folder` to the folder in `bucket` that you want the training results for the source model copied to. 
   + (Optional) `kms-key-id` to the AWS Key Management Service key ID for the model. 
   + (Optional) `key` to a tag key of your choosing. 
   + (Optional) `value` to a tag value of your choosing. 

   ```
   aws rekognition copy-project-version \
     --source-project-arn source-project-arn \
     --source-project-version-arn source-project-version-arn \
     --destination-project-arn destination-project-arn \
     --version-name version-name \
     --output-config '{"S3Bucket":"bucket","S3KeyPrefix":"folder"}' \
     --kms-key-id arn:myKey \
     --tags '{"key":"key"}' \
     --profile custom-labels-access
   ```

------
#### [ Python ]

   Use the following code. Supply the following command line parameters:
   + `source_project_arn` — the ARN of the source project in the source AWS account that contains the model version that you want to copy. 
   + `source_project_version-arn` — the ARN of the model version in the source AWS account that that you want to copy. 
   + `destination_project_arn` — the ARN of the destination project that you want to copy the model to. 
   + `destination_version_name` — a version name for the model in the destination project. 
   + `training_results` — the S3 location that you want the training results for the source model version copied to. 
   + (Optional) `kms_key_id` to the AWS Key Management Service key ID for the model. 
   + (Optional) `tag_name` to a tag key of your choosing. 
   + (Optional) `tag_value` to a tag value of your choosing. 

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   import argparse
   import logging
   import time
   import boto3
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   
   def copy_model(
       rekognition_client, source_project_arn, source_project_version_arn,
           destination_project_arn, training_results, destination_version_name):
       """
       Copies a version of a Amazon Rekognition Custom Labels model.
   
       :param rekognition_client: A Boto3 Amazon Rekognition Custom Labels client.
       :param source_project_arn: The ARN of the source project that contains the
       model that you want to copy.
       :param source_project_version_arn: The ARN of the model version that you want
       to copy.
       :param destination_project_Arn: The ARN of the project that you want to copy the model
       to.
       :param training_results: The Amazon S3 location where training results for the model
       should be stored.
       return: The model status and version.
       """
       try:
           logger.info("Copying model...%s from %s to %s ", source_project_version_arn,
                       source_project_arn,
                       destination_project_arn)
   
           output_bucket, output_folder = training_results.replace(
               "s3://", "").split("/", 1)
           output_config = {"S3Bucket": output_bucket,
                            "S3KeyPrefix": output_folder}
   
           response = rekognition_client.copy_project_version(
               DestinationProjectArn=destination_project_arn,
               OutputConfig=output_config,
               SourceProjectArn=source_project_arn,
               SourceProjectVersionArn=source_project_version_arn,
               VersionName=destination_version_name
           )
   
           destination_model_arn = response["ProjectVersionArn"]
   
           logger.info("Destination model ARN: %s", destination_model_arn)
   
           # Wait until training completes.
           finished = False
           status = "UNKNOWN"
           while finished is False:
               model_description = rekognition_client.describe_project_versions(ProjectArn=destination_project_arn,
                       VersionNames=[destination_version_name])
               status = model_description["ProjectVersionDescriptions"][0]["Status"]
   
               if status == "COPYING_IN_PROGRESS":
                   logger.info("Model copying in progress...")
                   time.sleep(60)
                   continue
   
               if status == "COPYING_COMPLETED":
                   logger.info("Model was successfully copied.")
   
               if status == "COPYING_FAILED":
                   logger.info(
                       "Model copy failed: %s ",
                       model_description["ProjectVersionDescriptions"][0]["StatusMessage"])
   
               finished = True
       except ClientError:
           logger.exception("Couldn't copy model.")
           raise
       else:
           return destination_model_arn, status
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "source_project_arn",
           help="The ARN of the project that contains the model that you want to copy."
       )
   
       parser.add_argument(
           "source_project_version_arn",
           help="The ARN of the model version that you want to copy."
       )
   
       parser.add_argument(
           "destination_project_arn",
           help="The ARN of the project which receives the copied model."
       )
   
       parser.add_argument(
           "destination_version_name",
           help="The version name for the model in the destination project."
       )
   
       parser.add_argument(
           "training_results",
           help="The S3 location in the destination account that receives the training results for the copied model."
       )
   
   
   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()
   
           print(
               f"Copying model version {args.source_project_version_arn} to project {args.destination_project_arn}")
   
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
   
           # Copy the model.
   
           model_arn, status = copy_model(rekognition_client,
                                          args.source_project_arn,
                                          args.source_project_version_arn,
                                          args.destination_project_arn,
                                          args.training_results,
                                          args.destination_version_name,
                                          )
   
           print(f"Finished copying model: {model_arn}")
           print(f"Status: {status}")
   
       except ClientError as err:
           print(f"Problem copying model: {err}")
   
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Java V2 ]

   Use the following code. Supply the following command line parameters:
   + `source_project_arn` — the ARN of the source project in the source AWS account that contains the model version that you want to copy. 
   + `source_project_version-arn` — the ARN of the model version in the source AWS account that that you want to copy. 
   + `destination_project_arn` — the ARN of the destination project that you want to copy the model to. 
   + `destination_version_name` — a version name for the model in the destination project. 
   + `output_bucket` — the S3 bucket that you want the training results for the source model version copied to. 
   + `output_folder` — the folder in the S3 that you want the training results for the source model version copied to. 

   ```
   /*
      Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
      SPDX-License-Identifier: Apache-2.0
   */
   
   package com.example.rekognition;
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.CopyProjectVersionRequest;
   import software.amazon.awssdk.services.rekognition.model.CopyProjectVersionResponse;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsRequest;
   import software.amazon.awssdk.services.rekognition.model.DescribeProjectVersionsResponse;
   import software.amazon.awssdk.services.rekognition.model.OutputConfig;
   import software.amazon.awssdk.services.rekognition.model.ProjectVersionDescription;
   
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   public class CopyModel {
   
       public static final Logger logger = Logger.getLogger(CopyModel.class.getName());
   
       public static ProjectVersionDescription copyMyModel(RekognitionClient rekClient,
               String sourceProjectArn,
               String sourceProjectVersionArn,
               String destinationProjectArn,
               String versionName,
               String outputBucket,
               String outputFolder) throws InterruptedException {
   
           try {
   
               OutputConfig outputConfig = OutputConfig.builder().s3Bucket(outputBucket).s3KeyPrefix(outputFolder).build();
   
               String[] logArguments = new String[] { versionName, sourceProjectArn, destinationProjectArn };
   
               logger.log(Level.INFO, "Copying model {0} for from project {1} to project {2}", logArguments);
   
               CopyProjectVersionRequest copyProjectVersionRequest = CopyProjectVersionRequest.builder()
                       .sourceProjectArn(sourceProjectArn)
                       .sourceProjectVersionArn(sourceProjectVersionArn)
                       .versionName(versionName)
                       .destinationProjectArn(destinationProjectArn)
                       .outputConfig(outputConfig)
                       .build();
   
               CopyProjectVersionResponse response = rekClient.copyProjectVersion(copyProjectVersionRequest);
   
               logger.log(Level.INFO, "Destination model ARN: {0}", response.projectVersionArn());
               logger.log(Level.INFO, "Copying model...");
   
               // wait until copying completes.
   
               boolean finished = false;
   
               ProjectVersionDescription copiedModel = null;
   
               while (Boolean.FALSE.equals(finished)) {
                   DescribeProjectVersionsRequest describeProjectVersionsRequest = DescribeProjectVersionsRequest.builder()
                           .versionNames(versionName)
                           .projectArn(destinationProjectArn)
                           .build();
   
                   DescribeProjectVersionsResponse describeProjectVersionsResponse = rekClient
                           .describeProjectVersions(describeProjectVersionsRequest);
   
                   for (ProjectVersionDescription projectVersionDescription : describeProjectVersionsResponse
                           .projectVersionDescriptions()) {
   
                       copiedModel = projectVersionDescription;
   
                       switch (projectVersionDescription.status()) {
   
                           case COPYING_IN_PROGRESS:
                               logger.log(Level.INFO, "Copying model...");
                               Thread.sleep(5000);
                               continue;
   
                           case COPYING_COMPLETED:
                               finished = true;
                               logger.log(Level.INFO, "Copying completed");
                               break;
   
                           case COPYING_FAILED:
                               finished = true;
                               logger.log(Level.INFO, "Copying failed...");
                               break;
   
                           default:
                               finished = true;
                               logger.log(Level.INFO, "Unexpected copy status %s",
                                       projectVersionDescription.statusAsString());
                               break;
   
                       }
   
                   }
   
               }
   
               logger.log(Level.INFO, "Finished copying model {0} for from project {1} to project {2}", logArguments);
   
               return copiedModel;
   
           } catch (RekognitionException e) {
               logger.log(Level.SEVERE, "Could not train model: {0}", e.getMessage());
               throw e;
           }
   
       }
   
       public static void main(String args[]) {
   
           String sourceProjectArn = null;
           String sourceProjectVersionArn = null;
           String destinationProjectArn = null;
           String versionName = null;
           String bucket = null;
           String location = null;
   
           final String USAGE = "\n" + "Usage: "
                   + "<source_project_arn> <source_project_version_arn> <destination_project_arn> <version_name> <output_bucket> <output_folder>\n\n"
                   + "Where:\n"
                   + "   source_project_arn - The ARN of the project that contains the model that you want to copy. \n\n"
                   + "   source_project_version_arn - The ARN of the project that contains the model that you want to copy. \n\n"
                   + "   destination_project_arn - The ARN of the destination project that you want to copy the model to. \n\n"
                   + "   version_name - A version name for the copied model.\n\n"
                   + "   output_bucket - The S3 bucket in which to place the training output. \n\n"
                   + "   output_folder - The folder within the bucket that the training output is stored in. \n\n";
   
           if (args.length != 6) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           sourceProjectArn = args[0];
           sourceProjectVersionArn = args[1];
           destinationProjectArn = args[2];
           versionName = args[3];
           bucket = args[4];
           location = args[5];
   
           try {
   
               // Get the Rekognition client.
               RekognitionClient rekClient = RekognitionClient.builder()
               .credentialsProvider(ProfileCredentialsProvider.create("custom-labels-access"))
               .region(Region.US_WEST_2)
               .build();
   
               // Copy the model.
               ProjectVersionDescription copiedModel = copyMyModel(rekClient,
                       sourceProjectArn,
                       sourceProjectVersionArn,
                       destinationProjectArn,
                       versionName,
                       bucket,
                       location);
   
               System.out.println(String.format("Model copied: %s Status: %s",
                       copiedModel.projectVersionArn(),
                       copiedModel.statusMessage()));
   
               rekClient.close();
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               System.exit(1);
           } catch (InterruptedException intError) {
               logger.log(Level.SEVERE, "Exception while sleeping: {0}", intError.getMessage());
               System.exit(1);
           }
   
       }
   
   }
   ```

------

# Listing project policies (SDK)


You can use the [ListProjectPolicies](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListProjectPolicies) operation to list the project policies that are attached to an Amazon Rekognition Custom Labels project.

**To list the project policies attached to a project (SDK)**

1. If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 4: Set up the AWS CLI and AWS SDKs](su-awscli-sdk.md).

1. Use the following code to list the project policies.

------
#### [ AWS CLI ]

   Change `project-arn` to the Amazon Resource Name of the project for which you want to list the attached project policies.

   ```
   aws rekognition list-project-policies \
     --project-arn project-arn \
     --profile custom-labels-access
   ```

------
#### [ Python ]

   Use the following code. Supply the following command line parameters:
   + project\$1arn — the Amazon Resource Name of the project for which you want to list the attached project policies. 

   For example: `python list_project_policies.py project_arn `

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Amazon Rekognition Custom Labels model example used in the service documentation:
   https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/md-copy-model-sdk.html
   Shows how to list the project policies in an Amazon Rekogntion Custom Labels project.
   """
   
   
   import argparse
   import logging
   import boto3
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   
   def display_project_policy(project_policy):
       """
       Displays information about a Custom Labels project policy.
       :param project_policy: The project policy (ProjectPolicy)
       that you want to display information about.
       """
       print(f"Policy name: {(project_policy['PolicyName'])}")
       print(f"Project Arn: {project_policy['ProjectArn']}")
       print(f"Document: {(project_policy['PolicyDocument'])}")
       print(f"Revision ID: {(project_policy['PolicyRevisionId'])}")
       print()
   
   
   
   def list_project_policies(rek_client, project_arn):
       """
       Describes an Amazon Rekognition Custom Labels project, or all projects.
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param project_arn: The Amazon Resource Name of the project you want to use.
       """
   
       try:
   
           max_results = 5
           pagination_token = ''
           finished = False
   
           logger.info("Listing project policies in: %s.", project_arn)
           print('Projects\n--------')
           while not finished:
   
               response = rek_client.list_project_policies(
                   ProjectArn=project_arn, MaxResults=max_results, NextToken=pagination_token)
   
               for project in response['ProjectPolicies']:
                   display_project_policy(project)
   
               if 'NextToken' in response:
                   pagination_token = response['NextToken']
               else:
                   finished = True
   
           logger.info("Finished listing project policies.")
   
       except ClientError as err:
           logger.exception(
               "Couldn't list policies for - %s: %s",
               project_arn,err.response['Error']['Message'])
           raise
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "project_arn",  help="The Amazon Resource Name of the project for which you want to list project policies."
       )
   
   
   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()
   
           print(f"Listing project policies in: {args.project_arn}")
   
           # List the project policies.
   
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
   
           list_project_policies(rekognition_client,
                                 args.project_arn)
   
       except ClientError as err:
           print(f"Problem list project_policies: {err}")
   
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Java V2 ]

   Use the following code. Supply the following command line parameters:
   + project\$1arn — The ARN of the project that has the project polices you want to list.

   ```
   /*
      Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
      SPDX-License-Identifier: Apache-2.0
   */
   
   package com.example.rekognition;
   
   import java.util.logging.Level;
   import java.util.logging.Logger;
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.ListProjectPoliciesRequest;
   import software.amazon.awssdk.services.rekognition.model.ListProjectPoliciesResponse;
   import software.amazon.awssdk.services.rekognition.model.ProjectPolicy;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   
   public class ListProjectPolicies {
   
       public static final Logger logger = Logger.getLogger(ListProjectPolicies.class.getName());
   
       public static void listMyProjectPolicies(RekognitionClient rekClient, String projectArn) {
   
           try {
   
               logger.log(Level.INFO, "Listing project policies for project: {0}", projectArn);
   
               // List the project policies.
   
               Boolean finished = false;
               String nextToken = null;
   
               while (Boolean.FALSE.equals(finished)) {
   
                   ListProjectPoliciesRequest listProjectPoliciesRequest = ListProjectPoliciesRequest.builder()
                           .maxResults(5)
                           .projectArn(projectArn)
                           .nextToken(nextToken)
                           .build();
   
                   ListProjectPoliciesResponse response = rekClient.listProjectPolicies(listProjectPoliciesRequest);
   
                   for (ProjectPolicy projectPolicy : response.projectPolicies()) {
   
                       System.out.println(String.format("Name: %s", projectPolicy.policyName()));
                       System.out.println(String.format("Revision ID: %s\n", projectPolicy.policyRevisionId()));
   
                   }
   
                   nextToken = response.nextToken();
   
                   if (nextToken == null) {
                       finished = true;
   
                   }
   
               }
   
               logger.log(Level.INFO, "Finished listing project policies for project: {0}", projectArn);
   
           } catch (
   
           RekognitionException e) {
               logger.log(Level.SEVERE, "Client error occurred: {0}", e.getMessage());
               throw e;
           }
   
       }
   
       public static void main(String args[]) {
   
           final String USAGE = "\n" + "Usage: " + "<project_arn> \n\n" + "Where:\n"
                   + "   project_arn - The ARN of the project with the project policies that you want to list.\n\n";
           ;
   
           if (args.length != 1) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           String projectArn = args[0];
   
           try {
   
               RekognitionClient rekClient = RekognitionClient.builder()
               .credentialsProvider(ProfileCredentialsProvider.create("custom-labels-access"))
               .region(Region.US_WEST_2)
               .build();
         
               // List the project policies.
               listMyProjectPolicies(rekClient, projectArn);
   
               rekClient.close();
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               System.exit(1);
           }
   
       }
   
   }
   ```

------

# Deleting a project policy (SDK)


You can use the [DeleteProjectPolicy](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteProjectPolicy) operation to delete a revision of an existing project policy from an Amazon Rekognition Custom Labels project. If you want to delete all revisions of a project policy that are attached to a project, use [ListProjectPolicies](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListProjectPolicies) to get the revision IDs of each project policy attached to the project. Then call `DeletePolicy` for each policy name. 

**To delete a revision of a project policy (SDK)**

1. If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 4: Set up the AWS CLI and AWS SDKs](su-awscli-sdk.md).

1. Use the following code to delete a project policy.

   DeletePolicy takes `ProjectARN`, `PolicyName` and `PolicyRevisionId`. `ProjectARN` and `PolicyName` are required for this API. `PolicyRevisionId` is optional, but can be included for the purposes of atomic updates.

------
#### [ AWS CLI ]

   Change the following values:
   + `policy-name` to the name of the project policy that you want to delete. 
   + `policy-revision-id` to the revision ID of the project policy that you want to delete. 
   + `project-arn` to the Amazon Resource Name of the project that contains the revision of the project policy that you want to delete.

   ```
   aws rekognition delete-project-policy \
       --policy-name policy-name \
       --policy-revision-id policy-revision-id \
       --project-arn project-arn \
     --profile custom-labels-access
   ```

------
#### [ Python ]

   Use the following code. Supply the following command line parameters:
   + `policy-name` – The name of the project policy that you want to delete. 
   + `project-arn` – The Amazon Resource Name of the project that contains the project policy that you want to delete.
   + `policy-revision-id` – The revision ID of the project policy that you want to delete. 

   For example: `python delete_project_policy.py policy_name project_arn` *policy\$1revision\$1id* 

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Amazon Rekognition Custom Labels model example used in the service documentation:
   https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/md-copy-model-sdk.html
   Shows how to delete a revision of a project policy.
   """
   
   import argparse
   import logging
   import boto3
   from botocore.exceptions import ClientError
   
   logger = logging.getLogger(__name__)
   
   
   def delete_project_policy(rekognition_client, policy_name,  project_arn, policy_revision_id=None):
       """
       Deletes a project policy.
   
       :param rekognition_client: A Boto3 Amazon Rekognition client.
       :param policy_name: The name of the project policy that you want to delete.
       :param policy_revision_id: The revsion ID for the project policy that you want to delete.
       :param project_arn: The Amazon Resource Name of the project that contains the project policy
       that you want to delete.
       """
       try:
           logger.info("Deleting project policy: %s", policy_name)
   
           if policy_revision_id is None:
               rekognition_client.delete_project_policy(
                   PolicyName=policy_name,
                   ProjectArn=project_arn)
   
           else:
               rekognition_client.delete_project_policy(
                   PolicyName=policy_name,
                   PolicyRevisionId=policy_revision_id,
                   ProjectArn=project_arn)
   
           logger.info("Deleted project policy: %s", policy_name)
       except ClientError:
           logger.exception("Couldn't delete project policy.")
           raise
   
   
   def confirm_project_policy_deletion(policy_name):
       """
       Confirms deletion of the project policy. Returns True if delete entered.
       :param model_arn: The ARN of the model that you want to delete.
       """
       print(
           f"Are you sure you wany to delete project policy {policy_name} ?\n", policy_name)
   
       delete = input("Enter delete to delete your project policy: ")
       if delete == "delete":
           return True
       else:
           return False
   
   
   def add_arguments(parser):
       """
       Adds command line arguments to the parser.
       :param parser: The command line parser.
       """
   
       parser.add_argument(
           "policy_name", help="The ARN of the project that contains the project policy that you want to delete."
       )
   
       parser.add_argument(
           "project_arn", help="The ARN of the project project policy you want to delete."
       )
   
       parser.add_argument(
           "--policy_revision_id", help="(Optional) The revision ID of the project policy that you want to delete.",
           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()
   
           if confirm_project_policy_deletion(args.policy_name) is True:
               print(f"Deleting project_policy: {args.policy_name}")
   
               session = boto3.Session(profile_name='custom-labels-access')
               rekognition_client = session.client("rekognition")
   
               # Delete the project policy.
   
               delete_project_policy(rekognition_client,
                                     args.policy_name,
                                     args.project_arn,
                                     args.policy_revision_id)
   
               print(f"Finished deleting project policy: {args.policy_name}")
           else:
               print(f"Not deleting project policy {args.policy_name}")
       except ClientError as err:
           print(f"Couldn't delete project policy in {args.policy_name}: {err}")
   
   
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Java V2 ]

   Use the following code. Supply the following command line parameters:
   + `policy-name` – The name of the project policy that you want to delete. 
   + `project-arn` – The Amazon Resource Name of the project that contains the project policy that you want to delete.
   + `policy-revision-id` – The revision ID of the project policy that you want to delete. 

   ```
   /*
      Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
      SPDX-License-Identifier: Apache-2.0
   */
   
   package com.example.rekognition;
   
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.DeleteProjectPolicyRequest;
   
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   
   public class DeleteProjectPolicy {
   
       public static final Logger logger = Logger.getLogger(DeleteProjectPolicy.class.getName());
   
       public static void deleteMyProjectPolicy(RekognitionClient rekClient, String projectArn,
               String projectPolicyName,
               String projectPolicyRevisionId)
               throws InterruptedException {
   
           try {
               String[] logArguments = new String[] { projectPolicyName, projectPolicyRevisionId };
   
               logger.log(Level.INFO, "Deleting: Project policy: {0} revision: {1}", logArguments);
   
               // Delete the project policy.
   
               DeleteProjectPolicyRequest deleteProjectPolicyRequest = DeleteProjectPolicyRequest.builder()
                       .policyName(projectPolicyName)
                       .policyRevisionId(projectPolicyRevisionId)
                       .projectArn(projectArn).build();
   
               rekClient.deleteProjectPolicy(deleteProjectPolicyRequest);
   
               logger.log(Level.INFO, "Deleted: Project policy: {0} revision: {1}", logArguments);
   
           } catch (
   
           RekognitionException e) {
               logger.log(Level.SEVERE, "Client error occurred: {0}", e.getMessage());
               throw e;
           }
   
       }
   
       public static void main(String args[]) {
   
           final String USAGE = "\n" + "Usage: " + "<project_arn> <project_policy_name> <project_policy_revision_id>\n\n"
                   + "Where:\n"
                   + "   project_arn - The ARN of the project that has the project policy that you want to delete.\n\n"
                   + "   project_policy_name - The name of the project policy that you want to delete.\n\n"
                   + "   project_policy_revision_id - The revision of the project policy that you want to delete.\n\n";
   
           if (args.length != 3) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           String projectArn = args[0];
           String projectPolicyName = args[1];
           String projectPolicyRevisionId = args[2];
   
           try {
   
               RekognitionClient rekClient = RekognitionClient.builder()
               .credentialsProvider(ProfileCredentialsProvider.create("custom-labels-access"))
               .region(Region.US_WEST_2)
               .build();
   
               // Delete the project policy.
               deleteMyProjectPolicy(rekClient, projectArn, projectPolicyName, projectPolicyRevisionId);
   
               System.out.println(String.format("project policy deleted: %s revision: %s", projectPolicyName,
                       projectPolicyRevisionId));
   
               rekClient.close();
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               System.exit(1);
           }
   
           catch (InterruptedException intError) {
               logger.log(Level.SEVERE, "Exception while sleeping: {0}", intError.getMessage());
               System.exit(1);
           }
   
       }
   
   }
   ```

------