

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

# 使用 Amazon Textract 分析身分文件
<a name="analyzing-document-identity"></a>

若要分析身分文件，您可以使用 AnalyzeID API 操作，並將文件檔案做為輸入傳遞。 `AnalyzeID`會傳回包含分析文字的 JSON 結構。如需詳細資訊，請參閱[分析身分文件](how-it-works-identity.md)。

您可以提供影像位元組陣列 (base64 編碼的影像位元組） 或 Amazon S3 物件的輸入文件。在此程序中，您會將映像檔案上傳至 S3 儲存貯體，並指定檔案名稱。

**分析身分文件 (API)**

1. 如果您尚未執行：

   1. 為使用者提供 `AmazonTextractFullAccess`和 `AmazonS3ReadOnlyAccess`許可。如需詳細資訊，請參閱[步驟 1：設定 AWS 帳戶並建立使用者](setting-up.md)。

   1. 安裝和設定 AWS CLI 和 AWS SDKs。如需詳細資訊，請參閱[步驟 2：設定 AWS CLI 和 AWS SDKs](setup-awscli-sdk.md)。

1. 將包含文件的影像上傳至 S3 儲存貯體。

   如需指示說明，請參閱《Amazon Simple Storage Service 使用者指南》**中的[上傳物件至 Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UploadingObjectsintoAmazonS3.html)。

1. 使用下列範例來呼叫 `AnalyzeID` 操作。

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

   

   下列範例會從 S3 儲存貯體接收輸入檔案，並在其上執行 `AnalyzeID`操作。在下列程式碼中，將 的值取代為 S3 儲存貯體`Bucket`的名稱，將 的值`Name`取代為儲存貯體中的檔案名稱。`profile-name` 將 取代為可擔任角色的設定檔名稱，並將 `region`取代為您要執行程式碼的區域。

   

   ```
   aws textract analyze-id \
       --document-pages '{"S3Object":{"Bucket":"{{bucket}}","Name":"{{name}}"}}' \
       --profile {{profile-name}} \
       --region {{region}}
   ```

   您也可以將另一個 Amazon S3 物件新增至輸入，以呼叫驅動程式授權正面和背面的 API。

   ```
   aws textract analyze-id \
       --document-pages '[{"S3Object":{"Bucket":"{{bucket}}","Name":"{{name front}}"}}, {"S3Object":{"Bucket":"{{bucket}}","Name":"{{name back}}"}}]' \
       --profile {{profile-name}} \
       --region {{region}}
   ```

   如果您在 Windows 裝置上存取 CLI，請使用雙引號而非單引號，並透過反斜線 (\\) 逸出內部雙引號，以解決您可能遇到的任何剖析器錯誤。例如，請參閱下列內容：

   ```
   aws textract analyze-id --document-pages "[{\"S3Object\":{\"Bucket\":\"{{bucket}}\",\"Name\":\"{{name}}\"}}]" --region {{region}}
   ```

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

   下列範例會從 S3 儲存貯體接收輸入檔案，並在其上執行 `AnalyzeID`操作，並傳回偵測到的鍵/值對。在下列程式碼中，將 的值取代為 S3 儲存貯體`bucket_name`的名稱，將 的值`file_name`取代為儲存貯體中的檔案名稱。`profile-name` 將 取代為可擔任角色的設定檔名稱，並將 `region`取代為您要執行程式碼的區域。

   ```
   import boto3
   
   def analyze_id(client, bucket_name, file_name):
   
       # Analyze document
       # process using S3 object
       response = client.analyze_id(
           DocumentPages=[{'S3Object': {'Bucket': bucket_name, 'Name': file_name}}])
   
       for doc_fields in response['IdentityDocuments']:
           for id_field in doc_fields['IdentityDocumentFields']:
               for key, val in id_field.items():
                   if "Type" in str(key):
                       print("Type: " + str(val['Text']))
               for key, val in id_field.items():
                   if "ValueDetection" in str(key):
                       print("Value Detection: " + str(val['Text']))
               print()
   
   def main():
       session = boto3.Session(profile_name='profile-name')
       client = session.client('textract', region_name='region')
       bucket_name = "bucket"
       file_name = "file"
   
       analyze_id(client, bucket_name, file_name)
   
   if __name__ == "__main__":
       main()
   ```

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

   下列範例會從 S3 儲存貯體接收輸入檔案，並在其上執行 `AnalyzeID`操作，並傳回偵測到的資料。在函數主要中，將 `s3bucket`和 的值取代`sourceDoc`為您在步驟 2 中使用的 Amazon S3 儲存貯體和文件映像的名稱。使用您開發人員設定檔的名稱取代 `credentialsProvider` 的值。

   ```
   /*
      Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
      SPDX-License-Identifier: Apache-2.0
   */
   
   package com.amazonaws.samples;
   
   
   import com.amazonaws.auth.profile.ProfileCredentialsProvider;
   import com.amazonaws.regions.Regions;
   import com.amazonaws.services.textract.AmazonTextractClient;
   import com.amazonaws.services.textract.AmazonTextractClientBuilder;
   import com.amazonaws.services.textract.model.*;
   import java.util.ArrayList;
   import java.util.List;
   
   public class AppTest1 {
   
    public static void main(String[] args) {
   
        final String USAGE = "\n" +
                "Usage:\n" +
                "    <s3bucket><sourceDoc> \n\n" +
                "Where:\n" +
                "    s3bucket - the Amazon S3 bucket where the document is located. \n" +
                "    sourceDoc - the name of the document. \n";
   
        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }
        
        
     // set provider credentials
        AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider("default");
   
        String s3bucket = "bucket-name"; //args[0];
        String sourceDoc = "sourcedoc-name";  //args[1];
        AmazonTextractClient textractClient = (AmazonTextractClient) AmazonTextractClientBuilder.standard().withCredentials(credentialsProvider)
                .withRegion(Regions.US_EAST_1)
                .build();
   
        getDocDetails(textractClient, s3bucket, sourceDoc);
    }
   
    public static void getDocDetails(AmazonTextractClient textractClient, String s3bucket, String sourceDoc ) {
   
       try {
   
            S3Object s3 = new S3Object();
            s3.setBucket(s3bucket);
            s3.setName(sourceDoc);
   
            com.amazonaws.services.textract.model.Document myDoc = new com.amazonaws.services.textract.model.Document();
            myDoc.setS3Object(s3);
   
            List<Document> list1 = new ArrayList();
            list1.add(myDoc);
   
            AnalyzeIDRequest idRequest = new AnalyzeIDRequest();
            idRequest.setDocumentPages(list1);
   
            AnalyzeIDResult result = textractClient.analyzeID(idRequest);
            List<IdentityDocument> docs =  result.getIdentityDocuments();
            for (IdentityDocument doc: docs) {
   
                List<IdentityDocumentField>idFields = doc.getIdentityDocumentFields();
                for (IdentityDocumentField field: idFields) {
                    System.out.println("Field type is "+ field.getType().getText());
                    System.out.println("Field value is "+ field.getValueDetection().getText());
                }
            }
   
       } catch (Exception e) {
            e.printStackTrace();
       }
    }
   }
   ```

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

   下列範例會從 S3 儲存貯體接收輸入檔案，並在其上執行 `AnalyzeID`操作，並傳回偵測到的資料。在函數主控中，將 `s3bucket`和 的值取代`sourceDoc`為您在步驟 2 中使用的 S3 儲存貯體和文件映像的名稱。

   在建立 的 行`profile-name`中`TextractClient`，將 取代為您的開發人員設定檔名稱。

   ```
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.core.SdkBytes;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.textract.TextractClient;
   import software.amazon.awssdk.services.textract.model.*;
   import java.io.File;
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.InputStream;
   import java.util.ArrayList;
   import java.util.Iterator;
   import java.util.List;
   // snippet-end:[textract.java2._analyze_doc.import]
   import java.util.Optional;
   
   import org.json.JSONObject;
   
   /**
    * Before running this Java V2 code example, set up your development environment, including your credentials.
    *
    * For more information, see the following documentation topic:
    *
    * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
    */
   public class DetectCelebrityVideo {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
                    "Usage:\n" +
                    "    <bucketName> <docName> \n\n" +
                    "Where:\n" +
                    "    bucketName - The name of the Amazon S3 bucket that contains the document. \n\n" +
                    "    docName - The document name (must be an image, i.e., book.png). \n";
   
           if (args.length != 2) {
                    System.out.println(usage);
                    System.exit(1);
           }
   
          String bucketName = args[0];
          String docName = args[1];
          Region region = Region.US_WEST_2;
          TextractClient textractClient = TextractClient.builder()
                   .region(region)
                   .credentialsProvider(ProfileCredentialsProvider.create("default"))
                   .build();
   
           analyzeID(textractClient, bucketName, docName);
           textractClient.close();
       }
   
       // snippet-start:[textract.java2._analyze_doc.main]
       public static void analyzeID(TextractClient textractClient, String bucketName, String docName) {
   
           try {
               S3Object s3Object = S3Object.builder()
                       .bucket(bucketName)
                       .name(docName)
                       .build();
   
                   // Create a Document object and reference the s3Object instance
               Document myDoc = Document.builder()
                       .s3Object(s3Object)
                       .build();
               
               AnalyzeIdRequest analyzeIdRequest = AnalyzeIdRequest.builder()
                       .documentPages(myDoc).build();
               
               AnalyzeIdResponse analyzeId = textractClient.analyzeID(analyzeIdRequest);
               
              // System.out.println(analyzeExpense.toString());          
               List<IdentityDocument> Docs = analyzeId.identityDocuments();
               for (IdentityDocument doc: Docs) {
                  System.out.println(doc);
               }
               
               
           } catch (TextractException e) {
   
               System.err.println(e.getMessage());
               System.exit(1);
           }
       }
       // snippet-end:[textract.java2._analyze_doc.main]
   }
   ```

------

1. 這將為您提供`AnalyzeID`操作的 JSON 輸出。