

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 停止 Amazon Rekognition 自訂標籤模型
<a name="rm-stop"></a>

您可以使用主控台或 [停止專案版本](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) 操作停止執行 Amazon Rekognition 自訂標籤模型。

**Topics**
+ [停止 Amazon Rekognition 自訂標籤模型 (主控台)](#rm-stop-console)
+ [停止 Amazon Rekognition 自訂標籤模型 (SDK)](#rm-stop-sdk)

## 停止 Amazon Rekognition 自訂標籤模型 (主控台)
<a name="rm-stop-console"></a>

請使用以下步驟來停止執行中的 Amazon Rekognition 自訂標籤模型。您可以從 主控台直接停止模型，或使用 主控台提供的 AWS SDK 程式碼。

**停止模型 (主控台)**

1. 開啟 Amazon Rekognition 主控台：[https://console.aws.amazon.com/rekognition/](https://console.aws.amazon.com/rekognition/)。

1. 選擇**使用自訂標籤**。

1. 選擇**開始使用**。

1. 在左側導覽視窗中，選擇 **專案**。

1. 在 **專案** 頁面中，選擇包含要停止的培訓模型的專案。

1. 在 **模型** 的區域中，選擇您要停止的模型。

1. 選擇 **使用模型** 標籤。

1. 

------
#### [ Stop model using the console ]

   1. 在 **啟動或停止模型** 的區域中，選擇 **停止**。

   1. 在 **停止模型** 的對話框中，輸入 **停止** 以確認您要停止模型。

   1. 選擇 **停止** 以停止模型。

------
#### [ Stop model using the AWS SDK ]

   在 **使用模型** 的區域中，執行以下操作：

   1. 選擇 **API 程式碼。**

   1. 選擇 **AWS CLI** 或 **Python**。

   1. 在 **停止模型** 中複製範例程式碼。

   1. 使用範例程式碼來停止模型。如需詳細資訊，請參閱[停止 Amazon Rekognition 自訂標籤模型 (SDK)](#rm-stop-sdk)。

------

1. 在頁面頂端選擇您的專案名稱，以返回專案概述頁面。

1. 在 **模型** 的區域中，檢查模型的狀態。當模型狀態顯示為 **已停止** 時，則表示模型已經停止。

## 停止 Amazon Rekognition 自訂標籤模型 (SDK)
<a name="rm-stop-sdk"></a>

您可以透過呼叫 [停止專案版本](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StopProjectVersion) API 並在 `ProjectVersionArn` 輸入參數中傳遞模型的 Amazon Resource Name (ARN) 來停止模型。

模型可能需要一段時間才能停止。若要檢查目前狀態，請使用 `DescribeProjectVersions`。

**停止模型 (SDK)**

1. 如果您尚未這麼做，請安裝並設定 AWS CLI 和 AWS SDKs。如需詳細資訊，請參閱[步驟 4：設定 AWS CLI 和 AWS SDKs](su-awscli-sdk.md)。

1. 使用下列範例程式碼來停止執行中的模型。

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

   將 `project-version-arn` 的值變更為您要停止的模型版本的 ARN。

   ```
   aws rekognition stop-project-version --project-version-arn "model arn" \
     --profile custom-labels-access
   ```

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

   以下範例會停止已在執行中的模型。

   請提供以下命令列參數：
   + `project_arn` — 包含您要停止的模型的專案的 ARN。
   + `model_arn` — 您要停止的模型 ARN。

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   
   """
   Purpose
   Shows how to stop a running Amazon Lookout for Vision model.
   """
   
   import argparse
   import logging
   import time
   import boto3
   
   from botocore.exceptions import ClientError
   
   
   logger = logging.getLogger(__name__)
   
   
   def get_model_status(rek_client, project_arn, model_arn):
       """
       Gets the current status of an Amazon Rekognition Custom Labels model
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param project_name:  The name of the project that you want to use.
       :param model_arn:  The name of the model that you want the status for.
       """
   
       logger.info ("Getting status for %s.", model_arn)
   
       # Extract the model version from the model arn.
       version_name=(model_arn.split("version/",1)[1]).rpartition('/')[0]
   
       # Get the model status.
       models=rek_client.describe_project_versions(ProjectArn=project_arn,
       VersionNames=[version_name])
   
       for model in models['ProjectVersionDescriptions']: 
           logger.info("Status: %s",model['StatusMessage'])
           return model["Status"]
   
       # No model found.
       logger.exception("Model %s not found.", model_arn)
       raise Exception("Model %s not found.", model_arn)
   
   
   def stop_model(rek_client, project_arn, model_arn):
       """
       Stops a running Amazon Rekognition Custom Labels Model.
       :param rek_client: The Amazon Rekognition Custom Labels Boto3 client.
       :param project_arn: The ARN of the project that you want to stop running.
       :param model_arn:  The ARN of the model (ProjectVersion) that you want to stop running.
       """
   
       logger.info("Stopping model: %s", model_arn)
   
       try:
           # Stop the model.
           response=rek_client.stop_project_version(ProjectVersionArn=model_arn)
   
           logger.info("Status: %s", response['Status'])
   
           # stops when hosting has stopped or failure.
           status = ""
           finished = False
   
           while finished is False:
   
               status=get_model_status(rek_client, project_arn, model_arn)
   
               if status == "STOPPING":
                   logger.info("Model stopping in progress...")
                   time.sleep(10)
                   continue
               if status == "STOPPED":
                   logger.info("Model is not running.")
                   finished = True
                   continue
   
               error_message = f"Error stopping model. Unexepected state: {status}"
               logger.exception(error_message)
               raise Exception(error_message)
   
           logger.info("finished. Status %s", status)
           return status
   
       except ClientError as err:
           logger.exception("Couldn't stop 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 stop."
       )
       parser.add_argument(
           "model_arn", help="The ARN of the model that you want to stop."
       )
   
   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()
   
           # Stop the model.
           session = boto3.Session(profile_name='custom-labels-access')
           rekognition_client = session.client("rekognition")
   
           status=stop_model(rekognition_client, args.project_arn, args.model_arn)
   
           print(f"Finished stopping model: {args.model_arn}")
           print(f"Status: {status}")
   
       except ClientError as err:
           logger.exception("Problem stopping model:%s",err)
           print(f"Failed to stop model: {err}")
       
       except Exception as err:
           logger.exception("Problem stopping model:%s", err)
           print(f"Failed to stop model: {err}")
   
   if __name__ == "__main__":
       main()
   ```

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

   請提供以下命令列參數：
   + `project_arn` — 包含您要停止的模型的專案的 ARN。
   + `model_arn` — 您要停止的模型 ARN。

   ```
   /*
      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.ProjectVersionDescription;
   import software.amazon.awssdk.services.rekognition.model.ProjectVersionStatus;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.StopProjectVersionRequest;
   import software.amazon.awssdk.services.rekognition.model.StopProjectVersionResponse;
   
   
   import java.util.logging.Level;
   import java.util.logging.Logger;
   
   public class StopModel {
   
       public static final Logger logger = Logger.getLogger(StopModel.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 stopMyModel(RekognitionClient rekClient, String projectArn, String modelArn)
               throws Exception, RekognitionException {
   
           try {
   
               logger.log(Level.INFO, "Stopping {0}", modelArn);
   
               StopProjectVersionRequest stopProjectVersionRequest = StopProjectVersionRequest.builder()
                       .projectVersionArn(modelArn).build();
   
               StopProjectVersionResponse response = rekClient.stopProjectVersion(stopProjectVersionRequest);
   
               logger.log(Level.INFO, "Status: {0}", response.statusAsString());
   
               // Get the model version
   
               int start = findForwardSlash(modelArn, 3) + 1;
               int end = findForwardSlash(modelArn, 4);
   
               String versionName = modelArn.substring(start, end);
   
               // wait until model stops
   
               DescribeProjectVersionsRequest describeProjectVersionsRequest = DescribeProjectVersionsRequest.builder()
                       .projectArn(projectArn).versionNames(versionName).build();
   
               boolean stopped = false;
   
               // Wait until create finishes
   
               do {
   
                   DescribeProjectVersionsResponse describeProjectVersionsResponse = rekClient
                           .describeProjectVersions(describeProjectVersionsRequest);
   
                   for (ProjectVersionDescription projectVersionDescription : describeProjectVersionsResponse
                           .projectVersionDescriptions()) {
   
                       ProjectVersionStatus status = projectVersionDescription.status();
   
                       logger.log(Level.INFO, "stopping model: {0} ", modelArn);
   
                       switch (status) {
   
                       case STOPPED:
                           logger.log(Level.INFO, "Model stopped");
                           stopped = true;
                           break;
   
                       case STOPPING:
                           Thread.sleep(5000);
                           break;
   
                       case FAILED:
                           String error = "Model stopping failed: " + projectVersionDescription.statusAsString() + " "
                                   + projectVersionDescription.statusMessage() + " " + modelArn;
                           logger.log(Level.SEVERE, error);
                           throw new Exception(error);
   
                       default:
                           String unexpectedError = "Unexpected stopping state: "
                                   + projectVersionDescription.statusAsString() + " "
                                   + projectVersionDescription.statusMessage() + " " + modelArn;
                           logger.log(Level.SEVERE, unexpectedError);
                           throw new Exception(unexpectedError);
                       }
                   }
   
               } while (stopped == false);
   
           } catch (RekognitionException e) {
               logger.log(Level.SEVERE, "Could not stop model: {0}", e.getMessage());
               throw e;
           }
   
       }
   
       public static void main(String[] args) {
   
           String modelArn = null;
           String projectArn = null;
   
   
           final String USAGE = "\n" + "Usage: " + "<project_name> <version_name>\n\n" + "Where:\n"
                   + "   project_arn - The ARN of the project that contains the model that you want to stop. \n\n"
                   + "   model_arn - The ARN of the model version that you want to stop.\n\n";
   
           if (args.length != 2) {
               System.out.println(USAGE);
               System.exit(1);
           }
   
           projectArn = args[0];
           modelArn = args[1];
   
   
           try {
   
               // Get the Rekognition client.
               RekognitionClient rekClient = RekognitionClient.builder()
               .credentialsProvider(ProfileCredentialsProvider.create("custom-labels-access"))
               .region(Region.US_WEST_2)
               .build();
   
               // Stop model
               stopMyModel(rekClient, projectArn, modelArn);
   
               System.out.println(String.format("Model stopped: %s", modelArn));
   
               rekClient.close();
   
           } catch (RekognitionException rekError) {
               logger.log(Level.SEVERE, "Rekognition client error: {0}", rekError.getMessage());
               System.exit(1);
           } catch (Exception rekError) {
               logger.log(Level.SEVERE, "Error: {0}", rekError.getMessage());
               System.exit(1);
           }
   
       }
   
   }
   ```

------