id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
textract-dg-024
textract-dg.pdf
24
button or check box. • KeyDetection – Object containing information about the detected key. • SignatureDetections – An array of SignatureDetection objects, which contain information regarding detected signatures. • SignatureDetection – Information regarding the confidence and geometry for the detected signatures. ExpenseDocument extractions contain structures defined in Invoice and Receipt Response Objects. IdentityDocument extractions contain structures defined in Identity Documentation Response Objects. For an example of the summary returned by the GetLendingAnalysisSummary operation, see the following: { "DocumentMetadata": { "Pages": 1 }, "JobStatus": "SUCCEEDED", Analyze Lending Response Objects 81 Amazon Textract Developer Guide "Summary": { "DocumentGroups": [ { "Type": "1005", "SplitDocuments": [ { "Index": 1, "Pages": [ 1 ] } ], "DetectedSignatures": [ { "Page": 1 } ], "UndetectedSignatures": [] } ], "UndetectedDocumentTypes": [ "1040_SCHEDULE_C", "1099_INT", "1099_SSA", "DEMOGRAPHIC_ADDENDUM", "1065", "1040", "1120_S", "IDENTITY_DOCUMENT", "SSA_89", "MORTGAGE_STATEMENT", "1099_MISC", "CHECKS", "HOA_STATEMENT", "INVESTMENT_STATEMENT", "1120", "1003", "VBA_26_0551", "1099_R", "PAYSLIPS", "1008", "W_2", "1099_NEC", "BANK_STATEMENT", Analyze Lending Response Objects 82 Amazon Textract Developer Guide "1040_SCHEDULE_E", "UTILITY_BILLS", "W_9", "UNCLASSIFIED", "HUD_92900_B", "PAYOFF_STATEMENT", "1099_G", "CREDIT_CARD_STATEMENT", "INVOICES", "RECEIPTS", "1040_SCHEDULE_D", "1099_DIV" ] }, "AnalyzeLendingModelVersion": "1.0" } The response elements returned by GetLendingAnalysisSummary include: • LendingSummary - Contains information regarding DocumentGroups and UndetectedDocumentTypes. • DocumentGroup - Contains information about all the documents grouped by the same document type. • DocumentGroups - Contains an array of all DocumentGroup objects. • Type - The type of the documents in a DocumentGroup. • SplitDocument - Contains information about the pages of a document, defined by logical boundary with regard to document type. • SplitDocuments - An array of SplitDocument objects. • Index - The index for a given document in a DocumentGroup of a specific Type. • Pages - An array of page numbers for a given document, ordered by a logical boundary with regard to document type. • UndetectedDocumentTypes - An array of strings, in which each string represents an undetected document type. For documents that have a signature field, the following structures are included in the response: • DetectedSignature – Contains information about the page where a signature was found. Analyze Lending Response Objects 83 Amazon Textract Developer Guide • DetectedSignatures –An array of DetectedSignature objects. • Page (within DetectedSignature and UndetectedSignature objects) – Physical page number in the document. • UndetectedSignature – Contains information about the page where a signature was expected, but was not found. Refer this list <add link> to understand where a signature is expected. • UndetectedSignatures – An array of UndetectedSignature objects. Document Types The following table contains a list of all document types recognized by Analyze Lending. Also indicated is whether the document has a signature field: Document Types Type 1003 1005 1008 1040 1065 1120 1040_SCHEDULE_C 1040_SCHEDULE_D 1040_SCHEDULE_E 1099_DIV 1099_G 1099_INT Document Types Signature YES YES YES YES YES YES NO NO NO NO NO NO 84 Amazon Textract Type 1099_MISC 1099_NEC 1099_R 1099_SSA 1120_S BANK_STATEMENT CHECKS CREDIT_CARD_STATEMENT DEMOGRAPHIC_ADDENDUM HOA_STATEMENT HUD_92900_B IDENTITY_DOCUMENT INVESTMENT_STATEMENT INVOICES MORTGAGE_STATEMENT PAYOFF_STATEMENT PAYSLIPS RECEIPTS SSA_89 UNCLASSIFIED Signature Developer Guide NO NO NO NO YES NO YES NO NO NO YES NO NO NO NO NO NO NO YES NO Document Types 85 Amazon Textract Type UTILITY_BILLS VBA_26_0551 W_2 W_9 Signature NO YES NO YES Developer Guide Document Types 86 Amazon Textract Developer Guide Processing Documents Synchronously Amazon Textract can detect and analyze text in single-page documents that are provided as images in JPEG, PNG, PDF, and TIFF format. The operations are synchronous and return results in near real time. For more information about documents, see Text Detection and Document Analysis Response Objects. This section covers how you can use Amazon Textract to detect and analyze text in a single-page document synchronously. To detect and analyze text in multipage documents, or to detect JPEG and PNG documents asynchronously, see Processing Documents Asynchronously. You can use Amazon Textract synchronous operations for the following purposes: • Text detection – You can detect lines and words on a single-page document image by using the DetectDocumentText operation. For more information, see Detecting Text. • Text analysis – You can identify relationships between detected text on a single-page document by using the AnalyzeDocument operation. For more information, see Analyzing Documents. • Invoice and receipt analysis – You can identify financial relationships between detected text on a single-page invoice or receipt using the AnalyzeExpense operation. For more information, see Analyzing Invoices and Receipts • Identity document analysis – You can analyze identity documents issued by the US Government and extract information along with common types of information found on identity documents. For more information, see Analyzing Identity Documents. Topics • Calling Amazon Textract Synchronous Operations • Detecting Document Text with Amazon Textract • Analyzing Document Text with Amazon Textract • Analyzing Invoices and Receipts with Amazon Textract • Analyzing Identity Documentation with Amazon Textract Calling Amazon Textract Synchronous Operations Amazon Textract operations process document images that are stored on a local
textract-dg-025
textract-dg.pdf
25
using the AnalyzeExpense operation. For more information, see Analyzing Invoices and Receipts • Identity document analysis – You can analyze identity documents issued by the US Government and extract information along with common types of information found on identity documents. For more information, see Analyzing Identity Documents. Topics • Calling Amazon Textract Synchronous Operations • Detecting Document Text with Amazon Textract • Analyzing Document Text with Amazon Textract • Analyzing Invoices and Receipts with Amazon Textract • Analyzing Identity Documentation with Amazon Textract Calling Amazon Textract Synchronous Operations Amazon Textract operations process document images that are stored on a local file system, or document images stored in an Amazon S3 bucket. You specify where the input document is located Calling Amazon Textract Synchronous Operations 87 Amazon Textract Developer Guide by using the Document input parameter. The document image can be in either PNG, JPEG, PDF, or TIFF format. Results for synchronous operations are returned immediately and are not stored for retrieval. For a complete example, see Detecting Document Text with Amazon Textract. Request The following describes how requests work in Amazon Textract. Documents Passed as Image Bytes You can pass a document image to an Amazon Textract operation by passing the image as a base64-encoded byte array. An example is a document image loaded from a local file system. Your code might not need to encode document file bytes if you're using an AWS SDK to call Amazon Textract API operations. The image bytes are specified in the Bytes field of the Document input parameter. The following example shows the input JSON for an Amazon Textract operation that passes the image bytes in the Bytes input parameter. { "Document": { "Bytes": "/9j/4AAQSk....." } } Note If you're using the AWS CLI, you can't pass image bytes to Amazon Textract operations. Instead, you must reference an image stored in an Amazon S3 bucket. The following Java code shows how to load an image from a local file system and call an Amazon Textract operation. String document="input.png"; ByteBuffer imageBytes; try (InputStream inputStream = new FileInputStream(new File(document))) { imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream)); Request 88 Amazon Textract } AmazonTextract client = AmazonTextractClientBuilder.defaultClient(); DetectDocumentTextRequest request = new DetectDocumentTextRequest() .withDocument(new Document() .withBytes(imageBytes)); Developer Guide DetectDocumentTextResult result = client.detectDocumentText(request); Documents Stored in an Amazon S3 Bucket Amazon Textract can analyze document images that are stored in an Amazon S3 bucket. You specify the bucket and file name by using the S3Object field of the Document input parameter. The following example shows the input JSON for an Amazon Textract operation that processes a document stored in an Amazon S3 bucket. { "Document": { "S3Object": { "Bucket": "bucket", "Name": "input.png" } } } The following example shows how to call an Amazon Textract operation using an image stored in an Amazon S3 bucket. String document="input.png"; String bucket="bucket"; AmazonTextract client = AmazonTextractClientBuilder.defaultClient(); DetectDocumentTextRequest request = new DetectDocumentTextRequest() .withDocument(new Document() .withS3Object(new S3Object() .withName(document) .withBucket(bucket))); DetectDocumentTextResult result = client.detectDocumentText(request); Request 89 Amazon Textract Using an adapter Developer Guide With Amazon Textract, you can customize the output or response of a call to AnalyzeDocument by using an AdapterId and adapter version. To use an adapter, you must first have created and trained an adapter using the Amazon Textract Console or the API. To apply your adapter, provide its ID when calling the AnalyzeDocument API. This enhances predictions on your documents. Note that when calling the Document, you can only use one adapter per page. "AdaptersConfig": { "Adapters": [ { "AdapterId": "2e9bf1c4aa31", "Version": "1" } ] } The following Java example shows how to create Queries and a list of adapters, then provide these to AnalyzeDocument, using the AWS SDK for Java. String document="input.png"; ByteBuffer imageBytes; try (InputStream inputStream = new FileInputStream(new File(document))) { imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream)); } AmazonTextract client = AmazonTextractClientBuilder.defaultClient(); List<Query> queries = new ArrayList<Query>(); queries.add(new Query().withText("What is the employee name?") .withAlias("CUST_NAME") .withPages(Arrays.asList("*"))); List<Adapter> adapters = new ArrayList<Adapter>(); adapters.add(new Adapter() .withAdapterId("1111111111") .withVersion("1") .withPages(Arrays.asList("*"))); Using an adapter 90 Amazon Textract Developer Guide AnalyzeDocumentRequest request = new AnalyzeDocumentRequest() .withFeatureTypes("QUERIES", "SIGNATURES") .withDocument(new Document() .withBytes(imageBytes)) .withAdaptersConfig(new AdaptersConfig() .withAdapters(adapters)); AnalyzeDocumentResult result = client.analyzeDocument(request); Response The following sample is the JSON response from a call to DetectDocumentText. For more information, see Detecting Text. { { "DocumentMetadata": { "Pages": 1 }, "Blocks": [ { "BlockType": "PAGE", "Geometry": { "BoundingBox": { "Width": 0.9995205998420715, "Height": 1.0, "Left": 0.0, "Top": 0.0 }, "Polygon": [ { "X": 0.0, "Y": 0.0 }, { "X": 0.9995205998420715, "Y": 2.297314024515845E-16 }, { "X": 0.9995205998420715, "Y": 1.0 Response 91 Amazon Textract }, { "X": 0.0, "Y": 1.0 } ] }, "Id": "ca4b9171-7109-4adb-a811-e09bbe4834dd", "Relationships": [ { "Type": "CHILD", "Ids": [ "26085884-d005-4144-b4c2-4d83dc50739b", "ee9d01bc-d91c-401d-8c0a-eec76f5f7862", "404bb3d3-d7ab-4008-a195-5dec87a08664", "8ae1b4ba-67c1-4486-bd20-54f461886ce9", "47aab5ab-be2c-4c73-97c7-d0a45454e843", "dd06bb49-6a56-4ea7-beec-a2aa09835c3c", "8837153d-81b8-4031-a49f-83a3d81803c2", "5dae3b74-9e95-4b62-99b7-93b88fe70648", "4508da80-64d8-42a8-8846-cfafe6eab10c", "e87be7a9-5519-42e1-b18e-ae10e2d3ed13", "f04bb223-d075-41c3-b328-7354611c826b", "a234f0e8-67de-46f4-a7c7-0bbe8d5159ce", "61b20e27-ff8a-450a-a8b1-bc0259f82fd6", "445f4fdd-c77b-4a7b-a2fc-6ca07cfe9ed7", "359f3870-7183-43f5-b638-970f5cefe4d5", "b9deea0a-244c-4d54-b774-cf03fbaaa8b1", "e2a43881-f620-44f2-b067-500ce7dc8d4d", "41756974-64ef-432d-b4b2-34702505975a", "93d96d32-8b4a-4a98-9578-8b4df4f227a6", "bc907357-63d6-43c0-ab87-80d7e76d377e", "2d727ca7-3acb-4bb9-a564-5885c90e9325", "f32a5989-cbfb-41e6-b0fc-ce1c77c014bd", "e0ba06d0-dbb6-4962-8047-8cac3adfe45a", "b6ed204d-ae01-4b75-bb91-c85d4147a37e", "ac4b9ee0-c9b2-4239-a741-5753e5282033", "ebc18885-48d7-45b8-90e3-d172b4357802", "babf6360-789e-49c1-9c78-0784acc14a0c" ] } ] }, { Response Developer Guide 92 Amazon Textract Developer Guide
textract-dg-026
textract-dg.pdf
26
}, "Blocks": [ { "BlockType": "PAGE", "Geometry": { "BoundingBox": { "Width": 0.9995205998420715, "Height": 1.0, "Left": 0.0, "Top": 0.0 }, "Polygon": [ { "X": 0.0, "Y": 0.0 }, { "X": 0.9995205998420715, "Y": 2.297314024515845E-16 }, { "X": 0.9995205998420715, "Y": 1.0 Response 91 Amazon Textract }, { "X": 0.0, "Y": 1.0 } ] }, "Id": "ca4b9171-7109-4adb-a811-e09bbe4834dd", "Relationships": [ { "Type": "CHILD", "Ids": [ "26085884-d005-4144-b4c2-4d83dc50739b", "ee9d01bc-d91c-401d-8c0a-eec76f5f7862", "404bb3d3-d7ab-4008-a195-5dec87a08664", "8ae1b4ba-67c1-4486-bd20-54f461886ce9", "47aab5ab-be2c-4c73-97c7-d0a45454e843", "dd06bb49-6a56-4ea7-beec-a2aa09835c3c", "8837153d-81b8-4031-a49f-83a3d81803c2", "5dae3b74-9e95-4b62-99b7-93b88fe70648", "4508da80-64d8-42a8-8846-cfafe6eab10c", "e87be7a9-5519-42e1-b18e-ae10e2d3ed13", "f04bb223-d075-41c3-b328-7354611c826b", "a234f0e8-67de-46f4-a7c7-0bbe8d5159ce", "61b20e27-ff8a-450a-a8b1-bc0259f82fd6", "445f4fdd-c77b-4a7b-a2fc-6ca07cfe9ed7", "359f3870-7183-43f5-b638-970f5cefe4d5", "b9deea0a-244c-4d54-b774-cf03fbaaa8b1", "e2a43881-f620-44f2-b067-500ce7dc8d4d", "41756974-64ef-432d-b4b2-34702505975a", "93d96d32-8b4a-4a98-9578-8b4df4f227a6", "bc907357-63d6-43c0-ab87-80d7e76d377e", "2d727ca7-3acb-4bb9-a564-5885c90e9325", "f32a5989-cbfb-41e6-b0fc-ce1c77c014bd", "e0ba06d0-dbb6-4962-8047-8cac3adfe45a", "b6ed204d-ae01-4b75-bb91-c85d4147a37e", "ac4b9ee0-c9b2-4239-a741-5753e5282033", "ebc18885-48d7-45b8-90e3-d172b4357802", "babf6360-789e-49c1-9c78-0784acc14a0c" ] } ] }, { Response Developer Guide 92 Amazon Textract Developer Guide "BlockType": "LINE", "Confidence": 99.93761444091797, "Text": "Employment Application", "Geometry": { "BoundingBox": { "Width": 0.3391372561454773, "Height": 0.06906412541866302, "Left": 0.29548385739326477, "Top": 0.027493247762322426 }, "Polygon": [ { "X": 0.29548385739326477, "Y": 0.027493247762322426 }, { "X": 0.6346210837364197, "Y": 0.027493247762322426 }, { "X": 0.6346210837364197, "Y": 0.0965573713183403 }, { "X": 0.29548385739326477, "Y": 0.0965573713183403 } ] }, "Id": "26085884-d005-4144-b4c2-4d83dc50739b", "Relationships": [ { "Type": "CHILD", "Ids": [ "ed48dacc-d089-498f-8e93-1cee1e5f39f3", "ac7370f3-cbb7-4cd9-a8f9-bdcb2252caaf" ] } ] }, { "BlockType": "LINE", "Confidence": 99.91246795654297, "Text": "Application Information", Response 93 Developer Guide Amazon Textract "Geometry": { "BoundingBox": { "Width": 0.19878505170345306, "Height": 0.03754019737243652, "Left": 0.03988289833068848, "Top": 0.14050349593162537 }, "Polygon": [ { "X": 0.03988289833068848, "Y": 0.14050349593162537 }, { "X": 0.23866795003414154, "Y": 0.14050349593162537 }, { "X": 0.23866795003414154, "Y": 0.1780436933040619 }, { "X": 0.03988289833068848, "Y": 0.1780436933040619 } ] }, "Id": "ee9d01bc-d91c-401d-8c0a-eec76f5f7862", "Relationships": [ { "Type": "CHILD", "Ids": [ "efe3fc6d-becb-4520-80ee-49a329386aee", "c2260852-6cfd-4a71-9fc6-62b2f9b02355" ] } ] }, { "BlockType": "LINE", "Confidence": 99.88693237304688, "Text": "Full Name: Jane Doe", "Geometry": { "BoundingBox": { "Width": 0.16733919084072113, Response 94 Amazon Textract Developer Guide "Height": 0.031106337904930115, "Left": 0.03899926319718361, "Top": 0.21361036598682404 }, "Polygon": [ { "X": 0.03899926319718361, "Y": 0.21361036598682404 }, { "X": 0.20633845031261444, "Y": 0.21361036598682404 }, { "X": 0.20633845031261444, "Y": 0.24471670389175415 }, { "X": 0.03899926319718361, "Y": 0.24471670389175415 } ] }, "Id": "404bb3d3-d7ab-4008-a195-5dec87a08664", "Relationships": [ { "Type": "CHILD", "Ids": [ "e94eb587-9545-4215-b0fc-8e8cb1172958", "090aeba5-8428-4b7a-a54b-7a95a774120e", "64ff0abb-736b-4a6b-aa8d-ad2c0086ae1d", "565ffc30-89d6-4295-b8c6-d22b4ed76584" ] } ] }, { "BlockType": "LINE", "Confidence": 99.9206314086914, "Text": "Phone Number: 555-0100", "Geometry": { "BoundingBox": { "Width": 0.3115004599094391, "Height": 0.047169625759124756, Response 95 Amazon Textract Developer Guide "Left": 0.03604753687977791, "Top": 0.2812676727771759 }, "Polygon": [ { "X": 0.03604753687977791, "Y": 0.2812676727771759 }, { "X": 0.3475480079650879, "Y": 0.2812676727771759 }, { "X": 0.3475480079650879, "Y": 0.32843729853630066 }, { "X": 0.03604753687977791, "Y": 0.32843729853630066 } ] }, "Id": "8ae1b4ba-67c1-4486-bd20-54f461886ce9", "Relationships": [ { "Type": "CHILD", "Ids": [ "d782f847-225b-4a1b-b52d-f252f8221b1f", "fa69c5cd-c80d-4fac-81df-569edae8d259", "d4bbc0f1-ae02-41cf-a26f-8a1e899968cc" ] } ] }, { "BlockType": "LINE", "Confidence": 99.48902893066406, "Text": "Home Address: 123 Any Street, Any Town. USA", "Geometry": { "BoundingBox": { "Width": 0.7431139945983887, "Height": 0.09577702730894089, "Left": 0.03359385207295418, "Top": 0.3258342146873474 Response 96 Developer Guide Amazon Textract }, "Polygon": [ { "X": 0.03359385207295418, "Y": 0.3258342146873474 }, { "X": 0.7767078280448914, "Y": 0.3258342146873474 }, { "X": 0.7767078280448914, "Y": 0.4216112196445465 }, { "X": 0.03359385207295418, "Y": 0.4216112196445465 } ] }, "Id": "47aab5ab-be2c-4c73-97c7-d0a45454e843", "Relationships": [ { "Type": "CHILD", "Ids": [ "acfbed90-4a00-42c6-8a90-d0a0756eea36", "046c8a40-bb0e-4718-9c71-954d3630e1dd", "82b838bc-4591-4287-8dea-60c94a4925e4", "5cdcde7a-f5a6-4231-a941-b6396e42e7ba", "beafd497-185f-487e-b070-db4df5803e94", "ef1b77fb-8ba6-41fe-ba53-dce039af22ed", "7b555310-e7f8-4cd2-bb3d-dcec37f3d90e", "b479c24d-448d-40ef-9ed5-36a6ef08e5c7" ] } ] }, { "BlockType": "LINE", "Confidence": 99.89382934570312, "Text": "Mailing Address: same as above", "Geometry": { "BoundingBox": { "Width": 0.26575741171836853, Response 97 Amazon Textract Developer Guide "Height": 0.039571404457092285, "Left": 0.03068041242659092, "Top": 0.43351811170578003 }, "Polygon": [ { "X": 0.03068041242659092, "Y": 0.43351811170578003 }, { "X": 0.2964377999305725, "Y": 0.43351811170578003 }, { "X": 0.2964377999305725, "Y": 0.4730895161628723 }, { "X": 0.03068041242659092, "Y": 0.4730895161628723 } ] }, "Id": "dd06bb49-6a56-4ea7-beec-a2aa09835c3c", "Relationships": [ { "Type": "CHILD", "Ids": [ "d7261cdc-6ac5-4711-903c-4598fe94952d", "287f80c3-6db2-4dd7-90ec-5f017c80aa31", "ce31c3ad-b51e-4068-be64-5fc9794bc1bc", "e96eb92c-6774-4d6f-8f4a-68a7618d4c66", "88b85c05-427a-4d4f-8cc4-3667234e8364" ] } ] }, { "BlockType": "LINE", "Confidence": 94.67343139648438, "Text": "Previous Employment History", "Geometry": { "BoundingBox": { "Width": 0.3309842050075531, Response 98 Amazon Textract Developer Guide "Height": 0.051920413970947266, "Left": 0.3194798231124878, "Top": 0.5172380208969116 }, "Polygon": [ { "X": 0.3194798231124878, "Y": 0.5172380208969116 }, { "X": 0.6504639983177185, "Y": 0.5172380208969116 }, { "X": 0.6504639983177185, "Y": 0.5691584348678589 }, { "X": 0.3194798231124878, "Y": 0.5691584348678589 } ] }, "Id": "8837153d-81b8-4031-a49f-83a3d81803c2", "Relationships": [ { "Type": "CHILD", "Ids": [ "8b324501-bf38-4ce9-9777-6514b7ade760", "b0cea99a-5045-464d-ac8a-a63ab0470995", "b92a6ee5-ca59-44dc-9c47-534c133b11e7" ] } ] }, { "BlockType": "LINE", "Confidence": 99.66949462890625, "Text": "Start Date", "Geometry": { "BoundingBox": { "Width": 0.08310240507125854, "Height": 0.030944595113396645, "Left": 0.034429505467414856, Response 99 Amazon Textract Developer Guide "Top": 0.6123942136764526 }, "Polygon": [ { "X": 0.034429505467414856, "Y": 0.6123942136764526 }, { "X": 0.1175319030880928, "Y": 0.6123942136764526 }, { "X": 0.1175319030880928, "Y": 0.6433387994766235 }, { "X": 0.034429505467414856, "Y": 0.6433387994766235 } ] }, "Id": "5dae3b74-9e95-4b62-99b7-93b88fe70648", "Relationships": [ { "Type": "CHILD", "Ids": [ "ffe8b8e0-df59-4ac5-9aba-6b54b7c51b45", "91e582cd-9871-4e9c-93cc-848baa426338" ] } ] }, { "BlockType": "LINE", "Confidence": 99.86717224121094, "Text": "End Date", "Geometry": { "BoundingBox": { "Width": 0.07581500709056854, "Height": 0.03223184868693352, "Left": 0.14846202731132507, "Top": 0.6120467782020569 }, "Polygon": [ Response 100 Developer Guide Amazon Textract { "X": 0.14846202731132507, "Y": 0.6120467782020569 }, { "X": 0.22427703440189362, "Y": 0.6120467782020569 }, { "X": 0.22427703440189362, "Y": 0.6442786455154419 }, { "X": 0.14846202731132507, "Y": 0.6442786455154419 } ] }, "Id": "4508da80-64d8-42a8-8846-cfafe6eab10c", "Relationships": [ { "Type": "CHILD", "Ids": [ "7c97b56b-699f-49b0-93f4-98e6d90b107c", "7af04e27-0c15-447e-a569-b30edb99a133" ] } ] }, { "BlockType": "LINE", "Confidence": 99.9539794921875, "Text": "Employer Name", "Geometry": { "BoundingBox": { "Width": 0.1347292959690094, "Height": 0.0392492413520813, "Left": 0.2647075653076172, "Top": 0.6140711903572083 }, "Polygon": [ { "X": 0.2647075653076172, "Y": 0.6140711903572083 Response 101 Developer Guide Amazon Textract }, { "X": 0.3994368314743042, "Y": 0.6140711903572083 }, { "X": 0.3994368314743042, "Y": 0.6533204317092896 }, { "X": 0.2647075653076172, "Y":
textract-dg-027
textract-dg.pdf
27
"Polygon": [ Response 100 Developer Guide Amazon Textract { "X": 0.14846202731132507, "Y": 0.6120467782020569 }, { "X": 0.22427703440189362, "Y": 0.6120467782020569 }, { "X": 0.22427703440189362, "Y": 0.6442786455154419 }, { "X": 0.14846202731132507, "Y": 0.6442786455154419 } ] }, "Id": "4508da80-64d8-42a8-8846-cfafe6eab10c", "Relationships": [ { "Type": "CHILD", "Ids": [ "7c97b56b-699f-49b0-93f4-98e6d90b107c", "7af04e27-0c15-447e-a569-b30edb99a133" ] } ] }, { "BlockType": "LINE", "Confidence": 99.9539794921875, "Text": "Employer Name", "Geometry": { "BoundingBox": { "Width": 0.1347292959690094, "Height": 0.0392492413520813, "Left": 0.2647075653076172, "Top": 0.6140711903572083 }, "Polygon": [ { "X": 0.2647075653076172, "Y": 0.6140711903572083 Response 101 Developer Guide Amazon Textract }, { "X": 0.3994368314743042, "Y": 0.6140711903572083 }, { "X": 0.3994368314743042, "Y": 0.6533204317092896 }, { "X": 0.2647075653076172, "Y": 0.6533204317092896 } ] }, "Id": "e87be7a9-5519-42e1-b18e-ae10e2d3ed13", "Relationships": [ { "Type": "CHILD", "Ids": [ "a9bfeb55-75cd-47cd-b953-728e602a3564", "9f0f9c06-d02c-4b07-bb39-7ade70be2c1b" ] } ] }, { "BlockType": "LINE", "Confidence": 99.35584259033203, "Text": "Position Held", "Geometry": { "BoundingBox": { "Width": 0.11393272876739502, "Height": 0.03415105864405632, "Left": 0.49973347783088684, "Top": 0.614840030670166 }, "Polygon": [ { "X": 0.49973347783088684, "Y": 0.614840030670166 }, { "X": 0.6136661767959595, Response 102 Amazon Textract Developer Guide "Y": 0.614840030670166 }, { "X": 0.6136661767959595, "Y": 0.6489911079406738 }, { "X": 0.49973347783088684, "Y": 0.6489911079406738 } ] }, "Id": "f04bb223-d075-41c3-b328-7354611c826b", "Relationships": [ { "Type": "CHILD", "Ids": [ "6d5edf02-845c-40e0-9514-e56d0d652ae0", "3297ab59-b237-45fb-ae60-a108f0c95ac2" ] } ] }, { "BlockType": "LINE", "Confidence": 99.9817886352539, "Text": "Reason for leaving", "Geometry": { "BoundingBox": { "Width": 0.16511960327625275, "Height": 0.04062700271606445, "Left": 0.7430596351623535, "Top": 0.6116235852241516 }, "Polygon": [ { "X": 0.7430596351623535, "Y": 0.6116235852241516 }, { "X": 0.9081792235374451, "Y": 0.6116235852241516 }, { Response 103 Amazon Textract Developer Guide "X": 0.9081792235374451, "Y": 0.6522505879402161 }, { "X": 0.7430596351623535, "Y": 0.6522505879402161 } ] }, "Id": "a234f0e8-67de-46f4-a7c7-0bbe8d5159ce", "Relationships": [ { "Type": "CHILD", "Ids": [ "f4b8cf26-d2da-4a76-8345-69562de3cc11", "386d4a63-1194-4c0e-a18d-4d074a0b1f93", "a8622541-1896-4d54-8d10-7da2c800ec5c" ] } ] }, { "BlockType": "LINE", "Confidence": 99.77413177490234, "Text": "1/15/2009", "Geometry": { "BoundingBox": { "Width": 0.08799663186073303, "Height": 0.03832906484603882, "Left": 0.03175082430243492, "Top": 0.691371738910675 }, "Polygon": [ { "X": 0.03175082430243492, "Y": 0.691371738910675 }, { "X": 0.11974745243787766, "Y": 0.691371738910675 }, { "X": 0.11974745243787766, "Y": 0.7297008037567139 Response 104 Developer Guide Amazon Textract }, { "X": 0.03175082430243492, "Y": 0.7297008037567139 } ] }, "Id": "61b20e27-ff8a-450a-a8b1-bc0259f82fd6", "Relationships": [ { "Type": "CHILD", "Ids": [ "da7a6482-0964-49a4-bc7d-56942ff3b4e1" ] } ] }, { "BlockType": "LINE", "Confidence": 99.72286224365234, "Text": "6/30/2011", "Geometry": { "BoundingBox": { "Width": 0.08843101561069489, "Height": 0.03991425037384033, "Left": 0.14642837643623352, "Top": 0.6919752955436707 }, "Polygon": [ { "X": 0.14642837643623352, "Y": 0.6919752955436707 }, { "X": 0.2348593920469284, "Y": 0.6919752955436707 }, { "X": 0.2348593920469284, "Y": 0.731889545917511 }, { "X": 0.14642837643623352, "Y": 0.731889545917511 Response 105 Amazon Textract } ] }, "Id": "445f4fdd-c77b-4a7b-a2fc-6ca07cfe9ed7", "Relationships": [ { "Type": "CHILD", "Ids": [ "5a8da66a-ecce-4ee9-a765-a46d6cdc6cde" Developer Guide ] } ] }, { "BlockType": "LINE", "Confidence": 99.86936950683594, "Text": "Any Company", "Geometry": { "BoundingBox": { "Width": 0.11800950765609741, "Height": 0.03943679481744766, "Left": 0.2626699209213257, "Top": 0.6972727179527283 }, "Polygon": [ { "X": 0.2626699209213257, "Y": 0.6972727179527283 }, { "X": 0.3806794285774231, "Y": 0.6972727179527283 }, { "X": 0.3806794285774231, "Y": 0.736709475517273 }, { "X": 0.2626699209213257, "Y": 0.736709475517273 } ] }, "Id": "359f3870-7183-43f5-b638-970f5cefe4d5", Response 106 Amazon Textract Developer Guide "Relationships": [ { "Type": "CHILD", "Ids": [ "77749c2b-aa7f-450e-8dd2-62bcaf253ba2", "713bad19-158d-4e3e-b01f-f5707ddb04e5" ] } ] }, { "BlockType": "LINE", "Confidence": 99.582275390625, "Text": "Assistant baker", "Geometry": { "BoundingBox": { "Width": 0.13280922174453735, "Height": 0.032666124403476715, "Left": 0.49814170598983765, "Top": 0.699238657951355 }, "Polygon": [ { "X": 0.49814170598983765, "Y": 0.699238657951355 }, { "X": 0.630950927734375, "Y": 0.699238657951355 }, { "X": 0.630950927734375, "Y": 0.7319048047065735 }, { "X": 0.49814170598983765, "Y": 0.7319048047065735 } ] }, "Id": "b9deea0a-244c-4d54-b774-cf03fbaaa8b1", "Relationships": [ { "Type": "CHILD", Response 107 Amazon Textract "Ids": [ "989944f9-f684-4714-87d8-9ad9a321d65c", "ae82e2aa-1601-4e0c-8340-1db7ad0c9a31" Developer Guide ] } ] }, { "BlockType": "LINE", "Confidence": 99.96180725097656, "Text": "relocated", "Geometry": { "BoundingBox": { "Width": 0.08668994903564453, "Height": 0.033302485942840576, "Left": 0.7426905632019043, "Top": 0.6974037289619446 }, "Polygon": [ { "X": 0.7426905632019043, "Y": 0.6974037289619446 }, { "X": 0.8293805122375488, "Y": 0.6974037289619446 }, { "X": 0.8293805122375488, "Y": 0.7307062149047852 }, { "X": 0.7426905632019043, "Y": 0.7307062149047852 } ] }, "Id": "e2a43881-f620-44f2-b067-500ce7dc8d4d", "Relationships": [ { "Type": "CHILD", "Ids": [ "a9cf9a8c-fdaa-413e-9346-5a28a98aebdb" ] Response 108 Amazon Textract } ] }, { "BlockType": "LINE", "Confidence": 99.98190307617188, "Text": "7/1/2011", "Geometry": { "BoundingBox": { "Width": 0.09747002273797989, "Height": 0.07067441940307617, "Left": 0.028500309213995934, "Top": 0.7745237946510315 }, "Polygon": [ { "X": 0.028500309213995934, "Y": 0.7745237946510315 }, { "X": 0.12597033381462097, "Y": 0.7745237946510315 }, { "X": 0.12597033381462097, "Y": 0.8451982140541077 }, { "X": 0.028500309213995934, "Y": 0.8451982140541077 } ] }, "Id": "41756974-64ef-432d-b4b2-34702505975a", "Relationships": [ { "Type": "CHILD", "Ids": [ "0f711065-1872-442a-ba6d-8fababaa452a" ] } ] }, { Response Developer Guide 109 Amazon Textract Developer Guide "BlockType": "LINE", "Confidence": 99.98418426513672, "Text": "8/10/2013", "Geometry": { "BoundingBox": { "Width": 0.10664612054824829, "Height": 0.06439518928527832, "Left": 0.14159755408763885, "Top": 0.7791688442230225 }, "Polygon": [ { "X": 0.14159755408763885, "Y": 0.7791688442230225 }, { "X": 0.24824367463588715, "Y": 0.7791688442230225 }, { "X": 0.24824367463588715, "Y": 0.8435640335083008 }, { "X": 0.14159755408763885, "Y": 0.8435640335083008 } ] }, "Id": "93d96d32-8b4a-4a98-9578-8b4df4f227a6", "Relationships": [ { "Type": "CHILD", "Ids": [ "a92d8eef-db28-45ba-801a-5da0f589d277" ] } ] }, { "BlockType": "LINE", "Confidence": 99.98075866699219, "Text": "Example Corp.", "Geometry": { Response 110 Amazon Textract Developer Guide "BoundingBox": { "Width": 0.2114926278591156, "Height": 0.058415766805410385, "Left": 0.26764172315597534, "Top": 0.794414758682251 }, "Polygon": [ { "X": 0.26764172315597534, "Y": 0.794414758682251 }, { "X": 0.47913435101509094, "Y": 0.794414758682251 }, { "X": 0.47913435101509094, "Y": 0.8528305292129517 }, { "X": 0.26764172315597534, "Y": 0.8528305292129517 } ] }, "Id": "bc907357-63d6-43c0-ab87-80d7e76d377e", "Relationships": [ { "Type": "CHILD", "Ids": [ "d6962efb-34ab-4ffb-9f2f-5f263e813558",
textract-dg-028
textract-dg.pdf
28
}, { "X": 0.24824367463588715, "Y": 0.7791688442230225 }, { "X": 0.24824367463588715, "Y": 0.8435640335083008 }, { "X": 0.14159755408763885, "Y": 0.8435640335083008 } ] }, "Id": "93d96d32-8b4a-4a98-9578-8b4df4f227a6", "Relationships": [ { "Type": "CHILD", "Ids": [ "a92d8eef-db28-45ba-801a-5da0f589d277" ] } ] }, { "BlockType": "LINE", "Confidence": 99.98075866699219, "Text": "Example Corp.", "Geometry": { Response 110 Amazon Textract Developer Guide "BoundingBox": { "Width": 0.2114926278591156, "Height": 0.058415766805410385, "Left": 0.26764172315597534, "Top": 0.794414758682251 }, "Polygon": [ { "X": 0.26764172315597534, "Y": 0.794414758682251 }, { "X": 0.47913435101509094, "Y": 0.794414758682251 }, { "X": 0.47913435101509094, "Y": 0.8528305292129517 }, { "X": 0.26764172315597534, "Y": 0.8528305292129517 } ] }, "Id": "bc907357-63d6-43c0-ab87-80d7e76d377e", "Relationships": [ { "Type": "CHILD", "Ids": [ "d6962efb-34ab-4ffb-9f2f-5f263e813558", "1876c8ea-d3e8-4c39-870e-47512b3b5080" ] } ] }, { "BlockType": "LINE", "Confidence": 99.91166687011719, "Text": "Baker", "Geometry": { "BoundingBox": { "Width": 0.09931200742721558, "Height": 0.06008726358413696, Response 111 Amazon Textract Developer Guide "Left": 0.5098910331726074, "Top": 0.787897527217865 }, "Polygon": [ { "X": 0.5098910331726074, "Y": 0.787897527217865 }, { "X": 0.609203040599823, "Y": 0.787897527217865 }, { "X": 0.609203040599823, "Y": 0.847984790802002 }, { "X": 0.5098910331726074, "Y": 0.847984790802002 } ] }, "Id": "2d727ca7-3acb-4bb9-a564-5885c90e9325", "Relationships": [ { "Type": "CHILD", "Ids": [ "00adeaef-ed57-44eb-b8a9-503575236d62" ] } ] }, { "BlockType": "LINE", "Confidence": 99.93852233886719, "Text": "better opp.", "Geometry": { "BoundingBox": { "Width": 0.18919607996940613, "Height": 0.06994765996932983, "Left": 0.7428008317947388, "Top": 0.7928366661071777 }, "Polygon": [ Response 112 Developer Guide Amazon Textract { "X": 0.7428008317947388, "Y": 0.7928366661071777 }, { "X": 0.9319968819618225, "Y": 0.7928366661071777 }, { "X": 0.9319968819618225, "Y": 0.8627843260765076 }, { "X": 0.7428008317947388, "Y": 0.8627843260765076 } ] }, "Id": "f32a5989-cbfb-41e6-b0fc-ce1c77c014bd", "Relationships": [ { "Type": "CHILD", "Ids": [ "c0fc9a58-7a4b-4f69-bafd-2cff32be2665", "bf6dc8ee-2fb3-4b6c-aee4-31e96912a2d8" ] } ] }, { "BlockType": "LINE", "Confidence": 99.92573547363281, "Text": "8/15/2013", "Geometry": { "BoundingBox": { "Width": 0.10257463902235031, "Height": 0.05412459373474121, "Left": 0.027909137308597565, "Top": 0.8608770370483398 }, "Polygon": [ { "X": 0.027909137308597565, "Y": 0.8608770370483398 Response 113 Developer Guide Amazon Textract }, { "X": 0.13048377633094788, "Y": 0.8608770370483398 }, { "X": 0.13048377633094788, "Y": 0.915001630783081 }, { "X": 0.027909137308597565, "Y": 0.915001630783081 } ] }, "Id": "e0ba06d0-dbb6-4962-8047-8cac3adfe45a", "Relationships": [ { "Type": "CHILD", "Ids": [ "5384f860-f857-4a94-9438-9dfa20eed1c6" ] } ] }, { "BlockType": "LINE", "Confidence": 99.99625396728516, "Text": "Present", "Geometry": { "BoundingBox": { "Width": 0.09982697665691376, "Height": 0.06888341903686523, "Left": 0.1420602649450302, "Top": 0.8511748909950256 }, "Polygon": [ { "X": 0.1420602649450302, "Y": 0.8511748909950256 }, { "X": 0.24188724160194397, "Y": 0.8511748909950256 Response 114 Developer Guide Amazon Textract }, { "X": 0.24188724160194397, "Y": 0.9200583100318909 }, { "X": 0.1420602649450302, "Y": 0.9200583100318909 } ] }, "Id": "b6ed204d-ae01-4b75-bb91-c85d4147a37e", "Relationships": [ { "Type": "CHILD", "Ids": [ "0bb96ed6-b2e6-4da4-90b3-b85561bbd89d" ] } ] }, { "BlockType": "LINE", "Confidence": 99.9826431274414, "Text": "AnyCompany", "Geometry": { "BoundingBox": { "Width": 0.18611276149749756, "Height": 0.08581399917602539, "Left": 0.2615866959095001, "Top": 0.869536280632019 }, "Polygon": [ { "X": 0.2615866959095001, "Y": 0.869536280632019 }, { "X": 0.4476994574069977, "Y": 0.869536280632019 }, { "X": 0.4476994574069977, "Y": 0.9553502798080444 Response 115 Developer Guide Amazon Textract }, { "X": 0.2615866959095001, "Y": 0.9553502798080444 } ] }, "Id": "ac4b9ee0-c9b2-4239-a741-5753e5282033", "Relationships": [ { "Type": "CHILD", "Ids": [ "25343360-d906-440a-88b7-92eb89e95949" ] } ] }, { "BlockType": "LINE", "Confidence": 99.99549102783203, "Text": "head baker", "Geometry": { "BoundingBox": { "Width": 0.1937451809644699, "Height": 0.056156039237976074, "Left": 0.49359121918678284, "Top": 0.8702592849731445 }, "Polygon": [ { "X": 0.49359121918678284, "Y": 0.8702592849731445 }, { "X": 0.6873363852500916, "Y": 0.8702592849731445 }, { "X": 0.6873363852500916, "Y": 0.9264153242111206 }, { "X": 0.49359121918678284, "Y": 0.9264153242111206 Response 116 Amazon Textract } ] }, "Id": "ebc18885-48d7-45b8-90e3-d172b4357802", "Relationships": [ { "Type": "CHILD", "Ids": [ "0ef3c194-8322-4575-94f1-82819ee57e3a", "d296acd9-3e9a-4985-95f8-f863614f2c46" Developer Guide ] } ] }, { "BlockType": "LINE", "Confidence": 99.98360443115234, "Text": "N/A, current", "Geometry": { "BoundingBox": { "Width": 0.22544169425964355, "Height": 0.06588292121887207, "Left": 0.7411766648292542, "Top": 0.8722732067108154 }, "Polygon": [ { "X": 0.7411766648292542, "Y": 0.8722732067108154 }, { "X": 0.9666183590888977, "Y": 0.8722732067108154 }, { "X": 0.9666183590888977, "Y": 0.9381561279296875 }, { "X": 0.7411766648292542, "Y": 0.9381561279296875 } ] }, Response 117 Amazon Textract Developer Guide "Id": "babf6360-789e-49c1-9c78-0784acc14a0c", "Relationships": [ { "Type": "CHILD", "Ids": [ "195cfb5b-ae06-4203-8520-4e4b0a73b5ce", "549ef3f9-3a13-4b77-bc25-fb2e0996839a" ] } ] }, { "BlockType": "WORD", "Confidence": 99.94815826416016, "Text": "Employment", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.17462396621704102, "Height": 0.06266549974679947, "Left": 0.29548385739326477, "Top": 0.03389188274741173 }, "Polygon": [ { "X": 0.29548385739326477, "Y": 0.03389188274741173 }, { "X": 0.4701078236103058, "Y": 0.03389188274741173 }, { "X": 0.4701078236103058, "Y": 0.0965573862195015 }, { "X": 0.29548385739326477, "Y": 0.0965573862195015 } ] }, "Id": "ed48dacc-d089-498f-8e93-1cee1e5f39f3" }, Response 118 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.92706298828125, "Text": "Application", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.15933875739574432, "Height": 0.062391020357608795, "Left": 0.47528234124183655, "Top": 0.027493247762322426 }, "Polygon": [ { "X": 0.47528234124183655, "Y": 0.027493247762322426 }, { "X": 0.6346211433410645, "Y": 0.027493247762322426 }, { "X": 0.6346211433410645, "Y": 0.08988427370786667 }, { "X": 0.47528234124183655, "Y": 0.08988427370786667 } ] }, "Id": "ac7370f3-cbb7-4cd9-a8f9-bdcb2252caaf" }, { "BlockType": "WORD", "Confidence": 99.9821548461914, "Text": "Application", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.09610454738140106, "Height": 0.03656719997525215, "Left": 0.03988289833068848, "Top": 0.14147649705410004 Response 119 Amazon Textract }, "Polygon": [ { "X": 0.03988289833068848, "Y": 0.14147649705410004 }, { "X": 0.13598744571208954, "Y": 0.14147649705410004 }, { "X": 0.13598744571208954, "Y": 0.1780436933040619 }, { "X": 0.03988289833068848, "Y": 0.1780436933040619 } ] }, "Id": "efe3fc6d-becb-4520-80ee-49a329386aee" }, { "BlockType": "WORD", "Confidence": 99.84278106689453, "Text": "Information", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.10029315203428268, "Height": 0.03209415823221207, "Left": 0.13837480545043945, "Top": 0.14050349593162537 }, "Polygon": [ { "X": 0.13837480545043945, "Y": 0.14050349593162537 }, { "X": 0.23866795003414154, "Y": 0.14050349593162537 }, { Response Developer Guide 120 Amazon Textract Developer
textract-dg-029
textract-dg.pdf
29
"BlockType": "WORD", "Confidence": 99.9821548461914, "Text": "Application", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.09610454738140106, "Height": 0.03656719997525215, "Left": 0.03988289833068848, "Top": 0.14147649705410004 Response 119 Amazon Textract }, "Polygon": [ { "X": 0.03988289833068848, "Y": 0.14147649705410004 }, { "X": 0.13598744571208954, "Y": 0.14147649705410004 }, { "X": 0.13598744571208954, "Y": 0.1780436933040619 }, { "X": 0.03988289833068848, "Y": 0.1780436933040619 } ] }, "Id": "efe3fc6d-becb-4520-80ee-49a329386aee" }, { "BlockType": "WORD", "Confidence": 99.84278106689453, "Text": "Information", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.10029315203428268, "Height": 0.03209415823221207, "Left": 0.13837480545043945, "Top": 0.14050349593162537 }, "Polygon": [ { "X": 0.13837480545043945, "Y": 0.14050349593162537 }, { "X": 0.23866795003414154, "Y": 0.14050349593162537 }, { Response Developer Guide 120 Amazon Textract Developer Guide "X": 0.23866795003414154, "Y": 0.17259766161441803 }, { "X": 0.13837480545043945, "Y": 0.17259766161441803 } ] }, "Id": "c2260852-6cfd-4a71-9fc6-62b2f9b02355" }, { "BlockType": "WORD", "Confidence": 99.83993530273438, "Text": "Full", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.03039788082242012, "Height": 0.031106330454349518, "Left": 0.03899926319718361, "Top": 0.21361036598682404 }, "Polygon": [ { "X": 0.03899926319718361, "Y": 0.21361036598682404 }, { "X": 0.06939714401960373, "Y": 0.21361036598682404 }, { "X": 0.06939714401960373, "Y": 0.24471670389175415 }, { "X": 0.03899926319718361, "Y": 0.24471670389175415 } ] }, "Id": "e94eb587-9545-4215-b0fc-8e8cb1172958" }, Response 121 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.93611907958984, "Text": "Name:", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.05555811896920204, "Height": 0.030184319242835045, "Left": 0.07123806327581406, "Top": 0.2137702852487564 }, "Polygon": [ { "X": 0.07123806327581406, "Y": 0.2137702852487564 }, { "X": 0.1267961859703064, "Y": 0.2137702852487564 }, { "X": 0.1267961859703064, "Y": 0.2439546138048172 }, { "X": 0.07123806327581406, "Y": 0.2439546138048172 } ] }, "Id": "090aeba5-8428-4b7a-a54b-7a95a774120e" }, { "BlockType": "WORD", "Confidence": 99.91043853759766, "Text": "Jane", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.03905024006962776, "Height": 0.02941947989165783, "Left": 0.12933772802352905, "Top": 0.214289128780365 Response 122 Amazon Textract }, "Polygon": [ { "X": 0.12933772802352905, "Y": 0.214289128780365 }, { "X": 0.16838796436786652, "Y": 0.214289128780365 }, { "X": 0.16838796436786652, "Y": 0.24370861053466797 }, { "X": 0.12933772802352905, "Y": 0.24370861053466797 } ] }, "Id": "64ff0abb-736b-4a6b-aa8d-ad2c0086ae1d" }, { "BlockType": "WORD", "Confidence": 99.86123657226562, "Text": "Doe", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.035229459404945374, "Height": 0.030427640303969383, "Left": 0.17110899090766907, "Top": 0.21377210319042206 }, "Polygon": [ { "X": 0.17110899090766907, "Y": 0.21377210319042206 }, { "X": 0.20633845031261444, "Y": 0.21377210319042206 }, { Response Developer Guide 123 Amazon Textract Developer Guide "X": 0.20633845031261444, "Y": 0.244199737906456 }, { "X": 0.17110899090766907, "Y": 0.244199737906456 } ] }, "Id": "565ffc30-89d6-4295-b8c6-d22b4ed76584" }, { "BlockType": "WORD", "Confidence": 99.92633056640625, "Text": "Phone", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.052783288061618805, "Height": 0.03104414977133274, "Left": 0.03604753687977791, "Top": 0.28701552748680115 }, "Polygon": [ { "X": 0.03604753687977791, "Y": 0.28701552748680115 }, { "X": 0.08883082121610641, "Y": 0.28701552748680115 }, { "X": 0.08883082121610641, "Y": 0.31805968284606934 }, { "X": 0.03604753687977791, "Y": 0.31805968284606934 } ] }, "Id": "d782f847-225b-4a1b-b52d-f252f8221b1f" }, Response 124 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.86275482177734, "Text": "Number:", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.07424934208393097, "Height": 0.030300479382276535, "Left": 0.0915418416261673, "Top": 0.28639692068099976 }, "Polygon": [ { "X": 0.0915418416261673, "Y": 0.28639692068099976 }, { "X": 0.16579118371009827, "Y": 0.28639692068099976 }, { "X": 0.16579118371009827, "Y": 0.3166973888874054 }, { "X": 0.0915418416261673, "Y": 0.3166973888874054 } ] }, "Id": "fa69c5cd-c80d-4fac-81df-569edae8d259" }, { "BlockType": "WORD", "Confidence": 99.97282409667969, "Text": "555-0100", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.17021971940994263, "Height": 0.047169629484415054, "Left": 0.17732827365398407, "Top": 0.2812676727771759 Response 125 Amazon Textract }, "Polygon": [ { "X": 0.17732827365398407, "Y": 0.2812676727771759 }, { "X": 0.3475480079650879, "Y": 0.2812676727771759 }, { "X": 0.3475480079650879, "Y": 0.32843729853630066 }, { "X": 0.17732827365398407, "Y": 0.32843729853630066 } ] }, "Id": "d4bbc0f1-ae02-41cf-a26f-8a1e899968cc" }, { "BlockType": "WORD", "Confidence": 99.66238403320312, "Text": "Home", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.049357783049345016, "Height": 0.03134990110993385, "Left": 0.03359385207295418, "Top": 0.36172014474868774 }, "Polygon": [ { "X": 0.03359385207295418, "Y": 0.36172014474868774 }, { "X": 0.0829516351222992, "Y": 0.36172014474868774 }, { Response Developer Guide 126 Amazon Textract Developer Guide "X": 0.0829516351222992, "Y": 0.3930700421333313 }, { "X": 0.03359385207295418, "Y": 0.3930700421333313 } ] }, "Id": "acfbed90-4a00-42c6-8a90-d0a0756eea36" }, { "BlockType": "WORD", "Confidence": 99.6871109008789, "Text": "Address:", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.07411003112792969, "Height": 0.0314042791724205, "Left": 0.08516156673431396, "Top": 0.3600046932697296 }, "Polygon": [ { "X": 0.08516156673431396, "Y": 0.3600046932697296 }, { "X": 0.15927159786224365, "Y": 0.3600046932697296 }, { "X": 0.15927159786224365, "Y": 0.3914089798927307 }, { "X": 0.08516156673431396, "Y": 0.3914089798927307 } ] }, "Id": "046c8a40-bb0e-4718-9c71-954d3630e1dd" }, Response 127 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.93781280517578, "Text": "123", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.05761868134140968, "Height": 0.05008566007018089, "Left": 0.1750781387090683, "Top": 0.35484206676483154 }, "Polygon": [ { "X": 0.1750781387090683, "Y": 0.35484206676483154 }, { "X": 0.23269681632518768, "Y": 0.35484206676483154 }, { "X": 0.23269681632518768, "Y": 0.40492773056030273 }, { "X": 0.1750781387090683, "Y": 0.40492773056030273 } ] }, "Id": "82b838bc-4591-4287-8dea-60c94a4925e4" }, { "BlockType": "WORD", "Confidence": 99.96530151367188, "Text": "Any", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.06814215332269669, "Height": 0.06354366987943649, "Left": 0.2550157308578491, "Top": 0.35471394658088684 Response 128 Amazon Textract }, "Polygon": [ { "X": 0.2550157308578491, "Y": 0.35471394658088684 }, { "X": 0.3231579065322876, "Y": 0.35471394658088684 }, { "X": 0.3231579065322876, "Y": 0.41825762391090393 }, { "X": 0.2550157308578491, "Y": 0.41825762391090393 } ] }, "Id": "5cdcde7a-f5a6-4231-a941-b6396e42e7ba" }, { "BlockType": "WORD", "Confidence": 99.87527465820312, "Text": "Street,", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.12156613171100616, "Height": 0.05449587106704712, "Left": 0.3357025980949402, "Top": 0.3550415635108948 }, "Polygon": [ { "X": 0.3357025980949402, "Y": 0.3550415635108948 }, { "X": 0.45726871490478516, "Y": 0.3550415635108948 }, { Response Developer Guide 129 Amazon Textract Developer Guide "X": 0.45726871490478516, "Y": 0.4095374345779419 }, { "X": 0.3357025980949402, "Y":
textract-dg-030
textract-dg.pdf
30
"BoundingBox": { "Width": 0.06814215332269669, "Height": 0.06354366987943649, "Left": 0.2550157308578491, "Top": 0.35471394658088684 Response 128 Amazon Textract }, "Polygon": [ { "X": 0.2550157308578491, "Y": 0.35471394658088684 }, { "X": 0.3231579065322876, "Y": 0.35471394658088684 }, { "X": 0.3231579065322876, "Y": 0.41825762391090393 }, { "X": 0.2550157308578491, "Y": 0.41825762391090393 } ] }, "Id": "5cdcde7a-f5a6-4231-a941-b6396e42e7ba" }, { "BlockType": "WORD", "Confidence": 99.87527465820312, "Text": "Street,", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.12156613171100616, "Height": 0.05449587106704712, "Left": 0.3357025980949402, "Top": 0.3550415635108948 }, "Polygon": [ { "X": 0.3357025980949402, "Y": 0.3550415635108948 }, { "X": 0.45726871490478516, "Y": 0.3550415635108948 }, { Response Developer Guide 129 Amazon Textract Developer Guide "X": 0.45726871490478516, "Y": 0.4095374345779419 }, { "X": 0.3357025980949402, "Y": 0.4095374345779419 } ] }, "Id": "beafd497-185f-487e-b070-db4df5803e94" }, { "BlockType": "WORD", "Confidence": 99.99514770507812, "Text": "Any", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.07748188823461533, "Height": 0.07339789718389511, "Left": 0.47723668813705444, "Top": 0.3482133150100708 }, "Polygon": [ { "X": 0.47723668813705444, "Y": 0.3482133150100708 }, { "X": 0.554718554019928, "Y": 0.3482133150100708 }, { "X": 0.554718554019928, "Y": 0.4216112196445465 }, { "X": 0.47723668813705444, "Y": 0.4216112196445465 } ] }, "Id": "ef1b77fb-8ba6-41fe-ba53-dce039af22ed" }, Response 130 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 96.80656433105469, "Text": "Town.", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.11213835328817368, "Height": 0.057233039289712906, "Left": 0.5563329458236694, "Top": 0.3331930637359619 }, "Polygon": [ { "X": 0.5563329458236694, "Y": 0.3331930637359619 }, { "X": 0.6684713363647461, "Y": 0.3331930637359619 }, { "X": 0.6684713363647461, "Y": 0.3904260993003845 }, { "X": 0.5563329458236694, "Y": 0.3904260993003845 } ] }, "Id": "7b555310-e7f8-4cd2-bb3d-dcec37f3d90e" }, { "BlockType": "WORD", "Confidence": 99.98260498046875, "Text": "USA", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.08771833777427673, "Height": 0.05706935003399849, "Left": 0.6889894604682922, "Top": 0.3258342146873474 Response 131 Amazon Textract }, "Polygon": [ { "X": 0.6889894604682922, "Y": 0.3258342146873474 }, { "X": 0.7767078280448914, "Y": 0.3258342146873474 }, { "X": 0.7767078280448914, "Y": 0.3829035460948944 }, { "X": 0.6889894604682922, "Y": 0.3829035460948944 } ] }, "Id": "b479c24d-448d-40ef-9ed5-36a6ef08e5c7" }, { "BlockType": "WORD", "Confidence": 99.9583969116211, "Text": "Mailing", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.06291338801383972, "Height": 0.03957144916057587, "Left": 0.03068041242659092, "Top": 0.43351811170578003 }, "Polygon": [ { "X": 0.03068041242659092, "Y": 0.43351811170578003 }, { "X": 0.09359379857778549, "Y": 0.43351811170578003 }, { Response Developer Guide 132 Amazon Textract Developer Guide "X": 0.09359379857778549, "Y": 0.4730895459651947 }, { "X": 0.03068041242659092, "Y": 0.4730895459651947 } ] }, "Id": "d7261cdc-6ac5-4711-903c-4598fe94952d" }, { "BlockType": "WORD", "Confidence": 99.87476348876953, "Text": "Address:", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.07364854216575623, "Height": 0.03147412836551666, "Left": 0.0954652726650238, "Top": 0.43450701236724854 }, "Polygon": [ { "X": 0.0954652726650238, "Y": 0.43450701236724854 }, { "X": 0.16911381483078003, "Y": 0.43450701236724854 }, { "X": 0.16911381483078003, "Y": 0.465981125831604 }, { "X": 0.0954652726650238, "Y": 0.465981125831604 } ] }, "Id": "287f80c3-6db2-4dd7-90ec-5f017c80aa31" }, Response 133 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.94071960449219, "Text": "same", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.04640670120716095, "Height": 0.026415130123496056, "Left": 0.17156922817230225, "Top": 0.44010937213897705 }, "Polygon": [ { "X": 0.17156922817230225, "Y": 0.44010937213897705 }, { "X": 0.2179759293794632, "Y": 0.44010937213897705 }, { "X": 0.2179759293794632, "Y": 0.46652451157569885 }, { "X": 0.17156922817230225, "Y": 0.46652451157569885 } ] }, "Id": "ce31c3ad-b51e-4068-be64-5fc9794bc1bc" }, { "BlockType": "WORD", "Confidence": 99.76510620117188, "Text": "as", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.02041218988597393, "Height": 0.025104399770498276, "Left": 0.2207803726196289, "Top": 0.44124215841293335 Response 134 Amazon Textract }, "Polygon": [ { "X": 0.2207803726196289, "Y": 0.44124215841293335 }, { "X": 0.24119256436824799, "Y": 0.44124215841293335 }, { "X": 0.24119256436824799, "Y": 0.4663465619087219 }, { "X": 0.2207803726196289, "Y": 0.4663465619087219 } ] }, "Id": "e96eb92c-6774-4d6f-8f4a-68a7618d4c66" }, { "BlockType": "WORD", "Confidence": 99.9301528930664, "Text": "above", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.05268359184265137, "Height": 0.03216424956917763, "Left": 0.24375422298908234, "Top": 0.4354657828807831 }, "Polygon": [ { "X": 0.24375422298908234, "Y": 0.4354657828807831 }, { "X": 0.2964377999305725, "Y": 0.4354657828807831 }, { Response Developer Guide 135 Amazon Textract Developer Guide "X": 0.2964377999305725, "Y": 0.4676300287246704 }, { "X": 0.24375422298908234, "Y": 0.4676300287246704 } ] }, "Id": "88b85c05-427a-4d4f-8cc4-3667234e8364" }, { "BlockType": "WORD", "Confidence": 85.3905029296875, "Text": "Previous", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.09860499948263168, "Height": 0.04000622034072876, "Left": 0.3194798231124878, "Top": 0.5194430351257324 }, "Polygon": [ { "X": 0.3194798231124878, "Y": 0.5194430351257324 }, { "X": 0.4180848002433777, "Y": 0.5194430351257324 }, { "X": 0.4180848002433777, "Y": 0.5594492554664612 }, { "X": 0.3194798231124878, "Y": 0.5594492554664612 } ] }, "Id": "8b324501-bf38-4ce9-9777-6514b7ade760" }, Response 136 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.14524841308594, "Text": "Employment", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.14039960503578186, "Height": 0.04645847901701927, "Left": 0.4214291274547577, "Top": 0.5219109654426575 }, "Polygon": [ { "X": 0.4214291274547577, "Y": 0.5219109654426575 }, { "X": 0.5618287324905396, "Y": 0.5219109654426575 }, { "X": 0.5618287324905396, "Y": 0.568369448184967 }, { "X": 0.4214291274547577, "Y": 0.568369448184967 } ] }, "Id": "b0cea99a-5045-464d-ac8a-a63ab0470995" }, { "BlockType": "WORD", "Confidence": 99.48454284667969, "Text": "History", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.08361124992370605, "Height": 0.05192042887210846, "Left": 0.5668527483940125, "Top": 0.5172380208969116 Response 137 Amazon Textract }, "Polygon": [ { "X": 0.5668527483940125, "Y": 0.5172380208969116 }, { "X": 0.6504639983177185, "Y": 0.5172380208969116 }, { "X": 0.6504639983177185, "Y": 0.5691584348678589 }, { "X": 0.5668527483940125, "Y": 0.5691584348678589 } ] }, "Id": "b92a6ee5-ca59-44dc-9c47-534c133b11e7" }, { "BlockType": "WORD", "Confidence": 99.78699493408203, "Text": "Start", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.041341401636600494, "Height": 0.030926469713449478, "Left": 0.034429505467414856, "Top": 0.6124123334884644 }, "Polygon": [ { "X": 0.034429505467414856, "Y": 0.6124123334884644 }, { "X": 0.07577090710401535, "Y": 0.6124123334884644 }, { Response Developer Guide 138 Amazon Textract Developer Guide "X": 0.07577090710401535, "Y": 0.6433387994766235 }, { "X": 0.034429505467414856, "Y": 0.6433387994766235 } ] }, "Id": "ffe8b8e0-df59-4ac5-9aba-6b54b7c51b45" }, { "BlockType": "WORD",
textract-dg-031
textract-dg.pdf
31
Response 137 Amazon Textract }, "Polygon": [ { "X": 0.5668527483940125, "Y": 0.5172380208969116 }, { "X": 0.6504639983177185, "Y": 0.5172380208969116 }, { "X": 0.6504639983177185, "Y": 0.5691584348678589 }, { "X": 0.5668527483940125, "Y": 0.5691584348678589 } ] }, "Id": "b92a6ee5-ca59-44dc-9c47-534c133b11e7" }, { "BlockType": "WORD", "Confidence": 99.78699493408203, "Text": "Start", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.041341401636600494, "Height": 0.030926469713449478, "Left": 0.034429505467414856, "Top": 0.6124123334884644 }, "Polygon": [ { "X": 0.034429505467414856, "Y": 0.6124123334884644 }, { "X": 0.07577090710401535, "Y": 0.6124123334884644 }, { Response Developer Guide 138 Amazon Textract Developer Guide "X": 0.07577090710401535, "Y": 0.6433387994766235 }, { "X": 0.034429505467414856, "Y": 0.6433387994766235 } ] }, "Id": "ffe8b8e0-df59-4ac5-9aba-6b54b7c51b45" }, { "BlockType": "WORD", "Confidence": 99.55198669433594, "Text": "Date", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.03923053666949272, "Height": 0.03072454035282135, "Left": 0.07830137014389038, "Top": 0.6123942136764526 }, "Polygon": [ { "X": 0.07830137014389038, "Y": 0.6123942136764526 }, { "X": 0.1175319105386734, "Y": 0.6123942136764526 }, { "X": 0.1175319105386734, "Y": 0.6431187391281128 }, { "X": 0.07830137014389038, "Y": 0.6431187391281128 } ] }, "Id": "91e582cd-9871-4e9c-93cc-848baa426338" }, Response 139 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.8897705078125, "Text": "End", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.03212086856365204, "Height": 0.03193363919854164, "Left": 0.14846202731132507, "Top": 0.6120467782020569 }, "Polygon": [ { "X": 0.14846202731132507, "Y": 0.6120467782020569 }, { "X": 0.1805828958749771, "Y": 0.6120467782020569 }, { "X": 0.1805828958749771, "Y": 0.6439804434776306 }, { "X": 0.14846202731132507, "Y": 0.6439804434776306 } ] }, "Id": "7c97b56b-699f-49b0-93f4-98e6d90b107c" }, { "BlockType": "WORD", "Confidence": 99.8445816040039, "Text": "Date", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.03987143933773041, "Height": 0.03142518177628517, "Left": 0.1844055950641632, "Top": 0.612853467464447 Response 140 Amazon Textract }, "Polygon": [ { "X": 0.1844055950641632, "Y": 0.612853467464447 }, { "X": 0.22427703440189362, "Y": 0.612853467464447 }, { "X": 0.22427703440189362, "Y": 0.6442786455154419 }, { "X": 0.1844055950641632, "Y": 0.6442786455154419 } ] }, "Id": "7af04e27-0c15-447e-a569-b30edb99a133" }, { "BlockType": "WORD", "Confidence": 99.9652328491211, "Text": "Employer", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.08150768280029297, "Height": 0.0392492301762104, "Left": 0.2647075653076172, "Top": 0.6140711903572083 }, "Polygon": [ { "X": 0.2647075653076172, "Y": 0.6140711903572083 }, { "X": 0.34621524810791016, "Y": 0.6140711903572083 }, { Response Developer Guide 141 Amazon Textract Developer Guide "X": 0.34621524810791016, "Y": 0.6533204317092896 }, { "X": 0.2647075653076172, "Y": 0.6533204317092896 } ] }, "Id": "a9bfeb55-75cd-47cd-b953-728e602a3564" }, { "BlockType": "WORD", "Confidence": 99.94273376464844, "Text": "Name", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.05018233880400658, "Height": 0.03248906135559082, "Left": 0.34925445914268494, "Top": 0.6162016987800598 }, "Polygon": [ { "X": 0.34925445914268494, "Y": 0.6162016987800598 }, { "X": 0.3994368016719818, "Y": 0.6162016987800598 }, { "X": 0.3994368016719818, "Y": 0.6486907601356506 }, { "X": 0.34925445914268494, "Y": 0.6486907601356506 } ] }, "Id": "9f0f9c06-d02c-4b07-bb39-7ade70be2c1b" }, Response 142 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 98.85071563720703, "Text": "Position", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.07007700204849243, "Height": 0.03255689889192581, "Left": 0.49973347783088684, "Top": 0.6164342164993286 }, "Polygon": [ { "X": 0.49973347783088684, "Y": 0.6164342164993286 }, { "X": 0.5698104500770569, "Y": 0.6164342164993286 }, { "X": 0.5698104500770569, "Y": 0.6489911079406738 }, { "X": 0.49973347783088684, "Y": 0.6489911079406738 } ] }, "Id": "6d5edf02-845c-40e0-9514-e56d0d652ae0" }, { "BlockType": "WORD", "Confidence": 99.86096954345703, "Text": "Held", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.04017873853445053, "Height": 0.03292537108063698, "Left": 0.5734874606132507, "Top": 0.614840030670166 Response 143 Amazon Textract }, "Polygon": [ { "X": 0.5734874606132507, "Y": 0.614840030670166 }, { "X": 0.6136662364006042, "Y": 0.614840030670166 }, { "X": 0.6136662364006042, "Y": 0.6477653980255127 }, { "X": 0.5734874606132507, "Y": 0.6477653980255127 } ] }, "Id": "3297ab59-b237-45fb-ae60-a108f0c95ac2" }, { "BlockType": "WORD", "Confidence": 99.97740936279297, "Text": "Reason", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.06497219949960709, "Height": 0.03248770162463188, "Left": 0.7430596351623535, "Top": 0.6136704087257385 }, "Polygon": [ { "X": 0.7430596351623535, "Y": 0.6136704087257385 }, { "X": 0.8080317974090576, "Y": 0.6136704087257385 }, { Response Developer Guide 144 Amazon Textract Developer Guide "X": 0.8080317974090576, "Y": 0.6461580991744995 }, { "X": 0.7430596351623535, "Y": 0.6461580991744995 } ] }, "Id": "f4b8cf26-d2da-4a76-8345-69562de3cc11" }, { "BlockType": "WORD", "Confidence": 99.98371887207031, "Text": "for", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.029645200818777084, "Height": 0.03462234139442444, "Left": 0.8108851909637451, "Top": 0.6117717623710632 }, "Polygon": [ { "X": 0.8108851909637451, "Y": 0.6117717623710632 }, { "X": 0.8405303955078125, "Y": 0.6117717623710632 }, { "X": 0.8405303955078125, "Y": 0.6463940739631653 }, { "X": 0.8108851909637451, "Y": 0.6463940739631653 } ] }, "Id": "386d4a63-1194-4c0e-a18d-4d074a0b1f93" }, Response 145 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.98424530029297, "Text": "leaving", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.06517849862575531, "Height": 0.040626998990774155, "Left": 0.8430007100105286, "Top": 0.6116235852241516 }, "Polygon": [ { "X": 0.8430007100105286, "Y": 0.6116235852241516 }, { "X": 0.9081792235374451, "Y": 0.6116235852241516 }, { "X": 0.9081792235374451, "Y": 0.6522505879402161 }, { "X": 0.8430007100105286, "Y": 0.6522505879402161 } ] }, "Id": "a8622541-1896-4d54-8d10-7da2c800ec5c" }, { "BlockType": "WORD", "Confidence": 99.77413177490234, "Text": "1/15/2009", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.08799663186073303, "Height": 0.03832906112074852, "Left": 0.03175082430243492, "Top": 0.691371738910675 Response 146 Amazon Textract }, "Polygon": [ { "X": 0.03175082430243492, "Y": 0.691371738910675 }, { "X": 0.11974745243787766, "Y": 0.691371738910675 }, { "X": 0.11974745243787766, "Y": 0.7297008037567139 }, { "X": 0.03175082430243492, "Y": 0.7297008037567139 } ] }, "Id": "da7a6482-0964-49a4-bc7d-56942ff3b4e1" }, { "BlockType": "WORD", "Confidence": 99.72286224365234, "Text": "6/30/2011", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.08843102306127548, "Height": 0.03991425037384033, "Left": 0.14642837643623352, "Top": 0.6919752955436707 }, "Polygon": [ { "X": 0.14642837643623352, "Y": 0.6919752955436707 }, { "X": 0.2348593920469284, "Y": 0.6919752955436707 }, { Response Developer Guide 147 Amazon Textract Developer Guide "X": 0.2348593920469284, "Y": 0.731889545917511 }, { "X": 0.14642837643623352, "Y": 0.731889545917511 } ] }, "Id": "5a8da66a-ecce-4ee9-a765-a46d6cdc6cde" }, { "BlockType": "WORD", "Confidence": 99.92295837402344, "Text": "Any", "TextType": "PRINTED", "Geometry": { "BoundingBox": {
textract-dg-032
textract-dg.pdf
32
"Y": 0.691371738910675 }, { "X": 0.11974745243787766, "Y": 0.691371738910675 }, { "X": 0.11974745243787766, "Y": 0.7297008037567139 }, { "X": 0.03175082430243492, "Y": 0.7297008037567139 } ] }, "Id": "da7a6482-0964-49a4-bc7d-56942ff3b4e1" }, { "BlockType": "WORD", "Confidence": 99.72286224365234, "Text": "6/30/2011", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.08843102306127548, "Height": 0.03991425037384033, "Left": 0.14642837643623352, "Top": 0.6919752955436707 }, "Polygon": [ { "X": 0.14642837643623352, "Y": 0.6919752955436707 }, { "X": 0.2348593920469284, "Y": 0.6919752955436707 }, { Response Developer Guide 147 Amazon Textract Developer Guide "X": 0.2348593920469284, "Y": 0.731889545917511 }, { "X": 0.14642837643623352, "Y": 0.731889545917511 } ] }, "Id": "5a8da66a-ecce-4ee9-a765-a46d6cdc6cde" }, { "BlockType": "WORD", "Confidence": 99.92295837402344, "Text": "Any", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.034067559987306595, "Height": 0.037968240678310394, "Left": 0.2626699209213257, "Top": 0.6972727179527283 }, "Polygon": [ { "X": 0.2626699209213257, "Y": 0.6972727179527283 }, { "X": 0.2967374622821808, "Y": 0.6972727179527283 }, { "X": 0.2967374622821808, "Y": 0.7352409362792969 }, { "X": 0.2626699209213257, "Y": 0.7352409362792969 } ] }, "Id": "77749c2b-aa7f-450e-8dd2-62bcaf253ba2" }, Response 148 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.81578063964844, "Text": "Company", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.08160992711782455, "Height": 0.03890080004930496, "Left": 0.29906952381134033, "Top": 0.6978086829185486 }, "Polygon": [ { "X": 0.29906952381134033, "Y": 0.6978086829185486 }, { "X": 0.3806794583797455, "Y": 0.6978086829185486 }, { "X": 0.3806794583797455, "Y": 0.736709475517273 }, { "X": 0.29906952381134033, "Y": 0.736709475517273 } ] }, "Id": "713bad19-158d-4e3e-b01f-f5707ddb04e5" }, { "BlockType": "WORD", "Confidence": 99.37964630126953, "Text": "Assistant", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.0789310410618782, "Height": 0.03139699995517731, "Left": 0.49814170598983765, "Top": 0.7005078196525574 Response 149 Amazon Textract }, "Polygon": [ { "X": 0.49814170598983765, "Y": 0.7005078196525574 }, { "X": 0.5770727396011353, "Y": 0.7005078196525574 }, { "X": 0.5770727396011353, "Y": 0.7319048047065735 }, { "X": 0.49814170598983765, "Y": 0.7319048047065735 } ] }, "Id": "989944f9-f684-4714-87d8-9ad9a321d65c" }, { "BlockType": "WORD", "Confidence": 99.784912109375, "Text": "baker", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.050264399498701096, "Height": 0.03237773850560188, "Left": 0.5806865096092224, "Top": 0.699238657951355 }, "Polygon": [ { "X": 0.5806865096092224, "Y": 0.699238657951355 }, { "X": 0.630950927734375, "Y": 0.699238657951355 }, { Response Developer Guide 150 Amazon Textract Developer Guide "X": 0.630950927734375, "Y": 0.7316163778305054 }, { "X": 0.5806865096092224, "Y": 0.7316163778305054 } ] }, "Id": "ae82e2aa-1601-4e0c-8340-1db7ad0c9a31" }, { "BlockType": "WORD", "Confidence": 99.96180725097656, "Text": "relocated", "TextType": "PRINTED", "Geometry": { "BoundingBox": { "Width": 0.08668994158506393, "Height": 0.03330250084400177, "Left": 0.7426905632019043, "Top": 0.6974037289619446 }, "Polygon": [ { "X": 0.7426905632019043, "Y": 0.6974037289619446 }, { "X": 0.8293805122375488, "Y": 0.6974037289619446 }, { "X": 0.8293805122375488, "Y": 0.7307062149047852 }, { "X": 0.7426905632019043, "Y": 0.7307062149047852 } ] }, "Id": "a9cf9a8c-fdaa-413e-9346-5a28a98aebdb" }, Response 151 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.98190307617188, "Text": "7/1/2011", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.09747002273797989, "Height": 0.07067439705133438, "Left": 0.028500309213995934, "Top": 0.7745237946510315 }, "Polygon": [ { "X": 0.028500309213995934, "Y": 0.7745237946510315 }, { "X": 0.12597033381462097, "Y": 0.7745237946510315 }, { "X": 0.12597033381462097, "Y": 0.8451982140541077 }, { "X": 0.028500309213995934, "Y": 0.8451982140541077 } ] }, "Id": "0f711065-1872-442a-ba6d-8fababaa452a" }, { "BlockType": "WORD", "Confidence": 99.98418426513672, "Text": "8/10/2013", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.10664612054824829, "Height": 0.06439515948295593, "Left": 0.14159755408763885, "Top": 0.7791688442230225 Response 152 Amazon Textract }, "Polygon": [ { "X": 0.14159755408763885, "Y": 0.7791688442230225 }, { "X": 0.24824367463588715, "Y": 0.7791688442230225 }, { "X": 0.24824367463588715, "Y": 0.843563973903656 }, { "X": 0.14159755408763885, "Y": 0.843563973903656 } ] }, "Id": "a92d8eef-db28-45ba-801a-5da0f589d277" }, { "BlockType": "WORD", "Confidence": 99.97722625732422, "Text": "Example", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.12127546221017838, "Height": 0.05682983994483948, "Left": 0.26764172315597534, "Top": 0.794414758682251 }, "Polygon": [ { "X": 0.26764172315597534, "Y": 0.794414758682251 }, { "X": 0.3889172077178955, "Y": 0.794414758682251 }, { Response Developer Guide 153 Amazon Textract Developer Guide "X": 0.3889172077178955, "Y": 0.8512446284294128 }, { "X": 0.26764172315597534, "Y": 0.8512446284294128 } ] }, "Id": "d6962efb-34ab-4ffb-9f2f-5f263e813558" }, { "BlockType": "WORD", "Confidence": 99.98429870605469, "Text": "Corp.", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.07650306820869446, "Height": 0.05481306090950966, "Left": 0.4026312530040741, "Top": 0.7980174422264099 }, "Polygon": [ { "X": 0.4026312530040741, "Y": 0.7980174422264099 }, { "X": 0.47913432121276855, "Y": 0.7980174422264099 }, { "X": 0.47913432121276855, "Y": 0.8528305292129517 }, { "X": 0.4026312530040741, "Y": 0.8528305292129517 } ] }, "Id": "1876c8ea-d3e8-4c39-870e-47512b3b5080" }, Response 154 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.91166687011719, "Text": "Baker", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.09931197017431259, "Height": 0.06008723005652428, "Left": 0.5098910331726074, "Top": 0.787897527217865 }, "Polygon": [ { "X": 0.5098910331726074, "Y": 0.787897527217865 }, { "X": 0.609203040599823, "Y": 0.787897527217865 }, { "X": 0.609203040599823, "Y": 0.8479847311973572 }, { "X": 0.5098910331726074, "Y": 0.8479847311973572 } ] }, "Id": "00adeaef-ed57-44eb-b8a9-503575236d62" }, { "BlockType": "WORD", "Confidence": 99.98870849609375, "Text": "better", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.10782185196876526, "Height": 0.06207133084535599, "Left": 0.7428008317947388, "Top": 0.7928366661071777 Response 155 Amazon Textract }, "Polygon": [ { "X": 0.7428008317947388, "Y": 0.7928366661071777 }, { "X": 0.8506226539611816, "Y": 0.7928366661071777 }, { "X": 0.8506226539611816, "Y": 0.8549079895019531 }, { "X": 0.7428008317947388, "Y": 0.8549079895019531 } ] }, "Id": "c0fc9a58-7a4b-4f69-bafd-2cff32be2665" }, { "BlockType": "WORD", "Confidence": 99.8883285522461, "Text": "opp.", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.07421936094760895, "Height": 0.058906231075525284, "Left": 0.8577775359153748, "Top": 0.8038780689239502 }, "Polygon": [ { "X": 0.8577775359153748, "Y": 0.8038780689239502 }, { "X": 0.9319969415664673, "Y": 0.8038780689239502 }, { Response Developer Guide 156 Amazon Textract Developer Guide "X": 0.9319969415664673, "Y": 0.8627843260765076 }, { "X": 0.8577775359153748, "Y": 0.8627843260765076 } ] }, "Id": "bf6dc8ee-2fb3-4b6c-aee4-31e96912a2d8" }, { "BlockType": "WORD", "Confidence": 99.92573547363281, "Text": "8/15/2013", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.10257463902235031, "Height": 0.05412459000945091, "Left": 0.027909137308597565, "Top": 0.8608770370483398 }, "Polygon":
textract-dg-033
textract-dg.pdf
33
"X": 0.8506226539611816, "Y": 0.8549079895019531 }, { "X": 0.7428008317947388, "Y": 0.8549079895019531 } ] }, "Id": "c0fc9a58-7a4b-4f69-bafd-2cff32be2665" }, { "BlockType": "WORD", "Confidence": 99.8883285522461, "Text": "opp.", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.07421936094760895, "Height": 0.058906231075525284, "Left": 0.8577775359153748, "Top": 0.8038780689239502 }, "Polygon": [ { "X": 0.8577775359153748, "Y": 0.8038780689239502 }, { "X": 0.9319969415664673, "Y": 0.8038780689239502 }, { Response Developer Guide 156 Amazon Textract Developer Guide "X": 0.9319969415664673, "Y": 0.8627843260765076 }, { "X": 0.8577775359153748, "Y": 0.8627843260765076 } ] }, "Id": "bf6dc8ee-2fb3-4b6c-aee4-31e96912a2d8" }, { "BlockType": "WORD", "Confidence": 99.92573547363281, "Text": "8/15/2013", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.10257463902235031, "Height": 0.05412459000945091, "Left": 0.027909137308597565, "Top": 0.8608770370483398 }, "Polygon": [ { "X": 0.027909137308597565, "Y": 0.8608770370483398 }, { "X": 0.13048377633094788, "Y": 0.8608770370483398 }, { "X": 0.13048377633094788, "Y": 0.915001630783081 }, { "X": 0.027909137308597565, "Y": 0.915001630783081 } ] }, "Id": "5384f860-f857-4a94-9438-9dfa20eed1c6" }, Response 157 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.99625396728516, "Text": "Present", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.09982697665691376, "Height": 0.06888339668512344, "Left": 0.1420602649450302, "Top": 0.8511748909950256 }, "Polygon": [ { "X": 0.1420602649450302, "Y": 0.8511748909950256 }, { "X": 0.24188724160194397, "Y": 0.8511748909950256 }, { "X": 0.24188724160194397, "Y": 0.9200583100318909 }, { "X": 0.1420602649450302, "Y": 0.9200583100318909 } ] }, "Id": "0bb96ed6-b2e6-4da4-90b3-b85561bbd89d" }, { "BlockType": "WORD", "Confidence": 99.9826431274414, "Text": "AnyCompany", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.18611273169517517, "Height": 0.08581399917602539, "Left": 0.2615866959095001, "Top": 0.869536280632019 Response 158 Amazon Textract }, "Polygon": [ { "X": 0.2615866959095001, "Y": 0.869536280632019 }, { "X": 0.4476994276046753, "Y": 0.869536280632019 }, { "X": 0.4476994276046753, "Y": 0.9553502798080444 }, { "X": 0.2615866959095001, "Y": 0.9553502798080444 } ] }, "Id": "25343360-d906-440a-88b7-92eb89e95949" }, { "BlockType": "WORD", "Confidence": 99.99523162841797, "Text": "head", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.07429949939250946, "Height": 0.05485520139336586, "Left": 0.49359121918678284, "Top": 0.8714361190795898 }, "Polygon": [ { "X": 0.49359121918678284, "Y": 0.8714361190795898 }, { "X": 0.5678907036781311, "Y": 0.8714361190795898 }, { Response Developer Guide 159 Amazon Textract Developer Guide "X": 0.5678907036781311, "Y": 0.926291286945343 }, { "X": 0.49359121918678284, "Y": 0.926291286945343 } ] }, "Id": "0ef3c194-8322-4575-94f1-82819ee57e3a" }, { "BlockType": "WORD", "Confidence": 99.99574279785156, "Text": "baker", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.1019822508096695, "Height": 0.05615599825978279, "Left": 0.585354208946228, "Top": 0.8702592849731445 }, "Polygon": [ { "X": 0.585354208946228, "Y": 0.8702592849731445 }, { "X": 0.6873364448547363, "Y": 0.8702592849731445 }, { "X": 0.6873364448547363, "Y": 0.9264153242111206 }, { "X": 0.585354208946228, "Y": 0.9264153242111206 } ] }, "Id": "d296acd9-3e9a-4985-95f8-f863614f2c46" }, Response 160 Developer Guide Amazon Textract { "BlockType": "WORD", "Confidence": 99.9880599975586, "Text": "N/A,", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.08230073750019073, "Height": 0.06588289886713028, "Left": 0.7411766648292542, "Top": 0.8722732067108154 }, "Polygon": [ { "X": 0.7411766648292542, "Y": 0.8722732067108154 }, { "X": 0.8234773874282837, "Y": 0.8722732067108154 }, { "X": 0.8234773874282837, "Y": 0.9381561279296875 }, { "X": 0.7411766648292542, "Y": 0.9381561279296875 } ] }, "Id": "195cfb5b-ae06-4203-8520-4e4b0a73b5ce" }, { "BlockType": "WORD", "Confidence": 99.97914123535156, "Text": "current", "TextType": "HANDWRITING", "Geometry": { "BoundingBox": { "Width": 0.12791454792022705, "Height": 0.04768490046262741, "Left": 0.8387037515640259, "Top": 0.8843405842781067 Response 161 Developer Guide Amazon Textract }, "Polygon": [ { "X": 0.8387037515640259, "Y": 0.8843405842781067 }, { "X": 0.9666182994842529, "Y": 0.8843405842781067 }, { "X": 0.9666182994842529, "Y": 0.9320254921913147 }, { "X": 0.8387037515640259, "Y": 0.9320254921913147 } ] }, "Id": "549ef3f9-3a13-4b77-bc25-fb2e0996839a" } ], "DetectDocumentTextModelVersion": "1.0", "ResponseMetadata": { "RequestId": "337129e6-3af7-4014-842b-f6484e82cbf6", "HTTPStatusCode": 200, "HTTPHeaders": { "x-amzn-requestid": "337129e6-3af7-4014-842b-f6484e82cbf6", "content-type": "application/x-amz-json-1.1", "content-length": "45675", "date": "Mon, 09 Nov 2020 23:54:38 GMT" }, "RetryAttempts": 0 } } } Detecting Document Text with Amazon Textract To detect text in a document, you use the DetectDocumentText operation, and pass a document file as input. DetectDocumentText returns a JSON structure that contains lines and words of Detecting Document Text 162 Amazon Textract Developer Guide detected text, the location of the text in the document, and the relationships between detected text. For more information, see Detecting Text. You can provide an input document as an image byte array (base64-encoded image bytes), or as an Amazon S3 object. In this procedure, you upload an image file to your S3 bucket and specify the file name. To detect text in a document (API) 1. If you haven't already: a. Give a user the AmazonTextractFullAccess and AmazonS3ReadOnlyAccess permissions. For more information, see Step 1: Set Up an AWS Account and Create a User. b. Install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. 2. Upload a document to your S3 bucket. For instructions, see Uploading Objects into Amazon S3 in the Amazon Simple Storage Service User Guide. 3. Use the following examples to call the DetectDocumentText operation. Java The following example code displays the document and boxes around lines of detected text. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace the value of credentialsProvider with the name of your developer profile. //Calls DetectDocumentText. //Loads document from S3 bucket. Displays the document and bounding boxes around detected lines/words of text. import java.awt.*; import java.awt.image.BufferedImage; import java.util.List; import javax.imageio.ImageIO; import javax.swing.*; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; Detecting Document Text 163 Amazon Textract Developer Guide import
textract-dg-034
textract-dg.pdf
34
to call the DetectDocumentText operation. Java The following example code displays the document and boxes around lines of detected text. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace the value of credentialsProvider with the name of your developer profile. //Calls DetectDocumentText. //Loads document from S3 bucket. Displays the document and bounding boxes around detected lines/words of text. import java.awt.*; import java.awt.image.BufferedImage; import java.util.List; import javax.imageio.ImageIO; import javax.swing.*; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; Detecting Document Text 163 Amazon Textract Developer Guide import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.textract.AmazonTextract; import com.amazonaws.services.textract.AmazonTextractClientBuilder; import com.amazonaws.services.textract.model.Block; import com.amazonaws.services.textract.model.BoundingBox; import com.amazonaws.services.textract.model.DetectDocumentTextRequest; import com.amazonaws.services.textract.model.DetectDocumentTextResult; import com.amazonaws.services.textract.model.Document; import com.amazonaws.services.textract.model.S3Object; import com.amazonaws.services.textract.model.Point; import com.amazonaws.services.textract.model.Relationship; public class DocumentText extends JPanel { private static final long serialVersionUID = 1L; BufferedImage image; DetectDocumentTextResult result; public DocumentText(DetectDocumentTextResult documentResult, BufferedImage bufImage) throws Exception { super(); result = documentResult; // Results of text detection. image = bufImage; // The image containing the document. } // Draws the image and text bounding box. public void paintComponent(Graphics g) { int height = image.getHeight(this); int width = image.getWidth(this); Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g. // Draw the image. g2d.drawImage(image, 0, 0, image.getWidth(this) , image.getHeight(this), this); // Iterate through blocks and display polygons around lines of detected text. Detecting Document Text 164 Amazon Textract Developer Guide List<Block> blocks = result.getBlocks(); for (Block block : blocks) { DisplayBlockInfo(block); if ((block.getBlockType()).equals("LINE")) { ShowPolygon(height, width, block.getGeometry().getPolygon(), g2d); /* ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d); */ } else { // its a word, so just show vertical lines. ShowPolygonVerticals(height, width, block.getGeometry().getPolygon(), g2d); } } } // Show bounding box at supplied location. private void ShowBoundingBox(int imageHeight, int imageWidth, BoundingBox box, Graphics2D g2d) { float left = imageWidth * box.getLeft(); float top = imageHeight * box.getTop(); // Display bounding box. g2d.setColor(new Color(0, 212, 0)); g2d.drawRect(Math.round(left), Math.round(top), Math.round(imageWidth * box.getWidth()), Math.round(imageHeight * box.getHeight())); } // Shows polygon at supplied location private void ShowPolygon(int imageHeight, int imageWidth, List<Point> points, Graphics2D g2d) { g2d.setColor(new Color(0, 0, 0)); Polygon polygon = new Polygon(); // Construct polygon and display for (Point point : points) { polygon.addPoint((Math.round(point.getX() * imageWidth)), Math.round(point.getY() * imageHeight)); } Detecting Document Text 165 Amazon Textract Developer Guide g2d.drawPolygon(polygon); } // Draws only the vertical lines in the supplied polygon. private void ShowPolygonVerticals(int imageHeight, int imageWidth, List<Point> points, Graphics2D g2d) { g2d.setColor(new Color(0, 212, 0)); Object[] parry = points.toArray(); g2d.setStroke(new BasicStroke(2)); g2d.drawLine(Math.round(((Point) parry[0]).getX() * imageWidth), Math.round(((Point) parry[0]).getY() * imageHeight), Math.round(((Point) parry[3]).getX() * imageWidth), Math.round(((Point) parry[3]).getY() * imageHeight)); g2d.setColor(new Color(255, 0, 0)); g2d.drawLine(Math.round(((Point) parry[1]).getX() * imageWidth), Math.round(((Point) parry[1]).getY() * imageHeight), Math.round(((Point) parry[2]).getX() * imageWidth), Math.round(((Point) parry[2]).getY() * imageHeight)); } //Displays information from a block returned by text detection and text analysis private void DisplayBlockInfo(Block block) { System.out.println("Block Id : " + block.getId()); if (block.getText()!=null) System.out.println(" Detected text: " + block.getText()); System.out.println(" Type: " + block.getBlockType()); if (block.getBlockType().equals("PAGE") !=true) { System.out.println(" Confidence: " + block.getConfidence().toString()); } if(block.getBlockType().equals("CELL")) { System.out.println(" Cell information:"); System.out.println(" Column: " + block.getColumnIndex()); System.out.println(" Row: " + block.getRowIndex()); System.out.println(" Column span: " + block.getColumnSpan()); System.out.println(" Row span: " + block.getRowSpan()); } Detecting Document Text 166 Amazon Textract Developer Guide System.out.println(" Relationships"); List<Relationship> relationships=block.getRelationships(); if(relationships!=null) { for (Relationship relationship : relationships) { System.out.println(" Type: " + relationship.getType()); System.out.println(" IDs: " + relationship.getIds().toString()); } } else { System.out.println(" No related Blocks"); } System.out.println(" Geometry"); System.out.println(" Bounding Box: " + block.getGeometry().getBoundingBox().toString()); System.out.println(" Polygon: " + block.getGeometry().getPolygon().toString()); List<String> entityTypes = block.getEntityTypes(); System.out.println(" Entity Types"); if(entityTypes!=null) { for (String entityType : entityTypes) { System.out.println(" Entity Type: " + entityType); } } else { System.out.println(" No entity type"); } if(block.getPage()!=null) System.out.println(" Page: " + block.getPage()); System.out.println(); } public static void main(String arg[]) throws Exception { // The S3 bucket and document String document = ""; String bucket = ""; // set provider credentials AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider("default"); Detecting Document Text 167 Amazon Textract Developer Guide AmazonS3 s3client = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider) .withEndpointConfiguration( new EndpointConfiguration("https:// s3.amazonaws.com","us-east-1")) .build(); // Get the document from S3 com.amazonaws.services.s3.model.S3Object s3object = s3client.getObject(bucket, document); S3ObjectInputStream inputStream = s3object.getObjectContent(); BufferedImage image = ImageIO.read(inputStream); // Call DetectDocumentText EndpointConfiguration endpoint = new EndpointConfiguration( "https://textract.us-east-1.amazonaws.com", "us-east-1"); AmazonTextract client = AmazonTextractClientBuilder.standard().withCredentials(credentialsProvider) .withEndpointConfiguration(endpoint).build(); DetectDocumentTextRequest request = new DetectDocumentTextRequest() .withDocument(new Document().withS3Object(new S3Object().withName(document).withBucket(bucket))); DetectDocumentTextResult result = client.detectDocumentText(request); // Create frame and panel. JFrame frame = new JFrame("RotateImage"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); DocumentText panel = new DocumentText(result, image); panel.setPreferredSize(new Dimension(image.getWidth() , image.getHeight() )); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } } Detecting Document Text 168 Amazon Textract Java V2 Developer Guide The following example code displays the document and boxes around lines of detected text. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name in the line that creates the TextractClient with the name of your developer profile. import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import
textract-dg-035
textract-dg.pdf
35
result = client.detectDocumentText(request); // Create frame and panel. JFrame frame = new JFrame("RotateImage"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); DocumentText panel = new DocumentText(result, image); panel.setPreferredSize(new Dimension(image.getWidth() , image.getHeight() )); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } } Detecting Document Text 168 Amazon Textract Java V2 Developer Guide The following example code displays the document and boxes around lines of detected text. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name in the line that creates the TextractClient with the name of your developer profile. import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.textract.model.S3Object; import software.amazon.awssdk.services.textract.TextractClient; import software.amazon.awssdk.services.textract.model.Document; import software.amazon.awssdk.services.textract.model.DetectDocumentTextRequest; import software.amazon.awssdk.services.textract.model.DetectDocumentTextResponse; import software.amazon.awssdk.services.textract.model.Block; import software.amazon.awssdk.services.textract.model.DocumentMetadata; import software.amazon.awssdk.services.textract.model.TextractException; import java.util.Iterator; import java.util.List; //snippet-end:[textract.java2._detect_s3_text.import] /** * 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 DetectText { public static void main(String[] args) { final String usage = "\n" + "Usage:\n" + " <bucketName> <docName> \n\n" + "Where:\n" + Detecting Document Text 169 Amazon Textract Developer Guide " 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_EAST_1; TextractClient textractClient = TextractClient.builder() .region(region) .credentialsProvider(ProfileCredentialsProvider.create("profile- name")) .build(); detectDocTextS3(textractClient, bucketName, docName); textractClient.close(); } // snippet-start:[textract.java2._detect_s3_text.main] public static void detectDocTextS3 (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(); DetectDocumentTextRequest detectDocumentTextRequest = DetectDocumentTextRequest.builder() .document(myDoc) .build(); Detecting Document Text 170 Amazon Textract Developer Guide DetectDocumentTextResponse textResponse = textractClient.detectDocumentText(detectDocumentTextRequest); for (Block block: textResponse.blocks()) { System.out.println("The block type is " +block.blockType().toString()); } DocumentMetadata documentMetadata = textResponse.documentMetadata(); System.out.println("The number of pages in the document is " +documentMetadata.pages()); } catch (TextractException e) { System.err.println(e.getMessage()); System.exit(1); } } // snippet-end:[textract.java2._detect_s3_text.main] } AWS CLI This AWS CLI command displays the JSON output for the detect-document-text CLI operation. Replace the values of Bucket and Name with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. aws textract detect-document-text \ --document '{"S3Object":{"Bucket":"bucket","Name":"document"}}' \ --profile profile-name \ --region region Python The following example code displays the document and boxes around detected lines of text. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name with the Detecting Document Text 171 Amazon Textract Developer Guide name of a profile that can assume the role and region with the region in which you want to run the code. #Detects text in a document stored in an S3 bucket. Display polygon box around text and angled text import boto3 import io from PIL import Image, ImageDraw def process_text_detection(s3_connection, client, bucket, document): #Get the document from S3 s3_object = s3_connection.Object(bucket,document) s3_response = s3_object.get() stream = io.BytesIO(s3_response['Body'].read()) image=Image.open(stream) #To process using image bytes: #image_binary = stream.getvalue() #response = client.detect_document_text(Document={'Bytes': image_binary}) # Detect text in the document # Process using S3 object response = client.detect_document_text( Document={'S3Object': {'Bucket': bucket, 'Name': document}}) # Get the text blocks blocks=response['Blocks'] width, height =image.size print ('Detected Document Text') # Create image showing bounding box/polygon the detected lines/text for block in blocks: # Display information about a block returned by text detection print('Type: ' + block['BlockType']) if block['BlockType'] != 'PAGE': print('Detected: ' + block['Text']) print('Confidence: ' + "{:.2f}".format(block['Confidence']) + "%") print('Id: {}'.format(block['Id'])) if 'Relationships' in block: Detecting Document Text 172 Amazon Textract Developer Guide print('Relationships: {}'.format(block['Relationships'])) print('Bounding Box: {}'.format(block['Geometry']['BoundingBox'])) print('Polygon: {}'.format(block['Geometry']['Polygon'])) print() draw=ImageDraw.Draw(image) # Draw WORD - Green - start of word, red - end of word if block['BlockType'] == "WORD": draw.line([(width * block['Geometry']['Polygon'][0]['X'], height * block['Geometry']['Polygon'][0]['Y']), (width * block['Geometry']['Polygon'][3]['X'], height * block['Geometry']['Polygon'][3]['Y'])],fill='green', width=2) draw.line([(width * block['Geometry']['Polygon'][1]['X'], height * block['Geometry']['Polygon'][1]['Y']), (width * block['Geometry']['Polygon'][2]['X'], height * block['Geometry']['Polygon'][2]['Y'])], fill='red', width=2) # Draw box around entire LINE if block['BlockType'] == "LINE": points=[] for polygon in block['Geometry']['Polygon']: points.append((width * polygon['X'], height * polygon['Y'])) draw.polygon((points), outline='black') # Display the image image.show() return len(blocks) def main(): session = boto3.Session(profile_name='profile-name') s3_connection = session.resource('s3') client = session.client('textract', region_name='region') bucket = '' document = '' block_count=process_text_detection(s3_connection,client,bucket,document) print("Blocks detected: " + str(block_count)) Detecting Document Text 173 Amazon Textract Developer Guide if __name__ == "__main__": main() Node.js The following Node.js example code displays the document and boxes around detected lines of text. It outputs an image of the results to the directory you run the code from. It makes use of the image-size and
textract-dg-036
textract-dg.pdf
36
LINE if block['BlockType'] == "LINE": points=[] for polygon in block['Geometry']['Polygon']: points.append((width * polygon['X'], height * polygon['Y'])) draw.polygon((points), outline='black') # Display the image image.show() return len(blocks) def main(): session = boto3.Session(profile_name='profile-name') s3_connection = session.resource('s3') client = session.client('textract', region_name='region') bucket = '' document = '' block_count=process_text_detection(s3_connection,client,bucket,document) print("Blocks detected: " + str(block_count)) Detecting Document Text 173 Amazon Textract Developer Guide if __name__ == "__main__": main() Node.js The following Node.js example code displays the document and boxes around detected lines of text. It outputs an image of the results to the directory you run the code from. It makes use of the image-size and images packages. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace the value of regionConfig with the name of the region your account is in. Replace the value of credentialswith the name of your developer profile. //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/ amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) async function main(){ // Import AWS const AWS = require("aws-sdk") // Use Image-Size to get const sizeOf = require('image-size'); // Image tool to draw buffers const images = require("images"); // Set variables var credentials = new AWS.SharedIniFileCredentials({profile: 'default'}); AWS.config.credentials = credentials; AWS.config.update({region:'region-name'}); const bucket = 'bucket-name' // the s3 bucket name const photo = 'photo-name' // the name of file // Create a canvas and get the context const { createCanvas } = require('canvas') const canvas = createCanvas(200, 200) const ctx = canvas.getContext('2d') // Connect to Textract const client = new AWS.Textract(); // Connect to S3 to display image Detecting Document Text 174 Amazon Textract Developer Guide const s3 = new AWS.S3(); // Define paramaters const params = { Document: { S3Object: { Bucket: bucket, Name: photo }, }, } // Function to display image async function getImage(){ const imageData = s3.getObject( { Bucket: bucket, Key: photo } ).promise(); return imageData; } // get image var imageData = await getImage() // Get the height, width of the image const dimensions = sizeOf(imageData.Body) const width = dimensions.width const height = dimensions.height console.log(imageData.Body) console.log(width, height) canvas.width = width; canvas.height = height; try{ // Call API and log response const res = await client.detectDocumentText(params).promise(); var image = images(imageData.Body).size(width, height) //console.log the type of block, text, text type, and confidence res.Blocks.forEach(block => { console.log(`Block Type: ${block.BlockType}`), Detecting Document Text 175 Amazon Textract Developer Guide console.log(`Text: ${block.Text}`) console.log(`TextType: ${block.TextType}`) console.log(`Confidence: ${block.Confidence}`) // Draw box around detected text using polygons ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.beginPath(); block.Geometry.Polygon.forEach(({X, Y}) => ctx.lineTo(width * X - 10, height * Y - 10) ); ctx.closePath(); ctx.stroke(); console.log("-----") }) // render image var buffer = canvas.toBuffer("image/png"); image.draw(images(buffer), 10, 10) image.save("output-image.jpg"); } catch (err){ console.error(err);} } main() .NET The following example provides detected text as a list. Replace the values of bucket and document with the names of the Amazon S3 bucket and document image that you used in step 2. using System; using System.Linq; using Amazon.Textract; using Amazon.Textract.Model; namespace TextractAnalyzeID { class Program { Detecting Document Text 176 Amazon Textract Developer Guide static async Task Main() { String document = "document"; String bucket = "bucket"; AmazonTextractClient textractClient = new AmazonTextractClient(); DetectDocumentTextRequest detectDocumentTextRequest = new DetectDocumentTextRequest() { Document = new Document() { S3Object = new S3Object() { Name = document, Bucket = bucket } } }; try { var DocumentText = await textractClient.DetectDocumentTextAsync(detectDocumentTextRequest); foreach (Block block in DocumentText.Blocks) { Console.WriteLine(block.BlockType); if (block.BlockType != "PAGE") { Console.WriteLine("Detected Text= " + block.Text); Console.WriteLine("Confidence= " + block.Confidence); } Console.WriteLine("Id= " + block.Id); foreach(Relationship relationship in block.Relationships) { Console.WriteLine(relationship.Type); relationship.Ids.ForEach(id => Console.WriteLine("Id= " + id)); } } } catch (Exception e) { Console.WriteLine(e.Message); Detecting Document Text 177 Amazon Textract Developer Guide } } } } 4. Run the example. The Python and Java examples display the document image. A black box surrounds each line of detected text. A green vertical line is the start of a detected word. A red vertical line is the end of a detected word. The AWS CLI example displays only the JSON output for the DetectDocumentText operation. Analyzing Document Text with Amazon Textract To analyze text in a document, you use the AnalyzeDocument operation, and pass a document file as input. AnalyzeDocument returns a JSON structure that contains the analyzed text. For more information, see Analyzing Documents. You can provide an input document as an image byte array (base64-encoded image bytes), or as an Amazon S3 object. In this procedure, you upload an image file to your S3 bucket and specify the file name. To analyze text in a document (API) 1. If you haven't already: a. Give a user the AmazonTextractFullAccess and AmazonS3ReadOnlyAccess permissions. For more information, see Step 1: Set Up an AWS Account and Create a User. b. Install and configure the AWS CLI and the AWS SDKs.
textract-dg-037
textract-dg.pdf
37
AnalyzeDocument returns a JSON structure that contains the analyzed text. For more information, see Analyzing Documents. You can provide an input document as an image byte array (base64-encoded image bytes), or as an Amazon S3 object. In this procedure, you upload an image file to your S3 bucket and specify the file name. To analyze text in a document (API) 1. If you haven't already: a. Give a user the AmazonTextractFullAccess and AmazonS3ReadOnlyAccess permissions. For more information, see Step 1: Set Up an AWS Account and Create a User. b. Install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. 2. Upload an image that contains a document to your S3 bucket. For instructions, see Uploading Objects into Amazon S3 in the Amazon Simple Storage Service User Guide. 3. Use the following examples to call the AnalyzeDocument operation. Java The following example code displays the document and boxes around detected items. Analyzing Document Text 178 Amazon Textract Developer Guide In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document image that you used in step 2. Replace the value of credentialsProvider with the name of your developer profile. //Loads document from S3 bucket. Displays the document and polygon around detected lines of text. import java.awt.*; import java.awt.image.BufferedImage; import java.util.List; import javax.imageio.ImageIO; import javax.swing.*; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.textract.AmazonTextract; import com.amazonaws.services.textract.AmazonTextractClientBuilder; import com.amazonaws.services.textract.model.AnalyzeDocumentRequest; import com.amazonaws.services.textract.model.AnalyzeDocumentResult; import com.amazonaws.services.textract.model.Block; import com.amazonaws.services.textract.model.BoundingBox; import com.amazonaws.services.textract.model.Document; import com.amazonaws.services.textract.model.S3Object; import com.amazonaws.services.textract.model.Point; import com.amazonaws.services.textract.model.Relationship; import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; public class AnalyzeDocument extends JPanel { private static final long serialVersionUID = 1L; BufferedImage image; AnalyzeDocumentResult result; public AnalyzeDocument(AnalyzeDocumentResult documentResult, BufferedImage bufImage) throws Exception { super(); result = documentResult; // Results of text detection. image = bufImage; // The image containing the document. Analyzing Document Text 179 Amazon Textract } Developer Guide // Draws the image and text bounding box. public void paintComponent(Graphics g) { int height = image.getHeight(this); int width = image.getWidth(this); Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g. // Draw the image. g2d.drawImage(image, 0, 0, image.getWidth(this), image.getHeight(this), this); // Iterate through blocks and display bounding boxes around everything. List<Block> blocks = result.getBlocks(); for (Block block : blocks) { DisplayBlockInfo(block); switch(block.getBlockType()) { case "KEY_VALUE_SET": if (block.getEntityTypes().contains("KEY")){ ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(255,0,0)); } else { //VALUE ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(0,255,0)); } break; case "TABLE": ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(0,0,255)); break; case "CELL": ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(255,255,0)); break; case "SELECTION_ELEMENT": if (block.getSelectionStatus().equals("SELECTED")) ShowSelectedElement(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(0,0,255)); Analyzing Document Text 180 Amazon Textract Developer Guide break; default: //PAGE, LINE & WORD //ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(200,200,0)); } } // uncomment to show polygon around all blocks //ShowPolygon(height,width,block.getGeometry().getPolygon(),g2d); } // Show bounding box at supplied location. private void ShowBoundingBox(int imageHeight, int imageWidth, BoundingBox box, Graphics2D g2d, Color color) { float left = imageWidth * box.getLeft(); float top = imageHeight * box.getTop(); // Display bounding box. g2d.setColor(color); g2d.drawRect(Math.round(left), Math.round(top), Math.round(imageWidth * box.getWidth()), Math.round(imageHeight * box.getHeight())); } private void ShowSelectedElement(int imageHeight, int imageWidth, BoundingBox box, Graphics2D g2d, Color color) { float left = imageWidth * box.getLeft(); float top = imageHeight * box.getTop(); // Display bounding box. g2d.setColor(color); g2d.fillRect(Math.round(left), Math.round(top), Math.round(imageWidth * box.getWidth()), Math.round(imageHeight * box.getHeight())); } // Shows polygon at supplied location Analyzing Document Text 181 Amazon Textract Developer Guide private void ShowPolygon(int imageHeight, int imageWidth, List<Point> points, Graphics2D g2d) { g2d.setColor(new Color(0, 0, 0)); Polygon polygon = new Polygon(); // Construct polygon and display for (Point point : points) { polygon.addPoint((Math.round(point.getX() * imageWidth)), Math.round(point.getY() * imageHeight)); } g2d.drawPolygon(polygon); } //Displays information from a block returned by text detection and text analysis private void DisplayBlockInfo(Block block) { System.out.println("Block Id : " + block.getId()); if (block.getText()!=null) System.out.println(" Detected text: " + block.getText()); System.out.println(" Type: " + block.getBlockType()); if (block.getBlockType().equals("PAGE") !=true) { System.out.println(" Confidence: " + block.getConfidence().toString()); } if(block.getBlockType().equals("CELL")) { System.out.println(" Cell information:"); System.out.println(" Column: " + block.getColumnIndex()); System.out.println(" Row: " + block.getRowIndex()); System.out.println(" Column span: " + block.getColumnSpan()); System.out.println(" Row span: " + block.getRowSpan()); } System.out.println(" Relationships"); List<Relationship> relationships=block.getRelationships(); if(relationships!=null) { for (Relationship relationship : relationships) { System.out.println(" Type: " + relationship.getType()); System.out.println(" IDs: " + relationship.getIds().toString()); } } else { Analyzing Document Text 182 Amazon Textract Developer Guide System.out.println(" No related Blocks"); } System.out.println(" Geometry"); System.out.println(" Bounding Box: " + block.getGeometry().getBoundingBox().toString()); System.out.println(" Polygon: " + block.getGeometry().getPolygon().toString()); List<String> entityTypes = block.getEntityTypes(); System.out.println(" Entity Types"); if(entityTypes!=null) { for (String entityType : entityTypes) { System.out.println(" Entity Type: " + entityType); } } else { System.out.println(" No entity type"); } if(block.getBlockType().equals("SELECTION_ELEMENT")) { System.out.print(" Selection element detected: "); if (block.getSelectionStatus().equals("SELECTED")){ System.out.println("Selected"); }else { System.out.println(" Not selected"); } } if(block.getPage()!=null) System.out.println(" Page: " + block.getPage()); System.out.println(); } public static void main(String arg[]) throws Exception { // The S3 bucket
textract-dg-038
textract-dg.pdf
38
" + relationship.getIds().toString()); } } else { Analyzing Document Text 182 Amazon Textract Developer Guide System.out.println(" No related Blocks"); } System.out.println(" Geometry"); System.out.println(" Bounding Box: " + block.getGeometry().getBoundingBox().toString()); System.out.println(" Polygon: " + block.getGeometry().getPolygon().toString()); List<String> entityTypes = block.getEntityTypes(); System.out.println(" Entity Types"); if(entityTypes!=null) { for (String entityType : entityTypes) { System.out.println(" Entity Type: " + entityType); } } else { System.out.println(" No entity type"); } if(block.getBlockType().equals("SELECTION_ELEMENT")) { System.out.print(" Selection element detected: "); if (block.getSelectionStatus().equals("SELECTED")){ System.out.println("Selected"); }else { System.out.println(" Not selected"); } } if(block.getPage()!=null) System.out.println(" Page: " + block.getPage()); System.out.println(); } public static void main(String arg[]) throws Exception { // The S3 bucket and document String document = ""; String bucket = ""; // set provider credentials AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider("default"); Analyzing Document Text 183 Amazon Textract Developer Guide AmazonS3 s3client = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider) .withEndpointConfiguration( new EndpointConfiguration("https:// s3.amazonaws.com","us-east-1")) .build(); // Get the document from S3 com.amazonaws.services.s3.model.S3Object s3object = s3client.getObject(bucket, document); S3ObjectInputStream inputStream = s3object.getObjectContent(); BufferedImage image = ImageIO.read(inputStream); // Call AnalyzeDocument EndpointConfiguration endpoint = new EndpointConfiguration( "https://textract.us-east-1.amazonaws.com", "us-east-1"); AmazonTextract client = AmazonTextractClientBuilder.standard().withCredentials(credentialsProvider) .withEndpointConfiguration(endpoint).build(); AnalyzeDocumentRequest request = new AnalyzeDocumentRequest() .withFeatureTypes("TABLES","FORMS","SIGNATURES") .withDocument(new Document(). withS3Object(new S3Object().withName(document).withBucket(bucket))); AnalyzeDocumentResult result = client.analyzeDocument(request); // Create frame and panel. JFrame frame = new JFrame("RotateImage"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); AnalyzeDocument panel = new AnalyzeDocument(result, image); panel.setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } } Analyzing Document Text 184 Amazon Textract Java V2 Developer Guide The following example code displays the document and boxes around lines of detected text. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name in the line that creates the TextractClient with the name of your developer profile. 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.AnalyzeDocumentRequest; import software.amazon.awssdk.services.textract.model.Document; import software.amazon.awssdk.services.textract.model.FeatureType; import software.amazon.awssdk.services.textract.model.S3Object; import software.amazon.awssdk.services.textract.model.AnalyzeDocumentResponse; import software.amazon.awssdk.services.textract.model.Block; import software.amazon.awssdk.services.textract.model.TextractException; 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] /** * 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 AnalyzeDocument { public static void main(String[] args) { Analyzing Document Text 185 Amazon Textract Developer Guide 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_EAST_1; TextractClient textractClient = TextractClient.builder() .region(region) .credentialsProvider(ProfileCredentialsProvider.create("profile- name")) .build(); analyzeDoc(textractClient, bucketName, docName); textractClient.close(); } // snippet-start:[textract.java2._analyze_doc.main] public static void analyzeDoc(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(); List<FeatureType> featureTypes = new ArrayList<FeatureType>(); featureTypes.add(FeatureType.FORMS); Analyzing Document Text 186 Amazon Textract Developer Guide featureTypes.add(FeatureType.TABLES); AnalyzeDocumentRequest analyzeDocumentRequest = AnalyzeDocumentRequest.builder() .featureTypes(featureTypes) .document(myDoc) .build(); AnalyzeDocumentResponse analyzeDocument = textractClient.analyzeDocument(analyzeDocumentRequest); List<Block> docInfo = analyzeDocument.blocks(); Iterator<Block> blockIterator = docInfo.iterator(); while(blockIterator.hasNext()) { Block block = blockIterator.next(); System.out.println("The block type is " +block.blockType().toString()); } } catch (TextractException e) { System.err.println(e.getMessage()); System.exit(1); } } // snippet-end:[textract.java2._analyze_doc.main] } AWS CLI This AWS CLI command displays the JSON output for the analyze-document CLI operation. Replace the values of Bucket and Name with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. aws textract analyze-document \ --document '{"S3Object":{"Bucket":"bucket","Name":"document"}}' \ --feature-types '["TABLES","FORMS","SIGNATURES"]' \ --profile profile-name \ --region region Analyzing Document Text 187 Amazon Textract Developer Guide In order to use the Queries feature, include the 'QUERIES' value in the 'feature-types' parameter and then provide a Queries object to the 'queries-config' parameter. To use an adapter, include any AdapterIds and Versions in a list of Adapters provided to the AdapterConfig parameter. aws textract analyze-document \ --document '{"S3Object":{"Bucket":"bucket","Name":"document"}}'\ --feature-types '["QUERIES"]' \ --queries-config '{"Queries":[{"Text":"Question"}]}' \ --profile profile-name \ --region region --adapters-config '{"Adapters": [{"AdapterId": "AdapterId", "Version": "1"]}' Python The following example code displays the document and boxes around detected items. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. To use an adapter, include any AdapterIds and Versions in a list of Adapters provided to the AdapterConfig parameter. #Analyzes text in a document stored in an S3 bucket. Display polygon box around text and angled text import boto3 import io from PIL
textract-dg-039
textract-dg.pdf
39
boxes around detected items. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. To use an adapter, include any AdapterIds and Versions in a list of Adapters provided to the AdapterConfig parameter. #Analyzes text in a document stored in an S3 bucket. Display polygon box around text and angled text import boto3 import io from PIL import Image, ImageDraw def ShowBoundingBox(draw,box,width,height,boxColor): left = width * box['Left'] top = height * box['Top'] draw.rectangle([left,top, left + (width * box['Width']), top +(height * box['Height'])],outline=boxColor) def ShowSelectedElement(draw,box,width,height,boxColor): left = width * box['Left'] top = height * box['Top'] Analyzing Document Text 188 Amazon Textract Developer Guide draw.rectangle([left,top, left + (width * box['Width']), top +(height * box['Height'])],fill=boxColor) # Displays information about a block returned by text detection and text analysis def DisplayBlockInformation(block): print('Id: {}'.format(block['Id'])) if 'Text' in block: print(' Detected: ' + block['Text']) print(' Type: ' + block['BlockType']) if 'Confidence' in block: print(' Confidence: ' + "{:.2f}".format(block['Confidence']) + "%") if block['BlockType'] == 'CELL': print(" Cell information") print(" Column:" + str(block['ColumnIndex'])) print(" Row:" + str(block['RowIndex'])) print(" Column Span:" + str(block['ColumnSpan'])) print(" RowSpan:" + str(block['ColumnSpan'])) if 'Relationships' in block: print(' Relationships: {}'.format(block['Relationships'])) print(' Geometry: ') print(' Bounding Box: {}'.format(block['Geometry']['BoundingBox'])) print(' Polygon: {}'.format(block['Geometry']['Polygon'])) if block['BlockType'] == "KEY_VALUE_SET": print (' Entity Type: ' + block['EntityTypes'][0]) if block['BlockType'] == 'SELECTION_ELEMENT': print(' Selection element detected: ', end='') if block['SelectionStatus'] =='SELECTED': print('Selected') else: print('Not selected') if 'Page' in block: print('Page: ' + block['Page']) print() def process_text_analysis(s3_connection, client, bucket, document): Analyzing Document Text 189 Amazon Textract Developer Guide # Get the document from S3 s3_object = s3_connection.Object(bucket,document) s3_response = s3_object.get() stream = io.BytesIO(s3_response['Body'].read()) image=Image.open(stream) # Analyze the document image_binary = stream.getvalue() response = client.analyze_document(Document={'Bytes': image_binary}, FeatureTypes=["TABLES", "FORMS", "SIGNATURES"]) ### Uncomment to process using S3 object ### #response = client.analyze_document( # Document={'S3Object': {'Bucket': bucket, 'Name': document}}, # FeatureTypes=["TABLES", "FORMS", "SIGNATURES"]) ### Uncomment to analyze a local file ### # with open("pathToFile", 'rb') as img_file: ### To display image using PIL ### # image = Image.open() ### Read bytes ### # img_bytes = img_file.read() # response = client.analyze_document(Document={'Bytes': img_bytes}, FeatureTypes=["TABLES", "FORMS", "SIGNATURES"]) #Get the text blocks blocks=response['Blocks'] width, height =image.size print ('Detected Document Text') # Create image showing bounding box/polygon the detected lines/text for block in blocks: DisplayBlockInformation(block) draw=ImageDraw.Draw(image) # Draw bounding boxes for different detected response objects if block['BlockType'] == "KEY_VALUE_SET": if block['EntityTypes'][0] == "KEY": ShowBoundingBox(draw, block['Geometry'] ['BoundingBox'],width,height,'red') else: ShowBoundingBox(draw, block['Geometry'] ['BoundingBox'],width,height,'green') Analyzing Document Text 190 Amazon Textract Developer Guide if block['BlockType'] == 'TABLE': ShowBoundingBox(draw, block['Geometry']['BoundingBox'],width,height, 'blue') if block['BlockType'] == 'CELL': ShowBoundingBox(draw, block['Geometry']['BoundingBox'],width,height, 'yellow') if block['BlockType'] == 'SELECTION_ELEMENT': if block['SelectionStatus'] =='SELECTED': ShowSelectedElement(draw, block['Geometry'] ['BoundingBox'],width,height, 'blue') # Display the image image.show() return len(blocks) def main(): session = boto3.Session(profile_name='profile-name') s3_connection = session.resource('s3') client = session.client('textract', region_name='region') bucket = "" document = "" block_count=process_text_analysis(s3_connection, client, bucket, document) print("Blocks detected: " + str(block_count)) if __name__ == "__main__": main() In order to use different features of the AnalyzeDocument operation, you provide the proper feature type to the features-type parameter. For example, to use the Queries feature, include the QUERIES value in the feature-types parameter and then provide a Queries object to the queries-config parameter. To query your document, add the query_document function in the following code to the preceding code example. Then, include the question variable and line that invokes the query_document function to the preceding main function. def query_document(client, bucket, document, question): # Analyze the document response = client.analyze_document(Document={'S3Object': {'Bucket': bucket, 'Name': document}}, FeatureTypes=["TABLES", "FORMS", "QUERIES"], Analyzing Document Text 191 Amazon Textract Developer Guide QueriesConfig={'Queries':[ {'Text':'{}'.format(question)} ]}) for block in response['Blocks']: if block["BlockType"] == "QUERY": print("Query info:") print(block["Query"]) if block["BlockType"] == "QUERY_RESULT": print("Query answer:") print(block["Text"]) question = "query here" query_document(client, bucket, document, question) Node.js The following example code displays the document and boxes around detected items. In the following code, replace the values of bucket and photo with the names of the Amazon S3 bucket and document that you used in step 2. Replace the value of region with the region associated with your account. Replace the value of credentials with the name of your developer profile. // Import required AWS SDK clients and commands for Node.js import { AnalyzeDocumentCommand } from "@aws-sdk/client-textract"; import { TextractClient } from "@aws-sdk/client-textract"; import {fromIni} from '@aws-sdk/credential-providers'; // Set the AWS Region. const REGION = "region"; //e.g. "us-east-1" const profileName = "default"; // Create SNS service object. const textractClient = new TextractClient({region: REGION, credentials: fromIni({profile: profileName,}), }); const bucket = 'buckets' const photo = 'photo' // Set params const params = { Analyzing Document Text 192 Amazon Textract Developer Guide Document: { S3Object: { Bucket: bucket, Name: photo }, }, FeatureTypes: ['TABLES', 'FORMS', 'SIGNATURES'], } const displayBlockInfo = async
textract-dg-040
textract-dg.pdf
40
developer profile. // Import required AWS SDK clients and commands for Node.js import { AnalyzeDocumentCommand } from "@aws-sdk/client-textract"; import { TextractClient } from "@aws-sdk/client-textract"; import {fromIni} from '@aws-sdk/credential-providers'; // Set the AWS Region. const REGION = "region"; //e.g. "us-east-1" const profileName = "default"; // Create SNS service object. const textractClient = new TextractClient({region: REGION, credentials: fromIni({profile: profileName,}), }); const bucket = 'buckets' const photo = 'photo' // Set params const params = { Analyzing Document Text 192 Amazon Textract Developer Guide Document: { S3Object: { Bucket: bucket, Name: photo }, }, FeatureTypes: ['TABLES', 'FORMS', 'SIGNATURES'], } const displayBlockInfo = async (response) => { try { response.Blocks.forEach(block => { console.log(`ID: ${block.Id}`) console.log(`Block Type: ${block.BlockType}`) if ("Text" in block && block.Text !== undefined){ console.log(`Text: ${block.Text}`) } else{} if ("Confidence" in block && block.Confidence !== undefined){ console.log(`Confidence: ${block.Confidence}`) } else{} if (block.BlockType == 'CELL'){ console.log("Cell info:") console.log(` Column Index - ${block.ColumnIndex}`) console.log(` Row - ${block.RowIndex}`) console.log(` Column Span - ${block.ColumnSpan}`) console.log(` Row Span - ${block.RowSpan}`) } if ("Relationships" in block && block.Relationships !== undefined){ console.log(block.Relationships) console.log("Geometry:") console.log(` Bounding Box - ${JSON.stringify(block.Geometry.BoundingBox)}`) console.log(` Polygon - ${JSON.stringify(block.Geometry.Polygon)}`) } console.log("-----") }); } catch (err) { console.log("Error", err); } } Analyzing Document Text 193 Amazon Textract Developer Guide const analyze_document_text = async () => { try { const analyzeDoc = new AnalyzeDocumentCommand(params); const response = await textractClient.send(analyzeDoc); //console.log(response) displayBlockInfo(response) return response; // For unit tests. } catch (err) { console.log("Error", err); } } analyze_document_text() .NET The following example displays detected text and their relationships in a list. Replace the values of bucket and document with the names of the Amazon S3 bucket and document image that you used in step 2. using System; using System.Linq; using System.Reflection.Emit; using Amazon.Runtime; using Amazon.Textract; using Amazon.Textract.Model; namespace TextractAnalyzeExpense { class Program { static async Task Main() { String document = "document"; String bucket = "bucket"; AmazonTextractClient textractClient = new AmazonTextractClient(); AnalyzeExpenseRequest analyzeExpenseRequest = new AnalyzeExpenseRequest() { Analyzing Document Text 194 Amazon Textract Developer Guide Document = new Document() { S3Object = new S3Object() { Name = document, Bucket = bucket } } }; try { var ExpenseAnalysis = await textractClient.AnalyzeExpenseAsync(analyzeExpenseRequest); Console.WriteLine("Line Items:"); foreach (ExpenseDocument expenseDocument in ExpenseAnalysis.ExpenseDocuments) { Console.WriteLine("Line Items:"); foreach(LineItemGroup linegroup in expenseDocument.LineItemGroups) { PrintLineItems.LineItemPrinter.LineItemParse(linegroup); } Console.WriteLine("Summary:\n"); foreach(ExpenseField summary in expenseDocument.SummaryFields) { if (summary.LabelDetection is not null) { Console.WriteLine(summary.LabelDetection.Text); } if (summary.ValueDetection is not null) { Console.WriteLine(summary.ValueDetection.Text); } } } } catch (Exception e) Analyzing Document Text 195 Amazon Textract { Console.WriteLine(e.Message); } Developer Guide } } } namespace PrintLineItems { class LineItemPrinter { public static void LineItemParse(LineItemGroup lineitemgroup) { foreach(LineItemFields lineitem in lineitemgroup.LineItems) { foreach(ExpenseField expense in lineitem.LineItemExpenseFields){ if (expense.LabelDetection is not null) { Console.WriteLine(expense.LabelDetection.Text); } if (expense.ValueDetection is not null) { Console.WriteLine(expense.ValueDetection.Text); } } } } } } 4. Run the example. The Python and Java examples display the document image with the following colored bounding boxes: • Red – KEY Block objects • Green – VALUE Block objects • Blue – TABLE Block objects • Yellow – CELL Block objects Analyzing Document Text 196 Amazon Textract Developer Guide Selection elements that are selected are filled with blue. The AWS CLI example displays only the JSON output for the AnalyzeDocument operation. Analyzing Invoices and Receipts with Amazon Textract To analyze invoice and receipt documents, use the AnalyzeExpense API operations and pass a document file as input. AnalyzeExpense is a synchronous operation that returns a JSON structure that contains the analyzed text. For more information, see Analyzing Invoices and Receipts. To analyze invoice and receipts asynchronously, use StartExpenseAnalysis to start processing an input document file and use GetExpenseAnalysis to get the results. You can provide an input document as an image byte array (base64-encoded image bytes), or as an Amazon S3 object. In this procedure, you upload an image file to your S3 bucket and specify the file name. To analyze an invoice or receipt (API) 1. If you haven't already: a. Give a user the AmazonTextractFullAccess and AmazonS3ReadOnlyAccess permissions. For more information, see Step 1: Set Up an AWS Account and Create a User. b. Install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. 2. Upload an image that contains a document to your S3 bucket. For instructions, see Uploading Objects into Amazon S3 in the Amazon Simple Storage Service User Guide. 3. Use the following examples to call the AnalyzeExpense operation. AWS CLI This AWS CLI command displays the JSON output for the analyze-expense CLI operation. Analyzing Invoice and Receipt Documents 197 Amazon Textract Developer Guide Replace the values of Bucket and Name with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name with the name of a profile that can assume the role and region with the region in which you want
textract-dg-041
textract-dg.pdf
41
to your S3 bucket. For instructions, see Uploading Objects into Amazon S3 in the Amazon Simple Storage Service User Guide. 3. Use the following examples to call the AnalyzeExpense operation. AWS CLI This AWS CLI command displays the JSON output for the analyze-expense CLI operation. Analyzing Invoice and Receipt Documents 197 Amazon Textract Developer Guide Replace the values of Bucket and Name with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. aws textract analyze-expense \ --document '{"S3Object": {"Bucket": "bucket","Name": "object"}}' \ --profile profile-name \ --region region Python The following example code displays the document and boxes around detected items. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document that you used in step 2. Replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. import boto3 import io from PIL import Image, ImageDraw def draw_bounding_box(key, val, width, height, draw): # If a key is Geometry, draw the bounding box info in it if "Geometry" in key: # Draw bounding box information box = val["BoundingBox"] left = width * box['Left'] top = height * box['Top'] draw.rectangle([left, top, left + (width * box['Width']), top + (height * box['Height'])], outline='black') # Takes a field as an argument and prints out the detected labels and values def print_labels_and_values(field): # Only if labels are detected and returned if "LabelDetection" in field: print("Summary Label Detection - Confidence: {}".format( str(field.get("LabelDetection")["Confidence"])) + ", " Analyzing Invoice and Receipt Documents 198 Amazon Textract Developer Guide + "Summary Values: {}".format(str(field.get("LabelDetection") ["Text"]))) print(field.get("LabelDetection")["Geometry"]) else: print("Label Detection - No labels returned.") if "ValueDetection" in field: print("Summary Value Detection - Confidence: {}".format( str(field.get("ValueDetection")["Confidence"])) + ", " + "Summary Values: {}".format(str(field.get("ValueDetection") ["Text"]))) print(field.get("ValueDetection")["Geometry"]) else: print("Value Detection - No values returned") def process_expense_analysis(s3_connection, client, bucket, document): # Get the document from S3 s3_object = s3_connection.Object(bucket, document) s3_response = s3_object.get() # opening binary stream using an in-memory bytes buffer stream = io.BytesIO(s3_response['Body'].read()) # loading stream into image image = Image.open(stream) # Analyze document # process using S3 object response = client.analyze_expense( Document={'S3Object': {'Bucket': bucket, 'Name': document}}) # Set width and height to display image and draw bounding boxes # Create drawing object width, height = image.size draw = ImageDraw.Draw(image) for expense_doc in response["ExpenseDocuments"]: for line_item_group in expense_doc["LineItemGroups"]: for line_items in line_item_group["LineItems"]: for expense_fields in line_items["LineItemExpenseFields"]: print_labels_and_values(expense_fields) print() print("Summary:") Analyzing Invoice and Receipt Documents 199 Amazon Textract Developer Guide for summary_field in expense_doc["SummaryFields"]: print_labels_and_values(summary_field) print() #For draw bounding boxes for line_item_group in expense_doc["LineItemGroups"]: for line_items in line_item_group["LineItems"]: for expense_fields in line_items["LineItemExpenseFields"]: for key, val in expense_fields["ValueDetection"].items(): if "Geometry" in key: draw_bounding_box(key, val, width, height, draw) for label in expense_doc["SummaryFields"]: if "LabelDetection" in label: for key, val in label["LabelDetection"].items(): draw_bounding_box(key, val, width, height, draw) # Display the image image.show() def main(): session = boto3.Session(profile_name='profile-name') s3_connection = session.resource('s3') client = session.client('textract', region_name='region') bucket = 'bucket' document = 'document' process_expense_analysis(s3_connection, client, bucket, document) if __name__ == "__main__": main() Java The following example code displays the document and boxes around detected items. In the function main, replace the values of bucket and document with the names of the Amazon S3 bucket and document image that you used in step 2. package com.amazonaws.samples; Analyzing Invoice and Receipt Documents 200 Amazon Textract Developer Guide import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.List; import java.util.concurrent.CompletableFuture; import javax.imageio.ImageIO; import javax.swing.*; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.*; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.textract.TextractClient; import software.amazon.awssdk.services.textract.model.AnalyzeExpenseRequest; import software.amazon.awssdk.services.textract.model.AnalyzeExpenseResponse; import software.amazon.awssdk.services.textract.model.BoundingBox; import software.amazon.awssdk.services.textract.model.Document; import software.amazon.awssdk.services.textract.model.ExpenseDocument; import software.amazon.awssdk.services.textract.model.ExpenseField; import software.amazon.awssdk.services.textract.model.LineItemFields; import software.amazon.awssdk.services.textract.model.LineItemGroup; import software.amazon.awssdk.services.textract.model.S3Object; import software.amazon.awssdk.services.textract.model.Point; /** * * Demo code to parse Textract AnalyzeExpense API * */ public class TextractAnalyzeExpenseSample extends JPanel { private static final long serialVersionUID = 1L; BufferedImage image; static AnalyzeExpenseResponse result; public TextractAnalyzeExpenseSample(AnalyzeExpenseResponse documentResult, BufferedImage bufImage) throws Exception { super(); Analyzing Invoice and Receipt Documents 201 Amazon Textract Developer Guide result = documentResult; // Results of analyzeexpense summaryfields and lineitemgroups detection. image = bufImage; // The image containing the document. } // Draws the image and text bounding box. public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g. // Draw the image. g2d.drawImage(image, 0, 0, image.getWidth(this), image.getHeight(this), this); // Iterate through summaryfields and lineitemgroups and display boundedboxes around lines of detected label and value. List<ExpenseDocument> expenseDocuments = result.expenseDocuments(); for (ExpenseDocument expenseDocument : expenseDocuments) { if (expenseDocument.hasSummaryFields()) { DisplayAnalyzeExpenseSummaryInfo(expenseDocument); List<ExpenseField> summaryfields = expenseDocument.summaryFields(); for (ExpenseField summaryfield : summaryfields) { if (summaryfield.valueDetection() != null) { ShowBoundingBox(image.getHeight(this), image.getWidth(this), summaryfield.valueDetection().geometry().boundingBox(), g2d, new Color(0, 0, 0)); } if (summaryfield.labelDetection() != null) {
textract-dg-042
textract-dg.pdf
42
The image containing the document. } // Draws the image and text bounding box. public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g. // Draw the image. g2d.drawImage(image, 0, 0, image.getWidth(this), image.getHeight(this), this); // Iterate through summaryfields and lineitemgroups and display boundedboxes around lines of detected label and value. List<ExpenseDocument> expenseDocuments = result.expenseDocuments(); for (ExpenseDocument expenseDocument : expenseDocuments) { if (expenseDocument.hasSummaryFields()) { DisplayAnalyzeExpenseSummaryInfo(expenseDocument); List<ExpenseField> summaryfields = expenseDocument.summaryFields(); for (ExpenseField summaryfield : summaryfields) { if (summaryfield.valueDetection() != null) { ShowBoundingBox(image.getHeight(this), image.getWidth(this), summaryfield.valueDetection().geometry().boundingBox(), g2d, new Color(0, 0, 0)); } if (summaryfield.labelDetection() != null) { ShowBoundingBox(image.getHeight(this), image.getWidth(this), summaryfield.labelDetection().geometry().boundingBox(), g2d, new Color(0, 0, 0)); } } } if (expenseDocument.hasLineItemGroups()) { Analyzing Invoice and Receipt Documents 202 Amazon Textract Developer Guide DisplayAnalyzeExpenseLineItemGroupsInfo(expenseDocument); List<LineItemGroup> lineitemgroups = expenseDocument.lineItemGroups(); for (LineItemGroup lineitemgroup : lineitemgroups) { if (lineitemgroup.hasLineItems()) { List<LineItemFields> lineItems = lineitemgroup.lineItems(); for (LineItemFields lineitemfield : lineItems) { if (lineitemfield.hasLineItemExpenseFields()) { List<ExpenseField> expensefields = lineitemfield.lineItemExpenseFields(); for (ExpenseField expensefield : expensefields) { if (expensefield.valueDetection() != null) { ShowBoundingBox(image.getHeight(this), image.getWidth(this), expensefield.valueDetection().geometry().boundingBox(), g2d, new Color(0, 0, 0)); } if (expensefield.labelDetection() != null) { ShowBoundingBox(image.getHeight(this), image.getWidth(this), expensefield.labelDetection().geometry().boundingBox(), g2d, new Color(0, 0, 0)); } } } } } } } } } // Show bounding box at supplied location. Analyzing Invoice and Receipt Documents 203 Amazon Textract Developer Guide private void ShowBoundingBox(float imageHeight, float imageWidth, BoundingBox box, Graphics2D g2d, Color color) { float left = imageWidth * box.left(); float top = imageHeight * box.top(); // Display bounding box. g2d.setColor(color); g2d.drawRect(Math.round(left), Math.round(top), Math.round(imageWidth * box.width()), Math.round(imageHeight * box.height())); } private void ShowSelectedElement(float imageHeight, float imageWidth, BoundingBox box, Graphics2D g2d, Color color) { float left = (float) imageWidth * (float) box.left(); float top = (float) imageHeight * (float) box.top(); System.out.println(left); System.out.println(top); // Display bounding box. g2d.setColor(color); g2d.fillRect(Math.round(left), Math.round(top), Math.round(imageWidth * box.width()), Math.round(imageHeight * box.height())); } // Shows polygon at supplied location private void ShowPolygon(int imageHeight, int imageWidth, List<Point> points, Graphics2D g2d) { g2d.setColor(new Color(0, 0, 0)); Polygon polygon = new Polygon(); // Construct polygon and display for (Point point : points) { polygon.addPoint((Math.round(point.x() * imageWidth)), Math.round(point.y() * imageHeight)); } g2d.drawPolygon(polygon); Analyzing Invoice and Receipt Documents 204 Amazon Textract } Developer Guide private void DisplayAnalyzeExpenseSummaryInfo(ExpenseDocument expensedocument) { System.out.println(" ExpenseId : " + expensedocument.expenseIndex()); System.out.println(" Expense Summary information:"); if (expensedocument.hasSummaryFields()) { List<ExpenseField> summaryfields = expensedocument.summaryFields(); for (ExpenseField summaryfield : summaryfields) { System.out.println(" Page: " + summaryfield.pageNumber()); if (summaryfield.type() != null) { System.out.println(" Expense Summary Field Type:" + summaryfield.type().text()); } if (summaryfield.labelDetection() != null) { System.out.println(" Expense Summary Field Label:" + summaryfield.labelDetection().text()); System.out.println(" Geometry"); System.out.println(" Bounding Box: " + summaryfield.labelDetection().geometry().boundingBox().toString()); System.out.println( " Polygon: " + summaryfield.labelDetection().geometry().polygon().toString()); } if (summaryfield.valueDetection() != null) { System.out.println(" Expense Summary Field Value:" + summaryfield.valueDetection().text()); System.out.println(" Geometry"); System.out.println(" Bounding Box: " + summaryfield.valueDetection().geometry().boundingBox().toString()); System.out.println( " Polygon: " + summaryfield.valueDetection().geometry().polygon().toString()); } } Analyzing Invoice and Receipt Documents 205 Amazon Textract Developer Guide } } private void DisplayAnalyzeExpenseLineItemGroupsInfo(ExpenseDocument expensedocument) { System.out.println(" ExpenseId : " + expensedocument.expenseIndex()); System.out.println(" Expense LineItemGroups information:"); if (expensedocument.hasLineItemGroups()) { List<LineItemGroup> lineitemgroups = expensedocument.lineItemGroups(); for (LineItemGroup lineitemgroup : lineitemgroups) { System.out.println(" Expense LineItemGroupsIndexID :" + lineitemgroup.lineItemGroupIndex()); if (lineitemgroup.hasLineItems()) { List<LineItemFields> lineItems = lineitemgroup.lineItems(); for (LineItemFields lineitemfield : lineItems) { if (lineitemfield.hasLineItemExpenseFields()) { List<ExpenseField> expensefields = lineitemfield.lineItemExpenseFields(); for (ExpenseField expensefield : expensefields) { if (expensefield.type() != null) { System.out.println(" Expense LineItem Field Type:" + expensefield.type().text()); } if (expensefield.valueDetection() != null) { System.out.println( " Expense Summary Field Value:" + expensefield.valueDetection().text()); System.out.println(" Geometry"); System.out.println(" Bounding Box: " + expensefield.valueDetection().geometry().boundingBox().toString()); Analyzing Invoice and Receipt Documents 206 Amazon Textract Developer Guide System.out.println(" Polygon: " + expensefield.valueDetection().geometry().polygon().toString()); } if (expensefield.labelDetection() != null) { System.out.println( " Expense LineItem Field Label:" + expensefield.labelDetection().text()); System.out.println(" Geometry"); System.out.println(" Bounding Box: " + expensefield.labelDetection().geometry().boundingBox().toString()); System.out.println(" Polygon: " + expensefield.labelDetection().geometry().polygon().toString()); } } } } } } } } public static void main(String arg[]) throws Exception { // Creates a default async client with credentials and AWS Region loaded from // the // environment S3AsyncClient client = S3AsyncClient.builder().region(Region.US_EAST_1).build(); System.out.println("Creating the S3 Client"); // Start the call to Amazon S3, not blocking to wait for the result CompletableFuture<ResponseBytes<GetObjectResponse>> responseFuture = client.getObject( GetObjectRequest.builder().bucket("textractanalyzeexpense").key("input/ sample-receipt.jpg").build(), Analyzing Invoice and Receipt Documents 207 Amazon Textract Developer Guide AsyncResponseTransformer.toBytes()); System.out.println("Successfully read the object"); // When future is complete (either successfully or in error), handle the // response CompletableFuture<ResponseBytes<GetObjectResponse>> operationCompleteFuture = responseFuture .whenComplete((getObjectResponse, exception) -> { if (getObjectResponse != null) { // At this point, the file my-file.out has been created with the data // from S3; let's just print the object version // Convert this into Async call and remove the below block from here and put it // outside TextractClient textractclient = TextractClient.builder().region(Region.US_EAST_1).build(); AnalyzeExpenseRequest request = AnalyzeExpenseRequest.builder() .document( Document.builder().s3Object(S3Object.builder().name("YOURObjectName") .bucket("YOURBucket").build()).build()) .build(); AnalyzeExpenseResponse result = textractclient.analyzeExpense(request); System.out.print(result.toString()); ByteArrayInputStream bais = new ByteArrayInputStream(getObjectResponse.asByteArray()); try { BufferedImage image = ImageIO.read(bais); System.out.println("Successfully read the image"); JFrame frame = new JFrame("Expense Image"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); TextractAnalyzeExpense panel = new TextractAnalyzeExpense(result, image); panel.setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } catch (IOException
textract-dg-043
textract-dg.pdf
43
{ if (getObjectResponse != null) { // At this point, the file my-file.out has been created with the data // from S3; let's just print the object version // Convert this into Async call and remove the below block from here and put it // outside TextractClient textractclient = TextractClient.builder().region(Region.US_EAST_1).build(); AnalyzeExpenseRequest request = AnalyzeExpenseRequest.builder() .document( Document.builder().s3Object(S3Object.builder().name("YOURObjectName") .bucket("YOURBucket").build()).build()) .build(); AnalyzeExpenseResponse result = textractclient.analyzeExpense(request); System.out.print(result.toString()); ByteArrayInputStream bais = new ByteArrayInputStream(getObjectResponse.asByteArray()); try { BufferedImage image = ImageIO.read(bais); System.out.println("Successfully read the image"); JFrame frame = new JFrame("Expense Image"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); TextractAnalyzeExpense panel = new TextractAnalyzeExpense(result, image); panel.setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } catch (IOException e) { Analyzing Invoice and Receipt Documents 208 Amazon Textract Developer Guide throw new RuntimeException(e); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // Handle the error exception.printStackTrace(); } }); // We could do other work while waiting for the AWS call to complete in // the background, but we'll just wait for "whenComplete" to finish instead operationCompleteFuture.join(); } } Node.js The following example code displays the document and boxes around detected items. In the function main, replace the values of bucket and photo with the names of the Amazon S3 bucket and document that you used in step 2. Replace profileName with the name of a profile that can assume the role and region with the region in which you want to run the code. // Import required AWS SDK clients and commands for Node.js import { AnalyzeExpenseCommand } from "@aws-sdk/client-textract"; import { TextractClient } from "@aws-sdk/client-textract"; import {fromIni} from '@aws-sdk/credential-providers'; // Set the AWS Region. const REGION = "region-name"; //e.g. "us-east-1" const profileName = "profile-name"; // Create SNS service object. const textractClient = new TextractClient({region: REGION, credentials: fromIni({profile: profileName,}), }); Analyzing Invoice and Receipt Documents 209 Amazon Textract Developer Guide const bucket = 'bucket-name' const photo = 'photo-name' // Set params const params = { Document: { S3Object: { Bucket: bucket, Name: photo }, }, } const process_text_detection = async () => { try { const aExpense = new AnalyzeExpenseCommand(params); const response = await textractClient.send(aExpense); //console.log(response) response.ExpenseDocuments.forEach(doc => { doc.LineItemGroups.forEach(items => { items.LineItems.forEach(fields => { fields.LineItemExpenseFields.forEach(expenseFields =>{ console.log(expenseFields) }) } )} ) } ) return response; // For unit tests. } catch (err) { console.log("Error", err); } } process_text_detection() 4. This will provide you with the JSON output for the AnalyzeExpense operation. Analyzing Invoice and Receipt Documents 210 Amazon Textract Developer Guide Analyzing Identity Documentation with Amazon Textract To analyze identity documents, you use the AnalyzeID API operation, and pass a document file as input. AnalyzeID returns a JSON structure that contains the analyzed text. For more information, see Analyzing Identity Documents. You can provide an input document as an image byte array (base64-encoded image bytes), or as an Amazon S3 object. In this procedure, you upload an image file to your S3 bucket and specify the file name. To analyze an identity document (API) 1. If you haven't already: a. Give a user the AmazonTextractFullAccess and AmazonS3ReadOnlyAccess permissions. For more information, see Step 1: Set Up an AWS Account and Create a User. b. Install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. 2. Upload an image that contains a document to your S3 bucket. For instructions, see Uploading Objects into Amazon S3 in the Amazon Simple Storage Service User Guide. 3. Use the following examples to call the AnalyzeID operation. AWS CLI The following example takes in an input file from an S3 bucket and runs the AnalyzeID operation on it. In the following code, replace the value of Bucket with the name of your S3 bucket and the value of Name with the name of the file in your bucket. Replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. aws textract analyze-id \ --document-pages '{"S3Object":{"Bucket":"bucket","Name":"name"}}' \ --profile profile-name \ --region region Analyzing ID Documents 211 Amazon Textract Developer Guide You can also call the API with the front and back of a driver's license by adding another Amazon S3 object to the input. aws textract analyze-id \ --document-pages '[{"S3Object":{"Bucket":"bucket","Name":"name front"}}, {"S3Object":{"Bucket":"bucket","Name":"name back"}}]' \ --profile profile-name \ --region region If you are accessing the CLI on a Windows device, use double quotes instead of single quotes and escape the inner double quotes by backslash (\) to address any parser errors you might encounter. For an example, see the following: aws textract analyze-id --document-pages "[{\"S3Object\":{\"Bucket\":\"bucket\", \"Name\":\"name\"}}]" --region region Python The following example takes in an input file from an S3 bucket and runs the AnalyzeID operation on it, returning the detected key-value pairs. In the following code, replace the value of bucket_name with the name of your S3
textract-dg-044
textract-dg.pdf
44
\ --document-pages '[{"S3Object":{"Bucket":"bucket","Name":"name front"}}, {"S3Object":{"Bucket":"bucket","Name":"name back"}}]' \ --profile profile-name \ --region region If you are accessing the CLI on a Windows device, use double quotes instead of single quotes and escape the inner double quotes by backslash (\) to address any parser errors you might encounter. For an example, see the following: aws textract analyze-id --document-pages "[{\"S3Object\":{\"Bucket\":\"bucket\", \"Name\":\"name\"}}]" --region region Python The following example takes in an input file from an S3 bucket and runs the AnalyzeID operation on it, returning the detected key-value pairs. In the following code, replace the value of bucket_name with the name of your S3 bucket and the value of file_name with the name of the file in your bucket. Replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. 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(): Analyzing ID Documents 212 Amazon Textract Developer Guide 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 The following example takes in an input file from an S3 bucket and runs the AnalyzeID operation on it, returning the detected data. In the function main, replace the values of s3bucket and sourceDoc with the names of the Amazon S3 bucket and document image that you used in step 2. Replace the value of credentialsProvider with the name of your developer profile. /* 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) { Analyzing ID Documents 213 Amazon Textract Developer Guide 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); Analyzing ID Documents 214 Amazon Textract Developer Guide 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 The following example takes in an input file from an S3 bucket and runs the AnalyzeID operation on it, returning the detected data. In the function main, replace the values of s3bucket and sourceDoc with the names of the S3 bucket and document image that you used in step 2. Replace profile-name in the line that creates the TextractClient with the name of your developer profile. 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; Analyzing ID Documents 215 Amazon Textract Developer Guide 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(); Analyzing ID Documents 216 Amazon Textract Developer Guide 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) {
textract-dg-045
textract-dg.pdf
45
{ 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(); Analyzing ID Documents 216 Amazon Textract Developer Guide 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] } 4. This will provide you with the JSON output for the AnalyzeID operation. Analyzing ID Documents 217 Amazon Textract Developer Guide Processing Documents Asynchronously You can use Amazon Textract to detect and analyze text in multipage documents in PDF or TIFF format, including invoices and receipts. Multipage document processing is an asynchronous operation, and it is useful for processing large, multipage documents. For example, a PDF file with over 1,000 pages takes a long time to process, but processing the PDF file asynchronously allows your application to complete other tasks while the operation completes. This section describes how you can use Amazon Textract to asynchronously detect and analyze text on a multipage or single-page document. Multipage documents must be in PDF or TIFF format. Single-page documents processed with asynchronous operations can be in JPEG, PNG, TIFF or PDF format. You can use Amazon Textract asynchronous operations for the following purposes: • Text detection – You can detect lines and words on a multipage document. The asynchronous operations are StartDocumentTextDetection and GetDocumentTextDetection. For more information, see Detecting Text. • Text analysis – You can identify relationships between detected text on a multipage document. The asynchronous operations are StartDocumentAnalysis and GetDocumentAnalysis. For more information, see Analyzing Documents. • Expense analysis – You can identify data relationships on multipage invoices and receipts. Amazon Textract treats each invoice or a receipt page of a multi-page document as an individual receipt or an invoice. It does not retain the context from one page to another of a multi-page document. The asynchronous operations are StartExpenseAnalysis and GetExpenseAnalysis. For more information, see Analyzing Invoices and Receipts. • Lending document analysis – You can classify and analyze lending documents using the Analyze Lending workflow, which classifies documents and then automatically sends the documents to the proper Amazon Textract operation for information extraction. You can start the asynchronous analysis of lending documents with StartLendingAnalysis, and retrieve the extracted information with GetLendingAnalysis or get a summary of the information with GetLendingAnalysisSummary. Analyze Lending returns the relevant information extracted from the documents, including detected signatures. You can also get the different types of documents in the submitted package, split by the logical boundaries for a given document type, if you use the OutputConfig feature. 218 Amazon Textract Topics • Calling Amazon Textract Asynchronous Operations • Configuring Amazon Textract for Asynchronous Operations • Detecting or Analyzing Text in a Multipage Document • Using the Analyze Lending Workflow • Amazon Textract Results Notification Developer Guide Calling Amazon Textract Asynchronous Operations Amazon Textract provides an asynchronous API that you can use to process multipage documents in PDF or TIFF format. You can also use asynchronous operations to process single-page documents that are in JPEG, PNG, TIFF, or PDF format. The information in this topic uses text detection operations to show how you to use Amazon Textract asynchronous operations. You can use the same approach with the text analysis operations of the section called “StartDocumentAnalysis” and the section called “GetDocumentAnalysis”. It also works the same with the section called “StartExpenseAnalysis” and the section called “GetExpenseAnalysis”. For an example, see Detecting or Analyzing Text in a Multipage Document. If you are analyzing lending documents, you can use the StartLendingAnalysis operation to classify document pages and send the classified pages to an Amazon Textract analysis operation. The pages are routed to analysis operations depending on their assigned class. You can retreive results for individual pages by using the GetLendingAnalysis operation, or retrieve a summary of the analysis with GetLendingAnalysisSummary. Amazon Textract asynchronously processes a document stored in an Amazon S3 bucket. You start processing by calling a Start operation, such as StartDocumentTextDetection. The completion status of the request is published to an Amazon Simple Notification Service (Amazon SNS) topic. To get the completion status from the Amazon SNS topic, you can use an Amazon Simple Queue Service (Amazon SQS) queue or an AWS Lambda function. After you have the completion status, you call a Get operation, such as GetDocumentTextDetection, to get the results of the request. Results of asynchronous calls are encrypted and stored for 7 days in a Amazon Textract owned bucket by default, unless you specify an Amazon
textract-dg-046
textract-dg.pdf
46
bucket. You start processing by calling a Start operation, such as StartDocumentTextDetection. The completion status of the request is published to an Amazon Simple Notification Service (Amazon SNS) topic. To get the completion status from the Amazon SNS topic, you can use an Amazon Simple Queue Service (Amazon SQS) queue or an AWS Lambda function. After you have the completion status, you call a Get operation, such as GetDocumentTextDetection, to get the results of the request. Results of asynchronous calls are encrypted and stored for 7 days in a Amazon Textract owned bucket by default, unless you specify an Amazon S3 bucket using an operation's OutputConfig Calling Asynchronous Operations 219 Amazon Textract Developer Guide argument. For information on how to let Amazon Textract send encrypted documents to your Amazon S3 bucket, see Permissions for Output Configuration. The following table shows the corresponding Start and Get operations for the different types of asynchronous processing supported by Amazon Textract: Start/Get API Operations for Amazon Textract Asynchronous Operations Processing Type Start API Get API Text Detection StartDocumentTextDetection GetDocumentTextDetection Text Analysis StartDocumentAnalysis GetDocumentAnalysis Expense Analysis StartExpenseAnalysis GetExpenseAnalysis Lending Analysis StartLendingAnalysis GetLendingAnalysis, GetLendingAnalysisSummary For an example that uses AWS Lambda functions, see Large scale document processing with Amazon Textract. The following diagram shows the process for detecting document text in a document image stored in an Amazon S3 bucket. In the diagram, an Amazon SQS queue gets the completion status from the Amazon SNS topic. The process displayed by the preceeding diagram is the same for analyzing text and invoices/ receipts. You start analyzing text by calling the section called “StartDocumentAnalysis” and start analyzing invoices/receipts by calling the section called “StartExpenseAnalysis” You get the results by calling the section called “GetDocumentAnalysis” or the section called “GetExpenseAnalysis” respectively. Starting Text Detection You start an Amazon Textract text detection request by calling StartDocumentTextDetection. The following is an example of a JSON request that's passed by StartDocumentTextDetection. { "DocumentLocation": { Starting Text Detection 220 Amazon Textract Developer Guide "S3Object": { "Bucket": "bucket", "Name": "image.pdf" } }, "ClientRequestToken": "DocumentDetectionToken", "NotificationChannel": { "SNSTopicArn": "arn:aws:sns:us-east-1:nnnnnnnnnn:topic", "RoleArn": "arn:aws:iam::nnnnnnnnnn:role/roleTopic" }, "JobTag": "Receipt" } The input parameter DocumentLocation provides the document file name and the Amazon S3 bucket to retrieve it from. NotificationChannel contains the Amazon Resource Name (ARN) of the Amazon SNS topic that Amazon Textract notifies when the text detection request finishes. The Amazon SNS topic must be in the same AWS Region as the Amazon Textract endpoint that you're calling. NotificationChannel also contains the ARN for a role that allows Amazon Textract to publish to the Amazon SNS topic. You give Amazon Textract publishing permissions to your Amazon SNS topics by creating an IAM service role. For more information, see Configuring Amazon Textract for Asynchronous Operations. You can also specify an optional input parameter, JobTag, that enables you to identify the job, or groups of jobs, in the completion status that's published to the Amazon SNS topic. For example, you can use JobTag to identify the type of document being processed, such as a tax form or receipt. To prevent accidental duplication of analysis jobs, you can optionally provide an idempotent token, ClientRequestToken. If you supply a value for ClientRequestToken, the Start operation returns the same JobId for multiple identical calls to the Start operation, such as StartDocumentTextDetection. A ClientRequestToken token has a lifetime of 7 days. After 7 days, you can reuse it. If you reuse the token during the token lifetime, the following happens: • If you reuse the token with same Start operation and the same input parameters, the same JobId is returned. The job isn't performed again and Amazon Textract doesn't send a completion status to the registered Amazon SNS topic. • If you reuse the token with the same Start operation and a minor input parameter change, you get an idempotentparametermismatchexception (HTTP status code: 400) exception raised. • If you reuse the token with a different Start operation, the operation succeeds. Starting Text Detection 221 Amazon Textract Developer Guide Another optional parameter available is OutputConfig, which lets you adjust where your output will be placed. By default, Amazon Textract will store the results internally, and can only be accessed by the Get API operations. With OutputConfig enabled, you can set the name of the bucket the output will be sent to, and the file prefix of the results, where you can download your results. Additionally, you can set the KMSKeyID parameter to a customer managed key to encrypt your output. Without this parameter set Amazon Textract will encrypt server-side using the AWS managed key for Amazon S3 Note Before using this parameter, ensure you have the PutObject permission for the output bucket. Additionally, ensure you have the Decrypt, ReEncrypt, GenerateDataKey, and DescribeKey permissions for the AWS KMS key if you decide to use it. The response
textract-dg-047
textract-dg.pdf
47
enabled, you can set the name of the bucket the output will be sent to, and the file prefix of the results, where you can download your results. Additionally, you can set the KMSKeyID parameter to a customer managed key to encrypt your output. Without this parameter set Amazon Textract will encrypt server-side using the AWS managed key for Amazon S3 Note Before using this parameter, ensure you have the PutObject permission for the output bucket. Additionally, ensure you have the Decrypt, ReEncrypt, GenerateDataKey, and DescribeKey permissions for the AWS KMS key if you decide to use it. The response to the StartDocumentTextDetection operation is a job identifier (JobId). Use JobId to track requests and get the analysis results after Amazon Textract has published the completion status to the Amazon SNS topic. The following is an example: {"JobId":"270c1cc5e1d0ea2fbc59d97cb69a72a5495da75851976b14a1784ca90fc180e3"} If you start too many jobs concurrently, calls to StartDocumentTextDetection raise a LimitExceededException exception (HTTP status code: 400) until the number of concurrently running jobs is below the Amazon Textract service limit. If you find that LimitExceededException exceptions are raised with bursts of activity, consider using an Amazon SQS queue to manage incoming requests. Contact AWS Support if you find that your average number of concurrent requests can't be managed by an Amazon SQS queue and you're still receiving LimitExceededException exceptions. Getting the Completion Status of an Amazon Textract Analysis Request Amazon Textract sends an analysis completion notification to the registered Amazon SNS topic. The notification includes the job identifier and the completion status of the operation in a JSON string. A successful text detection request has a SUCCEEDED status. For example, the following result shows the successful processing of a text detection job. { Getting the Completion Status of an Amazon Textract Analysis Request 222 Amazon Textract Developer Guide "JobId": "642492aea78a86a40665555dc375ee97bc963f342b29cd05030f19bd8fd1bc5f", "Status": "SUCCEEDED", "API": "StartDocumentTextDetection", "JobTag": "Receipt", "Timestamp": 1543599965969, "DocumentLocation": { "S3ObjectName": "document", "S3Bucket": "bucket" } } For more information, see Amazon Textract Results Notification. To get the status information published to the Amazon SNS topic by Amazon Textract, use one of the following options: • AWS Lambda – You can subscribe an AWS Lambda function that you write to an Amazon SNS topic. The function is called when Amazon Textract notifies the Amazon SNS topic that the request has completed. Use a Lambda function if you want server-side code to process the results of a text detection request. For example, you might want to use server-side code to annotate the image or create a report on the detected text before returning the information to a client application. • Amazon SQS – You can subscribe an Amazon SQS queue to an Amazon SNS topic. You then poll the Amazon SQS queue to retrieve the completion status published by Amazon Textract when a text detection request completes. For more information, see Detecting or Analyzing Text in a Multipage Document. Use an Amazon SQS queue if you want to call Amazon Textract operations only from a client application. Important We don't recommend getting the request completion status by repeatedly calling the Amazon Textract Get operation. This is because Amazon Textract throttles the Get operation if too many requests are made. If you're processing multiple documents at the same time, it's simpler and more efficient to monitor one SQS queue for the completion notification than to poll Amazon Textract for the status of each job individually. If you have configured your account to receive a results notification from an Amazon Simple Notification Service (Amazon SNS) topic or through an Amazon SQS queue, you should ensure that Getting the Completion Status of an Amazon Textract Analysis Request 223 Amazon Textract Developer Guide your account is secure by limiting the scope of Amazon Textract's access to just the resources you are using. This can be done by attaching a trust policy to your IAM service role. For information on how to do this, see Cross-service confused deputy prevention. Getting Amazon Textract Text Detection Results To get the results of a text detection request, first ensure that the completion status that's retrieved from the Amazon SNS topic is SUCCEEDED. Then call GetDocumentTextDetection, which passes the JobId value that's returned from StartDocumentTextDetection. The request JSON is similar to the following example: { "JobId": "270c1cc5e1d0ea2fbc59d97cb69a72a5495da75851976b14a1784ca90fc180e3", "MaxResults": 10, "SortBy": "TIMESTAMP" } JobId is the identifier for the text detection operation. Because text detection can generate large amounts of data, use MaxResults to specify the maximum number of results to return in a single Getoperation. The default value for MaxResults is 1,000. If you specify a value greater than 1,000, only 1,000 results are returned. If the operation doesn't return all of the results, a pagination token for the next page is returned. To get the next page of results, specify the token in the NextToken parameter. Note Results can be
textract-dg-048
textract-dg.pdf
48
the following example: { "JobId": "270c1cc5e1d0ea2fbc59d97cb69a72a5495da75851976b14a1784ca90fc180e3", "MaxResults": 10, "SortBy": "TIMESTAMP" } JobId is the identifier for the text detection operation. Because text detection can generate large amounts of data, use MaxResults to specify the maximum number of results to return in a single Getoperation. The default value for MaxResults is 1,000. If you specify a value greater than 1,000, only 1,000 results are returned. If the operation doesn't return all of the results, a pagination token for the next page is returned. To get the next page of results, specify the token in the NextToken parameter. Note Results can be retrieved only up to 7 days of job initialization time. The GetDocumentTextDetection operation response JSON is similar to the following. The total number of pages that are detected is returned in DocumentMetadata. The detected text is returned in the Blocks array. For information about Block objects, see Text Detection and Document Analysis Response Objects. { "DocumentMetadata": { "Pages": 1 }, "JobStatus": "SUCCEEDED", "Blocks": [ Getting Amazon Textract Text Detection Results 224 Developer Guide Amazon Textract { "BlockType": "PAGE", "Geometry": { "BoundingBox": { "Width": 1.0, "Height": 1.0, "Left": 0.0, "Top": 0.0 }, "Polygon": [ { "X": 0.0, "Y": 0.0 }, { "X": 1.0, "Y": 0.0 }, { "X": 1.0, "Y": 1.0 }, { "X": 0.0, "Y": 1.0 } ] }, "Id": "64533157-c47e-401a-930e-7ca1bb3ac3fa", "Relationships": [ { "Type": "CHILD", "Ids": [ "4297834d-dcb1-413b-8908-3b96866ebbb5", "1d85ba24-2877-4d09-b8b2-393833d769e9", "193e9c47-fd87-475a-ba09-3fda210d8784", "bd8aeb62-961b-4b47-b78a-e4ed9eeecd0f" ] } ], "Page": 1 }, { "BlockType": "LINE", Getting Amazon Textract Text Detection Results 225 Amazon Textract Developer Guide "Confidence": 53.301639556884766, "Text": "ellooworio", "Geometry": { "BoundingBox": { "Width": 0.9999999403953552, "Height": 0.5365243554115295, "Left": 0.0, "Top": 0.46347561478614807 }, "Polygon": [ { "X": 0.0, "Y": 0.46347561478614807 }, { "X": 0.9999999403953552, "Y": 0.46347561478614807 }, { "X": 0.9999999403953552, "Y": 1.0 }, { "X": 0.0, "Y": 1.0 } ] }, "Id": "4297834d-dcb1-413b-8908-3b96866ebbb5", "Relationships": [ { "Type": "CHILD", "Ids": [ "170c3eb9-5155-4bec-8c44-173bba537e70" ] } ], "Page": 1 }, { "BlockType": "LINE", "Confidence": 89.15632629394531, "Text": "He llo,", "Geometry": { Getting Amazon Textract Text Detection Results 226 Amazon Textract Developer Guide "BoundingBox": { "Width": 0.33642634749412537, "Height": 0.49159330129623413, "Left": 0.13885067403316498, "Top": 0.17169663310050964 }, "Polygon": [ { "X": 0.13885067403316498, "Y": 0.17169663310050964 }, { "X": 0.47527703642845154, "Y": 0.17169663310050964 }, { "X": 0.47527703642845154, "Y": 0.6632899641990662 }, { "X": 0.13885067403316498, "Y": 0.6632899641990662 } ] }, "Id": "1d85ba24-2877-4d09-b8b2-393833d769e9", "Relationships": [ { "Type": "CHILD", "Ids": [ "516ae823-3bab-4f9a-9d74-ad7150d128ab", "6bcf4ea8-bbe8-4686-91be-b98dd63bc6a6" ] } ], "Page": 1 }, { "BlockType": "LINE", "Confidence": 82.44834899902344, "Text": "worlo", "Geometry": { "BoundingBox": { "Width": 0.33182239532470703, Getting Amazon Textract Text Detection Results 227 Amazon Textract Developer Guide "Height": 0.3766750991344452, "Left": 0.5091826915740967, "Top": 0.23131252825260162 }, "Polygon": [ { "X": 0.5091826915740967, "Y": 0.23131252825260162 }, { "X": 0.8410050868988037, "Y": 0.23131252825260162 }, { "X": 0.8410050868988037, "Y": 0.607987642288208 }, { "X": 0.5091826915740967, "Y": 0.607987642288208 } ] }, "Id": "193e9c47-fd87-475a-ba09-3fda210d8784", "Relationships": [ { "Type": "CHILD", "Ids": [ "ed135c3b-35dd-4085-8f00-26aedab0125f" ] } ], "Page": 1 }, { "BlockType": "LINE", "Confidence": 88.50325775146484, "Text": "world", "Geometry": { "BoundingBox": { "Width": 0.35004907846450806, "Height": 0.19635874032974243, "Left": 0.527581512928009, "Top": 0.30100569128990173 Getting Amazon Textract Text Detection Results 228 Amazon Textract Developer Guide }, "Polygon": [ { "X": 0.527581512928009, "Y": 0.30100569128990173 }, { "X": 0.8776305913925171, "Y": 0.30100569128990173 }, { "X": 0.8776305913925171, "Y": 0.49736443161964417 }, { "X": 0.527581512928009, "Y": 0.49736443161964417 } ] }, "Id": "bd8aeb62-961b-4b47-b78a-e4ed9eeecd0f", "Relationships": [ { "Type": "CHILD", "Ids": [ "9e28834d-798e-4a62-8862-a837dfd895a6" ] } ], "Page": 1 }, { "BlockType": "WORD", "Confidence": 53.301639556884766, "Text": "ellooworio", "Geometry": { "BoundingBox": { "Width": 1.0, "Height": 0.5365243554115295, "Left": 0.0, "Top": 0.46347561478614807 }, "Polygon": [ { Getting Amazon Textract Text Detection Results 229 Amazon Textract Developer Guide "X": 0.0, "Y": 0.46347561478614807 }, { "X": 1.0, "Y": 0.46347561478614807 }, { "X": 1.0, "Y": 1.0 }, { "X": 0.0, "Y": 1.0 } ] }, "Id": "170c3eb9-5155-4bec-8c44-173bba537e70", "Page": 1 }, { "BlockType": "WORD", "Confidence": 88.46246337890625, "Text": "He", "Geometry": { "BoundingBox": { "Width": 0.15350718796253204, "Height": 0.29955607652664185, "Left": 0.13885067403316498, "Top": 0.21856294572353363 }, "Polygon": [ { "X": 0.13885067403316498, "Y": 0.21856294572353363 }, { "X": 0.292357861995697, "Y": 0.21856294572353363 }, { "X": 0.292357861995697, "Y": 0.5181190371513367 }, Getting Amazon Textract Text Detection Results 230 Developer Guide Amazon Textract { "X": 0.13885067403316498, "Y": 0.5181190371513367 } ] }, "Id": "516ae823-3bab-4f9a-9d74-ad7150d128ab", "Page": 1 }, { "BlockType": "WORD", "Confidence": 89.8501968383789, "Text": "llo,", "Geometry": { "BoundingBox": { "Width": 0.17724157869815826, "Height": 0.49159327149391174, "Left": 0.2980354428291321, "Top": 0.17169663310050964 }, "Polygon": [ { "X": 0.2980354428291321, "Y": 0.17169663310050964 }, { "X": 0.47527703642845154, "Y": 0.17169663310050964 }, { "X": 0.47527703642845154, "Y": 0.6632899045944214 }, { "X": 0.2980354428291321, "Y": 0.6632899045944214 } ] }, "Id": "6bcf4ea8-bbe8-4686-91be-b98dd63bc6a6", "Page": 1 }, { "BlockType": "WORD", Getting Amazon Textract Text Detection Results 231 Amazon Textract Developer Guide "Confidence": 82.44834899902344, "Text": "worlo", "Geometry": { "BoundingBox": { "Width": 0.33182239532470703, "Height": 0.3766750991344452, "Left": 0.5091826915740967, "Top": 0.23131252825260162 }, "Polygon": [ { "X": 0.5091826915740967, "Y": 0.23131252825260162 }, { "X": 0.8410050868988037, "Y": 0.23131252825260162 }, { "X": 0.8410050868988037, "Y": 0.607987642288208 }, { "X": 0.5091826915740967, "Y": 0.607987642288208 } ] }, "Id": "ed135c3b-35dd-4085-8f00-26aedab0125f", "Page": 1 }, { "BlockType": "WORD", "Confidence": 88.50325775146484, "Text": "world", "Geometry": { "BoundingBox": { "Width": 0.35004907846450806, "Height": 0.19635874032974243,
textract-dg-049
textract-dg.pdf
49
0.17169663310050964 }, { "X": 0.47527703642845154, "Y": 0.6632899045944214 }, { "X": 0.2980354428291321, "Y": 0.6632899045944214 } ] }, "Id": "6bcf4ea8-bbe8-4686-91be-b98dd63bc6a6", "Page": 1 }, { "BlockType": "WORD", Getting Amazon Textract Text Detection Results 231 Amazon Textract Developer Guide "Confidence": 82.44834899902344, "Text": "worlo", "Geometry": { "BoundingBox": { "Width": 0.33182239532470703, "Height": 0.3766750991344452, "Left": 0.5091826915740967, "Top": 0.23131252825260162 }, "Polygon": [ { "X": 0.5091826915740967, "Y": 0.23131252825260162 }, { "X": 0.8410050868988037, "Y": 0.23131252825260162 }, { "X": 0.8410050868988037, "Y": 0.607987642288208 }, { "X": 0.5091826915740967, "Y": 0.607987642288208 } ] }, "Id": "ed135c3b-35dd-4085-8f00-26aedab0125f", "Page": 1 }, { "BlockType": "WORD", "Confidence": 88.50325775146484, "Text": "world", "Geometry": { "BoundingBox": { "Width": 0.35004907846450806, "Height": 0.19635874032974243, "Left": 0.527581512928009, "Top": 0.30100569128990173 }, "Polygon": [ { Getting Amazon Textract Text Detection Results 232 Amazon Textract Developer Guide "X": 0.527581512928009, "Y": 0.30100569128990173 }, { "X": 0.8776305913925171, "Y": 0.30100569128990173 }, { "X": 0.8776305913925171, "Y": 0.49736443161964417 }, { "X": 0.527581512928009, "Y": 0.49736443161964417 } ] }, "Id": "9e28834d-798e-4a62-8862-a837dfd895a6", "Page": 1 } ] } Using an adapter With Amazon Textract, you can use an adapter when calling the StartDocumentAnalysis operation. To use an adapter, you must first create and train an adapter by using the Amazon Textract console. To apply your adapter, provide its ID when calling the StartDocumentAnalysis API operation. When calling the StartDocumentAnalysis operation, you can use up to one adapter per page. "AdaptersConfig": { "Adapters": [ { "AdapterId": "2e9bf1c4aa31", "Version": "1", "Pages": [ "1" ] } ] } Using an adapter 233 Amazon Textract Developer Guide Configuring Amazon Textract for Asynchronous Operations The following procedures show you how to configure Amazon Textract to use with an Amazon Simple Notification Service (Amazon SNS) topic and an Amazon Simple Queue Service (Amazon SQS) queue. Note If you're using these instructions to set up the Detecting or Analyzing Text in a Multipage Document example, you don't need to do steps 3 – 6. The example includes code to create and configure the Amazon SNS topic and Amazon SQS queue. To configure Amazon Textract 1. Set up an AWS account to access Amazon Textract. For more information, see Step 1: Set Up an AWS Account and Create a User. Ensure that the user has at least the following permissions: • AmazonTextractFullAccess • AmazonS3ReadOnlyAccess • AmazonSNSFullAccess • AmazonSQSFullAccess Additionally, insure that the user has permission to pass IAM roles to Amazon Textract. This is done through an IAM PassRole policy. A simple example of such a policy is below: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iam:PassRole", "Resource": "*", "Condition": { "StringEquals": {"iam:PassedToService": "textract.amazonaws.com"} } Configuring Asynchronous Operations 234 Amazon Textract } ] } Developer Guide 2. Install and configure the required AWS SDK. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. 3. Create an Amazon SNS standard topic. Prepend the topic name with AmazonTextract. Note the topic Amazon Resource Name (ARN). Ensure that the topic is in the same Region as the AWS endpoint that you're using with your AWS account. 4. Create an Amazon SQS standard queue by using the Amazon SQS console. Note the queue ARN. 5. Subscribe the queue to the topic you created in step 3. 6. Give permission to the Amazon SNS topic to send messages to the Amazon SQS queue. 7. Create an IAM service role to give Amazon Textract access to your Amazon SNS topics. Note the Amazon Resource Name (ARN) of the service role. For more information, see Giving Amazon Textract Access to Your Amazon SNS Topic. 8. Add the following inline policy to the IAM user that you created in step 1. { "Version": "2012-10-17", "Statement": [ { "Sid": "MySid", "Effect": "Allow", "Action": "iam:PassRole", "Resource": "Key policy ARN from step 7" } ] } Give the inline policy a name. 9. You can now run the examples in Detecting or Analyzing Text in a Multipage Document. Configuring Asynchronous Operations 235 Amazon Textract Developer Guide Giving Amazon Textract Access to Your Amazon SNS Topic Amazon Textract needs permission to send a message to your Amazon SNS topic when an asynchronous operation is complete. You use an IAM service role to give Amazon Textract access to the Amazon SNS topic. When you create the Amazon SNS topic, you must prepend the topic name with AmazonTextract—for example, AmazonTextractMyTopicName. 1. 2. Sign in to the IAM console (https://console.aws.amazon.com/iam). In the navigation pane, choose Roles. 3. Choose Create role. 4. 5. For Select type of trusted entity, choose AWS service. For Choose the service that will use this role, choose Textract. 6. Choose Next: Permissions. 7. Verify that the AmazonTextractServiceRole policy has been included in the list of attached policies. To display the policy in the list, enter part of the policy name in the Filter policies. 8. Choose Next: Tags. 9. You don't need to add tags, so choose Next: Review. 10. In the Review section, for Role name, enter a
textract-dg-050
textract-dg.pdf
50
Sign in to the IAM console (https://console.aws.amazon.com/iam). In the navigation pane, choose Roles. 3. Choose Create role. 4. 5. For Select type of trusted entity, choose AWS service. For Choose the service that will use this role, choose Textract. 6. Choose Next: Permissions. 7. Verify that the AmazonTextractServiceRole policy has been included in the list of attached policies. To display the policy in the list, enter part of the policy name in the Filter policies. 8. Choose Next: Tags. 9. You don't need to add tags, so choose Next: Review. 10. In the Review section, for Role name, enter a name for the role (for example, TextractRole). In Role description, update the description for the role, and then choose Create role. 11. Choose the new role to open the role's details page. 12. In the Summary, copy the Role ARN value and save it. 13. Choose Trust relationships. 14. Choose Edit trust relationship, and edit the trust policy. Ensure that your trust policy includes conditions that limit the scope of permissions to just the required resources, as this will help prevent the confused deputy problem. For more details about this potential security issue, see Cross-service confused deputy prevention. In the example below, replace the red text with your AWS account ID. { "Version": "2012-10-17", "Statement": { "Sid": "ConfusedDeputyPreventionExamplePolicy", "Effect": "Allow", "Principal": { Giving Amazon Textract Access to Your Amazon SNS Topic 236 Amazon Textract Developer Guide "Service": "textract.amazonaws.com" }, "Action": "sts:AssumeRole", "Condition": { "ArnLike": { "aws:SourceArn":"arn:aws:textract:*:123456789012:*" }, "StringEquals": { "aws:SourceAccount": "123456789012" } } } } 15. Choose Update Trust Policy. Permissions for Output Configuration You can have Amazon Textract send the results of asynchronous analysis operations to a designated Amazon S3 bucket by using the OutputConfig feature of asynchrnous API operations. If you are using the OutputConfig option for an asynchronous analysis operation to customize where the output of your operations is sent, additional configuration is required. You must let Amazon Textract decrypt your uploads and provide permissions for certain Amazon S3 operations. To Allow Decryption of S3 Bucket Uploads • You will need to provide the appropriate Users with the correct Amazon S3 permissions. Navigate to the Users section of the https://console.aws.amazon.com/iam/ and select the User you created in Step 1 of the To configure Amazon Textract section above. Choose to "Add inline policy" to your User and attach a JSON policy that includes the s3:GetObject, and s3:PutObject, s3:ListMultipartUploadParts, s3:ListBucketMultipartUploads, and s3:AbortMultipartUpload operations. Your JSON may look like the following: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:Get*", Permissions for Output Configuration 237 Amazon Textract Developer Guide "s3:List*", "s3:PutObject", "s3:GetObject", "s3-object-lambda:Get*", "s3-object-lambda:List*", "s3:ListMultipartUploadParts", "s3:ListBucketMultipartUploads", "s3:AbortMultipartUpload" ], "Resource": "*" } ] } To Provide AWS KMS Key Permissions • You mustadd permissions to your AWS Key Management Service key that will allow your service role to decrypt your uploads. The service role will need permission for kms:GenerateDataKey and kms:Decrypt actions. Ensure that the service role you created in Step 7 in the To configure Amazon Textract section has a permissions policy that looks like the following example. In the following example, replace ARN from Step 7 with the ARN of your service role: { "Sid": "Decrypt only", "Effect": "Allow", "Principal": { "AWS": "ARN from Step 7" }, "Action": [ "kms:Decrypt", "kms:ReEncrypt", "kms:GenerateDataKey", "kms:DescribeKey" ], "Resource": "*" } Permissions for Output Configuration 238 Amazon Textract Developer Guide Detecting or Analyzing Text in a Multipage Document This procedure shows you how to detect or analyze text in a multipage document by using Amazon Textract detection operations, a document stored in an Amazon S3 bucket, an Amazon SNS topic, and an Amazon SQS queue. Multipage document processing is an asynchronous operation. For more information, see Calling Amazon Textract Asynchronous Operations. You can choose the type of processing that you want the code to do: text detection, text analysis, or expense analysis. The processing results are returned in an array of the section called “Block” objects, which differ depending on the type of processing you use. To detect text in or analyze multipage documents, you do the following: 1. Create the Amazon SNS topic and the Amazon SQS queue. 2. Subscribe the queue the topic. 3. Give the topic permission to send messages to the queue. 4. Start processing the document. Use the appropriate operation for your chosen type of analysis: • StartDocumentTextDetection for text detection tasks. • StartDocumentAnalysis for text analysis tasks. • StartExpenseAnalysis for expense analysis tasks. 5. Get the completion status from the Amazon SQS queue. The example code tracks the job identifier (JobId) that's returned by the Start operation. It only gets the results for matching job identifiers that are read from the completion status. This is important if other applications are using the same queue and topic. For simplicity, the example deletes jobs that don't match.
textract-dg-051
textract-dg.pdf
51
send messages to the queue. 4. Start processing the document. Use the appropriate operation for your chosen type of analysis: • StartDocumentTextDetection for text detection tasks. • StartDocumentAnalysis for text analysis tasks. • StartExpenseAnalysis for expense analysis tasks. 5. Get the completion status from the Amazon SQS queue. The example code tracks the job identifier (JobId) that's returned by the Start operation. It only gets the results for matching job identifiers that are read from the completion status. This is important if other applications are using the same queue and topic. For simplicity, the example deletes jobs that don't match. Consider adding the deleted jobs to an Amazon SQS dead-letter queue for further investigation. 6. Get and display the processing results by calling the appropriate operation for your chosen type of analysis: • GetDocumentTextDetection for text detection tasks. • GetDocumentAnalysis for text analysis tasks. • GetExpenseAnalysis for expense analysis tasks. 7. Delete the Amazon SNS topic and the Amazon SQS queue. Detecting or Analyzing Text in a Multipage Document 239 Amazon Textract Developer Guide Performing Asynchronous Operations The example code for this procedure is provided in Java, Python, and the AWS CLI. Before you begin, install the appropriate AWS SDK. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. To detect or analyze text in a multipage document 1. Configure user access to Amazon Textract, and configure Amazon Textract access to Amazon SNS. For more information, see Configuring Amazon Textract for Asynchronous Operations. To complete this procedure, you need a multipage document file in PDF format. Skip steps 3 – 6 because the example code creates and configures the Amazon SNS topic and Amazon SQS queue. If completing the CLI example, you don't need to set up an SQS queue. 2. Upload a multipage document file in PDF or TIFF format to your Amazon S3 bucket. (Single- page documents in JPEG, PNG, TIFF, or PDF format can also be processed). For instructions, see Uploading Objects into Amazon S3 in the Amazon Simple Storage Service User Guide. 3. Use the following AWS SDK for Java, SDK for Python (Boto3), or AWS CLI code to either detect text or analyze text in a multipage document. In the main function: • Replace the value of roleArn with the IAM role ARN that you saved in Giving Amazon Textract Access to Your Amazon SNS Topic. • Replace the values of bucket and document with the bucket and document file name that you specified in step 2. • Replace the value of the type input parameter of the ProcessDocument function with the type of processing that you want to do. Use ProcessType.DETECTION to detect text. Use ProcessType.ANALYSIS to analyze text. • For the Python example, replace the value of region_name with the region your client is operating in. For the AWS CLI example, do the following: • When calling StartDocumentTextDetection, replace the value of bucket-name with the name of your S3 bucket, and replace file-name with the name of the file you specified in step 2. Specify the region of your bucket by replacing region-name with the name of your region. Take note that the CLI example does not make use of SQS. Performing Asynchronous Operations 240 Amazon Textract Developer Guide • When calling GetDocumentTextDetection replace job-id-number with the job-id returned by StartDocumentTextDetection. Specify the region of your bucket by replacing region-name with the name of your region. Java Replace the value of credentialsProvider with the name of your developer profile. import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.auth.policy.Condition; import com.amazonaws.auth.policy.Policy; import com.amazonaws.auth.policy.Principal; import com.amazonaws.auth.policy.Resource; import com.amazonaws.auth.policy.Statement; import com.amazonaws.auth.policy.Statement.Effect; import com.amazonaws.auth.policy.actions.SQSActions; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.AmazonSNSClientBuilder; import com.amazonaws.services.sns.model.CreateTopicRequest; import com.amazonaws.services.sns.model.CreateTopicResult; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.CreateQueueRequest; import com.amazonaws.services.sqs.model.Message; import com.amazonaws.services.sqs.model.QueueAttributeName; import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; import com.amazonaws.services.textract.AmazonTextract; import com.amazonaws.services.textract.AmazonTextractClientBuilder; import com.amazonaws.services.textract.model.Block; import com.amazonaws.services.textract.model.DocumentLocation; import com.amazonaws.services.textract.model.DocumentMetadata; import com.amazonaws.services.textract.model.GetDocumentAnalysisRequest; import com.amazonaws.services.textract.model.GetDocumentAnalysisResult; import com.amazonaws.services.textract.model.GetDocumentTextDetectionRequest; import com.amazonaws.services.textract.model.GetDocumentTextDetectionResult; import com.amazonaws.services.textract.model.NotificationChannel; import com.amazonaws.services.textract.model.Relationship; Performing Asynchronous Operations 241 Amazon Textract Developer Guide import com.amazonaws.services.textract.model.S3Object; import com.amazonaws.services.textract.model.StartDocumentAnalysisRequest; import com.amazonaws.services.textract.model.StartDocumentAnalysisResult; import com.amazonaws.services.textract.model.StartDocumentTextDetectionRequest; import com.amazonaws.services.textract.model.StartDocumentTextDetectionResult; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;; public class DocumentProcessor { private static String sqsQueueName=null; private static String snsTopicName=null; private static String snsTopicArn = null; private static String roleArn= null; private static String sqsQueueUrl = null; private static String sqsQueueArn = null; private static String startJobId = null; private static String bucket = null; private static String document = null; private static AmazonSQS sqs=null; private static AmazonSNS sns=null; private static AmazonTextract textract = null; public enum ProcessType { DETECTION,ANALYSIS } public static void main(String[] args) throws Exception { String document = "document"; String bucket = "bucket"; String roleArn="role"; // set provider credentials AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider("default"); sns = AmazonSNSClientBuilder.withCredentials(credentialsProvider) .withRegion(Regions.US_EAST_1) .build(); sqs= AmazonSQSClientBuilder.withCredentials(credentialsProvider) .withRegion(Regions.US_EAST_1) .build(); Performing Asynchronous Operations 242 Amazon Textract Developer Guide textract=AmazonTextractClientBuilder.withCredentials(credentialsProvider) .withRegion(Regions.US_EAST_1) .build(); CreateTopicandQueue(); ProcessDocument(bucket,document,roleArn,ProcessType.DETECTION); DeleteTopicandQueue(); System.out.println("Done!"); } // Creates an SNS topic and
textract-dg-052
textract-dg.pdf
52
String sqsQueueArn = null; private static String startJobId = null; private static String bucket = null; private static String document = null; private static AmazonSQS sqs=null; private static AmazonSNS sns=null; private static AmazonTextract textract = null; public enum ProcessType { DETECTION,ANALYSIS } public static void main(String[] args) throws Exception { String document = "document"; String bucket = "bucket"; String roleArn="role"; // set provider credentials AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider("default"); sns = AmazonSNSClientBuilder.withCredentials(credentialsProvider) .withRegion(Regions.US_EAST_1) .build(); sqs= AmazonSQSClientBuilder.withCredentials(credentialsProvider) .withRegion(Regions.US_EAST_1) .build(); Performing Asynchronous Operations 242 Amazon Textract Developer Guide textract=AmazonTextractClientBuilder.withCredentials(credentialsProvider) .withRegion(Regions.US_EAST_1) .build(); CreateTopicandQueue(); ProcessDocument(bucket,document,roleArn,ProcessType.DETECTION); DeleteTopicandQueue(); System.out.println("Done!"); } // Creates an SNS topic and SQS queue. The queue is subscribed to the topic. static void CreateTopicandQueue() { //create a new SNS topic snsTopicName="AmazonTextractTopic" + Long.toString(System.currentTimeMillis()); CreateTopicRequest createTopicRequest = new CreateTopicRequest(snsTopicName); CreateTopicResult createTopicResult = sns.createTopic(createTopicRequest); snsTopicArn=createTopicResult.getTopicArn(); //Create a new SQS Queue sqsQueueName="AmazonTextractQueue" + Long.toString(System.currentTimeMillis()); final CreateQueueRequest createQueueRequest = new CreateQueueRequest(sqsQueueName); sqsQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl(); sqsQueueArn = sqs.getQueueAttributes(sqsQueueUrl, Arrays.asList("QueueArn")).getAttributes().get("QueueArn"); //Subscribe SQS queue to SNS topic String sqsSubscriptionArn = sns.subscribe(snsTopicArn, "sqs", sqsQueueArn).getSubscriptionArn(); // Authorize queue Policy policy = new Policy().withStatements( new Statement(Effect.Allow) .withPrincipals(Principal.AllUsers) .withActions(SQSActions.SendMessage) .withResources(new Resource(sqsQueueArn)) Performing Asynchronous Operations 243 Amazon Textract Developer Guide .withConditions(new Condition().withType("ArnEquals").withConditionKey("aws:SourceArn").withValues(snsTopicArn)) ); Map queueAttributes = new HashMap(); queueAttributes.put(QueueAttributeName.Policy.toString(), policy.toJson()); sqs.setQueueAttributes(new SetQueueAttributesRequest(sqsQueueUrl, queueAttributes)); System.out.println("Topic arn: " + snsTopicArn); System.out.println("Queue arn: " + sqsQueueArn); System.out.println("Queue url: " + sqsQueueUrl); System.out.println("Queue sub arn: " + sqsSubscriptionArn ); } static void DeleteTopicandQueue() { if (sqs !=null) { sqs.deleteQueue(sqsQueueUrl); System.out.println("SQS queue deleted"); } if (sns!=null) { sns.deleteTopic(snsTopicArn); System.out.println("SNS topic deleted"); } } //Starts the processing of the input document. static void ProcessDocument(String inBucket, String inDocument, String inRoleArn, ProcessType type) throws Exception { bucket=inBucket; document=inDocument; roleArn=inRoleArn; switch(type) { case DETECTION: StartDocumentTextDetection(bucket, document); System.out.println("Processing type: Detection"); break; Performing Asynchronous Operations 244 Amazon Textract Developer Guide case ANALYSIS: StartDocumentAnalysis(bucket,document); System.out.println("Processing type: Analysis"); break; default: System.out.println("Invalid processing type. Choose Detection or Analysis"); throw new Exception("Invalid processing type"); } System.out.println("Waiting for job: " + startJobId); //Poll queue for messages List<Message> messages=null; int dotLine=0; boolean jobFound=false; //loop until the job status is published. Ignore other messages in queue. do{ messages = sqs.receiveMessage(sqsQueueUrl).getMessages(); if (dotLine++<40){ System.out.print("."); }else{ System.out.println(); dotLine=0; } if (!messages.isEmpty()) { //Loop through messages received. for (Message message: messages) { String notification = message.getBody(); // Get status and job id from notification. ObjectMapper mapper = new ObjectMapper(); JsonNode jsonMessageTree = mapper.readTree(notification); JsonNode messageBodyText = jsonMessageTree.get("Message"); ObjectMapper operationResultMapper = new ObjectMapper(); JsonNode jsonResultTree = operationResultMapper.readTree(messageBodyText.textValue()); JsonNode operationJobId = jsonResultTree.get("JobId"); JsonNode operationStatus = jsonResultTree.get("Status"); System.out.println("Job found was " + operationJobId); // Found job. Get the results and display. Performing Asynchronous Operations 245 Amazon Textract Developer Guide if(operationJobId.asText().equals(startJobId)){ jobFound=true; System.out.println("Job id: " + operationJobId ); System.out.println("Status : " + operationStatus.toString()); if (operationStatus.asText().equals("SUCCEEDED")){ switch(type) { case DETECTION: GetDocumentTextDetectionResults(); break; case ANALYSIS: GetDocumentAnalysisResults(); break; default: System.out.println("Invalid processing type. Choose Detection or Analysis"); throw new Exception("Invalid processing type"); } } else{ System.out.println("Document analysis failed"); } sqs.deleteMessage(sqsQueueUrl,message.getReceiptHandle()); } else{ System.out.println("Job received was not job " + startJobId); //Delete unknown message. Consider moving message to dead letter queue sqs.deleteMessage(sqsQueueUrl,message.getReceiptHandle()); } } } else { Thread.sleep(5000); } } while (!jobFound); Performing Asynchronous Operations 246 Amazon Textract Developer Guide System.out.println("Finished processing document"); } private static void StartDocumentTextDetection(String bucket, String document) throws Exception{ //Create notification channel NotificationChannel channel= new NotificationChannel() .withSNSTopicArn(snsTopicArn) .withRoleArn(roleArn); StartDocumentTextDetectionRequest req = new StartDocumentTextDetectionRequest() .withDocumentLocation(new DocumentLocation() .withS3Object(new S3Object() .withBucket(bucket) .withName(document))) .withJobTag("DetectingText") .withNotificationChannel(channel); StartDocumentTextDetectionResult startDocumentTextDetectionResult = textract.startDocumentTextDetection(req); startJobId=startDocumentTextDetectionResult.getJobId(); } //Gets the results of processing started by StartDocumentTextDetection private static void GetDocumentTextDetectionResults() throws Exception{ int maxResults=1000; String paginationToken=null; GetDocumentTextDetectionResult response=null; Boolean finished=false; while (finished==false) { GetDocumentTextDetectionRequest documentTextDetectionRequest= new GetDocumentTextDetectionRequest() .withJobId(startJobId) .withMaxResults(maxResults) .withNextToken(paginationToken); response = textract.getDocumentTextDetection(documentTextDetectionRequest); DocumentMetadata documentMetaData=response.getDocumentMetadata(); Performing Asynchronous Operations 247 Amazon Textract Developer Guide System.out.println("Pages: " + documentMetaData.getPages().toString()); //Show blocks information List<Block> blocks= response.getBlocks(); for (Block block : blocks) { DisplayBlockInfo(block); } paginationToken=response.getNextToken(); if (paginationToken==null) finished=true; } } private static void StartDocumentAnalysis(String bucket, String document) throws Exception{ //Create notification channel NotificationChannel channel= new NotificationChannel() .withSNSTopicArn(snsTopicArn) .withRoleArn(roleArn); StartDocumentAnalysisRequest req = new StartDocumentAnalysisRequest() .withFeatureTypes("TABLES","FORMS") .withDocumentLocation(new DocumentLocation() .withS3Object(new S3Object() .withBucket(bucket) .withName(document))) .withJobTag("AnalyzingText") .withNotificationChannel(channel); StartDocumentAnalysisResult startDocumentAnalysisResult = textract.startDocumentAnalysis(req); startJobId=startDocumentAnalysisResult.getJobId(); } //Gets the results of processing started by StartDocumentAnalysis private static void GetDocumentAnalysisResults() throws Exception{ int maxResults=1000; String paginationToken=null; GetDocumentAnalysisResult response=null; Boolean finished=false; Performing Asynchronous Operations 248 Amazon Textract Developer Guide //loops until pagination token is null while (finished==false) { GetDocumentAnalysisRequest documentAnalysisRequest= new GetDocumentAnalysisRequest() .withJobId(startJobId) .withMaxResults(maxResults) .withNextToken(paginationToken); response = textract.getDocumentAnalysis(documentAnalysisRequest); DocumentMetadata documentMetaData=response.getDocumentMetadata(); System.out.println("Pages: " + documentMetaData.getPages().toString()); //Show blocks, confidence and detection times List<Block> blocks= response.getBlocks(); for (Block block : blocks) { DisplayBlockInfo(block); } paginationToken=response.getNextToken(); if (paginationToken==null) finished=true; } } //Displays Block information for text detection and text analysis private static void DisplayBlockInfo(Block block) { System.out.println("Block Id : " + block.getId()); if (block.getText()!=null) System.out.println("\tDetected text: " + block.getText()); System.out.println("\tType: " + block.getBlockType()); if (block.getBlockType().equals("PAGE") !=true) { System.out.println("\tConfidence: " + block.getConfidence().toString()); } if(block.getBlockType().equals("CELL")) { System.out.println("\tCell information:"); System.out.println("\t\tColumn: " + block.getColumnIndex()); System.out.println("\t\tRow: " + block.getRowIndex()); Performing Asynchronous Operations 249 Amazon Textract Developer Guide System.out.println("\t\tColumn span: " + block.getColumnSpan()); System.out.println("\t\tRow span:
textract-dg-053
textract-dg.pdf
53
response = textract.getDocumentAnalysis(documentAnalysisRequest); DocumentMetadata documentMetaData=response.getDocumentMetadata(); System.out.println("Pages: " + documentMetaData.getPages().toString()); //Show blocks, confidence and detection times List<Block> blocks= response.getBlocks(); for (Block block : blocks) { DisplayBlockInfo(block); } paginationToken=response.getNextToken(); if (paginationToken==null) finished=true; } } //Displays Block information for text detection and text analysis private static void DisplayBlockInfo(Block block) { System.out.println("Block Id : " + block.getId()); if (block.getText()!=null) System.out.println("\tDetected text: " + block.getText()); System.out.println("\tType: " + block.getBlockType()); if (block.getBlockType().equals("PAGE") !=true) { System.out.println("\tConfidence: " + block.getConfidence().toString()); } if(block.getBlockType().equals("CELL")) { System.out.println("\tCell information:"); System.out.println("\t\tColumn: " + block.getColumnIndex()); System.out.println("\t\tRow: " + block.getRowIndex()); Performing Asynchronous Operations 249 Amazon Textract Developer Guide System.out.println("\t\tColumn span: " + block.getColumnSpan()); System.out.println("\t\tRow span: " + block.getRowSpan()); } System.out.println("\tRelationships"); List<Relationship> relationships=block.getRelationships(); if(relationships!=null) { for (Relationship relationship : relationships) { System.out.println("\t\tType: " + relationship.getType()); System.out.println("\t\tIDs: " + relationship.getIds().toString()); } } else { System.out.println("\t\tNo related Blocks"); } System.out.println("\tGeometry"); System.out.println("\t\tBounding Box: " + block.getGeometry().getBoundingBox().toString()); System.out.println("\t\tPolygon: " + block.getGeometry().getPolygon().toString()); List<String> entityTypes = block.getEntityTypes(); System.out.println("\tEntity Types"); if(entityTypes!=null) { for (String entityType : entityTypes) { System.out.println("\t\tEntity Type: " + entityType); } } else { System.out.println("\t\tNo entity type"); } if(block.getBlockType().equals("SELECTION_ELEMENT")) { System.out.print(" Selection element detected: "); if (block.getSelectionStatus().equals("SELECTED")){ System.out.println("Selected"); }else { System.out.println(" Not selected"); } } if(block.getPage()!=null) System.out.println("\tPage: " + block.getPage()); Performing Asynchronous Operations 250 Amazon Textract Developer Guide System.out.println(); } } Java V2 Replace the value of profile-name in the line that creates the TextractClient with the name of your developer profile. import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.textract.model.S3Object; import software.amazon.awssdk.services.textract.TextractClient; import software.amazon.awssdk.services.textract.model.StartDocumentAnalysisRequest; import software.amazon.awssdk.services.textract.model.DocumentLocation; import software.amazon.awssdk.services.textract.model.TextractException; import software.amazon.awssdk.services.textract.model.StartDocumentAnalysisResponse; import software.amazon.awssdk.services.textract.model.GetDocumentAnalysisRequest; import software.amazon.awssdk.services.textract.model.GetDocumentAnalysisResponse; import software.amazon.awssdk.services.textract.model.FeatureType; import java.util.ArrayList; import java.util.List; // snippet-end:[textract.java2._start_doc_analysis.import] /** * 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 StartDocumentAnalysis { public static void main(String[] args) { final String usage = "\n" + "Usage:\n" + Performing Asynchronous Operations 251 Amazon Textract Developer Guide " <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, for example, 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_EAST_1; TextractClient textractClient = TextractClient.builder() .region(region) .credentialsProvider(ProfileCredentialsProvider.create("profile- name")) .build(); String jobId = startDocAnalysisS3 (textractClient, bucketName, docName); System.out.println("Getting results for job "+jobId); String status = getJobResults(textractClient, jobId); System.out.println("The job status is "+status); textractClient.close(); } // snippet-start:[textract.java2._start_doc_analysis.main] public static String startDocAnalysisS3 (TextractClient textractClient, String bucketName, String docName) { try { List<FeatureType> myList = new ArrayList<>(); myList.add(FeatureType.TABLES); myList.add(FeatureType.FORMS); S3Object s3Object = S3Object.builder() .bucket(bucketName) .name(docName) .build(); DocumentLocation location = DocumentLocation.builder() .s3Object(s3Object) Performing Asynchronous Operations 252 Amazon Textract Developer Guide .build(); StartDocumentAnalysisRequest documentAnalysisRequest = StartDocumentAnalysisRequest.builder() .documentLocation(location) .featureTypes(myList) .build(); StartDocumentAnalysisResponse response = textractClient.startDocumentAnalysis(documentAnalysisRequest); // Get the job ID String jobId = response.jobId(); return jobId; } catch (TextractException e) { System.err.println(e.getMessage()); System.exit(1); } return "" ; } private static String getJobResults(TextractClient textractClient, String jobId) { boolean finished = false; int index = 0 ; String status = "" ; try { while (!finished) { GetDocumentAnalysisRequest analysisRequest = GetDocumentAnalysisRequest.builder() .jobId(jobId) .maxResults(1000) .build(); GetDocumentAnalysisResponse response = textractClient.getDocumentAnalysis(analysisRequest); status = response.jobStatus().toString(); if (status.compareTo("SUCCEEDED") == 0) finished = true; else { Performing Asynchronous Operations 253 Amazon Textract Developer Guide System.out.println(index + " status is: " + status); Thread.sleep(1000); } index++ ; } return status; } catch( InterruptedException e) { System.out.println(e.getMessage()); System.exit(1); } return ""; } // snippet-end:[textract.java2._start_doc_analysis.main] } AWS CLI This AWS CLI command starts the asynchronous detection of text in a specified document. It returns a job-id that can be used to retreive the results of the detection. aws textract start-document-text-detection --document-location "{\"S3Object\":{\"Bucket\":\"bucket-name\",\"Name\":\"file-name\"}}" -- region region-name This AWS CLI command returns the results for an Amazon Textract asynchronous operation when provided with a job-id. aws textract get-document-text-detection --region region-name --job-id job-id- number If you are accessing the CLI on a Windows device, use double quotes instead of single quotes and escape the inner double quotes by backslash (i.e. \) to address any parser errors you may encounter. For an example, see below aws textract start-document-text-detection --document-location "{\"S3Object\": {\"Bucket\":\"bucket\",\"Name\":\"document\"}}" --region region-name Performing Asynchronous Operations 254 Amazon Textract Developer Guide If you are analyzing a document with the StartDocumentAnalysis operation, you can provide values to the feature-type parameter. The following example demonstrates how to include the QUERIES value in the feature-types parameter and then provide a Queries object to the queries-config parameter. aws textract start-document-analysis \ --document '{"S3Object":{"Bucket":"bucket","Name":"document"}}'\ --feature-types '["QUERIES"]' \ --queries-config '{"Queries":[{"Text":"Question"}]}' Python Replace profile-name in the line that creates the TextractClient with the name of your developer profile. import boto3 import json import sys import time class ProcessType: DETECTION = 1 ANALYSIS = 2 class DocumentProcessor: jobId = '' region_name = '' roleArn = '' bucket = '' document = '' sqsQueueUrl = '' snsTopicArn = '' processType = '' def __init__(self, role, bucket, document, region):
textract-dg-054
textract-dg.pdf
54
The following example demonstrates how to include the QUERIES value in the feature-types parameter and then provide a Queries object to the queries-config parameter. aws textract start-document-analysis \ --document '{"S3Object":{"Bucket":"bucket","Name":"document"}}'\ --feature-types '["QUERIES"]' \ --queries-config '{"Queries":[{"Text":"Question"}]}' Python Replace profile-name in the line that creates the TextractClient with the name of your developer profile. import boto3 import json import sys import time class ProcessType: DETECTION = 1 ANALYSIS = 2 class DocumentProcessor: jobId = '' region_name = '' roleArn = '' bucket = '' document = '' sqsQueueUrl = '' snsTopicArn = '' processType = '' def __init__(self, role, bucket, document, region): self.roleArn = role self.bucket = bucket Performing Asynchronous Operations 255 Amazon Textract Developer Guide self.document = document self.region_name = region self.textract = boto3.client('textract', region_name=self.region_name) self.sqs = boto3.client('sqs', region_name=self.region_name) self.sns = boto3.client('sns', region_name=self.region_name) def ProcessDocument(self, type): jobFound = False self.processType = type validType = False # Determine which type of processing to perform if self.processType == ProcessType.DETECTION: response = self.textract.start_document_text_detection( DocumentLocation={'S3Object': {'Bucket': self.bucket, 'Name': self.document}}, NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn}) print('Processing type: Detection') validType = True # For document analysis, select which features you want to obtain with the FeatureTypes argument if self.processType == ProcessType.ANALYSIS: response = self.textract.start_document_analysis( DocumentLocation={'S3Object': {'Bucket': self.bucket, 'Name': self.document}}, FeatureTypes=["TABLES", "FORMS"], NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn}) print('Processing type: Analysis') validType = True if validType == False: print("Invalid processing type. Choose Detection or Analysis.") return print('Start Job Id: ' + response['JobId']) dotLine = 0 while jobFound == False: sqsResponse = self.sqs.receive_message(QueueUrl=self.sqsQueueUrl, MessageAttributeNames=['ALL'], Performing Asynchronous Operations 256 Amazon Textract Developer Guide MaxNumberOfMessages=10) if sqsResponse: if 'Messages' not in sqsResponse: if dotLine < 40: print('.', end='') dotLine = dotLine + 1 else: print() dotLine = 0 sys.stdout.flush() time.sleep(5) continue for message in sqsResponse['Messages']: notification = json.loads(message['Body']) textMessage = json.loads(notification['Message']) print(textMessage['JobId']) print(textMessage['Status']) if str(textMessage['JobId']) == response['JobId']: print('Matching Job Found:' + textMessage['JobId']) jobFound = True self.GetResults(textMessage['JobId']) self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) else: print("Job didn't match:" + str(textMessage['JobId']) + ' : ' + str(response['JobId'])) # Delete the unknown message. Consider sending to dead letter queue self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) print('Done!') def CreateTopicandQueue(self): millis = str(int(round(time.time() * 1000))) # Create SNS topic Performing Asynchronous Operations 257 Amazon Textract Developer Guide snsTopicName = "AmazonTextractTopic" + millis topicResponse = self.sns.create_topic(Name=snsTopicName) self.snsTopicArn = topicResponse['TopicArn'] # create SQS queue sqsQueueName = "AmazonTextractQueue" + millis self.sqs.create_queue(QueueName=sqsQueueName) self.sqsQueueUrl = self.sqs.get_queue_url(QueueName=sqsQueueName) ['QueueUrl'] attribs = self.sqs.get_queue_attributes(QueueUrl=self.sqsQueueUrl, AttributeNames=['QueueArn']) ['Attributes'] sqsQueueArn = attribs['QueueArn'] # Subscribe SQS queue to SNS topic self.sns.subscribe( TopicArn=self.snsTopicArn, Protocol='sqs', Endpoint=sqsQueueArn) # Authorize SNS to write SQS queue policy = """{{ "Version":"2012-10-17", "Statement":[ {{ "Sid":"MyPolicy", "Effect":"Allow", "Principal" : {{"AWS" : "*"}}, "Action":"SQS:SendMessage", "Resource": "{}", "Condition":{{ "ArnEquals":{{ "aws:SourceArn": "{}" }} }} }} ] }}""".format(sqsQueueArn, self.snsTopicArn) response = self.sqs.set_queue_attributes( QueueUrl=self.sqsQueueUrl, Performing Asynchronous Operations 258 Amazon Textract Developer Guide Attributes={ 'Policy': policy }) def DeleteTopicandQueue(self): self.sqs.delete_queue(QueueUrl=self.sqsQueueUrl) self.sns.delete_topic(TopicArn=self.snsTopicArn) # Display information about a block def DisplayBlockInfo(self, block): print("Block Id: " + block['Id']) print("Type: " + block['BlockType']) if 'EntityTypes' in block: print('EntityTypes: {}'.format(block['EntityTypes'])) if 'Text' in block: print("Text: " + block['Text']) if block['BlockType'] != 'PAGE' and "Confidence" in str(block['BlockType']): print("Confidence: " + "{:.2f}".format(block['Confidence']) + "%") print('Page: {}'.format(block['Page'])) if block['BlockType'] == 'CELL': print('Cell Information') print('\tColumn: {} '.format(block['ColumnIndex'])) print('\tRow: {}'.format(block['RowIndex'])) print('\tColumn span: {} '.format(block['ColumnSpan'])) print('\tRow span: {}'.format(block['RowSpan'])) if 'Relationships' in block: print('\tRelationships: {}'.format(block['Relationships'])) if ("Geometry") in str(block): print('Geometry') print('\tBounding Box: {}'.format(block['Geometry']['BoundingBox'])) print('\tPolygon: {}'.format(block['Geometry']['Polygon'])) if block['BlockType'] == 'SELECTION_ELEMENT': print(' Selection element detected: ', end='') if block['SelectionStatus'] == 'SELECTED': print('Selected') Performing Asynchronous Operations 259 Amazon Textract Developer Guide else: print('Not selected') if block["BlockType"] == "QUERY": print("Query info:") print(block["Query"]) if block["BlockType"] == "QUERY_RESULT": print("Query answer:") print(block["Text"]) def GetResults(self, jobId): maxResults = 1000 paginationToken = None finished = False while finished == False: response = None if self.processType == ProcessType.ANALYSIS: if paginationToken == None: response = self.textract.get_document_analysis(JobId=jobId, MaxResults=maxResults) else: response = self.textract.get_document_analysis(JobId=jobId, MaxResults=maxResults, NextToken=paginationToken) if self.processType == ProcessType.DETECTION: if paginationToken == None: response = self.textract.get_document_text_detection(JobId=jobId, MaxResults=maxResults) else: response = self.textract.get_document_text_detection(JobId=jobId, MaxResults=maxResults, Performing Asynchronous Operations 260 Amazon Textract Developer Guide NextToken=paginationToken) blocks = response['Blocks'] print('Detected Document Text') print('Pages: {}'.format(response['DocumentMetadata']['Pages'])) # Display block information for block in blocks: self.DisplayBlockInfo(block) print() print() if 'NextToken' in response: paginationToken = response['NextToken'] else: finished = True def GetResultsDocumentAnalysis(self, jobId): maxResults = 1000 paginationToken = None finished = False while finished == False: response = None if paginationToken == None: response = self.textract.get_document_analysis(JobId=jobId, MaxResults=maxResults) else: response = self.textract.get_document_analysis(JobId=jobId, MaxResults=maxResults, NextToken=paginationToken) # Get the text blocks blocks = response['Blocks'] print('Analyzed Document Text') print('Pages: {}'.format(response['DocumentMetadata']['Pages'])) # Display block information for block in blocks: self.DisplayBlockInfo(block) Performing Asynchronous Operations 261 Amazon Textract Developer Guide print() print() if 'NextToken' in response: paginationToken = response['NextToken'] else: finished = True def main(): roleArn = '' bucket = '' document = '' region_name = '' analyzer = DocumentProcessor(roleArn, bucket, document, region_name) analyzer.CreateTopicandQueue() analyzer.ProcessDocument(ProcessType.ANALYSIS) analyzer.DeleteTopicandQueue() if __name__ == "__main__": main() In order to use different features of the AnalyzeDocument operation, you provide the proper feature type to the features-type parameter. For example, to use the Queries feature, include the QUERIES value in the feature-types parameter
textract-dg-055
textract-dg.pdf
55
= response['Blocks'] print('Analyzed Document Text') print('Pages: {}'.format(response['DocumentMetadata']['Pages'])) # Display block information for block in blocks: self.DisplayBlockInfo(block) Performing Asynchronous Operations 261 Amazon Textract Developer Guide print() print() if 'NextToken' in response: paginationToken = response['NextToken'] else: finished = True def main(): roleArn = '' bucket = '' document = '' region_name = '' analyzer = DocumentProcessor(roleArn, bucket, document, region_name) analyzer.CreateTopicandQueue() analyzer.ProcessDocument(ProcessType.ANALYSIS) analyzer.DeleteTopicandQueue() if __name__ == "__main__": main() In order to use different features of the AnalyzeDocument operation, you provide the proper feature type to the features-type parameter. For example, to use the Queries feature, include the QUERIES value in the feature-types parameter and then provide a Queries object to the queries-config parameter. To query your document, replace the code block that makes a request to the StartDocumentAnalysis operation with the code block below, and enter your query. if self.processType == ProcessType.ANALYSIS: response = self.textract.start_document_analysis( DocumentLocation={'S3Object': {'Bucket': self.bucket, 'Name': self.document}}, FeatureTypes=["TABLES", "FORMS", "QUERIES"], QueriesConfig={'Queries':[ {'Text':'{}'.format("Enter query here")} ]}, Performing Asynchronous Operations 262 Amazon Textract Developer Guide NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn}) Node.JS In this example, replace the value of roleArn with the IAM role ARN that you saved in Giving Amazon Textract Access to Your Amazon SNS Topic. Replace the values of bucket and document with the bucket and document file name you specified in step 2 above. Replace the value of processType with the type of processing you'd like to use on the input document. Finally, replace the value of REGION with the region your client is operating in. Replace the value of profileName with the name of your developer profile. // snippet-start:[sqs.JavaScript.queues.createQueueV3] // Import required AWS SDK clients and commands for Node.js import { CreateQueueCommand, GetQueueAttributesCommand, GetQueueUrlCommand, SetQueueAttributesCommand, DeleteQueueCommand, ReceiveMessageCommand, DeleteMessageCommand } from "@aws-sdk/client-sqs"; import {CreateTopicCommand, SubscribeCommand, DeleteTopicCommand } from "@aws- sdk/client-sns"; import { SQSClient } from "@aws-sdk/client-sqs"; import { SNSClient } from "@aws-sdk/client-sns"; import { TextractClient, StartDocumentTextDetectionCommand, StartDocumentAnalysisCommand, GetDocumentAnalysisCommand, GetDocumentTextDetectionCommand, DocumentMetadata } from "@aws-sdk/client- textract"; import { stdout } from "process"; import {fromIni} from '@aws-sdk/credential-providers'; // Set the AWS Region. const REGION = "region-name"; //e.g. "us-east-1" const profileName = "profile-name"; // Create SNS service object. const textractClient = new TextractClient({region: REGION, credentials: fromIni({profile: profileName,}), }); const sqsClient = new SQSClient({region: REGION, credentials: fromIni({profile: profileName,}), }); const snsClient = new SNSClient({region: REGION, credentials: fromIni({profile: profileName,}), }); Performing Asynchronous Operations 263 Amazon Textract Developer Guide // Set bucket and video variables const bucket = "bucket-name"; const documentName = "document-name"; const roleArn = "role-arn" const processType = "DETECTION" var startJobId = "" var ts = Date.now(); const snsTopicName = "AmazonTextractExample" + ts; const snsTopicParams = {Name: snsTopicName} const sqsQueueName = "AmazonTextractQueue-" + ts; // Set the parameters const sqsParams = { QueueName: sqsQueueName, //SQS_QUEUE_URL Attributes: { DelaySeconds: "60", // Number of seconds delay. MessageRetentionPeriod: "86400", // Number of seconds delay. }, }; // Process a document based on operation type const processDocumment = async (type, bucket, videoName, roleArn, sqsQueueUrl, snsTopicArn) => { try { // Set job found and success status to false initially var jobFound = false var succeeded = false var dotLine = 0 var processType = type var validType = false if (processType == "DETECTION"){ var response = await textractClient.send(new StartDocumentTextDetectionCommand({DocumentLocation:{S3Object:{Bucket:bucket, Name:videoName}}, NotificationChannel:{RoleArn: roleArn, SNSTopicArn: snsTopicArn}})) console.log("Processing type: Detection") validType = true } Performing Asynchronous Operations 264 Amazon Textract Developer Guide if (processType == "ANALYSIS"){ var response = await textractClient.send(new StartDocumentAnalysisCommand({DocumentLocation:{S3Object:{Bucket:bucket, Name:videoName}}, NotificationChannel:{RoleArn: roleArn, SNSTopicArn: snsTopicArn}})) console.log("Processing type: Analysis") validType = true } if (validType == false){ console.log("Invalid processing type. Choose Detection or Analysis.") return } // while not found, continue to poll for response console.log(`Start Job ID: ${response.JobId}`) while (jobFound == false){ var sqsReceivedResponse = await sqsClient.send(new ReceiveMessageCommand({QueueUrl:sqsQueueUrl, MaxNumberOfMessages:'ALL', MaxNumberOfMessages:10})); if (sqsReceivedResponse){ var responseString = JSON.stringify(sqsReceivedResponse) if (!responseString.includes('Body')){ if (dotLine < 40) { console.log('.') dotLine = dotLine + 1 }else { console.log('') dotLine = 0 }; stdout.write('', () => { console.log(''); }); await new Promise(resolve => setTimeout(resolve, 5000)); continue } } // Once job found, log Job ID and return true if status is succeeded for (var message of sqsReceivedResponse.Messages){ console.log("Retrieved messages:") var notification = JSON.parse(message.Body) var rekMessage = JSON.parse(notification.Message) var messageJobId = rekMessage.JobId Performing Asynchronous Operations 265 Amazon Textract Developer Guide if (String(rekMessage.JobId).includes(String(startJobId))){ console.log('Matching job found:') console.log(rekMessage.JobId) jobFound = true // GET RESUlTS FUNCTION HERE var operationResults = await GetResults(processType, rekMessage.JobId) //GET RESULTS FUMCTION HERE console.log(rekMessage.Status) if (String(rekMessage.Status).includes(String("SUCCEEDED"))){ succeeded = true console.log("Job processing succeeded.") var sqsDeleteMessage = await sqsClient.send(new DeleteMessageCommand({QueueUrl:sqsQueueUrl, ReceiptHandle:message.ReceiptHandle})); } }else{ console.log("Provided Job ID did not match returned ID.") var sqsDeleteMessage = await sqsClient.send(new DeleteMessageCommand({QueueUrl:sqsQueueUrl, ReceiptHandle:message.ReceiptHandle})); } } console.log("Done!") } }catch (err) { console.log("Error", err); } } // Create the SNS topic and SQS Queue const createTopicandQueue = async () => { try { // Create SNS topic const topicResponse = await snsClient.send(new CreateTopicCommand(snsTopicParams)); const topicArn = topicResponse.TopicArn console.log("Success", topicResponse); // Create SQS Queue const sqsResponse = await sqsClient.send(new CreateQueueCommand(sqsParams)); console.log("Success", sqsResponse); const sqsQueueCommand = await sqsClient.send(new
textract-dg-056
textract-dg.pdf
56
GetResults(processType, rekMessage.JobId) //GET RESULTS FUMCTION HERE console.log(rekMessage.Status) if (String(rekMessage.Status).includes(String("SUCCEEDED"))){ succeeded = true console.log("Job processing succeeded.") var sqsDeleteMessage = await sqsClient.send(new DeleteMessageCommand({QueueUrl:sqsQueueUrl, ReceiptHandle:message.ReceiptHandle})); } }else{ console.log("Provided Job ID did not match returned ID.") var sqsDeleteMessage = await sqsClient.send(new DeleteMessageCommand({QueueUrl:sqsQueueUrl, ReceiptHandle:message.ReceiptHandle})); } } console.log("Done!") } }catch (err) { console.log("Error", err); } } // Create the SNS topic and SQS Queue const createTopicandQueue = async () => { try { // Create SNS topic const topicResponse = await snsClient.send(new CreateTopicCommand(snsTopicParams)); const topicArn = topicResponse.TopicArn console.log("Success", topicResponse); // Create SQS Queue const sqsResponse = await sqsClient.send(new CreateQueueCommand(sqsParams)); console.log("Success", sqsResponse); const sqsQueueCommand = await sqsClient.send(new GetQueueUrlCommand({QueueName: sqsQueueName})) Performing Asynchronous Operations 266 Amazon Textract Developer Guide const sqsQueueUrl = sqsQueueCommand.QueueUrl const attribsResponse = await sqsClient.send(new GetQueueAttributesCommand({QueueUrl: sqsQueueUrl, AttributeNames: ['QueueArn']})) const attribs = attribsResponse.Attributes console.log(attribs) const queueArn = attribs.QueueArn // subscribe SQS queue to SNS topic const subscribed = await snsClient.send(new SubscribeCommand({TopicArn: topicArn, Protocol:'sqs', Endpoint: queueArn})) const policy = { Version: "2012-10-17", Statement: [ { Sid: "MyPolicy", Effect: "Allow", Principal: {AWS: "*"}, Action: "SQS:SendMessage", Resource: queueArn, Condition: { ArnEquals: { 'aws:SourceArn': topicArn } } } ] }; const response = sqsClient.send(new SetQueueAttributesCommand({QueueUrl: sqsQueueUrl, Attributes: {Policy: JSON.stringify(policy)}})) console.log(response) console.log(sqsQueueUrl, topicArn) return [sqsQueueUrl, topicArn] } catch (err) { console.log("Error", err); } } const deleteTopicAndQueue = async (sqsQueueUrlArg, snsTopicArnArg) => { const deleteQueue = await sqsClient.send(new DeleteQueueCommand({QueueUrl: sqsQueueUrlArg})); Performing Asynchronous Operations 267 Amazon Textract Developer Guide const deleteTopic = await snsClient.send(new DeleteTopicCommand({TopicArn: snsTopicArnArg})); console.log("Successfully deleted.") } const displayBlockInfo = async (block) => { console.log(`Block ID: ${block.Id}`) console.log(`Block Type: ${block.BlockType}`) if (String(block).includes(String("EntityTypes"))){ console.log(`EntityTypes: ${block.EntityTypes}`) } if (String(block).includes(String("Text"))){ console.log(`EntityTypes: ${block.Text}`) } if (!String(block.BlockType).includes('PAGE')){ console.log(`Confidence: ${block.Confidence}`) } console.log(`Page: ${block.Page}`) if (String(block.BlockType).includes("CELL")){ console.log("Cell Information") console.log(`Column: ${block.ColumnIndex}`) console.log(`Row: ${block.RowIndex}`) console.log(`Column Span: ${block.ColumnSpan}`) console.log(`Row Span: ${block.RowSpan}`) if (String(block).includes("Relationships")){ console.log(`Relationships: ${block.Relationships}`) } } console.log("Geometry") console.log(`Bounding Box: ${JSON.stringify(block.Geometry.BoundingBox)}`) console.log(`Polygon: ${JSON.stringify(block.Geometry.Polygon)}`) if (String(block.BlockType).includes('SELECTION_ELEMENT')){ console.log('Selection Element detected:') if (String(block.SelectionStatus).includes('SELECTED')){ console.log('Selected') } else { console.log('Not Selected') } } } Performing Asynchronous Operations 268 Amazon Textract Developer Guide const GetResults = async (processType, JobID) => { var maxResults = 1000 var paginationToken = null var finished = false while (finished == false){ var response = null if (processType == 'ANALYSIS'){ if (paginationToken == null){ response = textractClient.send(new GetDocumentAnalysisCommand({JobId:JobID, MaxResults:maxResults})) }else{ response = textractClient.send(new GetDocumentAnalysisCommand({JobId:JobID, MaxResults:maxResults, NextToken:paginationToken})) } } if(processType == 'DETECTION'){ if (paginationToken == null){ response = textractClient.send(new GetDocumentTextDetectionCommand({JobId:JobID, MaxResults:maxResults})) }else{ response = textractClient.send(new GetDocumentTextDetectionCommand({JobId:JobID, MaxResults:maxResults, NextToken:paginationToken})) } } await new Promise(resolve => setTimeout(resolve, 5000)); console.log("Detected Documented Text") console.log(response) //console.log(Object.keys(response)) console.log(typeof(response)) var blocks = (await response).Blocks console.log(blocks) console.log(typeof(blocks)) var docMetadata = (await response).DocumentMetadata var blockString = JSON.stringify(blocks) var parsed = JSON.parse(JSON.stringify(blocks)) console.log(Object.keys(blocks)) Performing Asynchronous Operations 269 Amazon Textract Developer Guide console.log(`Pages: ${docMetadata.Pages}`) blocks.forEach((block)=> { displayBlockInfo(block) console.log() console.log() }) //console.log(blocks[0].BlockType) //console.log(blocks[1].BlockType) if(String(response).includes("NextToken")){ paginationToken = response.NextToken }else{ finished = true } } } // DELETE TOPIC AND QUEUE const main = async () => { var sqsAndTopic = await createTopicandQueue(); var process = await processDocumment(processType, bucket, documentName, roleArn, sqsAndTopic[0], sqsAndTopic[1]) var deleteResults = await deleteTopicAndQueue(sqsAndTopic[0], sqsAndTopic[1]) } main() 4. Run the code. The operation might take a while to finish. After it's finished, a list of blocks for detected or analyzed text is displayed. Using the Analyze Lending Workflow To detect text in, or analyze multipage lending documents, using the Analyze Lending workflow, you do the following: 1. Create the Amazon SNS topic and the Amazon SQS queue. 2. Subscribe the queue the topic. Using the Analyze Lending Workflow 270 Amazon Textract Developer Guide 3. Give the topic permission to send messages to the queue. 4. Start processing the document. Call StartLendingAnalysis operation. 5. Get the completion status from the Amazon SQS queue. The example code tracks the job identifier (JobId) that's returned by the Start operation. The example code only gets the results for matching job identifiers that are read from the completion status. This is important if other applications are using the same queue and topic. For simplicity, the example code deletes jobs that don't match. Consider adding the deleted jobs to an Amazon SQS dead-letter queue for further investigation. The results of the StartLendingAnalysis operation can be sent to an Amazon S3 bucket of your choice by using the OutputConfig feature. If you use this feature, you may have to do some additional configuration of your User and Service Role. For information on how to let Amazon Textract send encrypted documents to your Amazon S3 bucket, see Permissions for Output Configuration. 6. Get and display the processing results by calling the GetLendingAnalysis operation or the GetLendingAnalysisSummary operation. 7. Once you are finished processing documents, be sure to delete the Amazon SNS topic and the Amazon SQS queue. If you need to process additional documents, you can leave the Amazon SNS topic and Amazon SQS queue as they are and reuse them for the other documents. Performing Asynchronous Lending Analysis The example code for this procedure is provided for Python and the
textract-dg-057
textract-dg.pdf
57
information on how to let Amazon Textract send encrypted documents to your Amazon S3 bucket, see Permissions for Output Configuration. 6. Get and display the processing results by calling the GetLendingAnalysis operation or the GetLendingAnalysisSummary operation. 7. Once you are finished processing documents, be sure to delete the Amazon SNS topic and the Amazon SQS queue. If you need to process additional documents, you can leave the Amazon SNS topic and Amazon SQS queue as they are and reuse them for the other documents. Performing Asynchronous Lending Analysis The example code for this procedure is provided for Python and the AWS CLI. Before you begin, install the appropriate AWS SDK. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. 1. Configure user access to Amazon Textract, and configure Amazon Textract access to Amazon SNS. For more information, see Configuring Amazon Textract for Asynchronous Operations. To complete this procedure, you need a multipage document file in PDF format. You can skip steps 3 – 6 in the configuration instructions, because the example code creates and configures the Amazon SNS topic and Amazon SQS queue. If completing the CLI example, you don't need to set up an SQS queue. 2. Upload a multipage document file in PDF or TIFF format to your Amazon S3 bucket (you can also process single-page documents in JPEG, PNG, TIFF, or PDF formats). For instructions, see Uploading Objects into Amazon S3in the Amazon Simple Storage Service User Guide. Performing Asynchronous Lending Analysis 271 Amazon Textract Developer Guide 3. Use the following AWS SDK for Python (Boto3) or AWS CLI code to analyze text in a multipage lending document. In the main function: • Replace the value of roleArn with the IAM role ARN that you saved in Giving Amazon Textract Access to Your Amazon SNS Topic. • Replace the values of bucket and document with the bucket and document file name that you previously specified in the proceeding Step 2. • Replace the value of the type input parameter of the ProcessDocument function with the type of processing that you want to use. For example, use ProcessType.DETECTION to detect text, or use ProcessType.ANALYSIS to analyze text. • For the Python example, replace the value of region_name with the region your client is operating in. For the upcoming AWS CLI example code, do the following: • When calling the StartLendingAnalysis operation, replace the value of bucket-name with the name of your S3 bucket, and replace FileName with the name of the file you specified in step 2. Specify the region of your bucket by replacing region-name with the name of your region. Take note that the CLI example does not make use of SQS. • When calling the GetLendingAnalysis operation or the GetLendingAnalysisSummary operation, replace jobId with the jobId returned by StartLendingAnalysis. Specify the region of your bucket by replacing region-name with the name of your region. 4. Run the code for your chosen SDK or the AWS CLI. The operation might take a while to finish. After it's finished, a list of blocks for detected or analyzed text is displayed by the follwing examples: AWS CLI To start the lending document analysis use the following CLI command. If you want to see splitted documents, use the output-config argument, otherwise you can remove it : aws textract start-lending-analysis \ --document-location '{"S3Object":{"Bucket":"S3Bucket","Name":"FileName"}}' \ --output-config '{"S3Bucket": "S3Bucket", "S3Prefix": "S3Prefix"}' \ --kms-key-id '1234abcd-12ab-34cd-56ef-1234567890ab' \ --region 'region-name' Performing Asynchronous Lending Analysis 272 Amazon Textract Developer Guide To get the results of the lending document analysis use the following CLI command. The max-results argument is optional, and if you don't want to limit the number of results returned you can remove it: aws textract get-lending-analysis \ --job-id 'jobId' \ --region 'us-west-2' \ --max-results 30 To retrieve a summary of the results: aws textract get-lending-analysis-summary \ --job-id 'jobId' \ --region 'us-west-2' Python import boto3 import json import sys import time class DocumentProcessor: def __init__(self, role, bucket, document, region): self.roleArn = role self.bucket = bucket self.document = document self.region_name = region self.textract = boto3.client('textract', region_name=self.region_name) self.sqs = boto3.client('sqs') self.sns = boto3.client('sns') def ProcessDocument(self): jobFound = False response = self.textract.start_lending_analysis( DocumentLocation={'S3Object': {'Bucket': self.bucket, 'Name': self.document}}, Performing Asynchronous Lending Analysis 273 Amazon Textract Developer Guide NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn}) print('Processing type: Analysis') print('Start Job Id: ' + response['JobId']) dotLine = 0 while jobFound == False: sqsResponse = self.sqs.receive_message(QueueUrl=self.sqsQueueUrl, MessageAttributeNames=['ALL'], MaxNumberOfMessages=10) if sqsResponse: if 'Messages' not in sqsResponse: if dotLine < 40: print('.', end='') dotLine = dotLine + 1 else: print() dotLine = 0 sys.stdout.flush() time.sleep(5) continue for message in sqsResponse['Messages']: notification = json.loads(message['Body']) textMessage = json.loads(notification['Message']) print(textMessage['JobId']) print(textMessage['Status']) if str(textMessage['JobId']) == response['JobId']: print('Matching Job Found:' + textMessage['JobId']) jobFound = True self.GetResults(textMessage['JobId']) self.GetSummary(textMessage['JobId']) self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) else: print("Job didn't match:" + str(textMessage['JobId']) + ' : ' + str(response['JobId'])) # Delete the unknown message. Consider
textract-dg-058
textract-dg.pdf
58
Textract Developer Guide NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn}) print('Processing type: Analysis') print('Start Job Id: ' + response['JobId']) dotLine = 0 while jobFound == False: sqsResponse = self.sqs.receive_message(QueueUrl=self.sqsQueueUrl, MessageAttributeNames=['ALL'], MaxNumberOfMessages=10) if sqsResponse: if 'Messages' not in sqsResponse: if dotLine < 40: print('.', end='') dotLine = dotLine + 1 else: print() dotLine = 0 sys.stdout.flush() time.sleep(5) continue for message in sqsResponse['Messages']: notification = json.loads(message['Body']) textMessage = json.loads(notification['Message']) print(textMessage['JobId']) print(textMessage['Status']) if str(textMessage['JobId']) == response['JobId']: print('Matching Job Found:' + textMessage['JobId']) jobFound = True self.GetResults(textMessage['JobId']) self.GetSummary(textMessage['JobId']) self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) else: print("Job didn't match:" + str(textMessage['JobId']) + ' : ' + str(response['JobId'])) # Delete the unknown message. Consider sending to dead letter queue self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) Performing Asynchronous Lending Analysis 274 Amazon Textract Developer Guide print('Done!') def CreateTopicandQueue(self): millis = str(int(round(time.time() * 1000))) # Create SNS topic snsTopicName = "AmazonTextractTopic" + millis topicResponse = self.sns.create_topic(Name=snsTopicName) self.snsTopicArn = topicResponse['TopicArn'] # create SQS queue sqsQueueName = "AmazonTextractQueue" + millis self.sqs.create_queue(QueueName=sqsQueueName) self.sqsQueueUrl = self.sqs.get_queue_url(QueueName=sqsQueueName) ['QueueUrl'] attribs = self.sqs.get_queue_attributes(QueueUrl=self.sqsQueueUrl, AttributeNames=['QueueArn']) ['Attributes'] sqsQueueArn = attribs['QueueArn'] # Subscribe SQS queue to SNS topic self.sns.subscribe( TopicArn=self.snsTopicArn, Protocol='sqs', Endpoint=sqsQueueArn) # Authorize SNS to write SQS queue policy = """{{ "Version":"2012-10-17", "Statement":[ {{ "Sid":"MyPolicy", "Effect":"Allow", "Principal" : {{"AWS" : "*"}}, "Action":"sqs:*", "Resource": "{}", "Condition":{{ "ArnEquals":{{ "aws:SourceArn": "{}" Performing Asynchronous Lending Analysis 275 Amazon Textract Developer Guide }} }} }} ] }}""".format(sqsQueueArn, self.snsTopicArn) response = self.sqs.set_queue_attributes( QueueUrl=self.sqsQueueUrl, Attributes={ 'Policy': policy }) def DeleteTopicandQueue(self): self.sqs.delete_queue(QueueUrl=self.sqsQueueUrl) self.sns.delete_topic(TopicArn=self.snsTopicArn) # Display information about a block def DisplayExtractInfo(self, response): results = response['Results'] for page in results: print("Page Classification: {}".format(page["PageClassification"] ["PageType"])) print("Page Number: {}".format(page["Page"])) for extract in page["Extractions"]: for fields, vals in extract['LendingDocument'].items(): for val in vals: print("Document Type: {}".format(val['Type'])) detections = val['ValueDetections'] for i in detections: print(i['Text']) print('Geometry') print('\tBounding Box: {}'.format(i['Geometry'] ['BoundingBox'])) print('\tPolygon: {}'.format(i['Geometry'] ['Polygon'])) def GetSummary(self, jobId): maxResults = 1000 response = self.textract.get_lending_analysis_summary(JobId=jobId, MaxResults=maxResults) doc_groups = response['DocumentGroups'] print("Summary info:") for group in doc_groups: Performing Asynchronous Lending Analysis 276 Amazon Textract Developer Guide print("Document type: " + group['Type']) split_docs = group['SplitDocuments'] for doc in split_docs: print(doc) for idx, page in doc.items(): print(str(idx) + " - " + str(page)) def GetResults(self, jobId): maxResults = 1000 paginationToken = None finished = False while finished == False: response = None if paginationToken == None: response = self.textract.get_lending_analysis(JobId=jobId, MaxResults=maxResults) else: response = self.textract.get_lending_analysis(JobId=jobId, MaxResults=maxResults, NextToken=paginationToken) print('Detected Document Text') print('Pages: {}'.format(response['DocumentMetadata']['Pages'])) self.DisplayExtractInfo(response) if 'NextToken' in response: paginationToken = response['NextToken'] else: finished = True def main(): roleArn = '' bucket = '' document = '' region_name = '' analyzer = DocumentProcessor(roleArn, bucket, document, region_name) Performing Asynchronous Lending Analysis 277 Amazon Textract Developer Guide analyzer.CreateTopicandQueue() analyzer.ProcessDocument() analyzer.DeleteTopicandQueue() if __name__ == "__main__": main() Amazon Textract Results Notification Amazon Textract sends the status of an analysis request to an Amazon Simple Notification Service (Amazon SNS) topic. To get the notification from an Amazon SNS topic, use an Amazon SQS queue or an AWS Lambda function. For more information, see Calling Amazon Textract Asynchronous Operations. For an example, see Detecting or Analyzing Text in a Multipage Document. The status message sent by Amazon Simple Notification Service to Amazon SQS has the following JSON format: { "JobId": "String", "Status": "String", "API": "String", "JobTag": "String", "Timestamp": Number, "DocumentLocation": { "S3ObjectName": "String", "S3Bucket": "String" } } This table describes the different parameters within an Amazon SNS status. Parameter JobId Description The unique identifier that Amazon Textract assigns to the job. It matches a job identifier that's returned from a Start operation, such as StartDocumentTextDetection. Amazon Textract Results Notification 278 Amazon Textract Parameter Status API JobTag Timestamp DocumentLocation Developer Guide Description The status of the job. Valid values are SUCCEEDED, FAILED, or ERROR. The Amazon Textract operation used to analyze the input document, such as StartDocumentTextDetection or StartDocu mentAnalysis. The user-specified identifier for the job. You specify JobTag in a call to the Start operation, such as StartDocumentTextD etection. The Unix timestamp that indicates when the job finished, returned in milliseconds. Details about the document that was processed. Includes the file name and the Amazon S3 bucket that the file is stored in. If the value of "Status" in the Amazon SNS notification is "Failed", this indicates something has gone wrong with your analysis job. In this case, check for an error message returned by the Amazon Textract API operation and ensure your document matches the quotas specified bySet Quotas in Amazon Textract Amazon Textract Results Notification 279 Amazon Textract Developer Guide Customizing your Queries Responses Amazon Textract lets you customize the output of its pretrained Queries feature using adapters. You can use the Amazon Textract Console to create an adapter. This adapter can then be referenced when calling the AnalyzeDocument and StartDocumentAnalysis operations. When you create an adapter using the console, you upload your own documents for the purposes of training the adapter and testing its performance. You also add queries to your documents and then annotate your documents by linking these queries to the correct response
textract-dg-059
textract-dg.pdf
59
bySet Quotas in Amazon Textract Amazon Textract Results Notification 279 Amazon Textract Developer Guide Customizing your Queries Responses Amazon Textract lets you customize the output of its pretrained Queries feature using adapters. You can use the Amazon Textract Console to create an adapter. This adapter can then be referenced when calling the AnalyzeDocument and StartDocumentAnalysis operations. When you create an adapter using the console, you upload your own documents for the purposes of training the adapter and testing its performance. You also add queries to your documents and then annotate your documents by linking these queries to the correct response elements in your documents. Once you have created an adapter and annotated your documents, you can train the adapter, check its performance, and then use it when analyzing documents. Adapters are modular components are added to the existing Amazon Textract deep learning model, extending its capabilities for the tasks it’s trained on. By fine-tuning a deep learning model with adapters, you can customize the output for document analysis tasks related to your specific use case. To create and use an adapter, you must: • Upload sample documents for training • Designate the train and test datasets • Annotate your documents with queries and responses • Train the adapter • Get the AdapterId • Use the adapter when calling AnalyzeDocument Uploading sample documents To train the adapter, you must upload a set of sample documents representative of your use case. You can upload documents directly from your computer or an Amazon S3 bucket. For best results, provide as many documents for training as possible (up to a maximum of 2,500 pages training documents and 1000 test documents). Make sure that the documents represent all aspects of your use case. You must upload a minimum of five training and five testing documents. Designating training and test sets 280 Amazon Textract Developer Guide You must divide all of your documents into training and test sets. The training set is used to train the adapter. The adapter learns the patterns contained in these annotated documents. The test set is used to evaluate the adapter performance. For more information on training and testing data, see Preparing training and testing datasets. Annotating documents with queries and responses When annotating your documents, you have two choices: You can auto-label your documents using the pretrained Queries feature and then edit the labels where needed. Alternatively, you can manually label responses for each of your document queries. For more information on best practices for queries, see Best Practices for Queries. Train the adapter After you annotate the training data, you can initiate the training process for your adapter. Amazon Textract trains an adapter that's tailored to your documents. The adapter training takes 2-30 hours, depending on the size of the dataset and the AWS Region. When the training is complete, you can view the training status in the adapter details page. If the status is training failed, see Debugging training failures to debug the failure. Evaluate the adapter After each round of adapter training, review the performance metrics in the AWS Management Console to determine how close the adapter is to your desired level of performance. You can then further improve your adapter’s accuracy for your documents by uploading a new batch of training documents or by reviewing annotations for documents that have low accuracy scores. After you create an improved version of the adapter, you can use the AWS Console to delete any earlier adapter versions that you no longer need. For more information on evaluation metrics, see Evaluating and improving your adapters. Get the AdapterId Once the adapter has been trained, you can get the unique ID for your adapter to use with the Amazon Textract document analysis API operations. Retrieve the AdapterId by using the ListAdapterVersions API operation, or by using the AWS Management Console. Call the AnalyzeDocument API operation 281 Amazon Textract Developer Guide To apply your custom adapter, provide its ID when calling the AnalyzeDocument or StartDocumentAnalysis API operations. This enhances predictions on your documents. When calling API operations, you can use up to one adapter per page. Video demonstration and tutorial Creating adapters Before you can train an adapter, you must create an adapter. To do so, use the CreateAdapter operation. After you create an adapter, get information about it with the GetAdapter operation. Configuration elements of adapters can be updated with the UpdateAdapter operation. Get a list of adapters with the ListAdapters operation. Delete an adapter you no longer need with the DeleteAdapter operation. Create an Adapter To customize the Amazon Textract base model, create an adapter. To do so, use the CreateAdapter operation. When calling CreateAdapter, you provide an AdapterName and FeatureType as an input. Currently Queries is the only feature type supported. When creating an adapter you can also provide
textract-dg-060
textract-dg.pdf
60
adapter. To do so, use the CreateAdapter operation. After you create an adapter, get information about it with the GetAdapter operation. Configuration elements of adapters can be updated with the UpdateAdapter operation. Get a list of adapters with the ListAdapters operation. Delete an adapter you no longer need with the DeleteAdapter operation. Create an Adapter To customize the Amazon Textract base model, create an adapter. To do so, use the CreateAdapter operation. When calling CreateAdapter, you provide an AdapterName and FeatureType as an input. Currently Queries is the only feature type supported. When creating an adapter you can also provide a Description, Tags, and a ClientRequestToken. Finally, you can choose whether the adapter should be auto-updated with the AutoUpdate argument. After creating an adapter, you can start training it on your own sample documents by using the CreateAdapterVersion operation. To create an adapter with the Amazon Textract console: • Sign in to the Amazon Textract console. • Select Custom Queries from the left navigation panel. • Select Create adapter. To create an adapter with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: Creating adapters 282 Developer Guide Amazon Textract CLI aws textract create-adapter \ --adapter-name "test-w2" \ --feature-types '["QUERIES"]' \ --description 'demo' Get adapter You can retrieve configuration information for an adapter at any time by calling the GetAdapter operation and specifying an AdapterId. GetAdapter returns information on AdapterName, Description, CreationTime, AutoUpdate status, and FeatureTypes. To see details for your adapter with the console: • Sign into the AWS console for Amazon Textract. • Select Custom Queries from the navigation panel on the left. • From the list of Your adapters, select the adapter you want to view the details for. • Review the details for the adapter on your Adapter details page. To see details for your adapter with the CLI/SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract get-adapter \ --adapter-id "abcdef123456" Get adapter 283 Amazon Textract List adapters Developer Guide You can list all of the adapters associated with your account by using the ListAdapters operation. You can filter the list of returned adapters by the date and time of creation by using the AfterCreationTime and BeforeCreationTime arguments. You can also set a number of maximum results to return using MaxResults. To see a list of your adapters with the console: • Sign into the AWS console for Amazon Textract. • Select Custom Queries from the navigation panel on the left. • View your adapters in the list of your adapters. To create an adapter with the CLI/SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract list-adapters Update adapter With Amazon Textract, you can update some configuration options of an adapter. Simultaneously, you can update any adapter versions associated with the adapter. To do this, call the UpdateAdapter operation and provide the operation with the AdapterId and configuration elements that you want to update. The AdapterName and FeatureTypes elements cannot be updated. To update an adapter with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: List adapters 284 Developer Guide Amazon Textract CLI aws textract update-adapter \ --adapter-id 'abcdef123456' \ --description 'demo new' Delete an Adapter You can delete a custom Amazon Textract adapter at any time by calling the DeleteAdapter API operation. You can delete an adapter by providing the DeleteAdapter operation with the AdapterId of the adapter that you want to delete. Invoke DeleteAdapter will delete all Adapter Versions associated with the Adapter ARN. To delete an adapter with the console: • Sign in to the Amazon Textract console. • Select Custom Queries from the left navigation panel. • From the list of your adapters, select the adapter to delete. • Select Delete and follow the instructions to delete your adapter. To create an adapter with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS
textract-dg-061
textract-dg.pdf
61
want to delete. Invoke DeleteAdapter will delete all Adapter Versions associated with the Adapter ARN. To delete an adapter with the console: • Sign in to the Amazon Textract console. • Select Custom Queries from the left navigation panel. • From the list of your adapters, select the adapter to delete. • Select Delete and follow the instructions to delete your adapter. To create an adapter with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract delete-adapter \ --adapter-id 'abcdef123456' Delete an Adapter 285 Amazon Textract Developer Guide Preparing training and testing datasets Training and Testing Datasets The training dataset is the basis for creating an adapter. You must provide an annotated training dataset to train an adapter. This training dataset consists of user uploaded document pages, queries, and annotated query answers. The model learns from this dataset to improve its performance on the type of documents you provide. The testing dataset is used to evaluate the adapter’s performance. The testing dataset is created by using a slice of the original dataset that the model hasn’t seen before. This process assesses the adapter’s performance with new data, creating accurate measurements and metrics. You must divide all of your documents into training and test sets. The training set is used to train the adapter. The adapter learns the patterns contained in these annotated documents. The test set is used to evaluate the adapter performance. If you upload fewer than 20 documents, split them equally between train and test. If you upload more than 20 documents, assign 70% of data to training and 30% to testing. When splitting documents in the AWS Management Console, you can let Amazon Textract automatically split your documents. Alternatively, you can manually divide your documents into training and testing sets. Dataset components Datasets contain the four following components, which you must prepare yourself or by using the AWS Management Console: • Images - Images can be JPEG, PNG, 1-page PDF, or 1-page TIFF. If you are submitting multipage documents, the AWS Management Console will visualize each page separately for annotation. • Annotation file - The annotation file follows the Amazon Textract Block structure, though it contains only QUERY and QUERY_RESULT blocks. • Prelabeling files - This is the Block structure from the Amazon Textract current API response, pulled from the result of either the DetectDocumentText or AnalyzeDocument operations. If you have already called Amazon Textract before and stored the result of the operation, you can provide the references to those results. Amazon Textract accepts multiple prelabeling files in case your document page has multiple response files exported from an asynchronous API. • Manifest file - A JSONL-based file where each line points to an annotation file, the prelabeling file, or an image or single-page PDF. Refer to this manifest file format when structuring your manifest file. Preparing training and testing datasets 286 Amazon Textract Developer Guide Manifest files are contain one or more JSON lines, with each line containing information for a single image. What follows is a single line in a manifest file: { "source-ref": "s3://textract-adapters-sample-bucket-129090f9e-d51c-4034- a732-48caa3b532e7/adapters/0000000000/assets/1003_3_1.png", "source-ref-version": "uPNKaY_2I8dxj9Kp2sO0zDUt4q3MAJen", "source-ref-metadata": { "origin-ref": "s3://textract-adapters-sample-bucket-129090f9e-d51c-4034- a732-48caa3b532e7/adapters/0000000000/original_assets/1003_3.tiff", "page-number": 1 }, "annotations-ref": "s3://textract-adapters-sample-bucket-129090f9e-d51c-4034- a732-48caa3b532e7/adapters/0000000000/annotations/1003_3_1.png.json", "annotations-ref-version": "nwj_MC40zsAae_idwsdEa0r4ZQaVthGs", "annotations-ref-metadata": { "prelabeling-refs": [{ "prelabeling-ref": "s3://textract-adapters-sample- bucket-129090f9e-d51c-4034-a732-48caa3b532e7/adapters/0000000000/prelabels/ fd958ee156b5b5de1ee6101dd05263120790836856774c871b877baa35e2f373/1" "prelabeling-ref-version": "uPNKaY_2I8dxj9Kp2sO0zDUt4q3MAJen" ]}, "assignment": "TRAINING", "include": true, }, "schema-version": "1.0" } Note that the manifest file contains the following info: • source-ref: (Required) The Amazon S3 location of the image or single page file. The format is "s3://BUCKET/OBJECT_PATH". • source-ref-version: (Optional) The Amazon S3 object version of the image or single page file. • source-ref-metadata: (Optional) Metadata about the source-ref when this image of single page file should is part of a multipage document. This information is helpful when you want to evaluate the adapter on multipage documents. When not specified, we consider each source-ref as a standalone document. • origin-ref: (Required) The Amazon S3 location to the original multipage document. Preparing training and testing datasets 287 Amazon Textract Developer Guide • page-number: (Required) Page number of the source-ref in the original document. • annotations-ref: (Required) The Amazon S3 location of the customer performed annotations on the image. The format is "s3://BUCKET/OBJECT_PATH". • annotations-ref-metadata: (Required) Metadata about the annotations attribute. Holds prelabeling references, along with assignment type of the manifest line item, and if to include/ exclude the document from training. • prelabeling-refs: (Required) An list of files from the Amazon Textract asynchronous API response of the source-ref file. Each file in prelabeling-refs should contain a Block property, with at most of 1000 blocks. • prelabeling-ref (Required) The Amazon S3 location of the automatic annotations on
textract-dg-062
textract-dg.pdf
62
of the source-ref in the original document. • annotations-ref: (Required) The Amazon S3 location of the customer performed annotations on the image. The format is "s3://BUCKET/OBJECT_PATH". • annotations-ref-metadata: (Required) Metadata about the annotations attribute. Holds prelabeling references, along with assignment type of the manifest line item, and if to include/ exclude the document from training. • prelabeling-refs: (Required) An list of files from the Amazon Textract asynchronous API response of the source-ref file. Each file in prelabeling-refs should contain a Block property, with at most of 1000 blocks. • prelabeling-ref (Required) The Amazon S3 location of the automatic annotations on the image using the Amazon Textract API. • prelabeling-ref-version (Optional) The Amazon S3 object version of the prelabeling file. • assignment: (Required) Specify "TRAINING" if the image belongs to the training dataset. Otherwise, use "TESTING". • include: (Required) Specify true to include the line item for training. Otherwise, use false. • schema-version: (Optional) Version of the manifest file. The valid value is 1.0. For optimal accuracy improvements, see Best practices for Amazon Textract Custom Queries. Annotating the documents with queries and responses When annotating your documents, you can choose to auto-label your documents using the pretrained Queries feature and then edit the labels where needed. Alternatively, you can manually label responses for each of your document queries. When manually labeling your documents, Amazon Textract extracts the raw text from the document. After the raw text is extracted, you can use the AWS Management Console annotation interface to create queries for your documents. Link these queries to the relevant answers in your documents to establish a "ground truth" for training. When auto-labeling your documents, you specify the appropriate queries for your document. When you finish adding queries to your documents, Amazon Textract attempts to extract the proper elements from your documents, generating annotations. You must then verify the accuracy of these annotations, correcting any that are incorrect. By linking queries to answers, you teach the model what information is important in your documents. Preparing training and testing datasets 288 Amazon Textract Developer Guide When creating queries, consider the types of questions you will have to ask to retrieve the relevant data in your documents. For more information about this response structure, see Query Response Structures. For more information on best practices for queries, see Best Practices for Queries. You will need to train an adapter on representative samples of your documents. When you use the AWS Management Console for annotating the documents, the console prepares these files for you automatically. Training adapter versions After you have created an adapter and created training and testing datasets, you can train a version of that adapter using the CreateAdapterVersion operation. Create adapter version To customize the Amazon Textract base model to fit your specific use cases, create an adapter. After you create an adapter, you need to train the adapter. You can start training an adapter by calling the CreateAdapterVersion operation. You provide the operation with an AdapterId and use the DatasetConfig to specify an Amazon S3 bucket containing the dataset you want to train the adapter on. The manifest file you provide must follow a specific format. For more information, see Preparing training and testing datasets. You can also provide the operation with an optional KMSKeyId, optional ClientRequestToken, or any Tags to add to the adapter version. Running this operation requires the appropriate IAM permissions. For a sample IAM policy, see Permissions needed for CreateAdapterVersion. To create a new adapter version with the console: • Sign in to the Amazon Textract console. • Select Custom Queries from the left navigation panel. • From the list of Your adapters, select the adapter. • On the adapter details page, select Modify the dataset. • Select the Add documents dropdown menu and add documents to the training dataset. • On the following page, choose how to add your training documents (by S3 bucket or directly from your computer). • Choose Add documents to finish adding your documents to the dataset. • Wait until the auto-labeling is complete. Training adapter versions 289 Amazon Textract Developer Guide • Review the annotations by clicking Review Annotations. • Review each document, clicking “Submit and next”. • After you review all annotations, choose Train adapter to start training the new adapter. The number of successful trainings that can be performed per month is limited per AWS account. Refer to Set Quotas in Amazon Textract for more information regarding limits. To create an adapter version with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create a adapter: CLI aws textract create-adapter-version \ --adapter-id "012345678910" \ --dataset-config '{"ManifestS3Object":
textract-dg-063
textract-dg.pdf
63
annotations, choose Train adapter to start training the new adapter. The number of successful trainings that can be performed per month is limited per AWS account. Refer to Set Quotas in Amazon Textract for more information regarding limits. To create an adapter version with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create a adapter: CLI aws textract create-adapter-version \ --adapter-id "012345678910" \ --dataset-config '{"ManifestS3Object": {"Bucket":"amzn-s3-demo-source- bucket","Name":"test/sample-manifest.jsonl"}}' \ --output-config '{"S3Bucket": "amzn-s3-demo-destination-bucket", "S3Prefix": "prefix-string"}' Evaluating and improving your adapters Once you have finished the training process and created your adapter, it's important to evaluate how well the adapter is extracting information from your documents. Performance metrics Three metrics are provided in the Amazon Textract console to assist you in analyzing your adapter's performance: 1. Precision - Precision measures the percentage of extracted information (predictions) that are correct. The higher the precision rating, the fewer false positives there are. 2. Recall - Recall measures the percentage of total relevant items that are successfully identified and extracted by the model. The higher the recall value, the fewer false negatives there are. Evaluating and improving your adapters 290 Amazon Textract Developer Guide 3. F1 Score - The F1 score combines precision and recall into a single metric, providing a balanced measurement for overall extraction accuracy. The values for these measurements range from 0 to 1, with 1 being perfect extraction. These metrics are calculated by comparing the adapter's extractions to the "ground truth" annotations on the test set. By analyzing the F1, precision, and recall, you can determine where the adapter needs improvement. For example, low precision means many of the model’s predictions are false positives, therefore the adapter is extracting irrelevant data. In contrast, a low recall value means that the model is missing relevant data. Using these insights, you can refine the training data and retrain the adapter to increase performance. You can also check the performance of your model by testing it with new documents and queries that you specify. Use the Try Adapter option in the console to get predictions for these documents. This way, you can evaluate the adapter with your own test queries and documents and see real- world examples of how the adapter is performing. You can also retrieve metrics for an adapter version by using the GetAdapterVersion operation using an SDK or the CLI. Get a list of adapters that you want to retrieve metrics for by using the ListAdapterVersions API operation. Delete an adapter you no longer need with the DeleteAdapterVersion operation. Improving your model Adapter deployment is an iterative process, as you’ll likely need to retrain several times to reach your target level of accuracy. After you create and train your adapter, you’ll want to test and evaluate your adapter’s performance on various metrics and queries. If your adapter’s accuracy is lacking in any area, add new examples of those documents to increase the adapter’s performance for those queries. Try to provide the adapter with additional, varied examples that reflect the cases where it struggles. Providing your adapter with representative, varied documents enables it to handle diverse real-world examples. After adding new documents to your training set, retrain the adapter. Then re-evaluate on your test set and queries. Repeat this process until the adapter reaches your desired level of performance. Precision, recall, and F1 scores should gradually improve over successive training iterations. Evaluating and improving your adapters 291 Amazon Textract List adapter versions Developer Guide An Amazon Textract adapter can have a number of different versions associated with it. In order to see which adapter versions associated with a given adapter, you can call the ListAdapterVersions operation. The operation will return all versions of an adapter unless provided with filtering criteria using of the optional arguments such as AdapterId, AfterCreationTime, BeforeCreationTIme, Statuses, or MaxResults. To see a list of your adapter versions with the console: • Sign in to the Amazon Textract console. • Select Custom Queries from the left navigation panel. • From the list of your adapters, select the adapter. • View the adapter versions in the Adapter versions box. To create an adapter with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract list-adapter-versions Get an Adapter version You can retrieve configuration information and the current status of an adapter version by calling the GetAdapterVersion operation. When calling GetAdapterVersion, specify the AdapterId and the AdapterVersion. This
textract-dg-064
textract-dg.pdf
64
select the adapter. • View the adapter versions in the Adapter versions box. To create an adapter with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract list-adapter-versions Get an Adapter version You can retrieve configuration information and the current status of an adapter version by calling the GetAdapterVersion operation. When calling GetAdapterVersion, specify the AdapterId and the AdapterVersion. This returns information about the specified adapter version so that you can check the current operational status and configuration options. To see details for your adapter using the console: • Sign in to the Amazon Textract console. • Select Custom Queries from the left navigation panel. List adapter versions 292 Amazon Textract Developer Guide • From the list of your adapters, select the adapter. • Select the adapter version in the Adapter versions box. To see details for your adapter using the AWS CLI or AWS SDK • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract get-adapter-version \ --adapter-id "abcdef123456" \ --adapter-version "1" Delete adapter version You can delete an adapter version you’re no longer using by calling DeleteAdapterVersion. To delete an adapter version you provide the DeleteAdapterVersion operation with both the adapter’s AdapterId and the specific AdapterVersion that you want to delete. Note that you cannot delete adapter versions with an "IN_PROGRESS" status. To delete an adapter version with the console: • Sign in to the Amazon Textract console. • Select Custom Queries from the left navigation panel. • From the list of your adapters, select the adapter. • Select Delete and follow the instructions. • Select the adapter version that you want to delete from the list of versions in the Adapter versions box. • Select Delete and follow the instructions to delete your adapter. To delete an adapter with the AWS CLI or AWS SDK: Delete adapter version 293 Amazon Textract Developer Guide • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract delete-adapter-version \ --adapter-id "abcdef123456" \ --adapter-version "1" Debugging training failures If you are notified on the adapter details page that training has failed, refer to the status message to understand the error and correct it. There are two types of errors: creation errors and file errors. Some status messages are returned in the console, while others are displayed in a validation file. The validation file that is created alongside a training job contains information on the types of errors encountered when training. If the error message states that the error is a validation error ("Status message = Manifest file contains invalid records. Consult validation error file at OutputConfig path for more details."), refer to the validation file located in the S3 output bucket you chose during adapter training. The generated validation file is named validation_errors.jsonl. Each line in the file corresponds to a line in the manifest file, with errors yielded for each line in the manifest file that produces an error. The following is a list of all creation errors and possible causes: Error name CREATION_ERROR CREATION_ERROR Error description Manifest file contains invalid records. Consult validation error file at OutputConfig path for more details. No manifest file found. Ensure manifest file is provided. Debugging training failures 294 Amazon Textract CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR CREATION_ERROR Developer Guide Unable to access manifest file in specified S3 bucket. Manifest file located in an unsupported cross- Region S3 bucket. Contents of manifest file are empty. The manifest file size exceeds the maximum supported size. The manifest file has too many training documents. The manifest file has too many testing documents. The manifest file has too few training documents. The manifest file has too few testing documents. The manifest file has too few training, and testing documents. The manifest file has too many training, and testing documents. The manifest file has invalid encoding. Manifest file contains more training records than allowed limits. Manifest file contains more testing records than allowed limits. Unable to access the specified KMS key. Unable to access the S3 output bucket. Debugging training failures 295 Amazon Textract CREATION_ERROR Developer Guide Amazon Textract does not support cross-Reg ion Amazon S3 resources. The following is a list of file-related errors:
textract-dg-065
textract-dg.pdf
65
manifest file has too few training documents. The manifest file has too few testing documents. The manifest file has too few training, and testing documents. The manifest file has too many training, and testing documents. The manifest file has invalid encoding. Manifest file contains more training records than allowed limits. Manifest file contains more testing records than allowed limits. Unable to access the specified KMS key. Unable to access the S3 output bucket. Debugging training failures 295 Amazon Textract CREATION_ERROR Developer Guide Amazon Textract does not support cross-Reg ion Amazon S3 resources. The following is a list of file-related errors: Error name Error description ERROR_PAGE_COUNT_EXCEEDS_MAXIMUM ERROR_INVALID_FILE Number of pages for the same document exceeds maximum limit.(This happens when customer specified origin-ref and page_numb er in source-ref metadata.) The {source-ref|annotations-ref|prelabeling- refs} file(s) is invalid. Check S3 path and/or file properties. ERROR_INVALID_JSON_LINE The JSON line format is invalid ERROR_MANIFEST_JSON_DECODE_ERROR The record is not a valid JSON object. ERROR_DUPLICATE_SOURCE_REF A record with this source-ref already exists in the manifest. ERROR_IMAGE_TOO_LARGE The image resolution is too large. ERROR_INVALID_PAGE_COUNT The file is invalid. Expected number of pages to be 1. ERROR_INVALID_IMAGE Unsupported source reference file format. ERROR_INVALID_PDF Unsupported PDF file. ERROR_INVALID_PDF_PAGE_TOO_LARGE Unsupported PDF file. PDF page exceeds max dimensions. ERROR_INVALID_TIFF Unsupported TIFF file. ERROR_INVALID_TIFF_COMPRESSION Unsupported TIFF compression type. Debugging training failures 296 Amazon Textract Developer Guide ERROR_INVALID_ANNOTATIONS Invalid annotation or prelabeling file. ERROR_INVALID_ANNOTATIONS_FILE_FORMA T Invalid annotations file format. ERROR_MISSING_ANNOTATION_BLOCKS ERROR_INVALID_BLOCK ERROR_FILE_SIZE_LIMIT_EXCEEDED ERROR_INVALID_PERMISSIONS_DATASET_S3 _BUCKET Missing {PAGE|QUERY|QUERY_RESULT} block(s). Invalid {QUERY|QUERY_RESULT} block(s) found. The size of the {ref_file_type} file(s) exceeds the limit: {size_limit} MB. Unable to access the {ref_file_type} file(s). ERROR_FILE_NOT_FOUND The {ref_file_type} file(s) is not found. ERROR_FILE_NOT_FOUND_IN_REGION Amazon Textract does not support cross-Reg ion Amazon S3 resources. ERROR_QUERY_RESULT_TEXT_LENGTH_LIMIT _EXCEEDED QUERY_RESULT text length is greater than the maximum length. ERROR_QUERY_PER_PAGE_LIMIT_EXCEEDED Number of QUERY blocks is greater than the maximum allowed. ERROR_INVALID_DATA_FORMAT "Invalid data format in {filename}." ERROR_BLOCK_LIMIT_EXCEEDED "Number of {block_type} blocks is greater than the maximum allowed." ERROR_DUPLICATE_ORIGIN_REF_PAGE_NUMB ER_COMBINATION "A record with this origin-ref and page-number already exists in the manifest." ERROR_INVALID_BLOCK_RELATIONSHIP "Invalid block relationship(s) found." ERROR_DUPLICATED_BLOCK_ID "Blocks Id should be unique." Debugging training failures 297 Amazon Textract Developer Guide To see API error descriptions, see the Amazon Textract API Reference for the appropriate operation. If an error occurs when you try to create a new adapter with the CreateAdapterVersion operation, see the API Reference page. If an error occurs when using the Amazon Textract console, read the error pop-up for information on why the operation failed. Using Adapters during Inference After creating an adapter, you are provided with an ID and version for your custom adapter. You can provide this ID and version to AnalyzeDocument for synchronous document analysis, or the StartDocumentAnalysis operation for asynchronous analysis. Providing the Adapter ID will automatically integrate the adapter into the analysis process and use it to enhance predictions for your documents. This way, you can leverage the capabilities of AnalyzeDocument while customizing it to fit your needs. When multiple adapters must be applied to different pages in the same document, you can specify one or more adapter(s) and their respective adapter versions as part of the API request. You can use the Page parameter to specify which pages to apply an adapter to. This is similar to how the Page parameter for Queries works. Note the following: • If a page is not specified, it is set to ["1"] by default. • The following characters are valid in the parameter string: 1 2 3 4 5 6 7 8 9 - *. Blank spaces are not valid. • When using * to indicate all pages, it must be the only element in the list. • The Page parameter does not overlap across adapters. A page can only have one adapter applied to it. See the following example: AdaptersConfig={ 'Adapters': [ { 'AdapterId': ADAPTER_ID,'Version': '1', 'Pages': ["1-5"] }, { 'AdapterId': ADAPTER_ID, 'Version': '1', 'Pages':["6-*"] } ] }) Custom Queries tutorial This tutorial shows you how to create, train, evaluate, use, and manage adapters. Using Adapters during Inference 298 Amazon Textract Developer Guide With adapters, you can improve the accuracy of the Amazon Textract API operations, customizing the model’s behavior to fit your own needs and use cases. After you create an adapter with this tutorial, you can use it when analyzing your own documents with the AnalyzeDocumentAPI operation, and also retrain the adapter for future improvements. In this tutorial you’ll learn how to: • Create an adapter using the AWS Management Console. • Create a dataset for training your adapter. • Annotate your training data. • Train your adapter on your training dataset. • Review your adapter’s performance. • Retrain your adapter. • Use your adapter for document analysis. • Delete your adapter. Prerequisites Before you begin, we recommend that you read Creating adapters. You must also set up your AWS
textract-dg-066
textract-dg.pdf
66
adapter with this tutorial, you can use it when analyzing your own documents with the AnalyzeDocumentAPI operation, and also retrain the adapter for future improvements. In this tutorial you’ll learn how to: • Create an adapter using the AWS Management Console. • Create a dataset for training your adapter. • Annotate your training data. • Train your adapter on your training dataset. • Review your adapter’s performance. • Retrain your adapter. • Use your adapter for document analysis. • Delete your adapter. Prerequisites Before you begin, we recommend that you read Creating adapters. You must also set up your AWS account and install and configure an AWS SDK. For the SDK setup instructions, see Step 2: Set Up the AWS CLI and AWS SDKs. Create an adapter Before you can train or use an adapter you must create one. To create an adapter: 1. Sign in to the AWS Management Console and open the Amazon Textract console. 2. In the left pane, choose Custom Queries. The Amazon Textract Custom Queries landing page is shown. Prerequisites 299 Amazon Textract Developer Guide 3. The Custom Queries landing page show you a list of all your adapters, and there is also a button to create an adapter. Choose Create adapter to create your adapter. The number of successful trainings that can be performed per month is limited per AWS account. Refer to Set Quotas in Amazon Textract for more information regarding limits. 4. On the following page, enter the adapter name, choose whether to automatically update your adapter, and optionally add tags to it. Then, select Create adapter. When you choose 'auto- update' Amazon Textract will automatically update your adapter when the pretrained Queries feature is updated. After you create your adapter, you will be able to see the details for that adapter, including adapter name and the Adapter ID. The presence of these details verifies that the adapter has successfully been created. You can now create the datasets that will be used to train and test your adapter. Create an adapter 300 Amazon Textract Dataset creation Developer Guide In this step, you create a training dataset and a test dataset by uploading images from your local computer or from an Amazon S3 bucket. For more information about datasets, see Detecting Text Preparing training and testing datasets When uploading images from your local computer, you can upload up to 30 images at one time. If you have a large number of images to upload, consider creating the datasets by importing the images from an Amazon S3 bucket. 1. To start creating your dataset, choose your adapter from the list of adapters, and then choose Create dataset. 2. In the Dataset configuration section, choose either Manual split or Autosplit. With manual split, you can specify individual images as part of your training and testing datasets. If you choose Autosplit, it will define your training and testing sets automatically when you upload all of your images. Manual split is recommended for people who are training adapters for the first time. For now, choose Autosplit. Dataset creation 301 Amazon Textract Developer Guide 3. In the Training dataset details section, you can choose Upload documents from your computer or Import documents from S3 bucket. If you choose to import your documents from an Amazon S3 bucket, provide the path to the bucket and folder that contains your training images. If you upload your documents directly from your computer, note that you can only upload 30 documents at one time. For the purposes of this tutorial, choose Upload documents from your computer. 4. In the Test dataset details section, you can choose Upload documents from your computer or Import documents from S3 bucket. For the purposes of this tutorial, choose Upload documents from your computer. Dataset creation 302 Amazon Textract 5. Choose Create dataset. Developer Guide 6. After creating the dataset, you will be taken to a Dataset details page. The dataset details page shows you a list of all the documents in your entire dataset, and which part of the dataset (train or test) your document has been assigned to. View this under the Dataset assigned to column. You can also view the following: • Document name • Document status • Number of pages in the document • Document type • Document size • If the document is part of the training set or the testing set 7. Select Add documents to dataset and add at least five documents to both your training and testing datasets. If you previously selected Autosplit, you can add all the documents at once. 8. If you want to add more documents to your dataset, use the Add documents menu to do so. Before you can start training your adapter, you need to annotate your training documents with Queries. This is required
textract-dg-067
textract-dg.pdf
67
• Document status • Number of pages in the document • Document type • Document size • If the document is part of the training set or the testing set 7. Select Add documents to dataset and add at least five documents to both your training and testing datasets. If you previously selected Autosplit, you can add all the documents at once. 8. If you want to add more documents to your dataset, use the Add documents menu to do so. Before you can start training your adapter, you need to annotate your training documents with Queries. This is required to create the "annotations-ref" entries of your manifest file. After you add all your documents to the training or testing set, you can start the annotation process. Annotation and verification In this step, you assign Queries and labels to each document you uploaded to your training and test datasets. You link a Query to the relevant answers on a document page with the AWS Management Console annotation tool. To assign queries and answers to your documents: 1. Select Create queries from the Adapter landing page. 2. Add a query by entering it in the text box. Annotation and verification 303 Amazon Textract Developer Guide 3. To add more queries, choose Add new query. Queries can have a 'raw text' response or a 'binary - Yes/No' response. To created a query with a binary response use the advanced setting. 4. After creating your queries, you must assign labels to your documents. To set labels for your documents, select Auto-labeling or Manual labeling. Auto-labeling is recommended for your first time training the adapter. Select the Auto-labelling option, and then choose Start auto- labeling. Annotation and verification 304 Amazon Textract Developer Guide 5. The auto-labeling process will take some time to complete. When it's done, you're notified that “Auto-labeling is now completed.” After the labeling process is complete, you must verify the accuracy of the labeling. Select Verify documents in the Adapter details panel on the Details page, and then choose Start reviewing from the Dataset page. 6. In the annotation tool, you can select individual documents and view individual pages within those documents. Under the “Review responses” section, select a query that was assigned to your document page. If the answer to the query is incorrect, you can edit the response by clicking the Edit button for the query. Annotation and verification 305 Amazon Textract Developer Guide For queries with Yes/No answers, select Yes, No, or Empty. Then, choose Apply. When editing the OCR for the label assigned to a query, choose the provided response and then draw a bounding box around part of the document image. To do so, use the “B” shortcut key or the bounding box tool on the tool bar at the bottom of the annotation tool. Then, choose Apply. If a query should have more than one response element (answer), you can add additional responses. To do so, select the query and then choose Add a response. You are then prompted Annotation and verification 306 Amazon Textract Developer Guide to draw a bounding box on the area of the document that has the answer. Confirm that the label for your bounding box is correct. To add a new query for the document page, choose Add query. If you add a query, you must specify the query you want to add and then draw a bounding box for the query label. When you're done, choose Submit and next to proceed to the next document and the next set of queries and responses. Repeat until you review all of your queries and responses. After you review and evaluate all your queries and responses, select Submit and close. Training After you add all of your documents to the training set or the testing set and review the generated responses for your queries, you can train the adapter. Training 307 Amazon Textract To train the adapter: Developer Guide 1. Start by clicking Train adapter on the Dataset management page. 2. While initiating the training process, you can specify an Amazon S3 bucket that will contain the output of your adapter training job. If you specify an Amazon S3 bucket location that doesn’t exist yet, the bucket path will be created for you. You can also add tags to your adapter to track it, and customize your encryption settings. Customize the adapter training to fit your needs and then choose Train Adapter. 3. On the following page, choose Train Adapter to confirm that you want to start the training process. This will create your first version of your adapter. After the training process starts, you can monitor the training process status on the Adapter landing page. You're notified when the training process completes. Then, you can evaluate the adapter’s performance by inspecting
textract-dg-068
textract-dg.pdf
68
doesn’t exist yet, the bucket path will be created for you. You can also add tags to your adapter to track it, and customize your encryption settings. Customize the adapter training to fit your needs and then choose Train Adapter. 3. On the following page, choose Train Adapter to confirm that you want to start the training process. This will create your first version of your adapter. After the training process starts, you can monitor the training process status on the Adapter landing page. You're notified when the training process completes. Then, you can evaluate the adapter’s performance by inspecting metrics. Evaluating adapter performance To evaluate model performance, use the left navigation pane to select the adapter version to evaluate. Evaluating adapter performance 308 Amazon Textract Developer Guide By examining your adapter’s metrics, you can determine how your adapter is performing on the documents in your dataset and the queries you have defined. You can see the F1 Score, Precision, and Recall for your adapter across different elements of the training data: queries, documents, and pages. To switch between performance for these elements, choose the different tabs below the metrics display pane. You can also view baseline metrics at any time by toggling the Switch to baseline metrics switch. The summary of your adapter version’s performance also contains some tips on how to improve your adapter’s performance. You can review these tips at any time to improve your adapter. For more information about how to manage and improve your adapter, see Evaluating and improving your adapters. To demo your adapter and see its performance on a document: 1. Choose Try Adapter. 2. On the Try adapter page, you can choose a document to analyze with your adapter. Select the Choose document button and browse to the document’s location on your device. Alternatively, drag and drop the document into the Upload a document pane. Evaluating adapter performance 309 Amazon Textract Developer Guide After uploading a document, the Try Adapter page will update to display the results of the adapter’s analysis, including queries, query answers, and confidence levels. If you are satisfied with your adapter’s performance you can proceed to inference, using your adapter in a call to AnalyzeDocument or StartDocumentAnalysis . Otherwise, you can improve your adapter’s performance by retraining your adapter with additional documents. Improving an adapter To improve your adapter’s performance: 1. Choose Modify the dataset on the Adapter details page. 2. On the Dataset overview page, select Add documents. To retrain your adapter, add at least five more documents to the training dataset. 3. You are notified that the documents are added to the dataset. Select Start reviewing to review the results of the auto-labeling process. 4. Review the queries and responses. After you review and approve all the annotations for the documents you added, choose Submit and close. 5. On the dataset management page, choose Train adapter to start training your adapter on all of the data in your training dataset, including the new training documents. Every training job you run creates a new version of the adapter. Note the name of the new adapter version to be sure that you're evaluating the performance of the proper adapter version. Inference After creating an adapter, you are provided with an ID for your custom adapter. You can provide this ID to the AnalyzeDocument operation for synchronous document analysis, or the StartDocumentAnalysis operation for asynchronous analysis. Improving an adapter 310 Amazon Textract Developer Guide Providing the Adapter ID automatically integrates the adapter into the analysis process and uses it to enhance predictions for your documents. This way, you can leverage the capabilities of AnalyzeDocument while customizing it to fit your needs. For an example of how to run inference using your adapter and the AnalyzeDocument API operation, see Analyzing Document Text with Amazon Textract. When multiple adapters must be applied to different pages in the same document, you can specify one or more adapter(s) and their respective adapter versions as part of the API request. You can use the Page parameter to specify which pages to apply an adapter to. Note the following: This is similar to how the Page parameter for Queries works. Note the following: • If a page is not specified, it is set to ["1"] by default. • The following characters are valid in the parameter string: 1 2 3 4 5 6 7 8 9 - *. Blank spaces are not valid. • When using * to indicate all pages, it must be the only element in the list. • The Page parameter does not overlap across adapters. A page can only have one adapter applied to it. Adapter management The following steps are repeated iteratively (after initial training of your adapter): • Choose Modify the dataset on the Adapter details page of the
textract-dg-069
textract-dg.pdf
69
a page is not specified, it is set to ["1"] by default. • The following characters are valid in the parameter string: 1 2 3 4 5 6 7 8 9 - *. Blank spaces are not valid. • When using * to indicate all pages, it must be the only element in the list. • The Page parameter does not overlap across adapters. A page can only have one adapter applied to it. Adapter management The following steps are repeated iteratively (after initial training of your adapter): • Choose Modify the dataset on the Adapter details page of the Amazon Textract console. • Select Add documents. • Add at least five more documents to the training dataset to retrain your adapter. • You're notified that the documents have been added to the dataset. Select Start reviewing to review the results of the auto-labeling process. • Review the queries and responses. After you review and approve all the annotations for the new documents, select Train adapter. • Wait for the adapter to complete the new round of training, then check performance metrics for your new adapter version. Adapter management 311 Amazon Textract Developer Guide After you train your model to your target performance level, you can use your adapter for inference in your application. Be sure to delete adapter versions that you no longer need. To delete an adapter: • Go to the Adapters landing page, select the adapter, and choose Delete. • Type Delete into the text box, and then choose Delete. Copying adapters Adapter Versions can be copied from one AWS account to another within AWS Regions. In order to copy an adapter, you must have created an adapter in the destination AWS account using the Console or API. You are not required to train an adapter version, but the meta data (Adapter name and description) for the adapter must exist. This is to ensure you/your organization have access to the destination account. Note Your source and destination AWS accounts must be in the same AWS region to successfully copy an adapter. Please check the account regions before attempting to copy. Once you have created an adapter, submit a support ticket with the following details. You will need a support subscription before submitting the ticket: Region: xxx Source: AWS Account: Adapter ID: Adapter Version: Destination: AWS Account: Adapter ID: Copying adapters 312 Amazon Textract Developer Guide Once the adapter is copied over, you can use the destination adapter ID and version to make inference calls. You can test the inference API output using the same set of queries you used to train the source adapter. The destination adapter will return the same results as the source adapter. Copying adapters 313 Amazon Textract Developer Guide Best Practices Amazon Textract uses machine learning to read documents as a person would. It extracts text, tables, and forms from documents. Use the following best practices to get the best results from your documents. Provide an Optimal Input Document A suitable input for an Amazon Textract operation is a single or multipage document. Some examples are a legal document, a form, an ID, or a letter. A form is a document with questions or prompts for a user to provide answers. Some examples are a patient registration form, a tax form, or an insurance claim form. A document can be in JPEG, PNG, PDF, or TIFF format. With PDF and TIFF format files, you can process multipage documents. For information about how Amazon Textract represents documents as Block objects, see Text Detection and Document Analysis Response Objects. The following is an acceptable input document example. Provide an Optimal Input Document 314 Amazon Textract Developer Guide For information about document limits, see Quotas in Amazon Textract. For Amazon Textract synchronous operations, you can use input documents that are stored in an Amazon S3 bucket, or you can pass base64-encoded image bytes. For more information, see Calling Amazon Textract Synchronous Operations. For asynchronous operations, you need to supply input documents in an Amazon S3 bucket. For more information, see Calling Amazon Textract Asynchronous Operations. The following is a list of a few ways that you can optimize your input documents for better results. • Ensure that your document text is in a language that Amazon Textract supports. Currently, Amazon Textract supports English, Spanish, German, Italian, French, and Portuguese. Provide an Optimal Input Document 315 Amazon Textract Developer Guide • Provide a high quality image, ideally at least 150 DPI. • If your document is already in one of the file formats that Amazon Textract supports (PDF, TIFF, JPEG, and PNG), don't convert or downsample the document before uploading it to Amazon Textract. For the best results when extracting text from tables in documents, ensure that: • Tables in your document are visually separated from surrounding
textract-dg-070
textract-dg.pdf
70
that your document text is in a language that Amazon Textract supports. Currently, Amazon Textract supports English, Spanish, German, Italian, French, and Portuguese. Provide an Optimal Input Document 315 Amazon Textract Developer Guide • Provide a high quality image, ideally at least 150 DPI. • If your document is already in one of the file formats that Amazon Textract supports (PDF, TIFF, JPEG, and PNG), don't convert or downsample the document before uploading it to Amazon Textract. For the best results when extracting text from tables in documents, ensure that: • Tables in your document are visually separated from surrounding elements on the page. For example, the table isn't overlaid onto an image or complex pattern. • Text within the table is upright. For example, the text isn't rotated relative to other text on the page. When extracting text from tables, you might see inconsistent results when: • Merged table cells that span multiple columns. • Tables with cells, rows, or columns that are different from other parts of the same table. We recommend using text detection as a workaround. Use Confidence Scores You should take into account the confidence scores returned by Amazon Textract API operations and the sensitivity of their use case. A confidence score is a number between 0 and 100 that indicates the probability that a given prediction is correct. It helps you make informed decisions about how you use the results. In applications that are sensitive to detection errors (false positives), enforce a minimum confidence score threshold. The application should discard results below that threshold or flag situations as requiring a higher level of human scrutiny. The optimal threshold depends on the application. For archival purposes, such as documenting handwritten notes, it might be as low as 50%. Business processes involving financial decisions might require thresholds of 90% or higher. Use Confidence Scores 316 Amazon Textract Developer Guide Best Practices for Queries Example Queries Download the Example Queries document to see examples of queries for common document types across mortgage, insurance, healthcare and tax industries. General Best Practices for Queries Extracting Cells from Tables Construct a query that contains words from both row header and column header. Examples, for the image below Query 1: What date was the 2nd dose administered? Answer 1: 2/8/2021 Query 2: Who is the manufacturer of the 1st dose? Answer 2: Pfizer Extracting Tables using Queries Extraction of entire tables or whole rows or columns of information using queries is not supported. Long Answers Long answers increase response latency and can lead to timeouts. Try to ask questions that respond with answers to less than 100 words. Best Practices for Queries 317 Amazon Textract Passing Only Hints Developer Guide Passing only the the key name as the question will work when trying to extract standard key-value pairs from a form. We recommend framing full questions for all other extraction use cases. Examples, for the image below Query 1: Borrower's Name. Answer 1: Carlos Salazar Query 2: Social Security Number. Answer 2: 999-99-9999 General Phrasing of Questions Where possible, use words from the document to construct the query. • While Queries tries to do acronym / synonym matching for some common industry terms (SSN vs Tax ID vs Social Security Number), using language directly from the document will in general improve results. • Example: If the document says “job progress”, try to avoid calling it using other variations like “ project progress” or “program progress” or “job status” In general, ask a natural language question that starts with "What is / Where is / Who is..". The exception to this rule is when trying to extract standard key-value pairs in which case you can pass the key name as a query. Avoid ill-formed or grammatically incorrect questions since these could result in unexpected answers. • Example of ill-formed Query: When? Passing Only Hints 318 Amazon Textract Developer Guide • Example of well formed Query: When was the first vaccine dose administered? Be as specific as possible. Some examples follow. • When the document contains multiple sections (e. g. “Borrower” and “Co-Borrower”) and both sections have a field called SSN, ask: “What is the SSN for Borrower?” and “What is the SSN for Co-Borrower?” • When the document has multiple date related fields, be specific in the query language and ask “what is the date the document was signed on? or ”what is the the date of birth of the application“. Avoid asking ambiguous questions like ”What is the date?“ If you know the layout of the document beforehand, giving location hints improve accuracy of results. For example “What is the date at the top?” or ask “What is the date on the left?”, “What is the date at the bottom? Setting up Pages for Queries When working with queries for multipage
textract-dg-071
textract-dg.pdf
71
for Co-Borrower?” • When the document has multiple date related fields, be specific in the query language and ask “what is the date the document was signed on? or ”what is the the date of birth of the application“. Avoid asking ambiguous questions like ”What is the date?“ If you know the layout of the document beforehand, giving location hints improve accuracy of results. For example “What is the date at the top?” or ask “What is the date on the left?”, “What is the date at the bottom? Setting up Pages for Queries When working with queries for multipage documents, you can use the Page parameter to specify which pages to look for the query answer on. What follows is a list of best practices for setting up Pages • If a page is not specified, it is set to ["1"] by default. • The following characters are allowed in the parameter's string: 0 1 2 3 4 5 6 7 8 9 - *. No whitespace is allowed. • When using * to indicate all pages, it must be the only element in the list. • You can use page intervals, such as [“1-3”, “1-1”, “4-*”]. Where * indicates last page of document. • Specified pages must be greater than 0 and less than or equal to the number of pages in the document. Best Practices for Bulk Document Uploader The Bulk Document Uploader is an AWS Management Console tool intended to help you quickly evaluate how Textract performs on a set of your own documents, without the need to write any code. You can use the Bulk Document Uploader to process as many as 150 documents with one Setting up Pages for Queries 319 Amazon Textract Developer Guide of Textract’s features, instead of uploading and processing documents individually. You can bulk- upload documents directly from your computer or import documents from an existing Amazon S3 bucket. The Bulk Document Uploader provides results that you can download later for offline review. Each downloadable zip file contains both the Textract JSON API response file and human-readable CSV files of the output. The output results are available for download for 7 days after processing. After 14 days, documents are cleared from the Submitted Documents panel. To use the Bulk Document Uploader, follow these steps: 1. 2. 3. 4. Log in to the AWS Management Console and go to the Amazon Textract console. Select the Bulk Document Uploader from the navigation pane. Select the Upload Documents button. Specify the source of your documents. a. If you are using an Amazon S3 bucket for your documents, provide the S3 URL for the bucket and folder. If the folder you specified contains more than 150 documents, then only the top 150 documents listed in the S3 folder will be sent to Textract for processing. b. If you are uploading documents from your local device, you can upload up to 50 documents at one time. To upload additional documents (up to the maximum of 150), click the Add Documents button after your initial documents are uploaded. When uploading documents from your computer, your documents are uploaded to an Amazon S3 bucket that is created on your behalf. In the future, you can use the path to this S3 bucket to process the same set of documents . 5. Specify the Textract feature you want to use to process your documents. Select one Textract feature at a time to process your documents. You must create a separate request if you want to test more than one feature on your documents. If you select the “AnalyzeDocument - Queries” feature, write the Queries you want to test against your documents. Queries are only applied to the first page of each uploaded document. Consult the Queries Best Practices section when constructing your queries. 6. Select the Start Processing button to submit the documents to Textract for processing. 7. You can track document status and download the output results of processed documents in the Submitted Documents panel. After documents are submitted to Textract for processing, they are displayed as a list in the Submitted Documents panel. Each document is processed Best Practices for Bulk Document Uploader 320 Amazon Textract Developer Guide individually. The following information is displayed for each document: Name, Status, Upload Date, Document Type, Textract Feature, and Size. The Submitted Documents panel updates periodically, and you can manually refresh it to see if your processing is complete. Limits The following limits apply when using the Bulk Document Uploader • Accepted File Formats: JPEG, PNG, PDF, and TIFF files. (JPEG 2000-encoded images within PDFs are supported) • File Size and Page Count Limits: JPEG and PNG files have a 10 MB size limit. PDF and TIFF files have a 500 MB limit. • PDF and TIFF files have
textract-dg-072
textract-dg.pdf
72
Developer Guide individually. The following information is displayed for each document: Name, Status, Upload Date, Document Type, Textract Feature, and Size. The Submitted Documents panel updates periodically, and you can manually refresh it to see if your processing is complete. Limits The following limits apply when using the Bulk Document Uploader • Accepted File Formats: JPEG, PNG, PDF, and TIFF files. (JPEG 2000-encoded images within PDFs are supported) • File Size and Page Count Limits: JPEG and PNG files have a 10 MB size limit. PDF and TIFF files have a 500 MB limit. • PDF and TIFF files have a limit of 3,000 pages. • Up to 150 documents can be processed for each bulk processing request. To process more than 150 documents, submit multiple requests of up to 150 documents each by using the Bulk Document Uploader. • The AnalyzeLending and AnalyzeID API operations are not supported by the Bulk Document Uploader. • The Bulk Document Uploader incurs the same charges as regular Textract usage. For more information on Textract pricing, see here. Best practices for Amazon Textract Custom Queries Amazon Textract lets you customize the output of its pretrained Queries feature by training and using an adapter for its base model. With Amazon Textract Custom Queries, you can use your own documents and train an adapter to customize the base model, while keeping control over your proprietary documents. When creating queries for your adapters, use the following best practices. For more information about adapters, see Customizing your Queries Responses. 1. The sample data should contain layout variations and image variations that are representative of the documents to be used in production. 2. A minimum of five samples (per query level) are required for either training or testing. The more samples used for training, the better. Limits 321 Amazon Textract Developer Guide 3. The annotated Queries should have a variety of answers. For example, if the answer to a query is 'Yes' or 'No,' the annotated samples should have occurrences of both 'Yes' and 'No,' 4. Composed queries should have logical meanings and structures. For example, to extract a payee name on the check, the query should be ‘Who is the payee?’ and not ‘What is the name?’. 5. If a value that needs to be extracted has an associated key, include the key in the query for better results. If there are keys that occur multiple times, use hierarchical questions such as ‘What is the first name under borrower?’ and ‘What is the first name under co-borrower?’ 6. Maintain consistency in annotation style. If a field appears in multiple places on a document and you decide to annotate only one occurrence, follow the same guideline and annotate only one occurrence in all documents. Alternatively, if you choose to annotate all occurrences of a value, follow the same process for all documents. 7. Maintain consistency while annotating fields with spaces. If a field's value is ‘123 456 78’ and if you choose to annotate it as ‘12345678’ follow the same guideline for all documents. Do not change between annotating the value as ‘123 456 78’ and ‘12345678.’ 8. Annotate the data across all pages within a document even though you might run inference on only a few of the pages. If annotating all the pages is not feasible, split the document and use only the pages that you are able to annotate in your dataset. 9. Custom Queries does not support questions related to signatures (such as, 'Is the document signed?'). To know if a document is signed, use the signatures feature in your API request. 10.When correcting responses from pre-labeling, you can make small modifications to the text presented in the documents, such as correcting a few character errors, or removing spaces and punctuation. But if text isn't shown in the documents, don't enter it as a response. 11.Use the exact query used in training for inference. 12.Provide pre-labeling results only for the source-ref page. If you have pre-labeling results with Blocks that aren't from the source-ref page, it might impact performance. Best practices for Amazon Textract Custom Queries 322 Amazon Textract Developer Guide Handling Connection Errors An Amazon Textract operation can fail if you exceed the maximum number of transactions per second (TPS), causing the service to throttle your application, or when your connection drops. For example, if you make too many calls to Amazon Textract operations in a short period of time, it throttles your calls and sends a ProvisionedThroughputExceededException error in the operation response. For information about Amazon Textract TPS quotas, see Amazon Textract Quotas. To change a limit, you can access the Amazon Textract option in the Service Quotas console. You can manage throttling and dropped connections by automatically retrying the operation. You can specify the number of retries by including the Config
textract-dg-073
textract-dg.pdf
73
maximum number of transactions per second (TPS), causing the service to throttle your application, or when your connection drops. For example, if you make too many calls to Amazon Textract operations in a short period of time, it throttles your calls and sends a ProvisionedThroughputExceededException error in the operation response. For information about Amazon Textract TPS quotas, see Amazon Textract Quotas. To change a limit, you can access the Amazon Textract option in the Service Quotas console. You can manage throttling and dropped connections by automatically retrying the operation. You can specify the number of retries by including the Config parameter when you create the Amazon Textract client. We recommend a retry count of 5. The AWS SDK retries an operation the specified number of times before failing and throwing an exception. For more information, see Error Retries and Exponential Backoff in AWS. Note Automatic retries work for both synchronous and asynchronous operations. Before specifying automatic retries, make sure you have the most recent version of the AWS SDK. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. The following example shows how to automatically retry Amazon Textract operations when you're processing multiple documents. Prerequisites • If you haven't already: a. Give a user the AmazonTextractFullAccess and AmazonS3ReadOnlyAccess permissions. For more information, see Step 1: Set Up an AWS Account and Create a User. b. Install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. 323 Amazon Textract Developer Guide To automatically retry operations 1. Upload multiple document images to your S3 bucket to run the Synchronous example. Upload a multi-page document to your S3 bucket and run StartDocumentTextDetection on it to run the Asynchronous example. For instructions, see Uploading Objects into Amazon S3 in the Amazon Simple Storage Service User Guide. 2. The following examples demonstrate how to use the Config parameter to automatically retry an operation. The Synchronous example calls the DetectDocumentText operation, while the Asynchronous example calls the GetDocumentTextDetection operation. Sync Example Use the following examples to call the DetectDocumentText operation on the documents in your Amazon S3 bucket. In main, change the value of bucket to your S3 bucket. Change the value of documents to the names of the document images that you uploaded in step 2. import boto3 from botocore.client import Config # Documents def process_multiple_documents(bucket, documents): config = Config(retries = dict(max_attempts = 5)) # Amazon Textract client textract = boto3.client('textract', config=config) for documentName in documents: print("\nProcessing: {}\n==========================================".format(documentName)) # Call Amazon Textract response = textract.detect_document_text( Document={ 'S3Object': { 'Bucket': bucket, 'Name': documentName 324 Amazon Textract Developer Guide } }) # Print detected text for item in response["Blocks"]: if item["BlockType"] == "LINE": print ('\033[94m' + item["Text"] + '\033[0m') def main(): bucket = "" documents = ["document-image-1.png", "document-image-2.png", "document-image-3.png", "document-image-4.png", "document-image-5.png" ] process_multiple_documents(bucket, documents) if __name__ == "__main__": main() Async Example Use the following examples to call the GetDocumentTextDetection operation. It assumes you have already called StartDocumentTextDetection on the documents in your Amazon S3 bucket and obtained a JobId. In main, change the value of bucket to your S3 bucket and the value of roleArn to the Arn assigned to your Textract role. You'll also need to change the value of document to the name of your multi-page document in your Amazon S3 bucket. Finally, replace the value of region_name with the name of your region and provide the GetResults function with the name of your jobId. import boto3 from botocore.client import Config class DocumentProcessor: jobId = '' region_name = '' roleArn = '' bucket = '' document = '' 325 Amazon Textract Developer Guide sqsQueueUrl = '' snsTopicArn = '' processType = '' def __init__(self, role, bucket, document, region): self.roleArn = role self.bucket = bucket self.document = document self.region_name = region self.config = Config(retries = dict(max_attempts = 5)) self.textract = boto3.client('textract', region_name=self.region_name, config=self.config) self.sqs = boto3.client('sqs') self.sns = boto3.client('sns') # Display information about a block def DisplayBlockInfo(self, block): print("Block Id: " + block['Id']) print("Type: " + block['BlockType']) if 'EntityTypes' in block: print('EntityTypes: {}'.format(block['EntityTypes'])) if 'Text' in block: print("Text: " + block['Text']) if block['BlockType'] != 'PAGE': print("Confidence: " + "{:.2f}".format(block['Confidence']) + "%") print('Page: {}'.format(block['Page'])) if block['BlockType'] == 'CELL': print('Cell Information') print('\tColumn: {} '.format(block['ColumnIndex'])) print('\tRow: {}'.format(block['RowIndex'])) print('\tColumn span: {} '.format(block['ColumnSpan'])) print('\tRow span: {}'.format(block['RowSpan'])) if 'Relationships' in block: print('\tRelationships: {}'.format(block['Relationships'])) print('Geometry') print('\tBounding Box: {}'.format(block['Geometry']['BoundingBox'])) 326 Amazon Textract Developer Guide print('\tPolygon: {}'.format(block['Geometry']['Polygon'])) if block['BlockType'] == 'SELECTION_ELEMENT': print(' Selection element detected: ', end='') if block['SelectionStatus'] == 'SELECTED': print('Selected') else: print('Not selected') def GetResults(self, jobId): maxResults = 1000 paginationToken = None finished = False while finished == False: response = None if paginationToken == None: response = self.textract.get_document_text_detection(JobId=jobId, MaxResults=maxResults) else: response = self.textract.get_document_text_detection(JobId=jobId, MaxResults=maxResults, NextToken=paginationToken) blocks = response['Blocks'] print('Detected Document Text') print('Pages: {}'.format(response['DocumentMetadata']['Pages'])) # Display block information for block in blocks: self.DisplayBlockInfo(block) print()
textract-dg-074
textract-dg.pdf
74
print('Cell Information') print('\tColumn: {} '.format(block['ColumnIndex'])) print('\tRow: {}'.format(block['RowIndex'])) print('\tColumn span: {} '.format(block['ColumnSpan'])) print('\tRow span: {}'.format(block['RowSpan'])) if 'Relationships' in block: print('\tRelationships: {}'.format(block['Relationships'])) print('Geometry') print('\tBounding Box: {}'.format(block['Geometry']['BoundingBox'])) 326 Amazon Textract Developer Guide print('\tPolygon: {}'.format(block['Geometry']['Polygon'])) if block['BlockType'] == 'SELECTION_ELEMENT': print(' Selection element detected: ', end='') if block['SelectionStatus'] == 'SELECTED': print('Selected') else: print('Not selected') def GetResults(self, jobId): maxResults = 1000 paginationToken = None finished = False while finished == False: response = None if paginationToken == None: response = self.textract.get_document_text_detection(JobId=jobId, MaxResults=maxResults) else: response = self.textract.get_document_text_detection(JobId=jobId, MaxResults=maxResults, NextToken=paginationToken) blocks = response['Blocks'] print('Detected Document Text') print('Pages: {}'.format(response['DocumentMetadata']['Pages'])) # Display block information for block in blocks: self.DisplayBlockInfo(block) print() print() if 'NextToken' in response: paginationToken = response['NextToken'] else: 327 Amazon Textract Developer Guide finished = True def main(): roleArn = 'role-arn' bucket = 'bucket-name' document = 'document-name' region_name = 'region-name' analyzer = DocumentProcessor(roleArn, bucket, document, region_name) analyzer.GetResults("job-id") if __name__ == "__main__": main() 328 Amazon Textract Tutorials Developer Guide the section called “Block” objects that are returned from Amazon Textract operations contain the results of text detection and text analysis operations, such as the section called “AnalyzeDocument”. The following Python tutorials show some of the different ways that you can use Block objects. For example, you can export table information to a comma-separated values (CSV) file. The tutorials use synchronous Amazon Textract operations that return all results. If you want to use asynchronous operations such as the section called “StartDocumentAnalysis”, you need to change the example code to accommodate multiple batches of returned Block objects. To make use of the asynchronous operations example, ensure that you have followed the instructions given at Configuring Amazon Textract for Asynchronous Operations. For examples that show you other ways to use Amazon Textract, see Additional Code Samples. Topics • Prerequisites • Extracting Key-Value Pairs from a Form Document • Exporting Tables into a CSV File • Detecting text with an AWS Lambda function • Extracting and Sending Text to AWS Comprehend for Analysis • Additional Code Samples Prerequisites Before you can run the examples in this section, you have to configure your environment. To configure your environment 1. Give a user the AmazonTextractFullAccess permissions. For more information, see Step 1: Set Up an AWS Account and Create a User. 2. Install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. Prerequisites 329 Amazon Textract Developer Guide Extracting Key-Value Pairs from a Form Document The following Python example shows how to extract key-value pairs in form documents from the section called “Block” objects that are stored in a map. Block objects are returned from a call to the section called “AnalyzeDocument”. For more information, see Form Data (Key-Value Pairs). You use the following functions: • get_kv_map – Calls AnalyzeDocument, and stores the KEY and VALUE BLOCK objects in a map. • get_kv_relationship and find_value_block – Constructs the key-value relationships from the map. To extract key-value pairs from a form document 1. Configure your environment. For more information, see Prerequisites. 2. Save the following example code to a file named textract_python_kv_parser.py. In the function get_kv_map, replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. import boto3 import sys import re import json from collections import defaultdict def get_kv_map(file_name): with open(file_name, 'rb') as file: img_test = file.read() bytes_test = bytearray(img_test) print('Image loaded', file_name) # process using image bytes session = boto3.Session(profile_name='profile-name') client = session.client('textract', region_name='region') response = client.analyze_document(Document={'Bytes': bytes_test}, FeatureTypes=['FORMS']) # Get the text blocks blocks = response['Blocks'] Extracting Key-Value Pairs from a Form Document 330 Amazon Textract Developer Guide # get key and value maps key_map = {} value_map = {} block_map = {} for block in blocks: block_id = block['Id'] block_map[block_id] = block if block['BlockType'] == "KEY_VALUE_SET": if 'KEY' in block['EntityTypes']: key_map[block_id] = block else: value_map[block_id] = block return key_map, value_map, block_map def get_kv_relationship(key_map, value_map, block_map): kvs = defaultdict(list) for block_id, key_block in key_map.items(): value_block = find_value_block(key_block, value_map) key = get_text(key_block, block_map) val = get_text(value_block, block_map) kvs[key].append(val) return kvs def find_value_block(key_block, value_map): for relationship in key_block['Relationships']: if relationship['Type'] == 'VALUE': for value_id in relationship['Ids']: value_block = value_map[value_id] return value_block def get_text(result, blocks_map): text = '' if 'Relationships' in result: for relationship in result['Relationships']: if relationship['Type'] == 'CHILD': for child_id in relationship['Ids']: word = blocks_map[child_id] if word['BlockType'] == 'WORD': text += word['Text'] + ' ' Extracting Key-Value Pairs from a Form Document 331 Amazon Textract Developer Guide if word['BlockType'] == 'SELECTION_ELEMENT': if word['SelectionStatus'] == 'SELECTED': text += 'X ' return text def print_kvs(kvs): for key, value in kvs.items(): print(key, ":", value) def search_value(kvs, search_key): for key, value in kvs.items(): if re.search(search_key, key, re.IGNORECASE): return value def main(file_name): key_map, value_map, block_map = get_kv_map(file_name) # Get Key Value relationship kvs = get_kv_relationship(key_map, value_map, block_map) print("\n\n== FOUND KEY
textract-dg-075
textract-dg.pdf
75
'' if 'Relationships' in result: for relationship in result['Relationships']: if relationship['Type'] == 'CHILD': for child_id in relationship['Ids']: word = blocks_map[child_id] if word['BlockType'] == 'WORD': text += word['Text'] + ' ' Extracting Key-Value Pairs from a Form Document 331 Amazon Textract Developer Guide if word['BlockType'] == 'SELECTION_ELEMENT': if word['SelectionStatus'] == 'SELECTED': text += 'X ' return text def print_kvs(kvs): for key, value in kvs.items(): print(key, ":", value) def search_value(kvs, search_key): for key, value in kvs.items(): if re.search(search_key, key, re.IGNORECASE): return value def main(file_name): key_map, value_map, block_map = get_kv_map(file_name) # Get Key Value relationship kvs = get_kv_relationship(key_map, value_map, block_map) print("\n\n== FOUND KEY : VALUE pairs ===\n") print_kvs(kvs) # Start searching a key value while input('\n Do you want to search a value for a key? (enter "n" for exit) ') != 'n': search_key = input('\n Enter a search key:') print('The value is:', search_value(kvs, search_key)) if __name__ == "__main__": file_name = sys.argv[1] main(file_name) 3. At the command prompt, enter the following command. Replace file with the document image file that you want to analyze. python textract_python_kv_parser.py file 4. When you're prompted, enter a key that's in the input document. If the code detects the key, it displays the key's value. Extracting Key-Value Pairs from a Form Document 332 Amazon Textract Developer Guide Exporting Tables into a CSV File These Python examples show how to export tables from an image of a document into a comma- separated values (CSV) file. The example for synchronous document analysis collects table information from a call to the section called “AnalyzeDocument”. The example for asynchronous document analysis makes a call to the section called “StartDocumentAnalysis” and then retrives the results from the section called “GetDocumentAnalysis” as Block objects. Table information is returned as the section called “Block” objects from a call to the section called “AnalyzeDocument”. For more information, see Tables. The Block objects are stored in a map structure that's used to export the table data into a CSV file. Synchronous In this example, you will use the functions: • get_table_csv_results – Calls AnalyzeDocument, and builds a map of tables that are detected in the document. Creates a CSV representation of all detected tables. • generate_table_csv – Generates the CSV file for an individual table. • get_rows_columns_map – Gets the rows and columns from the map. • get_text – Gets the text from a cell. To export tables into a CSV file 1. Configure your environment. For more information, see Prerequisites. 2. Save the following example code to a file named textract_python_table_parser.py. In the function get_table_csv_results, replace profile-name with the name of a profile that can assume the role and region with the region in which you want to run the code. import webbrowser, os import json import boto3 import io from io import BytesIO import sys from pprint import pprint Exporting Tables into a CSV File 333 Amazon Textract Developer Guide def get_rows_columns_map(table_result, blocks_map): rows = {} scores = [] for relationship in table_result['Relationships']: if relationship['Type'] == 'CHILD': for child_id in relationship['Ids']: cell = blocks_map[child_id] if cell['BlockType'] == 'CELL': row_index = cell['RowIndex'] col_index = cell['ColumnIndex'] if row_index not in rows: # create new row rows[row_index] = {} # get confidence score scores.append(str(cell['Confidence'])) # get the text value rows[row_index][col_index] = get_text(cell, blocks_map) return rows, scores def get_text(result, blocks_map): text = '' if 'Relationships' in result: for relationship in result['Relationships']: if relationship['Type'] == 'CHILD': for child_id in relationship['Ids']: word = blocks_map[child_id] if word['BlockType'] == 'WORD': if "," in word['Text'] and word['Text'].replace(",", "").isnumeric(): text += '"' + word['Text'] + '"' + ' ' else: text += word['Text'] + ' ' if word['BlockType'] == 'SELECTION_ELEMENT': if word['SelectionStatus'] =='SELECTED': text += 'X ' return text def get_table_csv_results(file_name): Exporting Tables into a CSV File 334 Amazon Textract Developer Guide with open(file_name, 'rb') as file: img_test = file.read() bytes_test = bytearray(img_test) print('Image loaded', file_name) # process using image bytes # get the results session = boto3.Session(profile_name='profile-name') client = session.client('textract', region_name='region') response = client.analyze_document(Document={'Bytes': bytes_test}, FeatureTypes=['TABLES']) # Get the text blocks blocks=response['Blocks'] pprint(blocks) blocks_map = {} table_blocks = [] for block in blocks: blocks_map[block['Id']] = block if block['BlockType'] == "TABLE": table_blocks.append(block) if len(table_blocks) <= 0: return "<b> NO Table FOUND </b>" csv = '' for index, table in enumerate(table_blocks): csv += generate_table_csv(table, blocks_map, index +1) csv += '\n\n' return csv def generate_table_csv(table_result, blocks_map, table_index): rows, scores = get_rows_columns_map(table_result, blocks_map) table_id = 'Table_' + str(table_index) # get cells. csv = 'Table: {0}\n\n'.format(table_id) for row_index, cols in rows.items(): for col_index, text in cols.items(): col_indices = len(cols.items()) Exporting Tables into a CSV File 335 Amazon Textract Developer Guide csv += '{}'.format(text) + "," csv += '\n' csv += '\n\n Confidence Scores % (Table Cell) \n' cols_count = 0 for score in scores: cols_count += 1 csv += score + "," if cols_count == col_indices: csv += '\n' cols_count = 0 csv += '\n\n\n' return csv def main(file_name):
textract-dg-076
textract-dg.pdf
76
+1) csv += '\n\n' return csv def generate_table_csv(table_result, blocks_map, table_index): rows, scores = get_rows_columns_map(table_result, blocks_map) table_id = 'Table_' + str(table_index) # get cells. csv = 'Table: {0}\n\n'.format(table_id) for row_index, cols in rows.items(): for col_index, text in cols.items(): col_indices = len(cols.items()) Exporting Tables into a CSV File 335 Amazon Textract Developer Guide csv += '{}'.format(text) + "," csv += '\n' csv += '\n\n Confidence Scores % (Table Cell) \n' cols_count = 0 for score in scores: cols_count += 1 csv += score + "," if cols_count == col_indices: csv += '\n' cols_count = 0 csv += '\n\n\n' return csv def main(file_name): table_csv = get_table_csv_results(file_name) output_file = 'output.csv' # replace content with open(output_file, "wt") as fout: fout.write(table_csv) # show the results print('CSV OUTPUT FILE: ', output_file) if __name__ == "__main__": file_name = sys.argv[1] main(file_name) 3. At the command prompt, enter the following command. Replace file with the name of the document image file that you want to analyze. python textract_python_table_parser.py file When you run the example, the CSV output is saved in a file named output.csv. Asynchronous In this example, you will use make use of two different scripts. The first script starts the process of asynchronoulsy analyzing documents with StartDocumentAnalysis and gets the Block Exporting Tables into a CSV File 336 Amazon Textract Developer Guide information returned by GetDocumentAnalysis. The second script takes the returned Block information for each page, formats the data as a table, and saves the tables to a CSV file. To export tables into a CSV file 1. Configure your environment. For more information, see Prerequisites. 2. 3. Ensure that you have followed the instructions given at see Configuring Amazon Textract for Asynchronous Operations. The process documented on that page enables you to send and receive messages about the completion status of asynchronous jobs. In the following code example, replace the value of roleArn with the Arn assigned to the role that you created in Step 2. Replace the value of bucket with the name of the S3 bucket containing your document. Replace the value of document with the name of the document in your S3 bucket. Replace the value of region_name with the name of your bucket's region. Save the following example code to a file named start_doc_analysis_for_table_extraction.py.. import boto3 import time class DocumentProcessor: jobId = '' region_name = '' roleArn = '' bucket = '' document = '' sqsQueueUrl = '' snsTopicArn = '' processType = '' def __init__(self, role, bucket, document, region): self.roleArn = role self.bucket = bucket self.document = document self.region_name = region self.textract = boto3.client('textract', region_name=self.region_name) Exporting Tables into a CSV File 337 Amazon Textract Developer Guide self.sqs = boto3.client('sqs') self.sns = boto3.client('sns') def ProcessDocument(self): jobFound = False response = self.textract.start_document_analysis(DocumentLocation={'S3Object': {'Bucket': self.bucket, 'Name': self.document}}, FeatureTypes=["TABLES", "FORMS"], NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn}) print('Processing type: Analysis') print('Start Job Id: ' + response['JobId']) print('Done!') def CreateTopicandQueue(self): millis = str(int(round(time.time() * 1000))) # Create SNS topic snsTopicName = "AmazonTextractTopic" + millis topicResponse = self.sns.create_topic(Name=snsTopicName) self.snsTopicArn = topicResponse['TopicArn'] # create SQS queue sqsQueueName = "AmazonTextractQueue" + millis self.sqs.create_queue(QueueName=sqsQueueName) self.sqsQueueUrl = self.sqs.get_queue_url(QueueName=sqsQueueName) ['QueueUrl'] attribs = self.sqs.get_queue_attributes(QueueUrl=self.sqsQueueUrl, AttributeNames=['QueueArn']) ['Attributes'] sqsQueueArn = attribs['QueueArn'] # Subscribe SQS queue to SNS topic self.sns.subscribe(TopicArn=self.snsTopicArn, Protocol='sqs', Endpoint=sqsQueueArn) Exporting Tables into a CSV File 338 Amazon Textract Developer Guide # Authorize SNS to write SQS queue policy = """{{ "Version":"2012-10-17", "Statement":[ {{ "Sid":"MyPolicy", "Effect":"Allow", "Principal" : {{"AWS" : "*"}}, "Action":"SQS:SendMessage", "Resource": "{}", "Condition":{{ "ArnEquals":{{ "aws:SourceArn": "{}" }} }} }} ] }}""".format(sqsQueueArn, self.snsTopicArn) response = self.sqs.set_queue_attributes( QueueUrl=self.sqsQueueUrl, Attributes={ 'Policy': policy }) def main(): roleArn = 'role-arn' bucket = 'bucket-name' document = 'document-name' region_name = 'region-name' analyzer = DocumentProcessor(roleArn, bucket, document, region_name) analyzer.CreateTopicandQueue() analyzer.ProcessDocument() if __name__ == "__main__": main() 4. Run the code. The code will print a JobId. Copy this JobId down. 5. Wait for your job to finish processing, and after it has finished, copy the following code to a file named get_doc_analysis_for_table_extraction.py. Replace the value of jobId with the Job ID you copied down earlier. Replace the value of region_name with the name of the Exporting Tables into a CSV File 339 Amazon Textract Developer Guide region associated with your Textract role. Replace the value of file_name with the name you want to give the output CSV. import boto3 from pprint import pprint jobId = '' region_name = '' file_name = '' textract = boto3.client('textract', region_name=region_name) # Display information about a block def DisplayBlockInfo(block): print("Block Id: " + block['Id']) print("Type: " + block['BlockType']) if 'EntityTypes' in block: print('EntityTypes: {}'.format(block['EntityTypes'])) if 'Text' in block: print("Text: " + block['Text']) if block['BlockType'] != 'PAGE': print("Confidence: " + "{:.2f}".format(block['Confidence']) + "%") def GetResults(jobId, file_name): maxResults = 1000 paginationToken = None finished = False while finished == False: response = None if paginationToken == None: response = textract.get_document_analysis(JobId=jobId, MaxResults=maxResults) else: response = textract.get_document_analysis(JobId=jobId, MaxResults=maxResults, NextToken=paginationToken) Exporting Tables into a CSV File 340 Amazon Textract Developer Guide blocks = response['Blocks']
textract-dg-077
textract-dg.pdf
77
= '' region_name = '' file_name = '' textract = boto3.client('textract', region_name=region_name) # Display information about a block def DisplayBlockInfo(block): print("Block Id: " + block['Id']) print("Type: " + block['BlockType']) if 'EntityTypes' in block: print('EntityTypes: {}'.format(block['EntityTypes'])) if 'Text' in block: print("Text: " + block['Text']) if block['BlockType'] != 'PAGE': print("Confidence: " + "{:.2f}".format(block['Confidence']) + "%") def GetResults(jobId, file_name): maxResults = 1000 paginationToken = None finished = False while finished == False: response = None if paginationToken == None: response = textract.get_document_analysis(JobId=jobId, MaxResults=maxResults) else: response = textract.get_document_analysis(JobId=jobId, MaxResults=maxResults, NextToken=paginationToken) Exporting Tables into a CSV File 340 Amazon Textract Developer Guide blocks = response['Blocks'] table_csv = get_table_csv_results(blocks) output_file = file_name + ".csv" # replace content with open(output_file, "at") as fout: fout.write(table_csv) # show the results print('Detected Document Text') print('Pages: {}'.format(response['DocumentMetadata']['Pages'])) print('OUTPUT TO CSV FILE: ', output_file) # Display block information for block in blocks: DisplayBlockInfo(block) print() print() if 'NextToken' in response: paginationToken = response['NextToken'] else: finished = True def get_rows_columns_map(table_result, blocks_map): rows = {} for relationship in table_result['Relationships']: if relationship['Type'] == 'CHILD': for child_id in relationship['Ids']: try: cell = blocks_map[child_id] if cell['BlockType'] == 'CELL': row_index = cell['RowIndex'] col_index = cell['ColumnIndex'] if row_index not in rows: # create new row rows[row_index] = {} # get the text value rows[row_index][col_index] = get_text(cell, blocks_map) except KeyError: print("Error extracting Table data - {}:".format(KeyError)) pass return rows Exporting Tables into a CSV File 341 Amazon Textract Developer Guide def get_text(result, blocks_map): text = '' if 'Relationships' in result: for relationship in result['Relationships']: if relationship['Type'] == 'CHILD': for child_id in relationship['Ids']: try: word = blocks_map[child_id] if word['BlockType'] == 'WORD': text += word['Text'] + ' ' if word['BlockType'] == 'SELECTION_ELEMENT': if word['SelectionStatus'] == 'SELECTED': text += 'X ' except KeyError: print("Error extracting Table data - {}:".format(KeyError)) return text def get_table_csv_results(blocks): pprint(blocks) blocks_map = {} table_blocks = [] for block in blocks: blocks_map[block['Id']] = block if block['BlockType'] == "TABLE": table_blocks.append(block) if len(table_blocks) <= 0: return "<b> NO Table FOUND </b>" csv = '' for index, table in enumerate(table_blocks): csv += generate_table_csv(table, blocks_map, index + 1) csv += '\n\n' # In order to generate separate CSV file for every table, uncomment code below #inner_csv = '' #inner_csv += generate_table_csv(table, blocks_map, index + 1) #inner_csv += '\n\n' Exporting Tables into a CSV File 342 Amazon Textract Developer Guide #output_file = file_name + "___" + str(index) + ".csv" # replace content #with open(output_file, "at") as fout: # fout.write(inner_csv) return csv def generate_table_csv(table_result, blocks_map, table_index): rows = get_rows_columns_map(table_result, blocks_map) table_id = 'Table_' + str(table_index) # get cells. csv = 'Table: {0}\n\n'.format(table_id) for row_index, cols in rows.items(): for col_index, text in cols.items(): csv += '{}'.format(text) + "," csv += '\n' csv += '\n\n\n' return csv response_blocks = GetResults(jobId, file_name) 6. Run the code. After you have obtained you results, be sure to delete the associated SNS and SQS resources, or else you may accrue charges for them. Detecting text with an AWS Lambda function AWS Lambda is a compute service that you can use to run code without provisioning or managing servers. You can call Amazon Textract API operations from within an AWS Lambda function. The following instructions show how to create a Lambda function in Python that calls DetectDocumentText. The Lambda function returns a list of Block objects with information about the detected words and lines of text. The instructions include example Python code that shows you how to call the Lambda function with a document supplied from an Amazon S3 bucket or your local computer. Detecting text with an AWS Lambda function 343 Amazon Textract Developer Guide Images stored in Amazon S3 must be in single-page PDF or TIFF document format, or in JPEG or PNG format. Local images must be in single-page PDF or TIFF format. The Python code returns part of the JSON response for each Block type detected in the document. For an example that uses Lambda functions to process documents at a large scale, see Amazon Textract IDP CDK Constructs and Use machine learning to automate and process documents at scale. Topics • Step 1: Create an AWS Lambda function (console) • Step 2: (Optional) Create a layer (console) • Step 3: Add Python code (console) • Step 4: Try your Lambda function Step 1: Create an AWS Lambda function (console) In this step, you create an empty AWS Lambda function and an IAM execution role that lets your function call the DetectDocumentText operation. If you are supplying documents from Amazon S3, this step also shows you how to grant access to the bucket that stores your documents. Later you add the source code and optionally add a layer to the Lambda function. To create an AWS Lambda function (console) 1. Sign in to the AWS Management Console and open the AWS Lambda console at https:// console.aws.amazon.com/lambda/. 2. Choose Create function. For more information, see Create a Lambda Function with the
textract-dg-078
textract-dg.pdf
78
In this step, you create an empty AWS Lambda function and an IAM execution role that lets your function call the DetectDocumentText operation. If you are supplying documents from Amazon S3, this step also shows you how to grant access to the bucket that stores your documents. Later you add the source code and optionally add a layer to the Lambda function. To create an AWS Lambda function (console) 1. Sign in to the AWS Management Console and open the AWS Lambda console at https:// console.aws.amazon.com/lambda/. 2. Choose Create function. For more information, see Create a Lambda Function with the Console. 3. Choose the following options: • Choose Author from scratch. • Enter a value for Function name. • For Runtime, choose Python 3.9. • For Architecture, choose x86_64. 4. Choose Create function to create the AWS Lambda function. 5. On the function page, choose the Configuration tab. Step 1: Create an AWS Lambda function (console) 344 Amazon Textract Developer Guide 6. On the Permissions pane, under Execution role, choose the role name to open the role in the IAM console. 7. In the Permissions tab, choose Add permissions and then Create inline policy. 8. Choose the JSON tab and replace the policy with the following policy: { "Version": "2012-10-17", "Statement": [ { "Action": "textract:DetectDocumentText", "Resource": "*", "Effect": "Allow", "Sid": "DetectDocumentText" } ] } 9. Choose Review policy. 10. Enter a name for the policy, for example DetectDocumentText-access. 11. Choose Create policy. 12. If you are storing documents for analysis in an Amazon S3 bucket, you must add an Amazon S3 access policy. To do this, repeat steps 7 to 11 in the AWS Lambda console and make the following changes. a. For step 8, use the following policy. Replace bucket/folder path with the Amazon S3 bucket and folder path to the documents that you want to analyze. { "Version": "2012-10-17", "Statement": [ { "Sid": "S3Access", "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::bucket/folder path/*" } ] } b. For step 10, choose a different policy name, such as S3Bucket-access. Step 1: Create an AWS Lambda function (console) 345 Amazon Textract Developer Guide Step 2: (Optional) Create a layer (console) To run this example, you don't need to perform this step. The DetectDocumentText operation is included in the default Lambda Python environment as part of AWS SDK for Python (Boto3). If other parts of your Lambda function require recent AWS service updates that aren't in the default Lambda Python environment, then perform this step to add the most recent Boto3 SDK release as a layer to your function. First, you create a zip file archive that contains the Boto3 SDK. Then, you create a layer and add the zip file archive to the layer. For more information, see Using layers with your Lambda function. To create and add a layer (console) 1. Open a command prompt and enter the following commands to create a deployment package with the most recent version of the AWS SDK. pip install boto3 --target python/. zip boto3-layer.zip -r python/ 2. Note the name of the zip file (boto3-layer.zip), which you use in step 8 of this procedure. 3. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/. 4. In the navigation pane, choose Layers. 5. Choose Create layer. 6. 7. 8. Enter values for Name and Description. For Code entry type, choose Upload a .zip file and select Upload. In the dialog box, choose the zip file archive (boto3-layer.zip) that you created in step 1 of this procedure. 9. For Compatible runtimes, choose Python 3.9. 10. Choose Create to create the layer. 11. Choose the navigation pane menu icon. 12. In the navigation pane, choose Functions. 13. In the resources list, choose the function that you created previously in Step 1: Create an AWS Lambda function (console). 14. Choose the Code tab. 15. In the Layers section, choose Add a layer. Step 2: (Optional) Create a layer (console) 346 Amazon Textract 16. Choose Custom layers. 17. In Custom layers, choose the layer name that you entered in step 6. 18. In Version choose the layer version, which should be 1. 19. Choose Add. Developer Guide Step 3: Add Python code (console) In this step, you add Python code to your Lambda function by using the Lambda console code editor. The code detects text in a document with DetectDocumentText and returns a list of Block objects with information about the detected text. The document can be located in an Amazon S3 bucket or a local computer. Images stored in Amazon S3 must be single-page PDF or TIFF format documents or in JPEG or PNG format. Local images must be in single-page PDF or TIFF format. To add Python code (console) 1. Navigate to the Code tab. 2. In the code editor, replace the code in lambda_function.py with the following code:
textract-dg-079
textract-dg.pdf
79
your Lambda function by using the Lambda console code editor. The code detects text in a document with DetectDocumentText and returns a list of Block objects with information about the detected text. The document can be located in an Amazon S3 bucket or a local computer. Images stored in Amazon S3 must be single-page PDF or TIFF format documents or in JPEG or PNG format. Local images must be in single-page PDF or TIFF format. To add Python code (console) 1. Navigate to the Code tab. 2. In the code editor, replace the code in lambda_function.py with the following code: # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose An AWS lambda function that analyzes documents with Amazon Textract. """ import json import base64 import logging import boto3 from botocore.exceptions import ClientError # Set up logging. logger = logging.getLogger(__name__) # Get the boto3 client. textract_client = boto3.client('textract') Step 3: Add Python code (console) 347 Amazon Textract Developer Guide def lambda_handler(event, context): """ Lambda handler function param: event: The event object for the Lambda function. param: context: The context object for the lambda function. return: The list of Block objects recognized in the document passed in the event object. """ try: # Determine document source. if 'image' in event: # Decode the image image_bytes = event['image'].encode('utf-8') img_b64decoded = base64.b64decode(image_bytes) image = {'Bytes': img_b64decoded} elif 'S3Object' in event: image = {'S3Object': {'Bucket': event['S3Object']['Bucket'], 'Name': event['S3Object']['Name']} } else: raise ValueError( 'Invalid source. Only image base 64 encoded image bytes or S3Object are supported.') # Analyze the document. response = textract_client.detect_document_text(Document=image) # Get the Blocks blocks = response['Blocks'] lambda_response = { "statusCode": 200, "body": json.dumps(blocks) } except ClientError as err: error_message = "Couldn't analyze image. " + \ Step 3: Add Python code (console) 348 Amazon Textract Developer Guide err.response['Error']['Message'] lambda_response = { 'statusCode': 400, 'body': { "Error": err.response['Error']['Code'], "ErrorMessage": error_message } } logger.error("Error function %s: %s", context.invoked_function_arn, error_message) except ValueError as val_error: lambda_response = { 'statusCode': 400, 'body': { "Error": "ValueError", "ErrorMessage": format(val_error) } } logger.error("Error function %s: %s", context.invoked_function_arn, format(val_error)) return lambda_response 3. Choose Deploy to deploy your Lambda function. Step 4: Try your Lambda function Now that you’ve created your Lambda function, you can invoke it to detect text in a document. In this step, you use Python code on your computer to pass a local document or a document in an Amazon S3 bucket to your Lambda function. Documents passed from a local computer must be smaller than 6291456 bytes. If your documents are larger, upload them to an Amazon S3 bucket and call the script with the Amazon S3 path to the image. For information about uploading image files to an Amazon S3 bucket, see Uploading objects. Make sure you run the code in the same AWS Region in which you created the Lambda function. You can view the AWS Region for your Lambda function in the navigation bar of the function details page in the Lambda console. If the AWS Lambda function returns a timeout error, extend the timeout period for the Lambda function. For more information, see Configuring function timeout (console). Step 4: Try your Lambda function 349 Amazon Textract Developer Guide For more information about invoking a Lambda function from your code, see Invoking AWS Lambda Functions. To try your Lambda function 1. If you haven't already done so, do the following: a. Make sure that the user has lambda:InvokeFunction permission. You can use the following policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "InvokeLambda", "Effect": "Allow", "Action": "lambda:InvokeFunction", "Resource": "ARN for lambda function" } ] } You can get the ARN for your Lambda function from the function overview in the Lambda console. To provide access, add permissions to your users, groups, or roles: • Users and groups in AWS IAM Identity Center: Create a permission set. Follow the instructions in Create a permission set in the AWS IAM Identity Center User Guide. • Users managed in IAM through an identity provider: Create a role for identity federation. Follow the instructions in Create a role for a third- party identity provider (federation) in the IAM User Guide. • IAM users: • Create a role that your user can assume. Follow the instructions in Create a role for an IAM user in the IAM User Guide. Step 4: Try your Lambda function 350 Amazon Textract Developer Guide • (Not recommended) Attach a policy directly to a user or add a user to a user group. Follow the instructions in Adding permissions to a user (console) in the IAM User Guide. b. Install and configure AWS SDK for Python. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. 2. Save the following code to a file named client.py: # Copyright Amazon.com, Inc. or its affiliates. All
textract-dg-080
textract-dg.pdf
80
Follow the instructions in Create a role for an IAM user in the IAM User Guide. Step 4: Try your Lambda function 350 Amazon Textract Developer Guide • (Not recommended) Attach a policy directly to a user or add a user to a user group. Follow the instructions in Adding permissions to a user (console) in the IAM User Guide. b. Install and configure AWS SDK for Python. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. 2. Save the following code to a file named client.py: # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Test code for running the Amazon Textract Lambda function example code. """ import argparse import logging import base64 import json import io import boto3 from botocore.exceptions import ClientError from PIL import Image, ImageDraw logger = logging.getLogger(__name__) def analyze_image(function_name, image): """Analyzes a document with an AWS Lambda function. :param image: The document that you want to analyze. :return The list of Block objects in JSON format. """ lambda_client = boto3.client('lambda') lambda_payload = {} if image.startswith('s3://'): logger.info("Analyzing document from S3 bucket: %s", image) Step 4: Try your Lambda function 351 Amazon Textract Developer Guide bucket, key = image.replace("s3://", "").split("/", 1) s3_object = { 'Bucket': bucket, 'Name': key } lambda_payload = {"S3Object": s3_object} else: with open(image, 'rb') as image_file: logger.info("Analyzing local document: %s ", image) image_bytes = image_file.read() data = base64.b64encode(image_bytes).decode("utf8") lambda_payload = {"image": data} # Call the lambda function with the document. response = lambda_client.invoke(FunctionName=function_name, Payload=json.dumps(lambda_payload)) return json.loads(response['Payload'].read().decode()) def add_arguments(parser): """ Adds command line arguments to the parser. :param parser: The command line parser. """ parser.add_argument( "function", help="The name of the AWS Lambda function that you want " \ "to use to analyze the document.") parser.add_argument( "image", help="The document that you want to analyze.") def main(): """ Entrypoint for script. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") Step 4: Try your Lambda function 352 Amazon Textract Developer Guide # Get command line arguments. parser = argparse.ArgumentParser(usage=argparse.SUPPRESS) add_arguments(parser) args = parser.parse_args() # Get analysis results. result = analyze_image(args.function, args.image) status = result['statusCode'] blocks = result['body'] blocks = json.loads(blocks) if status == 200: for block in blocks: print('Type: ' + block['BlockType']) if block['BlockType'] != 'PAGE': print('Detected: ' + block['Text']) print('Confidence: ' + "{:.2f}".format(block['Confidence']) + "%") print('Id: {}'.format(block['Id'])) if 'Relationships' in block: print('Relationships: {}'.format(block['Relationships'])) print('Bounding Box: {}'.format(block['Geometry']['BoundingBox'])) print('Polygon: {}'.format(block['Geometry']['Polygon'])) print() print("Blocks detected: " + str(len(blocks))) else: print(f"Error: {result['statusCode']}") print(f"Message: {result['body']}") except ClientError as error: logging.error(error) print(error) if __name__ == "__main__": main() Step 4: Try your Lambda function 353 Amazon Textract Developer Guide 3. Run the code. For the command line argument, supply the Lambda function name and the document that you want to analyze. You can supply a path to a local document, or you can use the Amazon S3 path to an document stored in an Amazon S3 bucket. For example: python client.py function_name s3://bucket/path/document.jpg If the document is in an Amazon S3 bucket. make sure that it is the same bucket that you specified previously in step 12 of Step 1: Create an AWS Lambda function (console). If successful, your code returns a partial JSON response for each Block type detected in the document. Extracting and Sending Text to AWS Comprehend for Analysis Amazon Textract lets you include document text detection and analysis in your applications. With Amazon Textract you can extract text from a variety of different document types using both synchronous and asynchronous document processing. The extracted text can then be saved to a file or database, or sent to another AWS service for further processing. In this tutorial you carry out a common end-to-end workflow. This workflow involves: • Processing numerous input documents with Amazon Textract • Providing the extracted text to Amazon Comprehend for analysis • Saving both the analyzed text and the analysis data to an Amazon Simple Storage Service (S3) bucket You use the AWS SDK for Python for this tutorial. You can also see the AWS Documentation SDK examples GitHub repo for more Python tutorials. Prerequisites Before you begin this tutorial, you’ll need to install Python and complete the steps required to set up the Python AWS SDK. Beyond this, ensure that you have: • Created an AWS account and an IAM role • Properly configured your AWS access credentials • Created an Amazon S3 bucket Extracting and Sending Text to AWS Comprehend for Analysis 354 Amazon Textract Developer Guide • Configured Amazon Textract for Asynchronous processing, copying down the Amazon Resource Number (ARN) of the IAM role you configured for use with Amazon Textract • Granted your IAM role access to Amazon Comprehend • Selected a few documents for the purposes of text extraction/analysis and uploaded the document to Amazon S3. Ensure that the files you select for analysis are of the formats supported by Amazon Textract. Starting Asynchronous Document
textract-dg-081
textract-dg.pdf
81
IAM role • Properly configured your AWS access credentials • Created an Amazon S3 bucket Extracting and Sending Text to AWS Comprehend for Analysis 354 Amazon Textract Developer Guide • Configured Amazon Textract for Asynchronous processing, copying down the Amazon Resource Number (ARN) of the IAM role you configured for use with Amazon Textract • Granted your IAM role access to Amazon Comprehend • Selected a few documents for the purposes of text extraction/analysis and uploaded the document to Amazon S3. Ensure that the files you select for analysis are of the formats supported by Amazon Textract. Starting Asynchronous Document Text Detection You can extract the text from your documents and then analyze the extracted text with a service like Amazon Comprehend. Textract supports the extraction of text from multipage documents through asynchronous operations, which are for processing large, multipage documents. Processing a PDF file asynchronously allows your application to complete other tasks while it waits for the process to complete. This section will demonstrate how to import your documents from an Amazon S3 bucket and provide them to Textract’s asynchronous text detection operation. This tutorial assumes that you will be using Amazon S3 to store the files you want to extract text from. You’ll start by creating a class and functions that detect the text in your input documents. Your application will need to connect to the Textract client, as well as the Amazon SQS and Amazon SNS clients for the purposes of monitoring the completion status of the asynchronous job. 1. Start by writing the code to create an Amazon SNS topic and Amazon SQS queue. The following code sample creates a DocumentProcessor class that connects to the three required services and then creates both an Amazon SQS queue and Amazon SNS topic. The Amazon SNS topic is used to provide information about the job completion status to an Amazon SQS queue, which will be polled to obtain the completion status of a job. There are also methods to delete the Amazon SQS queue and Amazon SNS topic once the job has been completed and the resources are no longer needed. import boto3 import json import sys import time class DocumentProcessor: Starting Asynchronous Document Text Detection 355 Amazon Textract Developer Guide jobId = '' region_name = '' roleArn = '' bucket = '' document = '' sqsQueueUrl = '' snsTopicArn = '' processType = '' def __init__(self, role, bucket, document, region): self.roleArn = role self.bucket = bucket self.document = document self.region_name = region # Instantiates necessary AWS clients session = boto3.Session(profile_name='profile-name', region_name='self.region_name') self.textract = session.client('textract', region_name=self.region_name) self.sqs = session.client('sqs', region_name=self.region_name) self.sns = session.client('sns', region_name=self.region_name) def CreateTopicandQueue(self): millis = str(int(round(time.time() * 1000))) # Create SNS topic snsTopicName = "AmazonTextractTopic" + millis topicResponse = self.sns.create_topic(Name=snsTopicName) self.snsTopicArn = topicResponse['TopicArn'] # create SQS queue sqsQueueName = "AmazonTextractQueue" + millis self.sqs.create_queue(QueueName=sqsQueueName) self.sqsQueueUrl = self.sqs.get_queue_url(QueueName=sqsQueueName) ['QueueUrl'] attribs = self.sqs.get_queue_attributes(QueueUrl=self.sqsQueueUrl, AttributeNames=['QueueArn']) ['Attributes'] Starting Asynchronous Document Text Detection 356 Amazon Textract Developer Guide sqsQueueArn = attribs['QueueArn'] # Subscribe SQS queue to SNS topic self.sns.subscribe( TopicArn=self.snsTopicArn, Protocol='sqs', Endpoint=sqsQueueArn) # Authorize SNS to write SQS queue policy = """{{ "Version":"2012-10-17", "Statement":[ {{ "Sid":"MyPolicy", "Effect":"Allow", "Principal" : {{"AWS" : "*"}}, "Action":"SQS:SendMessage", "Resource": "{}", "Condition":{{ "ArnEquals":{{ "aws:SourceArn": "{}" }} }} }} ] }}""".format(sqsQueueArn, self.snsTopicArn) response = self.sqs.set_queue_attributes( QueueUrl=self.sqsQueueUrl, Attributes={ 'Policy': policy }) def DeleteTopicandQueue(self): self.sqs.delete_queue(QueueUrl=self.sqsQueueUrl) self.sns.delete_topic(TopicArn=self.snsTopicArn) 2. Write the code to call the StartDocumentTextDetection operation and get the results of the operation. The DocumentProcessor class will also need methods to: • Call the StartDocumentTextDetection operation Starting Asynchronous Document Text Detection 357 Amazon Textract Developer Guide • Poll an Amazon SQS for the job completion status • Retrieve the results of the job once it is done processing The following code creates the ProcessDocument and GetResults methods that call StartDocumentTextDetection and gets the extracted text, respectively. def ProcessDocument(self): # Checks if job found jobFound = False # Starts the text detection operation on the documents in the provided bucket # Sends status to supplied SNS topic arn response = self.textract.start_document_text_detection( DocumentLocation={'S3Object': {'Bucket': self.bucket, 'Name': self.document}}, NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn}) print('Processing type: Detection') print('Start Job Id: ' + response['JobId']) dotLine = 0 while jobFound == False: sqsResponse = self.sqs.receive_message(QueueUrl=self.sqsQueueUrl, MessageAttributeNames=['ALL'], MaxNumberOfMessages=10) # Waits until messages are found in the SQS queue if sqsResponse: if 'Messages' not in sqsResponse: if dotLine < 40: print('.', end='') dotLine = dotLine + 1 else: print() dotLine = 0 sys.stdout.flush() time.sleep(5) continue Starting Asynchronous Document Text Detection 358 Amazon Textract Developer Guide # Checks for a completed job that matches the jobID in the response from # StartDocumentTextDetection for message in sqsResponse['Messages']: notification = json.loads(message['Body']) textMessage = json.loads(notification['Message']) if str(textMessage['JobId']) == response['JobId']: print('Matching Job Found:' + textMessage['JobId']) jobFound = True text_data = self.GetResults(textMessage['JobId']) self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) return text_data else: print("Job didn't match:" + str(textMessage['JobId']) + ' : ' + str(response['JobId'])) # Delete the unknown message. Consider sending to
textract-dg-082
textract-dg.pdf
82
sqsResponse: if 'Messages' not in sqsResponse: if dotLine < 40: print('.', end='') dotLine = dotLine + 1 else: print() dotLine = 0 sys.stdout.flush() time.sleep(5) continue Starting Asynchronous Document Text Detection 358 Amazon Textract Developer Guide # Checks for a completed job that matches the jobID in the response from # StartDocumentTextDetection for message in sqsResponse['Messages']: notification = json.loads(message['Body']) textMessage = json.loads(notification['Message']) if str(textMessage['JobId']) == response['JobId']: print('Matching Job Found:' + textMessage['JobId']) jobFound = True text_data = self.GetResults(textMessage['JobId']) self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) return text_data else: print("Job didn't match:" + str(textMessage['JobId']) + ' : ' + str(response['JobId'])) # Delete the unknown message. Consider sending to dead letter queue self.sqs.delete_message(QueueUrl=self.sqsQueueUrl, ReceiptHandle=message['ReceiptHandle']) print('Done!') # gets the results of the completed text detection job # checks for pagination tokens to determine if there are multiple pages in the input doc def GetResults(self, jobId): maxResults = 1000 paginationToken = None finished = False while finished == False: response = None if paginationToken == None: response = self.textract.get_document_text_detection(JobId=jobId, MaxResults=maxResults) else: response = self.textract.get_document_text_detection(JobId=jobId, MaxResults=maxResults, Starting Asynchronous Document Text Detection 359 Amazon Textract Developer Guide NextToken=paginationToken) blocks = response['Blocks'] # List to hold detected text detected_text = [] # Display block information and add detected text to list for block in blocks: if 'Text' in block and block['BlockType'] == "LINE": detected_text.append(block['Text']) # If response contains a next token, update pagination token if 'NextToken' in response: paginationToken = response['NextToken'] else: finished = True return detected_text 3. Save the above code in a file called detectFileAsync.py. You use this file in the next section to handle the detection of text in your input documents. Processing Your Documents and Sending the Text to Comprehend Your application will use the class you created in the proceeding section to: • read documents from your Amazon S3 bucket • extract the text in those documents • send the text to Amazon Comprehend for analysis You start by creating some functions that utilize Amazon Comprehend to analyze the text detected in your input documents. A common type of text analysis is sentiment analysis, which aims to capture the affect of a statement (whether it is positive, negative, or neutral). You can also carry out entity detection and key phrase detection on the data. Processing Your Documents and Sending the Text to Comprehend 360 Amazon Textract Developer Guide The code below takes in the detected text and invokes the BatchDetectSentiment operation from Amazon Comprehend in order to carry out sentiment analysis. 1. Write the code to carry out sentiment analysis on your detected text. from detectFileAsync import DocumentProcessor import boto3 import pandas as pd # Detect sentiment def sentiment_analysis(detected_text, lang): comprehend = boto3.client("comprehend") detect_sent_response = comprehend.batch_detect_sentiment( TextList=detected_text, LanguageCode=lang) # Lists to hold sentiment labels and sentiment scores sentiments = [] pos_score = [] neg_score = [] neutral_score = [] mixed_score = [] # for all results add the Sentiment label and sentiment scores to lists for res in detect_sent_response['ResultList']: sentiments.append(res['Sentiment']) print(res['SentimentScore']) print(type(res['SentimentScore'])) for key, val in res['SentimentScore'].items(): if key == "Positive": pos_score.append(val) if key == "Negative": neg_score.append(val) if key == "Neutral": neutral_score.append(val) if key == "Mixed": mixed_score.append(val) return sentiments, pos_score, neg_score, neutral_score, mixed_score Processing Your Documents and Sending the Text to Comprehend 361 Amazon Textract Developer Guide You may also want to perform other analysis operations, such as entity detection or key phrase detection, on your detected text. You can write the functions to carry out these analysis operations on your text, just like you did for the proceeding sentiment analysis operation. 2. Write the code to carry out entity detection on your detected text. # detect entities def entity_detection(detected_text, lang): comprehend = boto3.client("comprehend") # convert and handle string here # do string handling detect_ent_response = comprehend.batch_detect_entities( TextList=detected_text, LanguageCode=lang) # To fold detected entities and entity types ents = [] types = [] # Get detected entities and types from the response returned by Comprehend for i in detect_ent_response['ResultList']: if len(i['Entities']) == 0: ents.append("N/A") types.append("N/A") else: sentence_ents = [] sentence_types = [] for entities in i['Entities']: sentence_ents.append(entities['Text']) sentence_types.append(entities['Type']) ents.append(sentence_ents) types.append(sentence_types) return ents, types 3. Write the code to carry out key phrase detection on your detected text. # Detect key phrases def key_phrases_detection(detected_text, lang): Processing Your Documents and Sending the Text to Comprehend 362 Amazon Textract Developer Guide comprehend = boto3.client("comprehend") key_phrases = [] detect_phrases_response = comprehend.batch_detect_key_phrases( TextList=detected_text, LanguageCode=lang) for i in detect_phrases_response['ResultList']: if len(i['KeyPhrases']) == 0: key_phrases.append("N/A") else: phrases = [] for phrase in i['KeyPhrases']: phrases.append(phrase['Text']) key_phrases.append(phrases) return key_phrases You need to create a function that invokes all of the code you’ve created so far. The function will use the DocumentProcessor class you created in your DetectAnalyzeFileAsync.py file, and then save the detected text to a variable for input into the three functions utilizing Amazon Comprehend that you previously wrote. The function will also need to construct a Pandas dataframe, into which the detected text and analysis data
textract-dg-083
textract-dg.pdf
83
= boto3.client("comprehend") key_phrases = [] detect_phrases_response = comprehend.batch_detect_key_phrases( TextList=detected_text, LanguageCode=lang) for i in detect_phrases_response['ResultList']: if len(i['KeyPhrases']) == 0: key_phrases.append("N/A") else: phrases = [] for phrase in i['KeyPhrases']: phrases.append(phrase['Text']) key_phrases.append(phrases) return key_phrases You need to create a function that invokes all of the code you’ve created so far. The function will use the DocumentProcessor class you created in your DetectAnalyzeFileAsync.py file, and then save the detected text to a variable for input into the three functions utilizing Amazon Comprehend that you previously wrote. The function will also need to construct a Pandas dataframe, into which the detected text and analysis data will be inserted. Finally, the Pandas dataframe will be saved as a CSV file. 4. Write the code to process your input documents with Textract and pass the detected text to Comprehend. def process_document(roleArn, bucket, document, region_name): # Create analyzer class from DocumentProcessor, create a topic and queue, use Textract to get text, # then delete topica and queue analyzer = DocumentProcessor(roleArn, bucket, document, region_name) analyzer.CreateTopicandQueue() extracted_text = analyzer.ProcessDocument() analyzer.DeleteTopicandQueue() # detect dominant language comprehend = boto3.client("comprehend") response = comprehend.detect_dominant_language(Text=str(extracted_text[:10])) print(response) Processing Your Documents and Sending the Text to Comprehend 363 Amazon Textract Developer Guide print(type(response)) lang = "" for i in response['Languages']: lang = i['LanguageCode'] print(lang) # or you can enter language code below # lang = "en" print("Lines in detected text:" + str(len(extracted_text))) sliced_list = [] start = 0 end = 24 while end < len(extracted_text): sliced_list.append(extracted_text[start:end]) start += 25 end += 25 print(sliced_list) # Create lists to hold analytics data, these will be turned into columns all_sents = [] all_scores = [] all_ents = [] all_types = [] all_key_phrases = [] all_pos_ratings = [] all_neg_ratings = [] all_neutral_ratings = [] all_mixed_ratings = [] # For every slice, get sentiment analysis, entity detection and key phrases, append results to lists for slice in sliced_list: slice_labels, pos_ratings, neg_ratings, neutral_ratings, mixed_ratings = sentiment_analysis(slice, lang) all_sents.append(slice_labels) all_pos_ratings.append(pos_ratings) all_neg_ratings.append(neg_ratings) all_neutral_ratings.append(neutral_ratings) all_mixed_ratings.append(mixed_ratings) slice_ents, slice_types = entity_detection(slice, lang) all_ents.append(slice_ents) all_types.append(slice_types) key_phrases = key_phrases_detection(slice, lang) Processing Your Documents and Sending the Text to Comprehend 364 Amazon Textract Developer Guide all_key_phrases.append(key_phrases) # List comprehension to flatten multiple lists into a single list extracted_text = [line for sublist in sliced_list for line in sublist] all_sents = [sent for sublist in all_sents for sent in sublist] all_scores = [score for sublist in all_scores for score in sublist] all_ents = [ents for sublist in all_ents for ents in sublist] all_types = [types for sublist in all_types for types in sublist] all_key_phrases = [kp for sublist in all_key_phrases for kp in sublist] all_mixed_ratings = [kp for sublist in all_mixed_ratings for kp in sublist] all_pos_ratings = [kp for sublist in all_pos_ratings for kp in sublist] all_neg_ratings = [kp for sublist in all_neg_ratings for kp in sublist] all_neutral_ratings = [kp for sublist in all_neutral_ratings for kp in sublist] print(len(extracted_text)) print(len(all_sents)) print(len(all_ents)) print(len(all_types)) print(len(all_key_phrases)) print("List of Recognized Entities:") # Create dataframe and save as CSV df = pd.DataFrame({'Sentences':extracted_text, 'Sentiment':all_sents, 'SentPosScore':all_pos_ratings, 'SentNegScore':all_neg_ratings, 'SentNeutralScore':all_neutral_ratings, 'SentMixedRatings':all_mixed_ratings, 'Entities':all_ents, 'EntityTypes':all_types,'KeyPhrases:':all_key_phrases}) analysis_results = str(document.replace(".","_") + "_" + "analysis" + ".csv") df.to_csv(analysis_results, index=False) print(df) print("Data written to file!") return extracted_text, analysis_results 5. Write the code to process your documents and upload the resulting data to S3. In the code sample below, replace the value of roleArn with the ARN of the role you configured for use with Amazon Textract. Replace the value of region_name with the region your account is operating in. Finally, replace the value bucket_name with the name of the S3 bucket containing your documents. Processing Your Documents and Sending the Text to Comprehend 365 Amazon Textract Developer Guide def main(): # Initialize S3 client and set RoleArn, region name, and bucket name s3 = boto3.client("s3") roleArn = '' region_name = '' bucket_name = '' # initialize global corpus full_corpus = [] # to hold all docs in bucket docs_list = [] # loop through docs in bucket, get names of all docs s3_resource = boto3.resource("s3") bucket = s3_resource.Bucket(bucket_name) for bucket_object in bucket.objects.all(): docs_list.append(bucket_object.key) print(docs_list) # For all the docs in the bucket, invoke document processing function, # add detected text to corpus of all text in batch docs, # and save CSV of comprehend analysis data and textract detected to S3 for i in docs_list: detected_text, analysis_results = process_document(roleArn, bucket_name, i, region_name) full_corpus.append(detected_text) print("Uploading file: {}".format(str(analysis_results))) name_of_file = str(analysis_results) s3.upload_file(name_of_file, bucket_name, name_of_file) # print the global corpus print(full_corpus) if __name__ == "__main__": main() 6. Put the proceeding code in the section into a Python file and run it. Processing Your Documents and Sending the Text to Comprehend 366 Amazon Textract Developer Guide You have successfully extracted text using Amazon Textract, sent the text to Amazon Comprehend for analysis, and then saved the results in a Amazon S3 bucket. Additional Code Samples The following table provides links to more Amazon Textract code examples. Example Description Amazon Textract Code
textract-dg-084
textract-dg.pdf
84
= process_document(roleArn, bucket_name, i, region_name) full_corpus.append(detected_text) print("Uploading file: {}".format(str(analysis_results))) name_of_file = str(analysis_results) s3.upload_file(name_of_file, bucket_name, name_of_file) # print the global corpus print(full_corpus) if __name__ == "__main__": main() 6. Put the proceeding code in the section into a Python file and run it. Processing Your Documents and Sending the Text to Comprehend 366 Amazon Textract Developer Guide You have successfully extracted text using Amazon Textract, sent the text to Amazon Comprehend for analysis, and then saved the results in a Amazon S3 bucket. Additional Code Samples The following table provides links to more Amazon Textract code examples. Example Description Amazon Textract Code Samples Show various ways in which you can use Amazon Textract. Large scale document processing with Amazon Textract Shows a serverless reference architecture that processes documents at a large scale. Amazon Textract Parser Shows how to parse the the section called “Block” objects returned by Amazon Textract operations. Amazon Textract Documentation Code Examples Code examples used in this guide. Textractor Shows how to convert Amazon Textract output into multiple formats. Generate Searchable PDF documents with Amazon Textract Shows how to create a searchable PDF document from different types of input documents such as JPG/PNG format images and scanned PDF documents. Additional Code Samples 367 Amazon Textract Developer Guide Security in Amazon Textract Cloud security at AWS is the highest priority. As an AWS customer, you benefit from a data center and network architecture that are built to meet the requirements of the most security-sensitive organizations. Use the following topics to learn how to secure your Amazon Textract resources. Topics • Data Protection in Amazon Textract • Identity and Access Management for Amazon Textract • Logging and Monitoring • Logging Amazon Textract API Calls with AWS CloudTrail • Tagging resources • Compliance Validation for Amazon Textract • Resilience in Amazon Textract • Cross-service confused deputy prevention • Infrastructure Security in Amazon Textract • Configuration and Vulnerability Analysis in Amazon Textract • Amazon Textract and interface VPC endpoints (AWS PrivateLink) Data Protection in Amazon Textract The AWS shared responsibility model applies to data protection in Amazon Textract. As described in this model, AWS is responsible for protecting the global infrastructure that runs all of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. This content includes the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the Data Privacy FAQ. For information about data protection in Europe, see the AWS Shared Responsibility Model and GDPR blog post on the AWS Security Blog. For data protection purposes, we recommend that you protect AWS account credentials and set up individual users with AWS IAM Identity Center or AWS Identity and Access Management (IAM). Data Protection 368 Amazon Textract Developer Guide That way, each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways: • Use multi-factor authentication (MFA) with each account. • Use SSL/TLS to communicate with AWS resources. We recommend TLS 1.2 or later. • Set up API and user activity logging with AWS CloudTrail. • Use AWS encryption solutions, along with all default security controls within AWS services. • Use advanced managed security services such as Amazon Macie, which assists in discovering and securing sensitive data that is stored in Amazon S3. • If you require FIPS 140-2 validated cryptographic modules when accessing AWS through a command line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints, see Federal Information Processing Standard (FIPS) 140-2. We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into free-form text fields such as a Name field. This includes when you work with Amazon Textract or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into free-form text fields may be picked up for inclusion in diagnostic logs. If you provide a URL to an external server, we strongly recommend that you do not include credentials information in the URL to validate your request to that server. For more information about data protection, see the AWS Shared Responsibility Model and GDPR blog post on the AWS Security Blog. Encryption in Amazon Textract Data encryption refers to protecting data while in transit and at rest. You can protect your data by using Amazon S3-Managed Keys or AWS KMS key at rest, alongside standard Transport Layer Security while in transit. Encryption at Rest The primary method of encrypting data in Amazon Textract is server-side encryption. Input documents passed from Amazon S3 buckets are encrypted by Amazon S3 and decrypted when you access them. As long as you authenticate your request and you have
textract-dg-085
textract-dg.pdf
85
data protection, see the AWS Shared Responsibility Model and GDPR blog post on the AWS Security Blog. Encryption in Amazon Textract Data encryption refers to protecting data while in transit and at rest. You can protect your data by using Amazon S3-Managed Keys or AWS KMS key at rest, alongside standard Transport Layer Security while in transit. Encryption at Rest The primary method of encrypting data in Amazon Textract is server-side encryption. Input documents passed from Amazon S3 buckets are encrypted by Amazon S3 and decrypted when you access them. As long as you authenticate your request and you have access permissions, there is no difference in the way you access encrypted or unencrypted objects. For example, if you share your objects using a presigned URL, that URL works the same way for both encrypted and unencrypted Encryption in Amazon Textract 369 Amazon Textract Developer Guide objects. Additionally, when you list objects in your bucket, the List API returns a list of all objects, regardless of whether they are encrypted. Amazon Textract uses two mutually exclusive methods of server-side encryption. Server-Side Encryption with Amazon S3-Managed Keys (SSE-S3) When you use server-side encryption with Amazon S3-Managed Keys (SSE-S3), each object is encrypted with a unique key. As an additional safeguard, this method encrypts the key itself with a master key that it regularly rotates. Amazon S3 server-side encryption uses one of the strongest block ciphers available, 256-bit Advanced Encryption Standard (AES-256), to encrypt your data. For more information, see Protecting Data Using Server-Side Encryption with Amazon S3-Managed Encryption Keys (SSE-S3). Server-Side Encryption with KMS keys Stored in AWS Key Management Service (SSE-KMS) Server-side encryption with KMS keys stored in AWS Key Management Service (SSE-KMS) is similar to SSE-S3, but with some additional benefits and charges for using this service. There are separate permissions for the use of a KMS key that provides added protection against unauthorized access of your objects in Amazon S3. SSE-KMS also provides you with an audit trail that shows when your KMS key was used and by whom. Additionally, you can create and manage KMS keys or use AWS managed keys that are unique to you, your service, and your Region. For more information, see Protecting Data Using Server-Side Encryption with KMS keys Stored in AWS Key Management Service (SSE-KMS). Encryption in Transit For data in transit, Amazon Textract uses Transport Layer Security (TLS) to encrypt data sent between the service and the agent. Additionally, Amazon Textract uses VPC endpoints to send data between the various microservices used when Amazon Textract processes a document. Internetwork Traffic Privacy Amazon Textract communicates exclusively through HTTPS endpoints, which are supported in all Regions supported by Amazon Textract Custom Queries Any content used for generating adapters is processed internally within Amazon Textract for the duration of the training. The content is encrypted at rest and in transit. The content is stored and Internetwork Traffic Privacy 370 Amazon Textract Developer Guide processed in the AWS Region where you are training the adapter, and is deleted once training completes. By default, the content is encrypted using AWS owned AWS KMS keys. If a KMSKeyId is provided when creating an adapter version, the content is encrypted using the Customer managed CMK provided. Customer content (training images, prelabeling results, annotations) is not logged or retained even for debugging purposes. Identity and Access Management for Amazon Textract AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be authenticated (signed in) and authorized (have permissions) to use Amazon Textract resources. IAM is an AWS service that you can use with no additional charge. Topics • Audience • Authenticating With Identities • Managing Access Using Policies • How Amazon Textract Works with IAM • Amazon Textract Identity-Based Policy Examples • Troubleshooting Amazon Textract Identity and Access Audience How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in Amazon Textract. Service user – If you use the Amazon Textract service to do your job, then your administrator provides you with the credentials and permissions that you need. As you use more Amazon Textract features to do your work, you might need additional permissions. Understanding how access is managed can help you request the right permissions from your administrator. If you cannot access a feature in Amazon Textract, see Troubleshooting Amazon Textract Identity and Access. Service administrator – If you're in charge of Amazon Textract resources at your company, you probably have full access to Amazon Textract. It's your job to determine which Amazon Textract features and resources your service users should access. You must then submit requests to your IAM administrator to change the permissions of your service users. Review the information on this page
textract-dg-086
textract-dg.pdf
86
do your work, you might need additional permissions. Understanding how access is managed can help you request the right permissions from your administrator. If you cannot access a feature in Amazon Textract, see Troubleshooting Amazon Textract Identity and Access. Service administrator – If you're in charge of Amazon Textract resources at your company, you probably have full access to Amazon Textract. It's your job to determine which Amazon Textract features and resources your service users should access. You must then submit requests to your IAM administrator to change the permissions of your service users. Review the information on this page Identity and Access Management 371 Amazon Textract Developer Guide to understand the basic concepts of IAM. To learn more about how your company can use IAM with Amazon Textract, see How Amazon Textract Works with IAM. IAM administrator – If you're an IAM administrator, you might want to learn details about how you can write policies to manage access to Amazon Textract. To view example Amazon Textract identity-based policies that you can use in IAM, see Amazon Textract Identity-Based Policy Examples. Authenticating With Identities Authentication is how you sign in to AWS using your identity credentials. You must be authenticated (signed in to AWS) as the AWS account root user, as an IAM user, or by assuming an IAM role. You can sign in to AWS as a federated identity by using credentials provided through an identity source. AWS IAM Identity Center (IAM Identity Center) users, your company's single sign-on authentication, and your Google or Facebook credentials are examples of federated identities. When you sign in as a federated identity, your administrator previously set up identity federation using IAM roles. When you access AWS by using federation, you are indirectly assuming a role. Depending on the type of user you are, you can sign in to the AWS Management Console or the AWS access portal. For more information about signing in to AWS, see How to sign in to your AWS account in the AWS Sign-In User Guide. If you access AWS programmatically, AWS provides a software development kit (SDK) and a command line interface (CLI) to cryptographically sign your requests by using your credentials. If you don't use AWS tools, you must sign requests yourself. For more information about using the recommended method to sign requests yourself, see AWS Signature Version 4 for API requests in the IAM User Guide. Regardless of the authentication method that you use, you might be required to provide additional security information. For example, AWS recommends that you use multi-factor authentication (MFA) to increase the security of your account. To learn more, see Multi-factor authentication in the AWS IAM Identity Center User Guide and AWS Multi-factor authentication in IAM in the IAM User Guide. AWS account root user When you create an AWS account, you begin with one sign-in identity that has complete access to all AWS services and resources in the account. This identity is called the AWS account root user and Authenticating With Identities 372 Amazon Textract Developer Guide is accessed by signing in with the email address and password that you used to create the account. We strongly recommend that you don't use the root user for your everyday tasks. Safeguard your root user credentials and use them to perform the tasks that only the root user can perform. For the complete list of tasks that require you to sign in as the root user, see Tasks that require root user credentials in the IAM User Guide. IAM Users and Groups An IAM user is an identity within your AWS account that has specific permissions for a single person or application. Where possible, we recommend relying on temporary credentials instead of creating IAM users who have long-term credentials such as passwords and access keys. However, if you have specific use cases that require long-term credentials with IAM users, we recommend that you rotate access keys. For more information, see Rotate access keys regularly for use cases that require long- term credentials in the IAM User Guide. An IAM group is an identity that specifies a collection of IAM users. You can't sign in as a group. You can use groups to specify permissions for multiple users at a time. Groups make permissions easier to manage for large sets of users. For example, you could have a group named IAMAdmins and give that group permissions to administer IAM resources. Users are different from roles. A user is uniquely associated with one person or application, but a role is intended to be assumable by anyone who needs it. Users have permanent long-term credentials, but roles provide temporary credentials. To learn more, see Use cases for IAM users in the IAM User Guide. IAM Roles An IAM role is an identity within your AWS
textract-dg-087
textract-dg.pdf
87
specify permissions for multiple users at a time. Groups make permissions easier to manage for large sets of users. For example, you could have a group named IAMAdmins and give that group permissions to administer IAM resources. Users are different from roles. A user is uniquely associated with one person or application, but a role is intended to be assumable by anyone who needs it. Users have permanent long-term credentials, but roles provide temporary credentials. To learn more, see Use cases for IAM users in the IAM User Guide. IAM Roles An IAM role is an identity within your AWS account that has specific permissions. It is similar to an IAM user, but is not associated with a specific person. To temporarily assume an IAM role in the AWS Management Console, you can switch from a user to an IAM role (console). You can assume a role by calling an AWS CLI or AWS API operation or by using a custom URL. For more information about methods for using roles, see Methods to assume a role in the IAM User Guide. IAM roles with temporary credentials are useful in the following situations: • Federated user access – To assign permissions to a federated identity, you create a role and define permissions for the role. When a federated identity authenticates, the identity is associated with the role and is granted the permissions that are defined by the role. For information about roles for federation, see Create a role for a third-party identity provider Authenticating With Identities 373 Amazon Textract Developer Guide (federation) in the IAM User Guide. If you use IAM Identity Center, you configure a permission set. To control what your identities can access after they authenticate, IAM Identity Center correlates the permission set to a role in IAM. For information about permissions sets, see Permission sets in the AWS IAM Identity Center User Guide. • Temporary IAM user permissions – An IAM user or role can assume an IAM role to temporarily take on different permissions for a specific task. • Cross-account access – You can use an IAM role to allow someone (a trusted principal) in a different account to access resources in your account. Roles are the primary way to grant cross- account access. However, with some AWS services, you can attach a policy directly to a resource (instead of using a role as a proxy). To learn the difference between roles and resource-based policies for cross-account access, see Cross account resource access in IAM in the IAM User Guide. • Cross-service access – Some AWS services use features in other AWS services. For example, when you make a call in a service, it's common for that service to run applications in Amazon EC2 or store objects in Amazon S3. A service might do this using the calling principal's permissions, using a service role, or using a service-linked role. • Forward access sessions (FAS) – When you use an IAM user or role to perform actions in AWS, you are considered a principal. When you use some services, you might perform an action that then initiates another action in a different service. FAS uses the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. FAS requests are only made when a service receives a request that requires interactions with other AWS services or resources to complete. In this case, you must have permissions to perform both actions. For policy details when making FAS requests, see Forward access sessions. • Service role – A service role is an IAM role that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see Create a role to delegate permissions to an AWS service in the IAM User Guide. • Service-linked role – A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. • Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials for applications that are running on an EC2 instance and making AWS CLI or AWS API requests. This is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance and make it available to all of its applications, you create an instance profile Authenticating With Identities 374 Amazon Textract Developer Guide that is attached to the instance. An instance profile contains the role and enables programs that are running on
textract-dg-088
textract-dg.pdf
88
the permissions for service-linked roles. • Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials for applications that are running on an EC2 instance and making AWS CLI or AWS API requests. This is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance and make it available to all of its applications, you create an instance profile Authenticating With Identities 374 Amazon Textract Developer Guide that is attached to the instance. An instance profile contains the role and enables programs that are running on the EC2 instance to get temporary credentials. For more information, see Use an IAM role to grant permissions to applications running on Amazon EC2 instances in the IAM User Guide. Managing Access Using Policies You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy is an object in AWS that, when associated with an identity or resource, defines their permissions. AWS evaluates these policies when a principal (user, root user, or role session) makes a request. Permissions in the policies determine whether the request is allowed or denied. Most policies are stored in AWS as JSON documents. For more information about the structure and contents of JSON policy documents, see Overview of JSON policies in the IAM User Guide. Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. By default, users and roles have no permissions. To grant users permission to perform actions on the resources that they need, an IAM administrator can create IAM policies. The administrator can then add the IAM policies to roles, and users can assume the roles. IAM policies define permissions for an action regardless of the method that you use to perform the operation. For example, suppose that you have a policy that allows the iam:GetRole action. A user with that policy can get role information from the AWS Management Console, the AWS CLI, or the AWS API. Identity-Based Policies Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see Define custom IAM permissions with customer managed policies in the IAM User Guide. Identity-based policies can be further categorized as inline policies or managed policies. Inline policies are embedded directly into a single user, group, or role. Managed policies are standalone policies that you can attach to multiple users, groups, and roles in your AWS account. Managed policies include AWS managed policies and customer managed policies. To learn how to choose between a managed policy or an inline policy, see Choose between managed policies and inline policies in the IAM User Guide. Managing Access Using Policies 375 Amazon Textract Resource-Based Policies Developer Guide Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must specify a principal in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services. Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies from IAM in a resource-based policy. Access Control Lists (ACLs) Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format. Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs. To learn more about ACLs, see Access control list (ACL) overview in the Amazon Simple Storage Service Developer Guide. Other Policy Types AWS supports additional, less-common policy types. These policy types can set the maximum permissions granted to you by the more common policy types. • Permissions boundaries – A permissions boundary is an advanced feature in which you set the maximum permissions that an identity-based policy can grant to an IAM entity (IAM user or role). You can set a permissions boundary for an entity. The resulting permissions are the intersection of an entity's identity-based policies and its permissions boundaries. Resource-based policies that specify the user or role in the Principal field are not limited by the permissions boundary. An explicit deny in any of these policies overrides the allow.
textract-dg-089
textract-dg.pdf
89
can set the maximum permissions granted to you by the more common policy types. • Permissions boundaries – A permissions boundary is an advanced feature in which you set the maximum permissions that an identity-based policy can grant to an IAM entity (IAM user or role). You can set a permissions boundary for an entity. The resulting permissions are the intersection of an entity's identity-based policies and its permissions boundaries. Resource-based policies that specify the user or role in the Principal field are not limited by the permissions boundary. An explicit deny in any of these policies overrides the allow. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. • Service control policies (SCPs) – SCPs are JSON policies that specify the maximum permissions for an organization or organizational unit (OU) in AWS Organizations. AWS Organizations is a service for grouping and centrally managing multiple AWS accounts that your business owns. If Managing Access Using Policies 376 Amazon Textract Developer Guide you enable all features in an organization, then you can apply service control policies (SCPs) to any or all of your accounts. The SCP limits permissions for entities in member accounts, including each AWS account root user. For more information about Organizations and SCPs, see Service control policies in the AWS Organizations User Guide. • Resource control policies (RCPs) – RCPs are JSON policies that you can use to set the maximum available permissions for resources in your accounts without updating the IAM policies attached to each resource that you own. The RCP limits permissions for resources in member accounts and can impact the effective permissions for identities, including the AWS account root user, regardless of whether they belong to your organization. For more information about Organizations and RCPs, including a list of AWS services that support RCPs, see Resource control policies (RCPs) in the AWS Organizations User Guide. • Session policies – Session policies are advanced policies that you pass as a parameter when you programmatically create a temporary session for a role or federated user. The resulting session's permissions are the intersection of the user or role's identity-based policies and the session policies. Permissions can also come from a resource-based policy. An explicit deny in any of these policies overrides the allow. For more information, see Session policies in the IAM User Guide. Multiple Policy Types When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see Policy evaluation logic in the IAM User Guide. How Amazon Textract Works with IAM Before you use IAM to manage access to Amazon Textract, you should understand what IAM features are available to use with Amazon Textract. To get a high-level view of how Amazon Textract and other AWS services work with IAM, see AWS Services That Work with IAM in the IAM User Guide. Topics • Amazon Textract Identity-Based Policies • Amazon Textract Resource-Based Policies • Authorization Based on Amazon Textract Tags • Amazon Textract IAM Roles How Amazon Textract Works with IAM 377 Amazon Textract Developer Guide Amazon Textract Identity-Based Policies With IAM identity-based policies, you can specify allowed or denied actions and resources and the conditions under which actions are allowed or denied. Amazon Textract supports specific actions, resources, and condition keys. To learn about all of the elements that you use in a JSON policy, see IAM JSON Policy Elements Reference in the IAM User Guide. Actions Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Action element of a JSON policy describes the actions that you can use to allow or deny access in a policy. Policy actions usually have the same name as the associated AWS API operation. There are some exceptions, such as permission-only actions that don't have a matching API operation. There are also some operations that require multiple actions in a policy. These additional actions are called dependent actions. Include actions in a policy to grant permissions to perform the associated operation. Asynchronous actions in Amazon Textract require two action permissions to be given, one for Start actions and one for Get actions. Additionally, if you are using an Amazon S3 bucket to pass documents, you will need to grant your account read access. In Amazon Textract, all policy actions start with: textract:. For example, to grant someone permission to run an Amazon Textract operation with the Amazon Textract AnalyzeDocument operation, you include the textract:AnalyzeDocument action in their policy. Policy statements must include either an Action or NotAction element. Amazon Textract defines its own set of actions that describe tasks that
textract-dg-090
textract-dg.pdf
90
operation. Asynchronous actions in Amazon Textract require two action permissions to be given, one for Start actions and one for Get actions. Additionally, if you are using an Amazon S3 bucket to pass documents, you will need to grant your account read access. In Amazon Textract, all policy actions start with: textract:. For example, to grant someone permission to run an Amazon Textract operation with the Amazon Textract AnalyzeDocument operation, you include the textract:AnalyzeDocument action in their policy. Policy statements must include either an Action or NotAction element. Amazon Textract defines its own set of actions that describe tasks that you can perform with this service. To specify multiple actions in a single statement, separate them with commas as follows. "Action": [ "textract:action1", "textract:action2" You can specify multiple actions using wildcards (*). For example, to specify all actions that begin with the word Describe, include the following action. "Action": "textract:Describe*" How Amazon Textract Works with IAM 378 Amazon Textract Developer Guide For a list of Amazon Textract actions, see Actions Defined by Amazon Textract in the IAM User Guide. Resources Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Resource JSON policy element specifies the object or objects to which the action applies. Statements must include either a Resource or a NotResource element. As a best practice, specify a resource using its Amazon Resource Name (ARN). You can do this for actions that support a specific resource type, known as resource-level permissions. For actions that don't support resource-level permissions, such as listing operations, use a wildcard (*) to indicate that the statement applies to all resources. "Resource": "*" For actions that supports resource-level permission, such as the AnalyzeDocument and GetAdapteroperations, use the ARN to indicate the resources: "Resource": [ # Adapter ARN "arn:aws:textract:<region>:<account-id>:/adapters/<adapter-id>", # Adapter version ARN "arn:aws:textract:<region>:<account-id>:/adapters/<adapter-id>/versions/<version>", # Use wildcard to indicate all versions under an adapter "arn:aws:textract:<region>:<account-id>:/adapters/<adapter-id>/versions/*" ] Condition Keys Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Condition element (or Condition block) lets you specify conditions in which a statement is in effect. The Condition element is optional. You can create conditional expressions that use condition operators, such as equals or less than, to match the condition in the policy with values in the request. How Amazon Textract Works with IAM 379 Amazon Textract Developer Guide If you specify multiple Condition elements in a statement, or multiple keys in a single Condition element, AWS evaluates them using a logical AND operation. If you specify multiple values for a single condition key, AWS evaluates the condition using a logical OR operation. All of the conditions must be met before the statement's permissions are granted. You can also use placeholder variables when you specify conditions. For example, you can grant an IAM user permission to access a resource only if it is tagged with their IAM user name. For more information, see IAM policy elements: variables and tags in the IAM User Guide. AWS supports global condition keys and service-specific condition keys. To see all AWS global condition keys, see AWS global condition context keys in the IAM User Guide. Amazon Textract does not provide any service-specific condition keys, but it does support using some global condition keys. For a list of all AWS global condition keys, see AWS Global Condition Context Keys in the IAM User Guide. Examples To view examples of Amazon Textract identity-based policies, see Amazon Textract Identity-Based Policy Examples. Amazon Textract Resource-Based Policies Amazon Textract does not support resource-based policies. Authorization Based on Amazon Textract Tags Amazon Textract resources supports tagging resources and controlling access based on tags. You can use the TagResource, UntagResource, and ListTagsForResource operations to manage resource tags. For access control based on tags, you can refer to AccessTags. Amazon Textract IAM Roles An IAM role is an entity within your AWS account that has specific permissions. How Amazon Textract Works with IAM 380 Amazon Textract Developer Guide Using Temporary Credentials with Amazon Textract You can use temporary credentials to sign in with federation, assume an IAM role, or to assume a cross-account role. You obtain temporary security credentials by calling AWS STS API operations such as AssumeRole or GetFederationToken. Amazon Textract supports using temporary credentials. Service-Linked Roles Service-linked roles allow AWS services to access resources in other services to complete an action on your behalf. Service-linked roles appear in your IAM account and are owned by the service. An IAM administrator can view but not edit the permissions for service-linked roles. Amazon Textract does not support service-linked roles. Note Because Amazon Textract does not support service-linked roles, it does not support AWS
textract-dg-091
textract-dg.pdf
91
federation, assume an IAM role, or to assume a cross-account role. You obtain temporary security credentials by calling AWS STS API operations such as AssumeRole or GetFederationToken. Amazon Textract supports using temporary credentials. Service-Linked Roles Service-linked roles allow AWS services to access resources in other services to complete an action on your behalf. Service-linked roles appear in your IAM account and are owned by the service. An IAM administrator can view but not edit the permissions for service-linked roles. Amazon Textract does not support service-linked roles. Note Because Amazon Textract does not support service-linked roles, it does not support AWS service principals. For more information about service principals, see AWS service principals in the IAM User Guide. Service Roles This feature allows a service to assume a service role on your behalf. This role allows the service to access resources in other services to complete an action on your behalf. Service roles appear in your IAM account and are owned by the account. This means that an IAM administrator can change the permissions for this role. However, doing so might break the functionality of the service. Amazon Textract supports service roles. If you are using a service role, you should ensure that your account is secure by limiting the scope of Amazon Textract access to only the resources that you're using. To do this, attach a trust policy to your IAM service role. For more information, see Cross-service confused deputy prevention. Amazon Textract Identity-Based Policy Examples By default, users and roles don't have permission to create or modify Amazon Textract resources. They also can't perform tasks using the AWS Management Console, AWS CLI, or AWS API. An Identity-Based Policy Examples 381 Amazon Textract Developer Guide administrator must create IAM policies that grant users and roles permission to perform specific API operations on the specified resources they need. The administrator then grants a user access to a role via temporary security credentials. To learn how to create an IAM identity-based policy using these example JSON policy documents, see Creating Policies on the JSON Tab in the IAM User Guide. Topics • Policy Best Practices • Allow Users to View Their Own Permissions • Giving Access to Synchronous Operations in Amazon Textract • Giving Access to Asynchronous Operations in Amazon Textract • Giving access to specific adapters in inference operations in Amazon Textract • Disallow user to use adapters in inference operations • Allow user to only use a specific group of adapters in inference operations, or no adapters Policy Best Practices Identity-based policies determine whether someone can create, access, or delete Amazon Textract resources in your account. These actions can incur costs for your AWS account. When you create or edit identity-based policies, follow these guidelines and recommendations: • Get started with AWS managed policies and move toward least-privilege permissions – To get started granting permissions to your users and workloads, use the AWS managed policies that grant permissions for many common use cases. They are available in your AWS account. We recommend that you reduce permissions further by defining AWS customer managed policies that are specific to your use cases. For more information, see AWS managed policies or AWS managed policies for job functions in the IAM User Guide. • Apply least-privilege permissions – When you set permissions with IAM policies, grant only the permissions required to perform a task. You do this by defining the actions that can be taken on specific resources under specific conditions, also known as least-privilege permissions. For more information about using IAM to apply permissions, see Policies and permissions in IAM in the IAM User Guide. • Use conditions in IAM policies to further restrict access – You can add a condition to your policies to limit access to actions and resources. For example, you can write a policy condition to Identity-Based Policy Examples 382 Amazon Textract Developer Guide specify that all requests must be sent using SSL. You can also use conditions to grant access to service actions if they are used through a specific AWS service, such as AWS CloudFormation. For more information, see IAM JSON policy elements: Condition in the IAM User Guide. • Use IAM Access Analyzer to validate your IAM policies to ensure secure and functional permissions – IAM Access Analyzer validates new and existing policies so that the policies adhere to the IAM policy language (JSON) and IAM best practices. IAM Access Analyzer provides more than 100 policy checks and actionable recommendations to help you author secure and functional policies. For more information, see Validate policies with IAM Access Analyzer in the IAM User Guide. • Require multi-factor authentication (MFA) – If you have a scenario that requires IAM users or a root user in your AWS account, turn on MFA for additional security. To require MFA when
textract-dg-092
textract-dg.pdf
92
IAM policies to ensure secure and functional permissions – IAM Access Analyzer validates new and existing policies so that the policies adhere to the IAM policy language (JSON) and IAM best practices. IAM Access Analyzer provides more than 100 policy checks and actionable recommendations to help you author secure and functional policies. For more information, see Validate policies with IAM Access Analyzer in the IAM User Guide. • Require multi-factor authentication (MFA) – If you have a scenario that requires IAM users or a root user in your AWS account, turn on MFA for additional security. To require MFA when API operations are called, add MFA conditions to your policies. For more information, see Secure API access with MFA in the IAM User Guide. For more information about best practices in IAM, see Security best practices in IAM in the IAM User Guide. Allow Users to View Their Own Permissions This example shows how you might create a policy that allows IAM users to view the inline and managed policies that are attached to their user identity. This policy includes permissions to complete this action on the console or programmatically using the AWS CLI or AWS API. { "Version": "2012-10-17", "Statement": [ { "Sid": "ViewOwnUserInfo", "Effect": "Allow", "Action": [ "iam:GetUserPolicy", "iam:ListGroupsForUser", "iam:ListAttachedUserPolicies", "iam:ListUserPolicies", "iam:GetUser" ], "Resource": ["arn:aws:iam::*:user/${aws:username}"] }, { Identity-Based Policy Examples 383 Amazon Textract Developer Guide "Sid": "NavigateInConsole", "Effect": "Allow", "Action": [ "iam:GetGroupPolicy", "iam:GetPolicyVersion", "iam:GetPolicy", "iam:ListAttachedGroupPolicies", "iam:ListGroupPolicies", "iam:ListPolicyVersions", "iam:ListPolicies", "iam:ListUsers" ], "Resource": "*" } ] } Giving Access to Synchronous Operations in Amazon Textract This example policy grants access to the synchronous actions in Amazon Textract to an IAM user in your AWS account. "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "textract:DetectDocumentText", "textract:AnalyzeDocument" ], "Resource": "*" } ] Giving Access to Asynchronous Operations in Amazon Textract The following example policy gives an IAM user on your AWS account access to all asynchronous operations used in Amazon Textract. { "Version": "2012-10-17", Identity-Based Policy Examples 384 Amazon Textract Developer Guide "Statement": [ { "Effect": "Allow", "Action": [ "textract:StartDocumentTextDetection", "textract:StartDocumentAnalysis", "textract:GetDocumentTextDetection", "textract:GetDocumentAnalysis" ], "Resource": "*" } ] } Giving access to specific adapters in inference operations in Amazon Textract Although you can use * to access all resources in inference operations, you can control a user's access to specific adapters. { "Version": "2012-10-17", "Statement": [ { "Sid": "OnlyAllowAccessVersionsOneAdapter", "Effect": "Allow", "Action": [ "textract:AnalyzeDocument", "textract:StartDocumentAnalysis" ], "Resource": [ "arn:aws:textract:<region>:<account-id>:/adapters/<adapter-id>/versions/*" ] } ] } Disallow user to use adapters in inference operations { "Version": "2012-10-17", "Statement": [ { Identity-Based Policy Examples 385 Amazon Textract Developer Guide "Sid": "AllowUsingTextractInferenceAPI", "Effect": "Allow", "Action": [ "textract:AnalyzeDocument", "textract:StartDocumentAnalysis" ], "Resource": [ "*" ] }, { "Sid": "DenyUsingAdaptersForInferenceAPI", "Effect": "Deny", "Action": [ "textract:AnalyzeDocument", "textract:StartDocumentAnalysis" ], "Resource": [ "arn:aws:textract:<region>:<account-id>:/adapters/*" ] } ] } Allow user to only use a specific group of adapters in inference operations, or no adapters Tag the specific adapters that you want to control by using the TagResource operation. The following example controls access to adapters tagged with {"env":"prod"}. { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowUsingTextractInferenceAPI", "Effect": "Allow", "Action": [ "textract:AnalyzeDocument", "textract:StartDocumentAnalysis" ], "Resource": [ "*" ] Identity-Based Policy Examples 386 Developer Guide Amazon Textract }, { "Sid": "DenyAdaptersWithoutSpecificTags", "Effect": "Deny", "Action": [ "textract:AnalyzeDocument", "textract:StartDocumentAnalysis" ], "Resource": [ "arn:aws:textract:<region>:<account-id>:/adapters/*" ], "Condition": { "StringNotEquals": { "aws:ResourceTag/env": "prod" } } } ] } Allow user to manage adapter and versions { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowManagingAdapterAndVersions", "Effect": "Allow", "Action": [ "textract:GetAdapter", "textract:DeleteAdapter", "textract:UpdateAdapter", "textract:GetAdapterVersion", "textract:DeleteAdapterVersion" ], "Resource": [ "arn:aws:textract:<region>:<account-id>:/adapters/<adapter-id>/versions/*" ] }, { "Sid": "AllowCreatingAndListingAdpaterAndVersions", "Effect": "Allow", "Action": [ Identity-Based Policy Examples 387 Amazon Textract Developer Guide "textract:CreateAdapter", "textract:CreateAdapterVersion", "textract:ListAdpaters", "textract:ListAdapterVersions" ], "Resource": [ "*" ] } ] } Permissions needed for CreateAdapterVersion In addition to "textract:CreateAdapterVersion" permission, the caller identity also needs Amazon S3 and AWS Key Management Service (AWS KMS) permission to your training data in Amazon S3 and the KMS key used to encrypt your data. { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCreatingAdapterVersions", "Effect": "Allow", "Action": [ "textract:CreateAdapterVersion" ], "Resource": [ "arn:aws:textract:<region>:<account-id>:/adapters/<adapter-id>" ] }, { "Sid": "AllowAccessingDataset", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:GetObjectVersion" ], "Resource": [ "arn:aws:s3:::datasetBucketName/*" ] }, { Identity-Based Policy Examples 388 Amazon Textract Developer Guide "Sid": "AllowAccessingOutputBucket", "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject", "s3:GetObjectVersion" ], "Resource": [ "arn:aws:s3:::outputConfigBucketName/*" ] }, { "Sid": "AllowUsingKmsKey", "Effect": "Allow", "Action": [ "kms:Decrypt", "kms:ReEncrypt", "kms:GenerateDataKey", "kms:DescribeKey" ], "Resource": [ "<KMS key ARN>" ] } ] } Troubleshooting Amazon Textract Identity and Access Use the following information to help you diagnose and fix common issues that you might encounter when working with Amazon Textract and IAM. Topics • I Am Not Authorized to Perform an Action in Amazon Textract • I Am Not Authorized to Perform iam:PassRole • I Want to Allow People Outside of My AWS Account to Access My Amazon Textract Resources Troubleshooting 389 Amazon Textract Developer Guide I Am Not
textract-dg-093
textract-dg.pdf
93
"arn:aws:s3:::outputConfigBucketName/*" ] }, { "Sid": "AllowUsingKmsKey", "Effect": "Allow", "Action": [ "kms:Decrypt", "kms:ReEncrypt", "kms:GenerateDataKey", "kms:DescribeKey" ], "Resource": [ "<KMS key ARN>" ] } ] } Troubleshooting Amazon Textract Identity and Access Use the following information to help you diagnose and fix common issues that you might encounter when working with Amazon Textract and IAM. Topics • I Am Not Authorized to Perform an Action in Amazon Textract • I Am Not Authorized to Perform iam:PassRole • I Want to Allow People Outside of My AWS Account to Access My Amazon Textract Resources Troubleshooting 389 Amazon Textract Developer Guide I Am Not Authorized to Perform an Action in Amazon Textract If the AWS Management Console tells you that you're not authorized to perform an action, then you must contact your administrator for assistance. Your administrator is the person that provided you with your username and password. The following example error occurs when the mateojackson IAM user tries to run DetectDocumentText on a test image but does not have textract:DetectDocumentText permissions. User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: textract:DetectDocumentText on resource: textimage.png In this case, Mateo asks their administrator to update their policies to allow access to the textimage.png resource using the textract:DetectDocumentText action. I Am Not Authorized to Perform iam:PassRole If you receive an error that you're not authorized to perform the iam:PassRole action, your policies must be updated to allow you to pass a role to Amazon Textract. Some AWS services allow you to pass an existing role to that service instead of creating a new service role or service-linked role. To do this, you must have permissions to pass the role to the service. The following example error occurs when an IAM user named marymajor tries to use the console to perform an action in Amazon Textract. However, the action requires the service to have permissions that are granted by a service role. Mary does not have permissions to pass the role to the service. User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole In this case, Mary's policies must be updated to allow her to perform the iam:PassRole action. If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials. Troubleshooting 390 Amazon Textract Developer Guide I Want to Allow People Outside of My AWS Account to Access My Amazon Textract Resources You can create a role that users in other accounts or people outside of your organization can use to access your resources. You can specify who is trusted to assume the role. For services that support resource-based policies or access control lists (ACLs), you can use those policies to grant people access to your resources. To learn more, consult the following: • To learn whether Amazon Textract supports these features, see How Amazon Textract Works with IAM. • To learn how to provide access to your resources across AWS accounts that you own, see Providing access to an IAM user in another AWS account that you own in the IAM User Guide. • To learn how to provide access to your resources to third-party AWS accounts, see Providing access to AWS accounts owned by third parties in the IAM User Guide. • To learn how to provide access through identity federation, see Providing access to externally authenticated users (identity federation) in the IAM User Guide. • To learn the difference between using roles and resource-based policies for cross-account access, see Cross account resource access in IAM in the IAM User Guide. Logging and Monitoring To monitor Amazon Textract, use Amazon CloudWatch. This section provides information on how to set up monitoring for Amazon Textract. It also provides reference content for Amazon Textract metrics. Topics • Monitoring Amazon Textract • CloudWatch Metrics for Amazon Textract Monitoring Amazon Textract With CloudWatch, you can get metrics for individual Amazon Textract operations or global Amazon Textract metrics for your account. You can use metrics to track the health of your Amazon Textract– based solution, and set up alarms to notify you when one or more metrics fall outside a defined Logging and Monitoring 391 Amazon Textract Developer Guide threshold. For example, you can see metrics for the number of server errors that have occurred. You can also see metrics for the number of times a specific Amazon Textract operation has succeeded. To see metrics, you can use Amazon CloudWatch, the AWS CLI, or the CloudWatch API. Using CloudWatch Metrics for Amazon Textract To use metrics, you must specify the following information: • The metric dimension or no dimension. A dimension is a name-value pair that helps you to uniquely identify a metric. Amazon Textract has one dimension, named Operation. It provides metrics for a specific operation. If you don't specify a dimension, the metric is scoped to all Amazon Textract operations within your
textract-dg-094
textract-dg.pdf
94
occurred. You can also see metrics for the number of times a specific Amazon Textract operation has succeeded. To see metrics, you can use Amazon CloudWatch, the AWS CLI, or the CloudWatch API. Using CloudWatch Metrics for Amazon Textract To use metrics, you must specify the following information: • The metric dimension or no dimension. A dimension is a name-value pair that helps you to uniquely identify a metric. Amazon Textract has one dimension, named Operation. It provides metrics for a specific operation. If you don't specify a dimension, the metric is scoped to all Amazon Textract operations within your account. • The metric name, such as UserErrorCount. You can get monitoring data for Amazon Textract by using the AWS Management Console, the AWS CLI, or the CloudWatch API. You can also use the CloudWatch API through one of the Amazon AWS Software Development Kits (SDKs) or the CloudWatch API tools. The console displays a series of graphs based on the raw data from the CloudWatch API. Depending on your needs, you might prefer to use either the graphs displayed in the console or retrieved from the API. The following list shows some common uses for the metrics. These are suggestions to get you started, not a comprehensive list. How Do I? Relevant Metrics How do I know if my application has reached the maximum number of requests per second? Monitor the Sum statistic of the Throttled Count metric. How can I monitor the request errors? How can I find the total number of requests? Use the Sum statistic of the UserError Count metric. Use the SampleCount statistic of the ResponseTime metric. This includes any request that results in an error. If you want to see only successful operation calls, use the SuccessfulRequestCount metric. Monitoring 392 Amazon Textract How Do I? How can I monitor the latency of Amazon Textract operation calls? Developer Guide Relevant Metrics Use the ResponseTime metric. You must have the appropriate CloudWatch permissions to monitor Amazon Textract with CloudWatch. For more information, see Authentication and Access Control for Amazon CloudWatch. Access Amazon Textract Metrics The following examples show how to access Amazon Textract metrics using the CloudWatch console, the AWS CLI, and the CloudWatch API. To view metrics (console) 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. Choose Metrics, choose the All Metrics tab, and then choose Amazon Textract. 3. Choose By operation, and then choose a metric. For example, choose the StartDocumentAnalysis metric to measure how many times asynchronous document analysis has been started. 4. Choose a value for the date range. The metric count displayed in the graph. To view metrics for successful StartDocumentAnalysis operation calls that have been made over a period of time (CLI) • Open the AWS CLI and enter the following command: aws cloudwatch get-metric-statistics \ --metric-name SuccessfulRequestCount \ --start-time 2019-02-01T00:00:00Z \ --period 3600 \ --end-time 2019-03-01T00:00:00Z \ --namespace AWS/Textract \ --dimensions Name=Operation,Value=StartDocumentAnalysis \ --statistics Sum Monitoring 393 Amazon Textract Developer Guide This example shows the successful StartDocumentAnalysis operation calls made over a period of time. For more information, see get-metric-statistics. To access metrics (CloudWatch API) • Call GetMetricStatistics. For more information, see the Amazon CloudWatch API Reference. Create an Alarm You can create a CloudWatch alarm that sends an Amazon Simple Notification Service (Amazon SNS) message when the alarm changes state. An alarm watches a single metric over a time period that you specify. It performs one or more actions based on the value of the metric relative to a given threshold over a number of time periods. The action is a notification sent to an Amazon SNS topic or an Auto Scaling policy. Alarms invoke actions for sustained state changes only. CloudWatch alarms don't invoke actions simply because they are in a particular state. The state must have changed and have been maintained for a specified number of time periods. To set an alarm (console) 1. Sign in to the AWS Management Console and open the CloudWatch console at https:// console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Alarms, and choose Create Alarm. This opens the Create Alarm Wizard. 3. Choose Select metric. 4. In the All metrics tab, choose Textract. 5. Choose By Operation, and then choose a metric. For example, choose StartDocumentAnalysis to set an alarm for a maximum number of asynchronous document analysis operations. 6. Choose the Graphed metrics tab. 7. For Statistic, choose Sum. 8. Choose Select metric. Monitoring 394 Amazon Textract Developer Guide 9. 10. Fill in the Name and Description. For Whenever, choose >=, and enter a maximum value of your choice. If you want CloudWatch to send you email when the alarm state is reached, for Whenever this alarm:, choose State is ALARM. To send alarms to an existing Amazon SNS topic, for Send notification to:, choose an existing SNS topic. To
textract-dg-095
textract-dg.pdf
95
metric. For example, choose StartDocumentAnalysis to set an alarm for a maximum number of asynchronous document analysis operations. 6. Choose the Graphed metrics tab. 7. For Statistic, choose Sum. 8. Choose Select metric. Monitoring 394 Amazon Textract Developer Guide 9. 10. Fill in the Name and Description. For Whenever, choose >=, and enter a maximum value of your choice. If you want CloudWatch to send you email when the alarm state is reached, for Whenever this alarm:, choose State is ALARM. To send alarms to an existing Amazon SNS topic, for Send notification to:, choose an existing SNS topic. To set the name and email addresses for a new email subscription list, choose New list. CloudWatch saves the list and displays it in the field so you can use it to set future alarms. Note If you use New list to create a new Amazon SNS topic, the email addresses must be verified before the intended recipients receive notifications. Amazon SNS sends email only when the alarm enters an alarm state. If this alarm state change happens before the email addresses are verified, intended recipients don't receive a notification. 11. Choose Create Alarm. To set an alarm (AWS CLI) • Open the AWS CLI and enter the following command. Change the value of the alarm- actions parameter to reference an Amazon SNS topic that you previously created. aws cloudwatch put-metric-alarm \ --alarm-name StartDocumentAnalysisUserErrors \ --alarm-description "Alarm when more than 10 StartDocumentAnalysys user errors occur within 5 minutes" \ --metric-name UserErrorCount \ --namespace AWS/Textract \ --statistic Sum \ --period 300 \ --threshold 10 \ --comparison-operator GreaterThanThreshold \ --evaluation-periods 1 \ --unit Count \ --dimensions Name=Operation,Value=StartDocumentAnalysis \ --alarm-actions arn:aws:sns:us-east-1:111111111111:alarmtopic This example shows how to create an alarm for when more than 10 user errors occur within 5 minutes for calls to StartDocumentAnalysis. For more information, see put-metric-alarm. Monitoring 395 Amazon Textract Developer Guide To set an alarm (CloudWatch API) • Call PutMetricAlarm. For more information, see Amazon CloudWatch API Reference. CloudWatch Metrics for Amazon Textract This section contains information about the Amazon CloudWatch metrics and the Operation dimension that are available for Amazon Textract. You can also see an aggregate view of Amazon Textract metrics from the Amazon Textract console. CloudWatch Metrics for Amazon Textract The following table summarizes the Amazon Textract metrics. Metric Description Successfu lRequestCount The number of successful requests. The response code range for a successful request is 200 to 299. Unit: Count Valid statistics: Sum,Average ThrottledCount The number of throttled requests. Amazon Textract throttles a request when it receives more requests than the limit of transactions per second set for your account. If the limit set for your account is frequently exceeded, you can request a limit increase. To change a limit, select the Amazon Textract option in the Service Quotas console. Unit: Count Valid statistics: Sum,Average ResponseTime The time in milliseconds for Amazon Textract to compute the response. Units: CloudWatch Metrics for Amazon Textract 396 Amazon Textract Developer Guide Metric Description 1. Count for Data Samples statistics 2. Milliseconds for Average statistics Valid statistics: Data Samples,Average Note The ResponseTime metric isn't included in the Amazon Textract metric pane. ServerErr orCount The number of server errors. The response code range for a server error is 500 to 599. Unit: Count Valid statistics: Sum,Average UserErrorCount The number of user errors (invalid parameters, invalid image, no permission, and so on). The response code range for a user error is 400 to 499. Unit: Count Valid statistics: Sum,Average CloudWatch Dimension for Amazon Textract To retrieve operation-specific metrics, use the AWS/Textract namespace and provide an operation dimension. For more information about dimensions, see Dimensions in the Amazon CloudWatch User Guide. Logging Amazon Textract API Calls with AWS CloudTrail Amazon Textract is integrated with AWS CloudTrail, a service that provides a record of actions taken by a user, role, or an AWS service in Amazon Textract. CloudTrail captures all API calls for Logging Amazon Textract API Calls with AWS CloudTrail 397 Amazon Textract Developer Guide Amazon Textract as events. The calls captured include calls from the Amazon Textract console and code calls to the Amazon Textract API operations. If you create a trail, you can enable continuous delivery of CloudTrail events to an Amazon S3 bucket, including events for Amazon Textract. If you don't configure a trail, you can still view the most recent events in the CloudTrail console in Event history. Using the information collected by CloudTrail, you can determine the request that was made to Amazon Textract, the IP address that the request was made from, who made the request, when it was made, and additional details. To learn more about CloudTrail, see the AWS CloudTrail User Guide. Amazon Textract Information in CloudTrail CloudTrail is enabled on your AWS account when you create the account. When activity occurs in Amazon Textract,
textract-dg-096
textract-dg.pdf
96
Amazon S3 bucket, including events for Amazon Textract. If you don't configure a trail, you can still view the most recent events in the CloudTrail console in Event history. Using the information collected by CloudTrail, you can determine the request that was made to Amazon Textract, the IP address that the request was made from, who made the request, when it was made, and additional details. To learn more about CloudTrail, see the AWS CloudTrail User Guide. Amazon Textract Information in CloudTrail CloudTrail is enabled on your AWS account when you create the account. When activity occurs in Amazon Textract, that activity is recorded in a CloudTrail event along with other AWS service events in Event history. You can view, search, and download recent events in your AWS account. For more information, see Viewing Events with CloudTrail Event History. For an ongoing record of events in your AWS account, including events for Amazon Textract, create a trail. A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you create a trail in the console, the trail applies to all AWS Regions. The trail logs events from all Regions in the AWS partition and delivers the log files to the Amazon S3 bucket that you specify. Additionally, you can configure other AWS services to further analyze and act upon the event data that's collected in CloudTrail logs. For more information, see the following: • Overview for Creating a Trail • CloudTrail Supported Services and Integrations • Configuring Amazon SNS Notifications for CloudTrail • Receiving CloudTrail Log Files from Multiple Regions and Receiving CloudTrail Log Files from Multiple Accounts All Amazon Textract operations are logged by CloudTrail and are documented in the API Reference. For example, calls to the DetectDocumentText, AnalyzeDocument, and GetDocumentText actions generate entries in the CloudTrail log files. Every event or log entry contains information about who generated the request. The identity information helps you determine the following: • Whether the request was made with root or user credentials. Amazon Textract Information in CloudTrail 398 Amazon Textract Developer Guide • Whether the request was made with temporary security credentials for a role or federated user. • Whether the request was made by another AWS service. For more information, see the CloudTrail userIdentity Element. Request Parameters and Response Fields That Aren't Logged For privacy purposes, certain request parameters and response fields aren't logged—for example, request image bytes or response bounding box information. Amazon S3 bucket names and file names supplied in request parameters are provided in CloudTrail log entries. No information about image bytes passed in a request is provided in a CloudTrail log. The following table shows the input parameters and response parameters that aren't logged for each Amazon Textract operation. Operation Request Parameters Response Fields AnalyzeDocument DetectDocumentText StartDocumentAnalysis GetDocumentAnalysis Bytes Bytes None None StartDocumentTextDetection None GetDocumentTextDetection None All All None All None All Understanding Amazon Textract Log File Entries A trail is a configuration that enables delivery of events as log files to an Amazon S3 bucket that you specify. CloudTrail log files contain one or more log entries. An event represents a single request from any source and includes information about the requested operation, the date and time of the operation, request parameters, and so on. CloudTrail log files aren't an ordered stack trace of the public API calls, so they don't appear in any specific order. The following example shows a CloudTrail log entry that demonstrates the AnalyzeDocument operation. The image bytes for the input document and the analysis results (responseElements) aren't logged. Understanding Amazon Textract Log File Entries 399 Amazon Textract Developer Guide { "eventVersion": "1.05", "userIdentity": { "type": "IAMUser", "principalId": "AIDACKCEVSQ6C2EXAMPLE", "arn": "arn:aws:iam::111111111111:user/janedoe", "accountId": "111111111111", "accessKeyId": "AIDACKCEVSQ6C2EXAMPLE", "userName": "janedoe" }, "eventTime": "2019-04-03T23:56:31Z", "eventSource": "textract.amazonaws.com", "eventName": "AnalyzeDocument", "awsRegion": "us-east-1", "sourceIPAddress": "198.51.100.0", "userAgent": "", "requestParameters": { "document": {}, "featureTypes": [ "TABLES" ] }, "responseElements": null, "requestID": "e387676b-d1f0-4ea7-85d6-f5a344052dce", "eventID": "c5db79ce-e4ea-4401-8517-784481d559f7", "eventType": "AwsApiCall", "recipientAccountId": "111111111111" } The following example shows a CloudTrail log entry for the StartDocumentAnalysis operation. The log entry includes the Amazon S3 bucket name and image file name in documentLocation. The log also includes the operation response. { "Records": [ { "eventVersion": "1.05", "userIdentity": { "type": "IAMUser", "principalId": "AIDACKCEVSQ6C2EXAMPLE", "arn": "arn:aws:iam::111111111111:user/janedoe", "accountId": "11111111111", Understanding Amazon Textract Log File Entries 400 Amazon Textract Developer Guide "accessKeyId": "AKIAIOSFODNN7EXAMPLE", "userName": "janedoe" }, "eventTime": "2019-04-04T01:42:24Z", "eventSource": "textract.amazonaws.com", "eventName": "StartDocumentAnalysis", "awsRegion": "us-east-1", "sourceIPAddress": "198.51.100.0", "userAgent": "", "requestParameters": { "documentLocation": { "s3Object": { "bucket": "bucket", "name": "document.png" } }, "featureTypes": [ "TABLES" ] }, "responseElements": { "jobId": "f3c718b444fa603d5d625ab967008f4b620d4650c9db8ca1cae01ef7efe51373" }, "requestID": "9ae352e8-9de1-41ad-b77b-85aa348c2e82", "eventID": "f741bca0-c3cb-4805-82ea-baf76439deef", "eventType": "AwsApiCall", "recipientAccountId": "111111111111" } ] } Tagging resources With Amazon Textract, you can tag resources like adapters for the purposes of managing secure access. To tag resources, use an AWS SDK or the AWS CLI. The topics in this section demonstrate
textract-dg-097
textract-dg.pdf
97
"arn": "arn:aws:iam::111111111111:user/janedoe", "accountId": "11111111111", Understanding Amazon Textract Log File Entries 400 Amazon Textract Developer Guide "accessKeyId": "AKIAIOSFODNN7EXAMPLE", "userName": "janedoe" }, "eventTime": "2019-04-04T01:42:24Z", "eventSource": "textract.amazonaws.com", "eventName": "StartDocumentAnalysis", "awsRegion": "us-east-1", "sourceIPAddress": "198.51.100.0", "userAgent": "", "requestParameters": { "documentLocation": { "s3Object": { "bucket": "bucket", "name": "document.png" } }, "featureTypes": [ "TABLES" ] }, "responseElements": { "jobId": "f3c718b444fa603d5d625ab967008f4b620d4650c9db8ca1cae01ef7efe51373" }, "requestID": "9ae352e8-9de1-41ad-b77b-85aa348c2e82", "eventID": "f741bca0-c3cb-4805-82ea-baf76439deef", "eventType": "AwsApiCall", "recipientAccountId": "111111111111" } ] } Tagging resources With Amazon Textract, you can tag resources like adapters for the purposes of managing secure access. To tag resources, use an AWS SDK or the AWS CLI. The topics in this section demonstrate how to manage your tags using the CLI. Tagging resources 401 Amazon Textract Tag resource Developer Guide Amazon Textract resources like adapters can be tagged using the TagResource operation. Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values. To tag a resource, use the TagResource operation and specify a list of tags as key-value pairs. To tag a resource with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract tag-resource --resource-arn arn:aws:textract:us-east-1:000000000000:/ adapters/a1b2c3d4e5c6 --tags Tag=Key List tags for resource Amazon Textract resources like adapters can be tagged using the TagResource operation. You can list all the tags associated with a resource by using the ListTagsForResource operation and providing the Amazon Resource Name (ARN) associated with the resource that you want to retrieve tags for. To list tags for a resource with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract list-tags-for-resource --region us-east-1 --resource-arn arn:aws:textract:us-east-1:000000000000:/adapters/a1b2c3d4e5c6 \ Tag resource 402 Amazon Textract { "Tags": { "Tag": "Key" } } Untag resource Developer Guide Amazon Textract resources like adapters can be tagged using the TagResource operation. You can remove any tags you no longer need from a resource by using the UntagResource operation. When calling UntagResource, provide the Amazon Resource Name (ARN) of the resource that you want to remove tags from. Also include a list of the tag-specific key values that you want to remove from the resource. To untag a resource with the AWS CLI or AWS SDK: • If you haven't already done so, install and configure the AWS CLI and the AWS SDKs. For more information, see Step 2: Set Up the AWS CLI and AWS SDKs. • Use the following code to create an adapter: CLI aws textract untag-resource --region us-east-1 arn:aws:textract:us- east-1:000000000000:/adapters/a1b2c3d4e5c6 --tag-keys Tag Compliance Validation for Amazon Textract Third-party auditors assess the security and compliance of Amazon Textract as part of multiple AWS compliance programs. These include HIPAA, SOC, ISO, and PCI. Untag resource 403 Amazon Textract Note Developer Guide If you are processing data through Textract service that is subject to PCI DSS compliance then you must opt out your account by contacting AWS Support and following the process provided to you. For a list of AWS services in scope of specific compliance programs, see AWS Services in Scope by Compliance Program. For general information, see AWS Compliance Programs. You can download third-party audit reports using AWS Artifact. For more information, see Downloading Reports in AWS Artifact. Your compliance responsibility when using Amazon Textract is determined by the sensitivity of your data, your company's compliance objectives, and applicable laws and regulations. AWS provides the following resources to help with compliance: • Security and Compliance Quick Start Guides – These deployment guides discuss architectural considerations and provide steps for deploying security- and compliance-focused baseline environments on AWS. • Architecting for HIPAA Security and Compliance Whitepaper – This whitepaper describes how companies can use AWS to create HIPAA-compliant applications. • AWS Compliance Resources – This collection of workbooks and guides might apply to your industry and location. • Evaluating Resources with Rules in the AWS Config Developer Guide – The AWS Config service assesses how well your resource configurations comply with internal practices, industry guidelines, and regulations. • AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS. The security hub helps you check your compliance with security industry standards and best practices. Resilience in Amazon Textract The AWS global infrastructure is built around AWS Regions and Availability Zones. AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected with low-latency, high-throughput,
textract-dg-098
textract-dg.pdf
98
to your industry and location. • Evaluating Resources with Rules in the AWS Config Developer Guide – The AWS Config service assesses how well your resource configurations comply with internal practices, industry guidelines, and regulations. • AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS. The security hub helps you check your compliance with security industry standards and best practices. Resilience in Amazon Textract The AWS global infrastructure is built around AWS Regions and Availability Zones. AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected with low-latency, high-throughput, and highly redundant networking. With Availability Zones, you can design and operate applications and databases that automatically fail over between zones Resilience 404 Amazon Textract Developer Guide without interruption. Availability Zones are more highly available, fault tolerant, and scalable than traditional single or multiple data center infrastructures. For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure. Note Cross region transfer of data is not permitted due to the General Data Protection Regulation (GDPR). Cross-service confused deputy prevention In AWS, cross-service impersonation can occur when one service (the calling service) calls another service (the called service). The calling service can be manipulated to act on another customer's resources even though it shouldn't have the proper permissions, resulting in the confused deputy problem. To prevent this, AWS provides tools that help you protect your data for all services with service principals that have been given access to resources in your account. We recommend using the aws:SourceArn and aws:SourceAccount global condition context keys in resource policies to limit the permissions that Amazon Textract gives another service to the resource. If the value of aws:SourceArn does not contain the account ID, such as an Amazon S3 bucket ARN, you must use both keys to limit permissions. If you use both keys and the aws:SourceArn value contains the account ID, the aws:SourceAccount value and the account in the aws:SourceArn value must use the same account ID when used in the same policy statement. Use aws:SourceArn if you want only one resource to be associated with the cross-service access. Use aws:SourceAccount if you want to allow any resource in that account to be associated with the cross-service use. The value of aws:SourceArn must be the ARN of the resource used by Textract, which is specified with the following format: arn:aws:rekognition:region:account:resource. The recommended approach to the confused deputy problem is to use the aws:SourceArn global condition context key with the full resource ARN. Cross-service confused deputy prevention 405 Amazon Textract Developer Guide If you don't know the full ARN of the resource or if you are specifying multiple resources, use the aws:SourceArn key with wildcard characters (*) for the unknown portions of the ARN. For example, arn:aws:textract:*:111122223333:*. In order to protect against the confused deputy problem, carry out the following steps: 1. In the navigation pane of the IAM console choose the Roles option. The console will display the roles for your current account. 2. Choose the name of the role that you want to modify. The role you modify should have the AmazonTextractServiceRole permissions policy. Select the Trust relationships tab. 3. Choose Edit trust policy. 4. On the Edit trust policy page, replace the default JSON policy with a policy that utilizes one or both of the aws:SourceArn and aws:SourceAccount global condition context keys. See the following example policies. 5. Choose Update policy. The following examples are trust policies that show how you can use the aws:SourceArn and aws:SourceAccount global condition context keys in Amazon Textract to prevent the confused deputy problem. You can specify multiple accounts in both the SourceAccount and SourceArn condition. Be sure to specify the ID of any trusted account in both conditions. If you are working with Amazon Textract's asynchronous operations, you could use a policy like the following in your IAM role. In the example below, replace the red replaceable text with the IDs of the accounts calling the API operations (your account ID and the IDs of any other trusted accounts): { "Version": "2012-10-17", "Statement": { "Sid": "ConfusedDeputyPreventionExamplePolicy", "Effect": "Allow", "Principal": { "Service": "textract.amazonaws.com" }, "Action": "sts:AssumeRole", "Condition": { "ArnLike": { Cross-service confused deputy prevention 406 Amazon Textract "aws:SourceArn": Developer Guide ["arn:aws:textract:*:123456789012:*","arn:aws:textract:*:111122223333:*"] }, "StringEquals": { "aws:SourceAccount": ["123456789012", "111122223333"] } } } } Infrastructure Security in Amazon Textract As a managed service, Amazon Textract is protected by AWS global network security. For information about AWS security services and how AWS protects infrastructure, see AWS Cloud Security. To design your AWS environment using the best practices for infrastructure security, see Infrastructure Protection in Security Pillar AWS Well‐Architected Framework. You use AWS published API calls to access Amazon Textract through the network. Clients must support the following: • Transport Layer Security (TLS). We require TLS 1.2 and recommend
textract-dg-099
textract-dg.pdf
99
406 Amazon Textract "aws:SourceArn": Developer Guide ["arn:aws:textract:*:123456789012:*","arn:aws:textract:*:111122223333:*"] }, "StringEquals": { "aws:SourceAccount": ["123456789012", "111122223333"] } } } } Infrastructure Security in Amazon Textract As a managed service, Amazon Textract is protected by AWS global network security. For information about AWS security services and how AWS protects infrastructure, see AWS Cloud Security. To design your AWS environment using the best practices for infrastructure security, see Infrastructure Protection in Security Pillar AWS Well‐Architected Framework. You use AWS published API calls to access Amazon Textract through the network. Clients must support the following: • Transport Layer Security (TLS). We require TLS 1.2 and recommend TLS 1.3. • Cipher suites with perfect forward secrecy (PFS) such as DHE (Ephemeral Diffie-Hellman) or ECDHE (Elliptic Curve Ephemeral Diffie-Hellman). Most modern systems such as Java 7 and later support these modes. Additionally, requests must be signed by using an access key ID and a secret access key that is associated with an IAM principal. Or you can use the AWS Security Token Service (AWS STS) to generate temporary security credentials to sign requests. Configuration and Vulnerability Analysis in Amazon Textract Configuration and IT controls are a shared responsibility between AWS and you, our customer. For more information, see the AWS shared responsibility model. Infrastructure Security 407 Amazon Textract Developer Guide Amazon Textract and interface VPC endpoints (AWS PrivateLink) You can establish a private connection between your VPC and Amazon Textract by creating an interface VPC endpoint. Interface endpoints are powered by AWS PrivateLink, a technology that enables you to privately access Amazon Textract APIs without an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection. Instances in your VPC don't need public IP addresses to communicate with Amazon Textract APIs. Traffic between your VPC and Amazon Textract does not leave the AWS network. Each interface endpoint is represented by one or more Elastic Network Interfaces in your subnets. For more information, see Interface VPC endpoints (AWS PrivateLink) in the Amazon VPC User Guide. Considerations for Amazon Textract VPC endpoints Before you set up an interface VPC endpoint for Amazon Textract, ensure that you review Interface endpoint properties and limitations in the Amazon VPC User Guide. Amazon Textract supports making calls to all of its API actions from your VPC. Creating an interface VPC endpoint for Amazon Textract You can create a VPC endpoint for the Amazon Textract service using either the Amazon VPC console or the AWS Command Line Interface (AWS CLI). For more information, see Creating an interface endpoint in the Amazon VPC User Guide. Create a VPC endpoint for Amazon Textract using the following service name: • com.amazonaws.region.textract - For creating an endpoint for most Amazon Textract operations. • com.amazonaws.region.textract-fips - For creating an endpoint for Amazon Textract that complies with the Federal Information Processing Standard (FIPS) Publication 140-2 US government standard. If you enable private DNS for the endpoint, you can make API requests to Amazon Textract using its default DNS name for the Region, for example, textract.us-east-1.amazonaws.com. VPC endpoints (AWS PrivateLink) 408 Amazon Textract Developer Guide For more information, see Accessing a service through an interface endpoint in the Amazon VPC User Guide. Creating a VPC endpoint policy for Amazon Textract You can attach an endpoint policy to your VPC endpoint that controls access to Amazon Textract. The policy specifies the following information: • The principal that can perform actions. • The actions that can be performed. • The resources on which actions can be performed. For more information, see Controlling access to services with VPC endpoints in the Amazon VPC User Guide. Example: VPC endpoint policy for Amazon Textract actions The following is an example of an endpoint policy for Amazon Textract. When attached to an endpoint, this policy grants access to the listed Amazon Textract actions for all principals on all resources. This example policy allows access to only the operations DetectDocumentText and AnalyzeDocument. Users can still call Amazon Textract operations from outside the VPC Endpoint. "Statement":[ { "Principal":"*", "Effect":"Allow", "Action":[ "textract:DetectDocumentText", "textract:AnalyzeDocument", ], "Resource":"*" } ] } Creating a VPC endpoint policy for Amazon Textract 409 Amazon Textract Developer Guide API Reference This section provides documentation for the Amazon Textract API operations. Topics • Actions • Data Types Actions The following actions are supported: • AnalyzeDocument • AnalyzeExpense • AnalyzeID • CreateAdapter • CreateAdapterVersion • DeleteAdapter • DeleteAdapterVersion • DetectDocumentText • GetAdapter • GetAdapterVersion • GetDocumentAnalysis • GetDocumentTextDetection • GetExpenseAnalysis • GetLendingAnalysis • GetLendingAnalysisSummary • ListAdapters • ListAdapterVersions • ListTagsForResource • StartDocumentAnalysis • StartDocumentTextDetection Actions 410 Amazon Textract • StartExpenseAnalysis • StartLendingAnalysis • TagResource • UntagResource • UpdateAdapter Developer Guide Actions 411 Amazon Textract AnalyzeDocument Developer Guide Analyzes an input document for relationships between detected items. The types of information returned are as follows: • Form data (key-value pairs). The related information is returned in two Block objects, each
textract-dg-100
textract-dg.pdf
100
The following actions are supported: • AnalyzeDocument • AnalyzeExpense • AnalyzeID • CreateAdapter • CreateAdapterVersion • DeleteAdapter • DeleteAdapterVersion • DetectDocumentText • GetAdapter • GetAdapterVersion • GetDocumentAnalysis • GetDocumentTextDetection • GetExpenseAnalysis • GetLendingAnalysis • GetLendingAnalysisSummary • ListAdapters • ListAdapterVersions • ListTagsForResource • StartDocumentAnalysis • StartDocumentTextDetection Actions 410 Amazon Textract • StartExpenseAnalysis • StartLendingAnalysis • TagResource • UntagResource • UpdateAdapter Developer Guide Actions 411 Amazon Textract AnalyzeDocument Developer Guide Analyzes an input document for relationships between detected items. The types of information returned are as follows: • Form data (key-value pairs). The related information is returned in two Block objects, each of type KEY_VALUE_SET: a KEY Block object and a VALUE Block object. For example, Name: Ana Silva Carolina contains a key and value. Name: is the key. Ana Silva Carolina is the value. • Table and table cell data. A TABLE Block object contains information about a detected table. A CELL Block object is returned for each cell in a table. • Lines and words of text. A LINE Block object contains one or more WORD Block objects. All lines and words that are detected in the document are returned (including text that doesn't have a relationship with the value of FeatureTypes). • Signatures. A SIGNATURE Block object contains the location information of a signature in a document. If used in conjunction with forms or tables, a signature can be given a Key-Value pairing or be detected in the cell of a table. • Query. A QUERY Block object contains the query text, alias and link to the associated Query results block object. • Query Result. A QUERY_RESULT Block object contains the answer to the query and an ID that connects it to the query asked. This Block also contains a confidence score. Selection elements such as check boxes and option buttons (radio buttons) can be detected in form data and in tables. A SELECTION_ELEMENT Block object contains information about a selection element, including the selection status. You can choose which type of analysis to perform by specifying the FeatureTypes list. The output is returned in a list of Block objects. AnalyzeDocument is a synchronous operation. To analyze documents asynchronously, use StartDocumentAnalysis. For more information, see Document Text Analysis. Request Syntax { "AdaptersConfig": { AnalyzeDocument 412 Amazon Textract Developer Guide "Adapters": [ { "AdapterId": "string", "Pages": [ "string" ], "Version": "string" } ] }, "Document": { "Bytes": blob, "S3Object": { "Bucket": "string", "Name": "string", "Version": "string" } }, "FeatureTypes": [ "string" ], "HumanLoopConfig": { "DataAttributes": { "ContentClassifiers": [ "string" ] }, "FlowDefinitionArn": "string", "HumanLoopName": "string" }, "QueriesConfig": { "Queries": [ { "Alias": "string", "Pages": [ "string" ], "Text": "string" } ] } } Request Parameters The request accepts the following data in JSON format. AdaptersConfig Specifies the adapter to be used when analyzing a document. Type: AdaptersConfig object AnalyzeDocument 413 Amazon Textract Required: No Document Developer Guide The input document as base64-encoded bytes or an Amazon S3 object. If you use the AWS CLI to call Amazon Textract operations, you can't pass image bytes. The document must be an image in JPEG, PNG, PDF, or TIFF format. If you're using an AWS SDK to call Amazon Textract, you might not need to base64-encode image bytes that are passed using the Bytes field. Type: Document object Required: Yes FeatureTypes A list of the types of analysis to perform. Add TABLES to the list to return information about the tables that are detected in the input document. Add FORMS to return detected form data. Add SIGNATURES to return the locations of detected signatures. Add LAYOUT to the list to return information about the layout of the document. All lines and words detected in the document are included in the response (including text that isn't related to the value of FeatureTypes). Type: Array of strings Valid Values: TABLES | FORMS | QUERIES | SIGNATURES | LAYOUT Required: Yes HumanLoopConfig Sets the configuration for the human in the loop workflow for analyzing documents. Type: HumanLoopConfig object Required: No QueriesConfig Contains Queries and the alias for those Queries, as determined by the input. Type: QueriesConfig object Required: No AnalyzeDocument 414 Developer Guide Amazon Textract Response Syntax { "AnalyzeDocumentModelVersion": "string", "Blocks": [ { "BlockType": "string", "ColumnIndex": number, "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, "SelectionStatus": "string", "Text": "string", "TextType": "string" AnalyzeDocument 415 Developer Guide Amazon Textract } ], "DocumentMetadata": { "Pages": number }, "HumanLoopActivationOutput": { "HumanLoopActivationConditionsEvaluationResults": "string", "HumanLoopActivationReasons": [ "string" ], "HumanLoopArn": "string" } } Response Elements If the action is successful,
textract-dg-101
textract-dg.pdf
101
number, "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, "SelectionStatus": "string", "Text": "string", "TextType": "string" AnalyzeDocument 415 Developer Guide Amazon Textract } ], "DocumentMetadata": { "Pages": number }, "HumanLoopActivationOutput": { "HumanLoopActivationConditionsEvaluationResults": "string", "HumanLoopActivationReasons": [ "string" ], "HumanLoopArn": "string" } } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. AnalyzeDocumentModelVersion The version of the model used to analyze the document. Type: String Blocks The items that are detected and analyzed by AnalyzeDocument. Type: Array of Block objects DocumentMetadata Metadata about the analyzed document. An example is the number of pages. Type: DocumentMetadata object HumanLoopActivationOutput Shows the results of the human in the loop evaluation. Type: HumanLoopActivationOutput object AnalyzeDocument 416 Amazon Textract Errors AccessDeniedException Developer Guide You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 BadDocumentException Amazon Textract isn't able to read the document. For more information on the document limits in Amazon Textract, see Quotas in Amazon Textract. HTTP Status Code: 400 DocumentTooLargeException The document can't be processed because it's too large. The maximum document size for synchronous operations 10 MB. The maximum document size for asynchronous operations is 500 MB for PDF files. HTTP Status Code: 400 HumanLoopQuotaExceededException Indicates you have exceeded the maximum number of active human in the loop workflows available HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 AnalyzeDocument 417 Amazon Textract InvalidS3ObjectException Developer Guide Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 UnsupportedDocumentException The format of the input document isn't supported. Documents for operations can be in PNG, JPEG, PDF, or TIFF format. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 AnalyzeDocument 418 Amazon Textract • AWS SDK for Python • AWS SDK for Ruby V3 Developer Guide AnalyzeDocument 419 Amazon Textract AnalyzeExpense Developer Guide AnalyzeExpense synchronously analyzes an input document for financially related relationships between text. Information is returned as ExpenseDocuments and seperated as follows: • LineItemGroups- A data set containing LineItems which store information about the lines of text, such as an item purchased and its price on a receipt. • SummaryFields- Contains all other information a receipt, such as header information or the vendors name. Request Syntax { "Document": { "Bytes": blob, "S3Object": { "Bucket": "string", "Name": "string", "Version": "string" } } } Request Parameters The request accepts the following data in JSON format. Document The input document, either as bytes or as an S3 object. You pass image bytes to an Amazon Textract API operation by using the Bytes property. For example, you would use the Bytes property to pass a document loaded from a local file system. Image bytes passed by using the Bytes property must be base64 encoded. Your code might not need to encode document file bytes if you're using an AWS SDK to call Amazon Textract API operations. AnalyzeExpense 420 Amazon Textract Developer Guide You pass images stored in an S3 bucket to an Amazon Textract API operation by using the S3Object property. Documents stored in an S3 bucket don't need to be base64 encoded. The AWS Region for the S3 bucket that contains the S3 object must match the AWS Region that you use for Amazon Textract operations. If you use the AWS CLI to call Amazon Textract operations, passing image bytes using the Bytes property isn't
textract-dg-102
textract-dg.pdf
102
might not need to encode document file bytes if you're using an AWS SDK to call Amazon Textract API operations. AnalyzeExpense 420 Amazon Textract Developer Guide You pass images stored in an S3 bucket to an Amazon Textract API operation by using the S3Object property. Documents stored in an S3 bucket don't need to be base64 encoded. The AWS Region for the S3 bucket that contains the S3 object must match the AWS Region that you use for Amazon Textract operations. If you use the AWS CLI to call Amazon Textract operations, passing image bytes using the Bytes property isn't supported. You must first upload the document to an Amazon S3 bucket, and then call the operation using the S3Object property. For Amazon Textract to process an S3 object, the user must have permission to access the S3 object. Type: Document object Required: Yes Response Syntax { "DocumentMetadata": { "Pages": number }, "ExpenseDocuments": [ { "Blocks": [ { "BlockType": "string", "ColumnIndex": number, "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, AnalyzeExpense 421 Amazon Textract Developer Guide "Y": number } ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, "SelectionStatus": "string", "Text": "string", "TextType": "string" } ], "ExpenseIndex": number, "LineItemGroups": [ { "LineItemGroupIndex": number, "LineItems": [ { "LineItemExpenseFields": [ { "Currency": { "Code": "string", "Confidence": number }, "GroupProperties": [ { "Id": "string", "Types": [ "string" ] } ], "LabelDetection": { "Confidence": number, AnalyzeExpense 422 Amazon Textract Developer Guide "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" }, "PageNumber": number, "Type": { "Confidence": number, "Text": "string" }, "ValueDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" } } ] } ] } AnalyzeExpense 423 Developer Guide Amazon Textract ], "SummaryFields": [ { "Currency": { "Code": "string", "Confidence": number }, "GroupProperties": [ { "Id": "string", "Types": [ "string" ] } ], "LabelDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" }, "PageNumber": number, "Type": { "Confidence": number, "Text": "string" }, "ValueDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number AnalyzeExpense 424 Amazon Textract Developer Guide }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" } } ] } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. DocumentMetadata Information about the input document. Type: DocumentMetadata object ExpenseDocuments The expenses detected by Amazon Textract. Type: Array of ExpenseDocument objects Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 AnalyzeExpense 425 Amazon Textract BadDocumentException Developer Guide Amazon Textract isn't able to read the document. For more information on the document limits in Amazon Textract, see Quotas in Amazon Textract. HTTP Status Code: 400 DocumentTooLargeException The document can't be processed because it's too large. The maximum document size for synchronous operations 10 MB. The maximum document size for asynchronous operations is 500 MB for PDF files. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 AnalyzeExpense 426 Amazon Textract ThrottlingException Developer Guide Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 UnsupportedDocumentException The format of the input document isn't supported. Documents for operations can be in PNG, JPEG, PDF, or TIFF format. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK
textract-dg-103
textract-dg.pdf
103
requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 AnalyzeExpense 426 Amazon Textract ThrottlingException Developer Guide Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 UnsupportedDocumentException The format of the input document isn't supported. Documents for operations can be in PNG, JPEG, PDF, or TIFF format. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 AnalyzeExpense 427 Amazon Textract AnalyzeID Developer Guide Analyzes identity documents for relevant information. This information is extracted and returned as IdentityDocumentFields, which records both the normalized field and value of the extracted text. Unlike other Amazon Textract operations, AnalyzeID doesn't return any Geometry data. Request Syntax { "DocumentPages": [ { "Bytes": blob, "S3Object": { "Bucket": "string", "Name": "string", "Version": "string" } } ] } Request Parameters The request accepts the following data in JSON format. DocumentPages The document being passed to AnalyzeID. Type: Array of Document objects Array Members: Minimum number of 1 item. Maximum number of 2 items. Required: Yes Response Syntax { "AnalyzeIDModelVersion": "string", "DocumentMetadata": { "Pages": number AnalyzeID 428 Amazon Textract }, "IdentityDocuments": [ { "Blocks": [ { "BlockType": "string", "ColumnIndex": number, "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, "SelectionStatus": "string", "Text": "string", "TextType": "string" } ], AnalyzeID Developer Guide 429 Amazon Textract Developer Guide "DocumentIndex": number, "IdentityDocumentFields": [ { "Type": { "Confidence": number, "NormalizedValue": { "Value": "string", "ValueType": "string" }, "Text": "string" }, "ValueDetection": { "Confidence": number, "NormalizedValue": { "Value": "string", "ValueType": "string" }, "Text": "string" } } ] } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. AnalyzeIDModelVersion The version of the AnalyzeIdentity API being used to process documents. Type: String DocumentMetadata Information about the input document. Type: DocumentMetadata object AnalyzeID 430 Amazon Textract IdentityDocuments Developer Guide The list of documents processed by AnalyzeID. Includes a number denoting their place in the list and the response structure for the document. Type: Array of IdentityDocument objects Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 BadDocumentException Amazon Textract isn't able to read the document. For more information on the document limits in Amazon Textract, see Quotas in Amazon Textract. HTTP Status Code: 400 DocumentTooLargeException The document can't be processed because it's too large. The maximum document size for synchronous operations 10 MB. The maximum document size for asynchronous operations is 500 MB for PDF files. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. AnalyzeID 431 Amazon Textract HTTP Status Code: 400 InvalidS3ObjectException Developer Guide Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 UnsupportedDocumentException The format of the input document isn't supported. Documents for operations can be in PNG, JPEG, PDF, or TIFF format. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin AnalyzeID 432 Amazon Textract • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK
textract-dg-104
textract-dg.pdf
104
UnsupportedDocumentException The format of the input document isn't supported. Documents for operations can be in PNG, JPEG, PDF, or TIFF format. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin AnalyzeID 432 Amazon Textract • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 Developer Guide AnalyzeID 433 Amazon Textract CreateAdapter Developer Guide Creates an adapter, which can be fine-tuned for enhanced performance on user provided documents. Takes an AdapterName and FeatureType. Currently the only supported feature type is QUERIES. You can also provide a Description, Tags, and a ClientRequestToken. You can choose whether or not the adapter should be AutoUpdated with the AutoUpdate argument. By default, AutoUpdate is set to DISABLED. Request Syntax { "AdapterName": "string", "AutoUpdate": "string", "ClientRequestToken": "string", "Description": "string", "FeatureTypes": [ "string" ], "Tags": { "string" : "string" } } Request Parameters The request accepts the following data in JSON format. AdapterName The name to be assigned to the adapter being created. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. Pattern: [a-zA-Z0-9-_]+ Required: Yes AutoUpdate Controls whether or not the adapter should automatically update. Type: String CreateAdapter 434 Amazon Textract Developer Guide Valid Values: ENABLED | DISABLED Required: No ClientRequestToken Idempotent token is used to recognize the request. If the same token is used with multiple CreateAdapter requests, the same session is returned. This token is employed to avoid unintentionally creating the same session multiple times. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: No Description The description to be assigned to the adapter being created. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Pattern: ^[a-zA-Z0-9\s!"\#\$%'&\(\)\*\+\,\-\./:;=\?@\[\\\]\^_`\{\|\}~><]+$ Required: No FeatureTypes The type of feature that the adapter is being trained on. Currrenly, supported feature types are: QUERIES Type: Array of strings Valid Values: TABLES | FORMS | QUERIES | SIGNATURES | LAYOUT Required: Yes Tags A list of tags to be added to the adapter. CreateAdapter 435 Amazon Textract Type: String to string map Developer Guide Map Entries: Minimum number of 0 items. Maximum number of 200 items. Key Length Constraints: Minimum length of 1. Maximum length of 128. Key Pattern: ^(?!aws:)[\p{L}\p{Z}\p{N}_.:/=+\-@]*$ Value Length Constraints: Minimum length of 0. Maximum length of 256. Value Pattern: ^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$ Required: No Response Syntax { "AdapterId": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. AdapterId A string containing the unique ID for the adapter that has been created. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. CreateAdapter 436 Amazon Textract HTTP Status Code: 400 ConflictException Updating or deleting a resource can cause an inconsistent state. HTTP Status Code: 400 IdempotentParameterMismatchException Developer Guide A ClientRequestToken input parameter was reused with an operation, but at least one of the other input parameters is different from the previous call to the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 LimitExceededException An Amazon Textract service limit was exceeded. For example, if you start too many asynchronous jobs concurrently, calls to start operations (StartDocumentTextDetection, for example) raise a LimitExceededException exception (HTTP status code: 400) until the number of concurrently running jobs is below the Amazon Textract service limit. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 CreateAdapter 437 Amazon Textract Developer Guide ServiceQuotaExceededException Returned when a request cannot be completed as it would exceed a maximum service quota. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET •
textract-dg-105
textract-dg.pdf
105
this limit, contact Amazon Textract. HTTP Status Code: 400 CreateAdapter 437 Amazon Textract Developer Guide ServiceQuotaExceededException Returned when a request cannot be completed as it would exceed a maximum service quota. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 CreateAdapter 438 Amazon Textract CreateAdapterVersion Developer Guide Creates a new version of an adapter. Operates on a provided AdapterId and a specified dataset provided via the DatasetConfig argument. Requires that you specify an Amazon S3 bucket with the OutputConfig argument. You can provide an optional KMSKeyId, an optional ClientRequestToken, and optional tags. Request Syntax { "AdapterId": "string", "ClientRequestToken": "string", "DatasetConfig": { "ManifestS3Object": { "Bucket": "string", "Name": "string", "Version": "string" } }, "KMSKeyId": "string", "OutputConfig": { "S3Bucket": "string", "S3Prefix": "string" }, "Tags": { "string" : "string" } } Request Parameters The request accepts the following data in JSON format. AdapterId A string containing a unique ID for the adapter that will receive a new version. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. Required: Yes CreateAdapterVersion 439 Amazon Textract ClientRequestToken Developer Guide Idempotent token is used to recognize the request. If the same token is used with multiple CreateAdapterVersion requests, the same session is returned. This token is employed to avoid unintentionally creating the same session multiple times. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: No DatasetConfig Specifies a dataset used to train a new adapter version. Takes a ManifestS3Object as the value. Type: AdapterVersionDatasetConfig object Required: Yes KMSKeyId The identifier for your AWS Key Management Service key (AWS KMS key). Used to encrypt your documents. Type: String Length Constraints: Minimum length of 1. Maximum length of 2048. Pattern: ^[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,2048}$ Required: No OutputConfig Sets whether or not your output will go to a user created bucket. Used to set the name of the bucket, and the prefix on the output file. OutputConfig is an optional parameter which lets you adjust where your output will be placed. By default, Amazon Textract will store the results internally and can only be accessed by the Get API operations. With OutputConfig enabled, you can set the name of the bucket the output will be sent to the file prefix of the results where you can download your results. Additionally, you can set the KMSKeyID parameter to a customer master key (CMK) to encrypt CreateAdapterVersion 440 Amazon Textract Developer Guide your output. Without this parameter set Amazon Textract will encrypt server-side using the AWS managed CMK for Amazon S3. Decryption of Customer Content is necessary for processing of the documents by Amazon Textract. If your account is opted out under an AI services opt out policy then all unencrypted Customer Content is immediately and permanently deleted after the Customer Content has been processed by the service. No copy of of the output is retained by Amazon Textract. For information about how to opt out, see Managing AI services opt-out policy. For more information on data privacy, see the Data Privacy FAQ. Type: OutputConfig object Required: Yes Tags A set of tags (key-value pairs) that you want to attach to the adapter version. Type: String to string map Map Entries: Minimum number of 0 items. Maximum number of 200 items. Key Length Constraints: Minimum length of 1. Maximum length of 128. Key Pattern: ^(?!aws:)[\p{L}\p{Z}\p{N}_.:/=+\-@]*$ Value Length Constraints: Minimum length of 0. Maximum length of 256. Value Pattern: ^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$ Required: No Response Syntax { "AdapterId": "string", "AdapterVersion": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. CreateAdapterVersion 441 Amazon Textract Developer Guide The following data is returned in JSON format by the service. AdapterId A string containing the unique ID for the adapter that has received a new version. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. AdapterVersion A string describing the new version of the adapter. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 ConflictException Updating or deleting a resource can cause an inconsistent state.
textract-dg-106
textract-dg.pdf
106
data is returned in JSON format by the service. AdapterId A string containing the unique ID for the adapter that has received a new version. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. AdapterVersion A string describing the new version of the adapter. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 ConflictException Updating or deleting a resource can cause an inconsistent state. HTTP Status Code: 400 IdempotentParameterMismatchException A ClientRequestToken input parameter was reused with an operation, but at least one of the other input parameters is different from the previous call to the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 CreateAdapterVersion 442 Amazon Textract InvalidKMSKeyException Developer Guide Indicates you do not have decrypt permissions with the KMS key entered, or the KMS key was entered incorrectly. HTTP Status Code: 400 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 LimitExceededException An Amazon Textract service limit was exceeded. For example, if you start too many asynchronous jobs concurrently, calls to start operations (StartDocumentTextDetection, for example) raise a LimitExceededException exception (HTTP status code: 400) until the number of concurrently running jobs is below the Amazon Textract service limit. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ResourceNotFoundException Returned when an operation tried to access a nonexistent resource. HTTP Status Code: 400 CreateAdapterVersion 443 Amazon Textract Developer Guide ServiceQuotaExceededException Returned when a request cannot be completed as it would exceed a maximum service quota. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 CreateAdapterVersion 444 Amazon Textract DeleteAdapter Developer Guide Deletes an Amazon Textract adapter. Takes an AdapterId and deletes the adapter specified by the ID. Request Syntax { "AdapterId": "string" } Request Parameters The request accepts the following data in JSON format. AdapterId A string containing a unique ID for the adapter to be deleted. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 ConflictException Updating or deleting a resource can cause an inconsistent state. DeleteAdapter 445 Amazon Textract HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException Developer Guide An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ResourceNotFoundException Returned when an operation tried to access a nonexistent resource. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: DeleteAdapter 446 Developer Guide Amazon Textract • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 •
textract-dg-107
textract-dg.pdf
107
Status Code: 400 ResourceNotFoundException Returned when an operation tried to access a nonexistent resource. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: DeleteAdapter 446 Developer Guide Amazon Textract • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 DeleteAdapter 447 Amazon Textract DeleteAdapterVersion Developer Guide Deletes an Amazon Textract adapter version. Requires that you specify both an AdapterId and a AdapterVersion. Deletes the adapter version specified by the AdapterId and the AdapterVersion. Request Syntax { "AdapterId": "string", "AdapterVersion": "string" } Request Parameters The request accepts the following data in JSON format. AdapterId A string containing a unique ID for the adapter version that will be deleted. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. Required: Yes AdapterVersion Specifies the adapter version to be deleted. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. Required: Yes Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. DeleteAdapterVersion 448 Amazon Textract Errors AccessDeniedException Developer Guide You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 ConflictException Updating or deleting a resource can cause an inconsistent state. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ResourceNotFoundException Returned when an operation tried to access a nonexistent resource. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. DeleteAdapterVersion 449 Amazon Textract HTTP Status Code: 500 ValidationException Developer Guide Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 DeleteAdapterVersion 450 Amazon Textract DetectDocumentText Developer Guide Detects text in the input document. Amazon Textract can detect lines of text and the words that make up a line of text. The input document must be in one of the following image formats: JPEG, PNG, PDF, or TIFF. DetectDocumentText returns the detected text in an array of Block objects. Each document page has as an associated Block of type PAGE. Each PAGE Block object is the parent of LINE Block objects that represent the lines of detected text on a page. A LINE Block object is a parent for each word that makes up the line. Words are represented by Block objects of type WORD. DetectDocumentText is a synchronous operation. To analyze documents asynchronously, use StartDocumentTextDetection. For more information, see Document Text Detection. Request Syntax { "Document": { "Bytes": blob, "S3Object": { "Bucket": "string", "Name": "string", "Version": "string" } } } Request Parameters The request accepts the following data in JSON format. Document The input document as base64-encoded bytes or an Amazon S3 object. If you use the AWS CLI to call Amazon Textract operations, you can't pass image bytes. The document must be an image in JPEG or PNG format. If you're using an AWS SDK to call Amazon Textract, you might not need to base64-encode image bytes that are passed using the Bytes field. DetectDocumentText 451 Developer Guide Amazon Textract Type: Document object Required: Yes Response Syntax { "Blocks": [ { "BlockType": "string", "ColumnIndex": number, "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Id": "string", "Page":
textract-dg-108
textract-dg.pdf
108
call Amazon Textract operations, you can't pass image bytes. The document must be an image in JPEG or PNG format. If you're using an AWS SDK to call Amazon Textract, you might not need to base64-encode image bytes that are passed using the Bytes field. DetectDocumentText 451 Developer Guide Amazon Textract Type: Document object Required: Yes Response Syntax { "Blocks": [ { "BlockType": "string", "ColumnIndex": number, "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, DetectDocumentText 452 Amazon Textract Developer Guide "SelectionStatus": "string", "Text": "string", "TextType": "string" } ], "DetectDocumentTextModelVersion": "string", "DocumentMetadata": { "Pages": number } } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Blocks An array of Block objects that contain the text that's detected in the document. Type: Array of Block objects DetectDocumentTextModelVersion Type: String DocumentMetadata Metadata about the document. It contains the number of pages that are detected in the document. Type: DocumentMetadata object Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 DetectDocumentText 453 Amazon Textract BadDocumentException Developer Guide Amazon Textract isn't able to read the document. For more information on the document limits in Amazon Textract, see Quotas in Amazon Textract. HTTP Status Code: 400 DocumentTooLargeException The document can't be processed because it's too large. The maximum document size for synchronous operations 10 MB. The maximum document size for asynchronous operations is 500 MB for PDF files. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 DetectDocumentText 454 Amazon Textract ThrottlingException Developer Guide Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 UnsupportedDocumentException The format of the input document isn't supported. Documents for operations can be in PNG, JPEG, PDF, or TIFF format. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 DetectDocumentText 455 Amazon Textract GetAdapter Developer Guide Gets configuration information for an adapter specified by an AdapterId, returning information on AdapterName, Description, CreationTime, AutoUpdate status, and FeatureTypes. Request Syntax { "AdapterId": "string" } Request Parameters The request accepts the following data in JSON format. AdapterId A string containing a unique ID for the adapter. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. Required: Yes Response Syntax { "AdapterId": "string", "AdapterName": "string", "AutoUpdate": "string", "CreationTime": number, "Description": "string", "FeatureTypes": [ "string" ], "Tags": { "string" : "string" } } Response Elements If the action is successful, the service sends back an HTTP 200 response. GetAdapter 456 Amazon Textract Developer Guide The following data is returned in JSON format by the service. AdapterId A string identifying the adapter that information has been retrieved for. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. AdapterName The name of the requested adapter. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. Pattern: [a-zA-Z0-9-_]+ AutoUpdate Binary value indicating if the adapter is being automatically updated or not. Type: String Valid Values: ENABLED | DISABLED CreationTime The date and time the requested adapter was created at. Type: Timestamp Description The description for the requested adapter. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Pattern: ^[a-zA-Z0-9\s!"\#\$%'&\(\)\*\+\,\-\./:;=\?@\[\\\]\^_`\{\|\}~><]+$ FeatureTypes List of the targeted feature types for the requested adapter. GetAdapter 457 Amazon Textract Type: Array of strings Developer
textract-dg-109
textract-dg.pdf
109
12. Maximum length of 1011. AdapterName The name of the requested adapter. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. Pattern: [a-zA-Z0-9-_]+ AutoUpdate Binary value indicating if the adapter is being automatically updated or not. Type: String Valid Values: ENABLED | DISABLED CreationTime The date and time the requested adapter was created at. Type: Timestamp Description The description for the requested adapter. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Pattern: ^[a-zA-Z0-9\s!"\#\$%'&\(\)\*\+\,\-\./:;=\?@\[\\\]\^_`\{\|\}~><]+$ FeatureTypes List of the targeted feature types for the requested adapter. GetAdapter 457 Amazon Textract Type: Array of strings Developer Guide Valid Values: TABLES | FORMS | QUERIES | SIGNATURES | LAYOUT Tags A set of tags (key-value pairs) associated with the adapter that has been retrieved. Type: String to string map Map Entries: Minimum number of 0 items. Maximum number of 200 items. Key Length Constraints: Minimum length of 1. Maximum length of 128. Key Pattern: ^(?!aws:)[\p{L}\p{Z}\p{N}_.:/=+\-@]*$ Value Length Constraints: Minimum length of 0. Maximum length of 256. Value Pattern: ^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$ Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 GetAdapter 458 Amazon Textract Developer Guide ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ResourceNotFoundException Returned when an operation tried to access a nonexistent resource. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 GetAdapter 459 Amazon Textract Developer Guide GetAdapter 460 Amazon Textract GetAdapterVersion Developer Guide Gets configuration information for the specified adapter version, including: AdapterId, AdapterVersion, FeatureTypes, Status, StatusMessage, DatasetConfig, KMSKeyId, OutputConfig, Tags and EvaluationMetrics. Request Syntax { "AdapterId": "string", "AdapterVersion": "string" } Request Parameters The request accepts the following data in JSON format. AdapterId A string specifying a unique ID for the adapter version you want to retrieve information for. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. Required: Yes AdapterVersion A string specifying the adapter version you want to retrieve information for. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. Required: Yes Response Syntax { "AdapterId": "string", "AdapterVersion": "string", "CreationTime": number, GetAdapterVersion 461 Amazon Textract Developer Guide "DatasetConfig": { "ManifestS3Object": { "Bucket": "string", "Name": "string", "Version": "string" } }, "EvaluationMetrics": [ { "AdapterVersion": { "F1Score": number, "Precision": number, "Recall": number }, "Baseline": { "F1Score": number, "Precision": number, "Recall": number }, "FeatureType": "string" } ], "FeatureTypes": [ "string" ], "KMSKeyId": "string", "OutputConfig": { "S3Bucket": "string", "S3Prefix": "string" }, "Status": "string", "StatusMessage": "string", "Tags": { "string" : "string" } } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. AdapterId A string containing a unique ID for the adapter version being retrieved. GetAdapterVersion 462 Amazon Textract Type: String Developer Guide Length Constraints: Minimum length of 12. Maximum length of 1011. AdapterVersion A string containing the adapter version that has been retrieved. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. CreationTime The time that the adapter version was created. Type: Timestamp DatasetConfig Specifies a dataset used to train a new adapter version. Takes a ManifestS3Objec as the value. Type: AdapterVersionDatasetConfig object EvaluationMetrics The evaluation metrics (F1 score, Precision, and Recall) for the requested version, grouped by baseline metrics and adapter version. Type: Array of AdapterVersionEvaluationMetric objects FeatureTypes List of the targeted feature types for the requested adapter version. Type: Array of strings Valid Values: TABLES | FORMS | QUERIES | SIGNATURES | LAYOUT KMSKeyId The identifier for your AWS Key Management Service key (AWS KMS key). Used to encrypt your documents. Type: String Length Constraints: Minimum length of 1. Maximum length of 2048. GetAdapterVersion 463 Amazon Textract Developer Guide Pattern:
textract-dg-110
textract-dg.pdf
110
adapter version. Takes a ManifestS3Objec as the value. Type: AdapterVersionDatasetConfig object EvaluationMetrics The evaluation metrics (F1 score, Precision, and Recall) for the requested version, grouped by baseline metrics and adapter version. Type: Array of AdapterVersionEvaluationMetric objects FeatureTypes List of the targeted feature types for the requested adapter version. Type: Array of strings Valid Values: TABLES | FORMS | QUERIES | SIGNATURES | LAYOUT KMSKeyId The identifier for your AWS Key Management Service key (AWS KMS key). Used to encrypt your documents. Type: String Length Constraints: Minimum length of 1. Maximum length of 2048. GetAdapterVersion 463 Amazon Textract Developer Guide Pattern: ^[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,2048}$ OutputConfig Sets whether or not your output will go to a user created bucket. Used to set the name of the bucket, and the prefix on the output file. OutputConfig is an optional parameter which lets you adjust where your output will be placed. By default, Amazon Textract will store the results internally and can only be accessed by the Get API operations. With OutputConfig enabled, you can set the name of the bucket the output will be sent to the file prefix of the results where you can download your results. Additionally, you can set the KMSKeyID parameter to a customer master key (CMK) to encrypt your output. Without this parameter set Amazon Textract will encrypt server-side using the AWS managed CMK for Amazon S3. Decryption of Customer Content is necessary for processing of the documents by Amazon Textract. If your account is opted out under an AI services opt out policy then all unencrypted Customer Content is immediately and permanently deleted after the Customer Content has been processed by the service. No copy of of the output is retained by Amazon Textract. For information about how to opt out, see Managing AI services opt-out policy. For more information on data privacy, see the Data Privacy FAQ. Type: OutputConfig object Status The status of the adapter version that has been requested. Type: String Valid Values: ACTIVE | AT_RISK | DEPRECATED | CREATION_ERROR | CREATION_IN_PROGRESS StatusMessage A message that describes the status of the requested adapter version. Type: String Length Constraints: Minimum length of 1. Maximum length of 256. Pattern: ^[a-zA-Z0-9\s!"\#\$%'&\(\)\*\+\,\-\./:;=\?@\[\\\]\^_`\{\|\}~><]+$ GetAdapterVersion 464 Amazon Textract Tags Developer Guide A set of tags (key-value pairs) that are associated with the adapter version. Type: String to string map Map Entries: Minimum number of 0 items. Maximum number of 200 items. Key Length Constraints: Minimum length of 1. Maximum length of 128. Key Pattern: ^(?!aws:)[\p{L}\p{Z}\p{N}_.:/=+\-@]*$ Value Length Constraints: Minimum length of 0. Maximum length of 256. Value Pattern: ^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$ Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. GetAdapterVersion 465 Amazon Textract HTTP Status Code: 400 ResourceNotFoundException Developer Guide Returned when an operation tried to access a nonexistent resource. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 GetAdapterVersion 466 Amazon Textract GetDocumentAnalysis Developer Guide Gets the results for an Amazon Textract asynchronous operation that analyzes text in a document. You start asynchronous text analysis by calling StartDocumentAnalysis, which returns a job identifier (JobId). When the text analysis operation finishes, Amazon Textract publishes a completion status to the Amazon Simple Notification Service (Amazon SNS) topic that's registered in the initial call to StartDocumentAnalysis. To get the results of the text-detection operation, first check that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call GetDocumentAnalysis, and pass the job identifier (JobId) from the initial call to StartDocumentAnalysis. GetDocumentAnalysis returns an array of Block objects. The following types of information are returned: • Form data (key-value pairs). The related information is returned in two Block objects,
textract-dg-111
textract-dg.pdf
111
returns a job identifier (JobId). When the text analysis operation finishes, Amazon Textract publishes a completion status to the Amazon Simple Notification Service (Amazon SNS) topic that's registered in the initial call to StartDocumentAnalysis. To get the results of the text-detection operation, first check that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call GetDocumentAnalysis, and pass the job identifier (JobId) from the initial call to StartDocumentAnalysis. GetDocumentAnalysis returns an array of Block objects. The following types of information are returned: • Form data (key-value pairs). The related information is returned in two Block objects, each of type KEY_VALUE_SET: a KEY Block object and a VALUE Block object. For example, Name: Ana Silva Carolina contains a key and value. Name: is the key. Ana Silva Carolina is the value. • Table and table cell data. A TABLE Block object contains information about a detected table. A CELL Block object is returned for each cell in a table. • Lines and words of text. A LINE Block object contains one or more WORD Block objects. All lines and words that are detected in the document are returned (including text that doesn't have a relationship with the value of the StartDocumentAnalysis FeatureTypes input parameter). • Query. A QUERY Block object contains the query text, alias and link to the associated Query results block object. • Query Results. A QUERY_RESULT Block object contains the answer to the query and an ID that connects it to the query asked. This Block also contains a confidence score. Note While processing a document with queries, look out for INVALID_REQUEST_PARAMETERS output. This indicates that either the per page query limit has been exceeded or that the operation is trying to query a page in the document which doesn’t exist. GetDocumentAnalysis 467 Amazon Textract Developer Guide Selection elements such as check boxes and option buttons (radio buttons) can be detected in form data and in tables. A SELECTION_ELEMENT Block object contains information about a selection element, including the selection status. Use the MaxResults parameter to limit the number of blocks that are returned. If there are more results than specified in MaxResults, the value of NextToken in the operation response contains a pagination token for getting the next set of results. To get the next page of results, call GetDocumentAnalysis, and populate the NextToken request parameter with the token value that's returned from the previous call to GetDocumentAnalysis. For more information, see Document Text Analysis. Request Syntax { "JobId": "string", "MaxResults": number, "NextToken": "string" } Request Parameters The request accepts the following data in JSON format. JobId A unique identifier for the text-detection job. The JobId is returned from StartDocumentAnalysis. A JobId value is only valid for 7 days. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: Yes MaxResults The maximum number of results to return per paginated call. The largest value that you can specify is 1,000. If you specify a value greater than 1,000, a maximum of 1,000 results is returned. The default value is 1,000. GetDocumentAnalysis 468 Amazon Textract Type: Integer Valid Range: Minimum value of 1. Required: No NextToken Developer Guide If the previous response was incomplete (because there are more blocks to retrieve), Amazon Textract returns a pagination token in the response. You can use this pagination token to retrieve the next set of blocks. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* Required: No Response Syntax { "AnalyzeDocumentModelVersion": "string", "Blocks": [ { "BlockType": "string", "ColumnIndex": number, "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } GetDocumentAnalysis 469 Developer Guide Amazon Textract ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, "SelectionStatus": "string", "Text": "string", "TextType": "string" } ], "DocumentMetadata": { "Pages": number }, "JobStatus": "string", "NextToken": "string", "StatusMessage": "string", "Warnings": [ { "ErrorCode": "string", "Pages": [ number ] } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. AnalyzeDocumentModelVersion GetDocumentAnalysis 470 Amazon Textract Type: String Blocks The results of the text-analysis operation. Type: Array of Block objects DocumentMetadata Developer Guide Information about a document that Amazon Textract processed. DocumentMetadata is returned in every page of paginated responses from an Amazon Textract video operation. Type: DocumentMetadata object JobStatus The current status of the text detection job. Type: String Valid Values: IN_PROGRESS | SUCCEEDED | FAILED | PARTIAL_SUCCESS NextToken If the response is truncated, Amazon Textract returns this token. You can use this token
textract-dg-112
textract-dg.pdf
112
back an HTTP 200 response. The following data is returned in JSON format by the service. AnalyzeDocumentModelVersion GetDocumentAnalysis 470 Amazon Textract Type: String Blocks The results of the text-analysis operation. Type: Array of Block objects DocumentMetadata Developer Guide Information about a document that Amazon Textract processed. DocumentMetadata is returned in every page of paginated responses from an Amazon Textract video operation. Type: DocumentMetadata object JobStatus The current status of the text detection job. Type: String Valid Values: IN_PROGRESS | SUCCEEDED | FAILED | PARTIAL_SUCCESS NextToken If the response is truncated, Amazon Textract returns this token. You can use this token in the subsequent request to retrieve the next set of text detection results. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* StatusMessage Returns if the detection job could not be completed. Contains explanation for what error occured. Type: String Warnings A list of warnings that occurred during the document-analysis operation. Type: Array of Warning objects GetDocumentAnalysis 471 Amazon Textract Errors AccessDeniedException Developer Guide You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidJobIdException An invalid job identifier was passed to an asynchronous analysis operation. HTTP Status Code: 400 InvalidKMSKeyException Indicates you do not have decrypt permissions with the KMS key entered, or the KMS key was entered incorrectly. HTTP Status Code: 400 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 GetDocumentAnalysis 472 Amazon Textract Developer Guide ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 GetDocumentAnalysis 473 Amazon Textract Developer Guide GetDocumentTextDetection Gets the results for an Amazon Textract asynchronous operation that detects text in a document. Amazon Textract can detect lines of text and the words that make up a line of text. You start asynchronous text detection by calling StartDocumentTextDetection, which returns a job identifier (JobId). When the text detection operation finishes, Amazon Textract publishes a completion status to the Amazon Simple Notification Service (Amazon SNS) topic that's registered in the initial call to StartDocumentTextDetection. To get the results of the text-detection operation, first check that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call GetDocumentTextDetection, and pass the job identifier (JobId) from the initial call to StartDocumentTextDetection. GetDocumentTextDetection returns an array of Block objects. Each document page has as an associated Block of type PAGE. Each PAGE Block object is the parent of LINE Block objects that represent the lines of detected text on a page. A LINE Block object is a parent for each word that makes up the line. Words are represented by Block objects of type WORD. Use the MaxResults parameter to limit the number of blocks that are returned. If there are more results than specified in MaxResults, the value of NextToken in the operation response contains a pagination token for getting the next set of results. To get the next page of results, call GetDocumentTextDetection, and populate the NextToken request parameter with the token value that's returned from the previous call to GetDocumentTextDetection. For more information, see Document Text Detection. Request Syntax { "JobId": "string", "MaxResults": number, "NextToken": "string" } Request Parameters The request accepts the following data in JSON format. GetDocumentTextDetection 474 Amazon Textract JobId Developer Guide A unique identifier for the text detection job. The JobId is returned from StartDocumentTextDetection. A JobId value is only valid for 7 days. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: Yes MaxResults The maximum number of results to return per paginated call. The largest value you can specify is 1,000. If you specify a value
textract-dg-113
textract-dg.pdf
113
to GetDocumentTextDetection. For more information, see Document Text Detection. Request Syntax { "JobId": "string", "MaxResults": number, "NextToken": "string" } Request Parameters The request accepts the following data in JSON format. GetDocumentTextDetection 474 Amazon Textract JobId Developer Guide A unique identifier for the text detection job. The JobId is returned from StartDocumentTextDetection. A JobId value is only valid for 7 days. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: Yes MaxResults The maximum number of results to return per paginated call. The largest value you can specify is 1,000. If you specify a value greater than 1,000, a maximum of 1,000 results is returned. The default value is 1,000. Type: Integer Valid Range: Minimum value of 1. Required: No NextToken If the previous response was incomplete (because there are more blocks to retrieve), Amazon Textract returns a pagination token in the response. You can use this pagination token to retrieve the next set of blocks. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* Required: No Response Syntax { "Blocks": [ { "BlockType": "string", GetDocumentTextDetection 475 Amazon Textract Developer Guide "ColumnIndex": number, "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, "SelectionStatus": "string", "Text": "string", "TextType": "string" } ], "DetectDocumentTextModelVersion": "string", "DocumentMetadata": { "Pages": number }, "JobStatus": "string", "NextToken": "string", GetDocumentTextDetection 476 Amazon Textract Developer Guide "StatusMessage": "string", "Warnings": [ { "ErrorCode": "string", "Pages": [ number ] } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Blocks The results of the text-detection operation. Type: Array of Block objects DetectDocumentTextModelVersion Type: String DocumentMetadata Information about a document that Amazon Textract processed. DocumentMetadata is returned in every page of paginated responses from an Amazon Textract video operation. Type: DocumentMetadata object JobStatus The current status of the text detection job. Type: String Valid Values: IN_PROGRESS | SUCCEEDED | FAILED | PARTIAL_SUCCESS NextToken If the response is truncated, Amazon Textract returns this token. You can use this token in the subsequent request to retrieve the next set of text-detection results. GetDocumentTextDetection 477 Amazon Textract Type: String Developer Guide Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* StatusMessage Returns if the detection job could not be completed. Contains explanation for what error occured. Type: String Warnings A list of warnings that occurred during the text-detection operation for the document. Type: Array of Warning objects Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidJobIdException An invalid job identifier was passed to an asynchronous analysis operation. HTTP Status Code: 400 InvalidKMSKeyException Indicates you do not have decrypt permissions with the KMS key entered, or the KMS key was entered incorrectly. HTTP Status Code: 400 GetDocumentTextDetection 478 Amazon Textract InvalidParameterException Developer Guide An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 GetDocumentTextDetection 479 Amazon Textract • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 Developer Guide GetDocumentTextDetection 480 Amazon Textract GetExpenseAnalysis Developer Guide Gets the results for an Amazon Textract asynchronous operation that analyzes invoices and receipts. Amazon Textract finds contact information, items purchased, and vendor name, from input invoices and receipts. You start asynchronous invoice/receipt analysis by calling StartExpenseAnalysis,
textract-dg-114
textract-dg.pdf
114
• AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 GetDocumentTextDetection 479 Amazon Textract • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 Developer Guide GetDocumentTextDetection 480 Amazon Textract GetExpenseAnalysis Developer Guide Gets the results for an Amazon Textract asynchronous operation that analyzes invoices and receipts. Amazon Textract finds contact information, items purchased, and vendor name, from input invoices and receipts. You start asynchronous invoice/receipt analysis by calling StartExpenseAnalysis, which returns a job identifier (JobId). Upon completion of the invoice/receipt analysis, Amazon Textract publishes the completion status to the Amazon Simple Notification Service (Amazon SNS) topic. This topic must be registered in the initial call to StartExpenseAnalysis. To get the results of the invoice/ receipt analysis operation, first ensure that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call GetExpenseAnalysis, and pass the job identifier (JobId) from the initial call to StartExpenseAnalysis. Use the MaxResults parameter to limit the number of blocks that are returned. If there are more results than specified in MaxResults, the value of NextToken in the operation response contains a pagination token for getting the next set of results. To get the next page of results, call GetExpenseAnalysis, and populate the NextToken request parameter with the token value that's returned from the previous call to GetExpenseAnalysis. For more information, see Analyzing Invoices and Receipts. Request Syntax { "JobId": "string", "MaxResults": number, "NextToken": "string" } Request Parameters The request accepts the following data in JSON format. JobId A unique identifier for the text detection job. The JobId is returned from StartExpenseAnalysis. A JobId value is only valid for 7 days. Type: String GetExpenseAnalysis 481 Amazon Textract Developer Guide Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: Yes MaxResults The maximum number of results to return per paginated call. The largest value you can specify is 20. If you specify a value greater than 20, a maximum of 20 results is returned. The default value is 20. Type: Integer Valid Range: Minimum value of 1. Required: No NextToken If the previous response was incomplete (because there are more blocks to retrieve), Amazon Textract returns a pagination token in the response. You can use this pagination token to retrieve the next set of blocks. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* Required: No Response Syntax { "AnalyzeExpenseModelVersion": "string", "DocumentMetadata": { "Pages": number }, "ExpenseDocuments": [ { "Blocks": [ { "BlockType": "string", "ColumnIndex": number, GetExpenseAnalysis 482 Amazon Textract Developer Guide "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, "SelectionStatus": "string", "Text": "string", "TextType": "string" } ], "ExpenseIndex": number, "LineItemGroups": [ { "LineItemGroupIndex": number, "LineItems": [ { "LineItemExpenseFields": [ GetExpenseAnalysis 483 Amazon Textract Developer Guide { "Currency": { "Code": "string", "Confidence": number }, "GroupProperties": [ { "Id": "string", "Types": [ "string" ] } ], "LabelDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" }, "PageNumber": number, "Type": { "Confidence": number, "Text": "string" }, "ValueDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ GetExpenseAnalysis 484 Amazon Textract Developer Guide { "X": number, "Y": number } ] }, "Text": "string" } } ] } ] } ], "SummaryFields": [ { "Currency": { "Code": "string", "Confidence": number }, "GroupProperties": [ { "Id": "string", "Types": [ "string" ] } ], "LabelDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" }, GetExpenseAnalysis 485 Amazon Textract Developer Guide "PageNumber": number, "Type": { "Confidence": number, "Text": "string" }, "ValueDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" } } ] } ], "JobStatus": "string", "NextToken": "string", "StatusMessage": "string", "Warnings": [ { "ErrorCode": "string", "Pages": [ number ] } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. GetExpenseAnalysis 486 Amazon Textract AnalyzeExpenseModelVersion The current model version of AnalyzeExpense. Type: String DocumentMetadata Developer Guide Information about a document that
textract-dg-115
textract-dg.pdf
115
}, "ValueDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" } } ] } ], "JobStatus": "string", "NextToken": "string", "StatusMessage": "string", "Warnings": [ { "ErrorCode": "string", "Pages": [ number ] } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. GetExpenseAnalysis 486 Amazon Textract AnalyzeExpenseModelVersion The current model version of AnalyzeExpense. Type: String DocumentMetadata Developer Guide Information about a document that Amazon Textract processed. DocumentMetadata is returned in every page of paginated responses from an Amazon Textract operation. Type: DocumentMetadata object ExpenseDocuments The expenses detected by Amazon Textract. Type: Array of ExpenseDocument objects JobStatus The current status of the text detection job. Type: String Valid Values: IN_PROGRESS | SUCCEEDED | FAILED | PARTIAL_SUCCESS NextToken If the response is truncated, Amazon Textract returns this token. You can use this token in the subsequent request to retrieve the next set of text-detection results. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* StatusMessage Returns if the detection job could not be completed. Contains explanation for what error occured. Type: String Warnings A list of warnings that occurred during the text-detection operation for the document. GetExpenseAnalysis 487 Amazon Textract Developer Guide Type: Array of Warning objects Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidJobIdException An invalid job identifier was passed to an asynchronous analysis operation. HTTP Status Code: 400 InvalidKMSKeyException Indicates you do not have decrypt permissions with the KMS key entered, or the KMS key was entered incorrectly. HTTP Status Code: 400 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 GetExpenseAnalysis 488 Amazon Textract HTTP Status Code: 400 ProvisionedThroughputExceededException Developer Guide The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 GetExpenseAnalysis 489 Amazon Textract GetLendingAnalysis Developer Guide Gets the results for an Amazon Textract asynchronous operation that analyzes text in a lending document. You start asynchronous text analysis by calling StartLendingAnalysis, which returns a job identifier (JobId). When the text analysis operation finishes, Amazon Textract publishes a completion status to the Amazon Simple Notification Service (Amazon SNS) topic that's registered in the initial call to StartLendingAnalysis. To get the results of the text analysis operation, first check that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call GetLendingAnalysis, and pass the job identifier (JobId) from the initial call to StartLendingAnalysis. Request Syntax { "JobId": "string", "MaxResults": number, "NextToken": "string" } Request Parameters The request accepts the following data in JSON format. JobId A unique identifier for the lending or text-detection job. The JobId is returned from StartLendingAnalysis. A JobId value is only valid for 7 days. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: Yes GetLendingAnalysis 490 Amazon Textract MaxResults Developer Guide The maximum number of results to return per paginated call. The largest value that you can specify is 30. If you specify a value greater than 30, a maximum of 30 results is returned. The default value is 30. Type: Integer Valid Range: Minimum value of 1. Required: No NextToken If the previous response was incomplete, Amazon Textract returns a pagination token in the response. You can use this pagination token to retrieve the next set of lending results. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* Required: No Response Syntax { "AnalyzeLendingModelVersion": "string", "DocumentMetadata": { "Pages": number },
textract-dg-116
textract-dg.pdf
116
to return per paginated call. The largest value that you can specify is 30. If you specify a value greater than 30, a maximum of 30 results is returned. The default value is 30. Type: Integer Valid Range: Minimum value of 1. Required: No NextToken If the previous response was incomplete, Amazon Textract returns a pagination token in the response. You can use this pagination token to retrieve the next set of lending results. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* Required: No Response Syntax { "AnalyzeLendingModelVersion": "string", "DocumentMetadata": { "Pages": number }, "JobStatus": "string", "NextToken": "string", "Results": [ { "Extractions": [ { "ExpenseDocument": { "Blocks": [ { "BlockType": "string", "ColumnIndex": number, "ColumnSpan": number, GetLendingAnalysis 491 Amazon Textract Developer Guide "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, "SelectionStatus": "string", "Text": "string", "TextType": "string" } ], "ExpenseIndex": number, "LineItemGroups": [ { "LineItemGroupIndex": number, "LineItems": [ { "LineItemExpenseFields": [ { GetLendingAnalysis 492 Amazon Textract Developer Guide "Currency": { "Code": "string", "Confidence": number }, "GroupProperties": [ { "Id": "string", "Types": [ "string" ] } ], "LabelDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" }, "PageNumber": number, "Type": { "Confidence": number, "Text": "string" }, "ValueDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { GetLendingAnalysis 493 Amazon Textract Developer Guide "X": number, "Y": number } ] }, "Text": "string" } } ] } ] } ], "SummaryFields": [ { "Currency": { "Code": "string", "Confidence": number }, "GroupProperties": [ { "Id": "string", "Types": [ "string" ] } ], "LabelDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" }, "PageNumber": number, GetLendingAnalysis 494 Amazon Textract Developer Guide "Type": { "Confidence": number, "Text": "string" }, "ValueDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "Text": "string" } } ] }, "IdentityDocument": { "Blocks": [ { "BlockType": "string", "ColumnIndex": number, "ColumnSpan": number, "Confidence": number, "EntityTypes": [ "string" ], "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number GetLendingAnalysis 495 Amazon Textract Developer Guide } ] }, "Id": "string", "Page": number, "Query": { "Alias": "string", "Pages": [ "string" ], "Text": "string" }, "Relationships": [ { "Ids": [ "string" ], "Type": "string" } ], "RowIndex": number, "RowSpan": number, "SelectionStatus": "string", "Text": "string", "TextType": "string" } ], "DocumentIndex": number, "IdentityDocumentFields": [ { "Type": { "Confidence": number, "NormalizedValue": { "Value": "string", "ValueType": "string" }, "Text": "string" }, "ValueDetection": { "Confidence": number, "NormalizedValue": { "Value": "string", "ValueType": "string" }, "Text": "string" } } ] GetLendingAnalysis 496 Developer Guide Amazon Textract }, "LendingDocument": { "LendingFields": [ { "KeyDetection": { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "SelectionStatus": "string", "Text": "string" }, "Type": "string", "ValueDetections": [ { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] }, "SelectionStatus": "string", "Text": "string" } GetLendingAnalysis 497 Developer Guide Amazon Textract ] } ], "SignatureDetections": [ { "Confidence": number, "Geometry": { "BoundingBox": { "Height": number, "Left": number, "Top": number, "Width": number }, "Polygon": [ { "X": number, "Y": number } ] } } ] } } ], "Page": number, "PageClassification": { "PageNumber": [ { "Confidence": number, "Value": "string" } ], "PageType": [ { "Confidence": number, "Value": "string" } ] } } ], "StatusMessage": "string", "Warnings": [ GetLendingAnalysis 498 Amazon Textract Developer Guide { "ErrorCode": "string", "Pages": [ number ] } ] } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. AnalyzeLendingModelVersion The current model version of the Analyze Lending API. Type: String DocumentMetadata Information about the input document. Type: DocumentMetadata object JobStatus The current status of the lending analysis job. Type: String Valid Values: IN_PROGRESS | SUCCEEDED | FAILED | PARTIAL_SUCCESS NextToken If the response is truncated, Amazon Textract returns this token. You can use this token in the subsequent request to retrieve the next set of lending results. Type: String Length Constraints: Minimum length of 1. Maximum
textract-dg-117
textract-dg.pdf
117
action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. AnalyzeLendingModelVersion The current model version of the Analyze Lending API. Type: String DocumentMetadata Information about the input document. Type: DocumentMetadata object JobStatus The current status of the lending analysis job. Type: String Valid Values: IN_PROGRESS | SUCCEEDED | FAILED | PARTIAL_SUCCESS NextToken If the response is truncated, Amazon Textract returns this token. You can use this token in the subsequent request to retrieve the next set of lending results. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* GetLendingAnalysis 499 Amazon Textract Results Developer Guide Holds the information returned by one of AmazonTextract's document analysis operations for the pinstripe. Type: Array of LendingResult objects StatusMessage Returns if the lending analysis job could not be completed. Contains explanation for what error occurred. Type: String Warnings A list of warnings that occurred during the lending analysis operation. Type: Array of Warning objects Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidJobIdException An invalid job identifier was passed to an asynchronous analysis operation. HTTP Status Code: 400 InvalidKMSKeyException Indicates you do not have decrypt permissions with the KMS key entered, or the KMS key was entered incorrectly. GetLendingAnalysis 500 Amazon Textract HTTP Status Code: 400 InvalidParameterException Developer Guide An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 GetLendingAnalysis 501 Amazon Textract • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 Developer Guide GetLendingAnalysis 502 Amazon Textract Developer Guide GetLendingAnalysisSummary Gets summarized results for the StartLendingAnalysis operation, which analyzes text in a lending document. The returned summary consists of information about documents grouped together by a common document type. Information like detected signatures, page numbers, and split documents is returned with respect to the type of grouped document. You start asynchronous text analysis by calling StartLendingAnalysis, which returns a job identifier (JobId). When the text analysis operation finishes, Amazon Textract publishes a completion status to the Amazon Simple Notification Service (Amazon SNS) topic that's registered in the initial call to StartLendingAnalysis. To get the results of the text analysis operation, first check that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call GetLendingAnalysisSummary, and pass the job identifier (JobId) from the initial call to StartLendingAnalysis. Request Syntax { "JobId": "string" } Request Parameters The request accepts the following data in JSON format. JobId A unique identifier for the lending or text-detection job. The JobId is returned from StartLendingAnalysis. A JobId value is only valid for 7 days. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: Yes GetLendingAnalysisSummary 503 Amazon Textract Response Syntax Developer Guide { "AnalyzeLendingModelVersion": "string", "DocumentMetadata": { "Pages": number }, "JobStatus": "string", "StatusMessage": "string", "Summary": { "DocumentGroups": [ { "DetectedSignatures": [ { "Page": number } ], "SplitDocuments": [ { "Index": number, "Pages": [ number ] } ], "Type": "string", "UndetectedSignatures": [ { "Page": number } ] } ], "UndetectedDocumentTypes": [ "string" ] }, "Warnings": [ { "ErrorCode": "string", "Pages": [ number ] } ] } GetLendingAnalysisSummary 504 Amazon Textract Response Elements Developer Guide If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. AnalyzeLendingModelVersion The current model version of the Analyze Lending API. Type: String DocumentMetadata Information about the input document. Type: DocumentMetadata object JobStatus The current status of the lending analysis job. Type: String Valid Values: IN_PROGRESS | SUCCEEDED | FAILED | PARTIAL_SUCCESS StatusMessage Returns if the
textract-dg-118
textract-dg.pdf
118
"Page": number } ] } ], "UndetectedDocumentTypes": [ "string" ] }, "Warnings": [ { "ErrorCode": "string", "Pages": [ number ] } ] } GetLendingAnalysisSummary 504 Amazon Textract Response Elements Developer Guide If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. AnalyzeLendingModelVersion The current model version of the Analyze Lending API. Type: String DocumentMetadata Information about the input document. Type: DocumentMetadata object JobStatus The current status of the lending analysis job. Type: String Valid Values: IN_PROGRESS | SUCCEEDED | FAILED | PARTIAL_SUCCESS StatusMessage Returns if the lending analysis could not be completed. Contains explanation for what error occurred. Type: String Summary Contains summary information for documents grouped by type. Type: LendingSummary object Warnings A list of warnings that occurred during the lending analysis operation. Type: Array of Warning objects GetLendingAnalysisSummary 505 Amazon Textract Errors AccessDeniedException Developer Guide You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidJobIdException An invalid job identifier was passed to an asynchronous analysis operation. HTTP Status Code: 400 InvalidKMSKeyException Indicates you do not have decrypt permissions with the KMS key entered, or the KMS key was entered incorrectly. HTTP Status Code: 400 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 GetLendingAnalysisSummary 506 Amazon Textract Developer Guide ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 GetLendingAnalysisSummary 507 Amazon Textract ListAdapters Lists all adapters that match the specified filtration criteria. Developer Guide Request Syntax { "AfterCreationTime": number, "BeforeCreationTime": number, "MaxResults": number, "NextToken": "string" } Request Parameters The request accepts the following data in JSON format. AfterCreationTime Specifies the lower bound for the ListAdapters operation. Ensures ListAdapters returns only adapters created after the specified creation time. Type: Timestamp Required: No BeforeCreationTime Specifies the upper bound for the ListAdapters operation. Ensures ListAdapters returns only adapters created before the specified creation time. Type: Timestamp Required: No MaxResults The maximum number of results to return when listing adapters. Type: Integer Valid Range: Minimum value of 1. Required: No ListAdapters 508 Amazon Textract NextToken Developer Guide Identifies the next page of results to return when listing adapters. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* Required: No Response Syntax { "Adapters": [ { "AdapterId": "string", "AdapterName": "string", "CreationTime": number, "FeatureTypes": [ "string" ] } ], "NextToken": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Adapters A list of adapters that matches the filtering criteria specified when calling ListAdapters. Type: Array of AdapterOverview objects NextToken Identifies the next page of results to return when listing adapters. Type: String ListAdapters 509 Amazon Textract Developer Guide Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP
textract-dg-119
textract-dg.pdf
119
Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. ListAdapters 510 Amazon Textract HTTP Status Code: 400 See Also Developer Guide For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 ListAdapters 511 Amazon Textract ListAdapterVersions Developer Guide List all version of an adapter that meet the specified filtration criteria. Request Syntax { "AdapterId": "string", "AfterCreationTime": number, "BeforeCreationTime": number, "MaxResults": number, "NextToken": "string" } Request Parameters The request accepts the following data in JSON format. AdapterId A string containing a unique ID for the adapter to match for when listing adapter versions. Type: String Length Constraints: Minimum length of 12. Maximum length of 1011. Required: No AfterCreationTime Specifies the lower bound for the ListAdapterVersions operation. Ensures ListAdapterVersions returns only adapter versions created after the specified creation time. Type: Timestamp Required: No BeforeCreationTime Specifies the upper bound for the ListAdapterVersions operation. Ensures ListAdapterVersions returns only adapter versions created after the specified creation time. Type: Timestamp Required: No ListAdapterVersions 512 Amazon Textract MaxResults Developer Guide The maximum number of results to return when listing adapter versions. Type: Integer Valid Range: Minimum value of 1. Required: No NextToken Identifies the next page of results to return when listing adapter versions. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* Required: No Response Syntax { "AdapterVersions": [ { "AdapterId": "string", "AdapterVersion": "string", "CreationTime": number, "FeatureTypes": [ "string" ], "Status": "string", "StatusMessage": "string" } ], "NextToken": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. ListAdapterVersions 513 Amazon Textract AdapterVersions Developer Guide Adapter versions that match the filtering criteria specified when calling ListAdapters. Type: Array of AdapterVersionOverview objects NextToken Identifies the next page of results to return when listing adapter versions. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Pattern: .*\S.* Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. ListAdapterVersions 514 Amazon Textract HTTP Status Code: 400 ResourceNotFoundException Developer Guide Returned when an operation tried to access a nonexistent resource. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 ListAdapterVersions 515 Developer Guide Amazon Textract ListTagsForResource Lists all tags for an Amazon Textract resource. Request Syntax { "ResourceARN": "string" } Request Parameters The request accepts the following data in JSON format. ResourceARN The Amazon Resource Name (ARN) that specifies the resource to list tags for. Type: String Length Constraints: Minimum length of 1. Maximum length of 1011. Required: Yes Response Syntax { "Tags": { "string" : "string" } } Response Elements If the action
textract-dg-120
textract-dg.pdf
120
for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 ListAdapterVersions 515 Developer Guide Amazon Textract ListTagsForResource Lists all tags for an Amazon Textract resource. Request Syntax { "ResourceARN": "string" } Request Parameters The request accepts the following data in JSON format. ResourceARN The Amazon Resource Name (ARN) that specifies the resource to list tags for. Type: String Length Constraints: Minimum length of 1. Maximum length of 1011. Required: Yes Response Syntax { "Tags": { "string" : "string" } } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Tags A set of tags (key-value pairs) that are part of the requested resource. ListTagsForResource 516 Amazon Textract Type: String to string map Developer Guide Map Entries: Minimum number of 0 items. Maximum number of 200 items. Key Length Constraints: Minimum length of 1. Maximum length of 128. Key Pattern: ^(?!aws:)[\p{L}\p{Z}\p{N}_.:/=+\-@]*$ Value Length Constraints: Minimum length of 0. Maximum length of 256. Value Pattern: ^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$ Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. HTTP Status Code: 500 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ListTagsForResource 517 Amazon Textract ResourceNotFoundException Developer Guide Returned when an operation tried to access a nonexistent resource. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. HTTP Status Code: 500 ValidationException Indicates that a request was not valid. Check request for proper formatting. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 ListTagsForResource 518 Amazon Textract Developer Guide StartDocumentAnalysis Starts the asynchronous analysis of an input document for relationships between detected items such as key-value pairs, tables, and selection elements. StartDocumentAnalysis can analyze text in documents that are in JPEG, PNG, TIFF, and PDF format. The documents are stored in an Amazon S3 bucket. Use DocumentLocation to specify the bucket name and file name of the document. StartDocumentAnalysis returns a job identifier (JobId) that you use to get the results of the operation. When text analysis is finished, Amazon Textract publishes a completion status to the Amazon Simple Notification Service (Amazon SNS) topic that you specify in NotificationChannel. To get the results of the text analysis operation, first check that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call GetDocumentAnalysis, and pass the job identifier (JobId) from the initial call to StartDocumentAnalysis. For more information, see Document Text Analysis. Request Syntax { "AdaptersConfig": { "Adapters": [ { "AdapterId": "string", "Pages": [ "string" ], "Version": "string" } ] }, "ClientRequestToken": "string", "DocumentLocation": { "S3Object": { "Bucket": "string", "Name": "string", "Version": "string" } }, "FeatureTypes": [ "string" ], "JobTag": "string", "KMSKeyId": "string", "NotificationChannel": { StartDocumentAnalysis 519 Amazon Textract Developer Guide "RoleArn": "string", "SNSTopicArn": "string" }, "OutputConfig": { "S3Bucket": "string", "S3Prefix": "string" }, "QueriesConfig": { "Queries": [ { "Alias": "string", "Pages": [ "string" ], "Text": "string" } ] } } Request Parameters The request accepts the following data in JSON format. AdaptersConfig Specifies the adapter to be used when analyzing a document. Type: AdaptersConfig object Required: No ClientRequestToken The idempotent token that you use to identify the start request. If you use the same token with multiple StartDocumentAnalysis requests, the same JobId is returned. Use ClientRequestToken to prevent the same job from being accidentally started more than once. For more information, see Calling Amazon Textract Asynchronous Operations. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: No StartDocumentAnalysis 520 Amazon Textract DocumentLocation The location of the document to be processed. Type: DocumentLocation object Required: Yes FeatureTypes Developer Guide A list of the types of analysis to perform. Add TABLES to the list to return information about the tables that are detected in the input document. Add
textract-dg-121
textract-dg.pdf
121
the same token with multiple StartDocumentAnalysis requests, the same JobId is returned. Use ClientRequestToken to prevent the same job from being accidentally started more than once. For more information, see Calling Amazon Textract Asynchronous Operations. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: No StartDocumentAnalysis 520 Amazon Textract DocumentLocation The location of the document to be processed. Type: DocumentLocation object Required: Yes FeatureTypes Developer Guide A list of the types of analysis to perform. Add TABLES to the list to return information about the tables that are detected in the input document. Add FORMS to return detected form data. To perform both types of analysis, add TABLES and FORMS to FeatureTypes. All lines and words detected in the document are included in the response (including text that isn't related to the value of FeatureTypes). Type: Array of strings Valid Values: TABLES | FORMS | QUERIES | SIGNATURES | LAYOUT Required: Yes JobTag An identifier that you specify that's included in the completion notification published to the Amazon SNS topic. For example, you can use JobTag to identify the type of document that the completion notification corresponds to (such as a tax form or a receipt). Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: [a-zA-Z0-9_.\-:]+ Required: No KMSKeyId The KMS key used to encrypt the inference results. This can be in either Key ID or Key Alias format. When a KMS key is provided, the KMS key will be used for server-side encryption of the objects in the customer bucket. When this parameter is not enabled, the result will be encrypted server side,using SSE-S3. Type: String StartDocumentAnalysis 521 Amazon Textract Developer Guide Length Constraints: Minimum length of 1. Maximum length of 2048. Pattern: ^[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,2048}$ Required: No NotificationChannel The Amazon SNS topic ARN that you want Amazon Textract to publish the completion status of the operation to. Type: NotificationChannel object Required: No OutputConfig Sets if the output will go to a customer defined bucket. By default, Amazon Textract will save the results internally to be accessed by the GetDocumentAnalysis operation. Type: OutputConfig object Required: No QueriesConfig Type: QueriesConfig object Required: No Response Syntax { "JobId": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. StartDocumentAnalysis 522 Amazon Textract JobId Developer Guide The identifier for the document text detection job. Use JobId to identify the job in a subsequent call to GetDocumentAnalysis. A JobId value is only valid for 7 days. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 BadDocumentException Amazon Textract isn't able to read the document. For more information on the document limits in Amazon Textract, see Quotas in Amazon Textract. HTTP Status Code: 400 DocumentTooLargeException The document can't be processed because it's too large. The maximum document size for synchronous operations 10 MB. The maximum document size for asynchronous operations is 500 MB for PDF files. HTTP Status Code: 400 IdempotentParameterMismatchException A ClientRequestToken input parameter was reused with an operation, but at least one of the other input parameters is different from the previous call to the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. StartDocumentAnalysis 523 Amazon Textract HTTP Status Code: 500 InvalidKMSKeyException Developer Guide Indicates you do not have decrypt permissions with the KMS key entered, or the KMS key was entered incorrectly. HTTP Status Code: 400 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 LimitExceededException An Amazon Textract service limit was exceeded. For example, if you start too many asynchronous jobs concurrently, calls to start operations (StartDocumentTextDetection, for example) raise a LimitExceededException exception (HTTP status code: 400) until the number of concurrently running jobs is below the Amazon Textract service limit. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. StartDocumentAnalysis 524 Amazon Textract Developer Guide HTTP Status Code: 500 UnsupportedDocumentException The format of the input document isn't supported. Documents
textract-dg-122
textract-dg.pdf
122
For example, if you start too many asynchronous jobs concurrently, calls to start operations (StartDocumentTextDetection, for example) raise a LimitExceededException exception (HTTP status code: 400) until the number of concurrently running jobs is below the Amazon Textract service limit. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. StartDocumentAnalysis 524 Amazon Textract Developer Guide HTTP Status Code: 500 UnsupportedDocumentException The format of the input document isn't supported. Documents for operations can be in PNG, JPEG, PDF, or TIFF format. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 StartDocumentAnalysis 525 Amazon Textract Developer Guide StartDocumentTextDetection Starts the asynchronous detection of text in a document. Amazon Textract can detect lines of text and the words that make up a line of text. StartDocumentTextDetection can analyze text in documents that are in JPEG, PNG, TIFF, and PDF format. The documents are stored in an Amazon S3 bucket. Use DocumentLocation to specify the bucket name and file name of the document. StartTextDetection returns a job identifier (JobId) that you use to get the results of the operation. When text detection is finished, Amazon Textract publishes a completion status to the Amazon Simple Notification Service (Amazon SNS) topic that you specify in NotificationChannel. To get the results of the text detection operation, first check that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call GetDocumentTextDetection, and pass the job identifier (JobId) from the initial call to StartDocumentTextDetection. For more information, see Document Text Detection. Request Syntax { "ClientRequestToken": "string", "DocumentLocation": { "S3Object": { "Bucket": "string", "Name": "string", "Version": "string" } }, "JobTag": "string", "KMSKeyId": "string", "NotificationChannel": { "RoleArn": "string", "SNSTopicArn": "string" }, "OutputConfig": { "S3Bucket": "string", "S3Prefix": "string" } } StartDocumentTextDetection 526 Amazon Textract Request Parameters The request accepts the following data in JSON format. ClientRequestToken Developer Guide The idempotent token that's used to identify the start request. If you use the same token with multiple StartDocumentTextDetection requests, the same JobId is returned. Use ClientRequestToken to prevent the same job from being accidentally started more than once. For more information, see Calling Amazon Textract Asynchronous Operations. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: No DocumentLocation The location of the document to be processed. Type: DocumentLocation object Required: Yes JobTag An identifier that you specify that's included in the completion notification published to the Amazon SNS topic. For example, you can use JobTag to identify the type of document that the completion notification corresponds to (such as a tax form or a receipt). Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: [a-zA-Z0-9_.\-:]+ Required: No KMSKeyId The KMS key used to encrypt the inference results. This can be in either Key ID or Key Alias format. When a KMS key is provided, the KMS key will be used for server-side encryption of StartDocumentTextDetection 527 Amazon Textract Developer Guide the objects in the customer bucket. When this parameter is not enabled, the result will be encrypted server side,using SSE-S3. Type: String Length Constraints: Minimum length of 1. Maximum length of 2048. Pattern: ^[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,2048}$ Required: No NotificationChannel The Amazon SNS topic ARN that you want Amazon Textract to publish the completion status of the operation to. Type: NotificationChannel object Required: No OutputConfig Sets if the output will go to a customer defined bucket. By default Amazon Textract will save the results internally to be accessed with the GetDocumentTextDetection operation. Type: OutputConfig object Required: No Response Syntax { "JobId": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. StartDocumentTextDetection 528 Amazon Textract JobId Developer Guide The identifier of the text detection job for the document. Use JobId to identify the job in a subsequent call to GetDocumentTextDetection. A JobId value is only valid for 7 days. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 BadDocumentException Amazon Textract isn't able to read the document. For more
textract-dg-123
textract-dg.pdf
123
returned in JSON format by the service. StartDocumentTextDetection 528 Amazon Textract JobId Developer Guide The identifier of the text detection job for the document. Use JobId to identify the job in a subsequent call to GetDocumentTextDetection. A JobId value is only valid for 7 days. Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Errors AccessDeniedException You aren't authorized to perform the action. Use the Amazon Resource Name (ARN) of an authorized user or IAM role to perform the operation. HTTP Status Code: 400 BadDocumentException Amazon Textract isn't able to read the document. For more information on the document limits in Amazon Textract, see Quotas in Amazon Textract. HTTP Status Code: 400 DocumentTooLargeException The document can't be processed because it's too large. The maximum document size for synchronous operations 10 MB. The maximum document size for asynchronous operations is 500 MB for PDF files. HTTP Status Code: 400 IdempotentParameterMismatchException A ClientRequestToken input parameter was reused with an operation, but at least one of the other input parameters is different from the previous call to the operation. HTTP Status Code: 400 InternalServerError Amazon Textract experienced a service issue. Try your call again. StartDocumentTextDetection 529 Amazon Textract HTTP Status Code: 500 InvalidKMSKeyException Developer Guide Indicates you do not have decrypt permissions with the KMS key entered, or the KMS key was entered incorrectly. HTTP Status Code: 400 InvalidParameterException An input parameter violated a constraint. For example, in synchronous operations, an InvalidParameterException exception occurs when neither of the S3Object or Bytes values are supplied in the Document request parameter. Validate your parameter before calling the API operation again. HTTP Status Code: 400 InvalidS3ObjectException Amazon Textract is unable to access the S3 object that's specified in the request. for more information, Configure Access to Amazon S3 For troubleshooting information, see Troubleshooting Amazon S3 HTTP Status Code: 400 LimitExceededException An Amazon Textract service limit was exceeded. For example, if you start too many asynchronous jobs concurrently, calls to start operations (StartDocumentTextDetection, for example) raise a LimitExceededException exception (HTTP status code: 400) until the number of concurrently running jobs is below the Amazon Textract service limit. HTTP Status Code: 400 ProvisionedThroughputExceededException The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon Textract. HTTP Status Code: 400 ThrottlingException Amazon Textract is temporarily unable to process the request. Try your call again. StartDocumentTextDetection 530 Amazon Textract Developer Guide HTTP Status Code: 500 UnsupportedDocumentException The format of the input document isn't supported. Documents for operations can be in PNG, JPEG, PDF, or TIFF format. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 StartDocumentTextDetection 531 Amazon Textract StartExpenseAnalysis Developer Guide Starts the asynchronous analysis of invoices or receipts for data like contact information, items purchased, and vendor names. StartExpenseAnalysis can analyze text in documents that are in JPEG, PNG, and PDF format. The documents must be stored in an Amazon S3 bucket. Use the DocumentLocation parameter to specify the name of your S3 bucket and the name of the document in that bucket. StartExpenseAnalysis returns a job identifier (JobId) that you will provide to GetExpenseAnalysis to retrieve the results of the operation. When the analysis of the input invoices/receipts is finished, Amazon Textract publishes a completion status to the Amazon Simple Notification Service (Amazon SNS) topic that you provide to the NotificationChannel. To obtain the results of the invoice and receipt analysis operation, ensure that the status value published to the Amazon SNS topic is SUCCEEDED. If so, call GetExpenseAnalysis, and pass the job identifier (JobId) that was returned by your call to StartExpenseAnalysis. For more information, see Analyzing Invoices and Receipts. Request Syntax { "ClientRequestToken": "string", "DocumentLocation": { "S3Object": { "Bucket": "string", "Name": "string", "Version": "string" } }, "JobTag": "string", "KMSKeyId": "string", "NotificationChannel": { "RoleArn": "string", "SNSTopicArn": "string" }, "OutputConfig": { "S3Bucket": "string", "S3Prefix": "string" } } StartExpenseAnalysis 532 Amazon Textract Request Parameters The request accepts the following data in JSON format. ClientRequestToken Developer Guide The idempotent token that's used to identify the start request. If you use the same token with multiple StartDocumentTextDetection requests, the same JobId is returned. Use ClientRequestToken to prevent the same job from being accidentally started more than once. For more information, see Calling Amazon Textract Asynchronous Operations Type: String Length Constraints: Minimum length of 1. Maximum length of 64. Pattern: ^[a-zA-Z0-9-_]+$ Required: No DocumentLocation The location of the document to be