Search in sources :

Example 1 with KeyValuePairHint

use of com.google.cloud.documentai.v1beta2.KeyValuePairHint in project java-document-ai by googleapis.

the class BatchParseFormBeta method batchParseFormGcs.

public static void batchParseFormGcs(String projectId, String location, String outputGcsBucketName, String outputGcsPrefix, String inputGcsUri) throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DocumentUnderstandingServiceClient client = DocumentUnderstandingServiceClient.create()) {
        // Configure the request for processing the PDF
        String parent = String.format("projects/%s/locations/%s", projectId, location);
        // Improve form parsing results by providing key-value pair hints.
        // For each key hint, key is text that is likely to appear in the
        // document as a form field name (i.e. "DOB").
        // Value types are optional, but can be one or more of:
        // ADDRESS, LOCATION, ORGANIZATION, PERSON, PHONE_NUMBER, ID,
        // NUMBER, EMAIL, PRICE, TERMS, DATE, NAME
        KeyValuePairHint keyValuePairHint = KeyValuePairHint.newBuilder().setKey("Phone").addValueTypes("PHONE_NUMBER").build();
        KeyValuePairHint keyValuePairHint2 = KeyValuePairHint.newBuilder().setKey("Contact").addValueTypes("EMAIL").addValueTypes("NAME").build();
        // Setting enabled=True enables form extraction
        FormExtractionParams params = FormExtractionParams.newBuilder().setEnabled(true).addKeyValuePairHints(keyValuePairHint).addKeyValuePairHints(keyValuePairHint2).build();
        GcsSource inputUri = GcsSource.newBuilder().setUri(inputGcsUri).build();
        // mime_type can be application/pdf, image/tiff,
        // and image/gif, or application/json
        InputConfig config = InputConfig.newBuilder().setGcsSource(inputUri).setMimeType("application/pdf").build();
        GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(String.format("gs://%s/%s", outputGcsBucketName, outputGcsPrefix)).build();
        OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).setPagesPerShard(1).build();
        ProcessDocumentRequest request = ProcessDocumentRequest.newBuilder().setFormExtractionParams(params).setInputConfig(config).setOutputConfig(outputConfig).build();
        BatchProcessDocumentsRequest requests = BatchProcessDocumentsRequest.newBuilder().addRequests(request).setParent(parent).build();
        // Batch process document using a long-running operation.
        OperationFuture<BatchProcessDocumentsResponse, OperationMetadata> future = client.batchProcessDocumentsAsync(requests);
        // Wait for operation to complete.
        System.out.println("Waiting for operation to complete...");
        future.get(360, TimeUnit.SECONDS);
        System.out.println("Document processing complete.");
        Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
        Bucket bucket = storage.get(outputGcsBucketName);
        // List all of the files in the Storage bucket.
        Page<Blob> blobs = bucket.list(Storage.BlobListOption.currentDirectory(), Storage.BlobListOption.prefix(outputGcsPrefix));
        int idx = 0;
        for (Blob blob : blobs.iterateAll()) {
            if (!blob.isDirectory()) {
                System.out.printf("Fetched file #%d\n", ++idx);
                // Read the results
                // Download and store json data in a temp file.
                File tempFile = File.createTempFile("file", ".json");
                Blob fileInfo = storage.get(BlobId.of(outputGcsBucketName, blob.getName()));
                fileInfo.downloadTo(tempFile.toPath());
                // Parse json file into Document.
                FileReader reader = new FileReader(tempFile);
                Document.Builder builder = Document.newBuilder();
                JsonFormat.parser().merge(reader, builder);
                Document document = builder.build();
                // Get all of the document text as one big string.
                String text = document.getText();
                // Process the output.
                if (document.getPagesCount() > 0) {
                    Document.Page page1 = document.getPages(0);
                    for (Document.Page.FormField field : page1.getFormFieldsList()) {
                        String fieldName = getText(field.getFieldName(), text);
                        String fieldValue = getText(field.getFieldValue(), text);
                        System.out.println("Extracted form fields pair:");
                        System.out.printf("\t(%s, %s))", fieldName, fieldValue);
                    }
                }
                // Clean up temp file.
                tempFile.deleteOnExit();
            }
        }
    }
}
Also used : BatchProcessDocumentsResponse(com.google.cloud.documentai.v1beta2.BatchProcessDocumentsResponse) DocumentUnderstandingServiceClient(com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient) GcsSource(com.google.cloud.documentai.v1beta2.GcsSource) Page(com.google.api.gax.paging.Page) Document(com.google.cloud.documentai.v1beta2.Document) InputConfig(com.google.cloud.documentai.v1beta2.InputConfig) FileReader(java.io.FileReader) BatchProcessDocumentsRequest(com.google.cloud.documentai.v1beta2.BatchProcessDocumentsRequest) OperationMetadata(com.google.cloud.documentai.v1beta2.OperationMetadata) ProcessDocumentRequest(com.google.cloud.documentai.v1beta2.ProcessDocumentRequest) KeyValuePairHint(com.google.cloud.documentai.v1beta2.KeyValuePairHint) Blob(com.google.cloud.storage.Blob) KeyValuePairHint(com.google.cloud.documentai.v1beta2.KeyValuePairHint) OutputConfig(com.google.cloud.documentai.v1beta2.OutputConfig) Storage(com.google.cloud.storage.Storage) Bucket(com.google.cloud.storage.Bucket) FormExtractionParams(com.google.cloud.documentai.v1beta2.FormExtractionParams) GcsDestination(com.google.cloud.documentai.v1beta2.GcsDestination) File(java.io.File)

Example 2 with KeyValuePairHint

use of com.google.cloud.documentai.v1beta2.KeyValuePairHint in project java-document-ai by googleapis.

the class ParseFormBeta method parseForm.

public static void parseForm(String projectId, String location, String inputGcsUri) throws IOException, ExecutionException, InterruptedException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DocumentUnderstandingServiceClient client = DocumentUnderstandingServiceClient.create()) {
        // Configure the request for processing the PDF
        String parent = String.format("projects/%s/locations/%s", projectId, location);
        // Improve form parsing results by providing key-value pair hints.
        // For each key hint, key is text that is likely to appear in the
        // document as a form field name (i.e. "DOB").
        // Value types are optional, but can be one or more of:
        // ADDRESS, LOCATION, ORGANIZATION, PERSON, PHONE_NUMBER, ID,
        // NUMBER, EMAIL, PRICE, TERMS, DATE, NAME
        KeyValuePairHint keyValuePairHint = KeyValuePairHint.newBuilder().setKey("Phone").addValueTypes("PHONE_NUMBER").build();
        KeyValuePairHint keyValuePairHint2 = KeyValuePairHint.newBuilder().setKey("Contact").addValueTypes("EMAIL").addValueTypes("NAME").build();
        // Setting enabled=True enables form extraction
        FormExtractionParams params = FormExtractionParams.newBuilder().setEnabled(true).addKeyValuePairHints(keyValuePairHint).addKeyValuePairHints(keyValuePairHint2).build();
        GcsSource uri = GcsSource.newBuilder().setUri(inputGcsUri).build();
        // mime_type can be application/pdf, image/tiff,
        // and image/gif, or application/json
        InputConfig config = InputConfig.newBuilder().setGcsSource(uri).setMimeType("application/pdf").build();
        ProcessDocumentRequest request = ProcessDocumentRequest.newBuilder().setParent(parent).setFormExtractionParams(params).setInputConfig(config).build();
        // Recognizes text entities in the PDF document
        Document response = client.processDocument(request);
        // Get all of the document text as one big string
        String text = response.getText();
        // Process the output
        if (response.getPagesCount() > 0) {
            Document.Page page1 = response.getPages(0);
            for (Document.Page.FormField field : page1.getFormFieldsList()) {
                String fieldName = getText(field.getFieldName(), text);
                String fieldValue = getText(field.getFieldValue(), text);
                System.out.println("Extracted form fields pair:");
                System.out.printf("\t(%s, %s))", fieldName, fieldValue);
            }
        }
    }
}
Also used : KeyValuePairHint(com.google.cloud.documentai.v1beta2.KeyValuePairHint) DocumentUnderstandingServiceClient(com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient) GcsSource(com.google.cloud.documentai.v1beta2.GcsSource) FormExtractionParams(com.google.cloud.documentai.v1beta2.FormExtractionParams) InputConfig(com.google.cloud.documentai.v1beta2.InputConfig) Document(com.google.cloud.documentai.v1beta2.Document) ProcessDocumentRequest(com.google.cloud.documentai.v1beta2.ProcessDocumentRequest)

Aggregations

Document (com.google.cloud.documentai.v1beta2.Document)2 DocumentUnderstandingServiceClient (com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient)2 FormExtractionParams (com.google.cloud.documentai.v1beta2.FormExtractionParams)2 GcsSource (com.google.cloud.documentai.v1beta2.GcsSource)2 InputConfig (com.google.cloud.documentai.v1beta2.InputConfig)2 KeyValuePairHint (com.google.cloud.documentai.v1beta2.KeyValuePairHint)2 ProcessDocumentRequest (com.google.cloud.documentai.v1beta2.ProcessDocumentRequest)2 Page (com.google.api.gax.paging.Page)1 BatchProcessDocumentsRequest (com.google.cloud.documentai.v1beta2.BatchProcessDocumentsRequest)1 BatchProcessDocumentsResponse (com.google.cloud.documentai.v1beta2.BatchProcessDocumentsResponse)1 GcsDestination (com.google.cloud.documentai.v1beta2.GcsDestination)1 OperationMetadata (com.google.cloud.documentai.v1beta2.OperationMetadata)1 OutputConfig (com.google.cloud.documentai.v1beta2.OutputConfig)1 Blob (com.google.cloud.storage.Blob)1 Bucket (com.google.cloud.storage.Bucket)1 Storage (com.google.cloud.storage.Storage)1 File (java.io.File)1 FileReader (java.io.FileReader)1