Ejemplos de Amazon Textract usando SDK para Java 2.x - AWS SDK for Java 2.x

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Ejemplos de Amazon Textract usando SDK para Java 2.x

Los siguientes ejemplos de código muestran cómo realizar acciones e implementar escenarios comunes AWS SDK for Java 2.x con Amazon Textract.

Las acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Mientras las acciones muestran cómo llamar a las funciones de servicio individuales, es posible ver las acciones en contexto en los escenarios relacionados y en los ejemplos entre servicios.

Los escenarios son ejemplos de código que muestran cómo llevar a cabo una tarea específica llamando a varias funciones dentro del mismo servicio.

Cada ejemplo incluye un enlace a GitHub, donde puede encontrar instrucciones sobre cómo configurar y ejecutar el código en su contexto.

Acciones

En el siguiente ejemplo de código, se muestra cómo usar AnalyzeDocument.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

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.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; /** * 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) { final String usage = """ Usage: <sourceDoc>\s Where: sourceDoc - The path where the document is located (must be an image, for example, C:/AWS/book.png).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String sourceDoc = args[0]; Region region = Region.US_EAST_2; TextractClient textractClient = TextractClient.builder() .region(region) .build(); analyzeDoc(textractClient, sourceDoc); textractClient.close(); } public static void analyzeDoc(TextractClient textractClient, String sourceDoc) { try { InputStream sourceStream = new FileInputStream(new File(sourceDoc)); SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); // Get the input Document object as bytes Document myDoc = Document.builder() .bytes(sourceBytes) .build(); List<FeatureType> featureTypes = new ArrayList<FeatureType>(); featureTypes.add(FeatureType.FORMS); 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 | FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • Para obtener más información sobre la API, consulta AnalyzeDocumentla Referencia AWS SDK for Java 2.x de la API.

En el siguiente ejemplo de código, se muestra cómo usar DetectDocumentText.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Detectar texto de un documento de entrada.

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.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.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; /** * 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 DetectDocumentText { public static void main(String[] args) { final String usage = """ Usage: <sourceDoc>\s Where: sourceDoc - The path where the document is located (must be an image, for example, C:/AWS/book.png).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String sourceDoc = args[0]; Region region = Region.US_EAST_2; TextractClient textractClient = TextractClient.builder() .region(region) .build(); detectDocText(textractClient, sourceDoc); textractClient.close(); } public static void detectDocText(TextractClient textractClient, String sourceDoc) { try { InputStream sourceStream = new FileInputStream(new File(sourceDoc)); SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); // Get the input Document object as bytes. Document myDoc = Document.builder() .bytes(sourceBytes) .build(); DetectDocumentTextRequest detectDocumentTextRequest = DetectDocumentTextRequest.builder() .document(myDoc) .build(); // Invoke the Detect operation. DetectDocumentTextResponse textResponse = textractClient.detectDocumentText(detectDocumentTextRequest); List<Block> docInfo = textResponse.blocks(); for (Block block : docInfo) { 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 | FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } } }

Detectar texto de un documento ubicado en un bucket de Amazon S3.

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; /** * 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 DetectDocumentTextS3 { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <docName>\s Where: bucketName - The name of the Amazon S3 bucket that contains the document.\s docName - The document name (must be an image, i.e., book.png).\s """; 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) .build(); detectDocTextS3(textractClient, bucketName, docName); textractClient.close(); } 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(); 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); } } }
  • Para obtener más información sobre la API, consulta DetectDocumentTextla Referencia AWS SDK for Java 2.x de la API.

En el siguiente ejemplo de código, se muestra cómo usar StartDocumentAnalysis.

SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

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; /** * 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 = """ Usage: <bucketName> <docName>\s Where: bucketName - The name of the Amazon S3 bucket that contains the document.\s docName - The document name (must be an image, for example, book.png).\s """; 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) .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(); } 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) .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 { 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 ""; } }
  • Para obtener más información sobre la API, consulta StartDocumentAnalysisla Referencia AWS SDK for Java 2.x de la API.