

# Copying an Amazon Rekognition Custom Labels model (SDK)
<a name="md-copy-model-overview"></a>

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
<a name="md-create-project-policy-document"></a>

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)
<a name="md-attach-project-policy"></a>

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)
<a name="md-copy-model-sdk"></a>

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)
<a name="md-list-project-policies"></a>

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)
<a name="md-delete-project-policy.title"></a>

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);
           }
   
       }
   
   }
   ```

------