Search in sources :

Example 1 with TableExtractionParams

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

the class BatchParseTableBeta method batchParseTableGcs.

public static void batchParseTableGcs(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);
        TableBoundHint tableBoundHints = TableBoundHint.newBuilder().setBoundingBox(// Each vertice coordinate must be a number between 0 and 1
        BoundingPoly.newBuilder().addNormalizedVertices(NormalizedVertex.newBuilder().setX(0).setX(0).build()).addNormalizedVertices(NormalizedVertex.newBuilder().setX(1).setX(0).build()).addNormalizedVertices(NormalizedVertex.newBuilder().setX(1).setX(1).build()).addNormalizedVertices(NormalizedVertex.newBuilder().setX(0).setX(1).build()).build()).setPageNumber(1).build();
        TableExtractionParams params = TableExtractionParams.newBuilder().setEnabled(true).addTableBoundHints(tableBoundHints).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().setTableExtractionParams(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);
                    if (page1.getTablesCount() > 0) {
                        Document.Page.Table table = page1.getTables(0);
                        System.out.println("Results from first table processed:");
                        System.out.println("Header row:");
                        if (table.getHeaderRowsCount() > 0) {
                            Document.Page.Table.TableRow headerRow = table.getHeaderRows(0);
                            for (Document.Page.Table.TableCell tableCell : headerRow.getCellsList()) {
                                if (!tableCell.getLayout().getTextAnchor().getTextSegmentsList().isEmpty()) {
                                    // Extract shards from the text field
                                    // First shard in document doesn't have startIndex property
                                    List<Document.TextAnchor.TextSegment> textSegments = tableCell.getLayout().getTextAnchor().getTextSegmentsList();
                                    int startIdx = textSegments.size() > 0 ? (int) textSegments.get(0).getStartIndex() : 0;
                                    int endIdx = (int) textSegments.get(0).getEndIndex();
                                    System.out.printf("\t%s", text.substring(startIdx, endIdx));
                                }
                            }
                        }
                    }
                }
                // 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) TableExtractionParams(com.google.cloud.documentai.v1beta2.TableExtractionParams) 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) Blob(com.google.cloud.storage.Blob) TableBoundHint(com.google.cloud.documentai.v1beta2.TableBoundHint) TableBoundHint(com.google.cloud.documentai.v1beta2.TableBoundHint) OutputConfig(com.google.cloud.documentai.v1beta2.OutputConfig) Storage(com.google.cloud.storage.Storage) Bucket(com.google.cloud.storage.Bucket) GcsDestination(com.google.cloud.documentai.v1beta2.GcsDestination) File(java.io.File)

Example 2 with TableExtractionParams

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

the class ParseTableBeta method parseTable.

public static void parseTable(String projectId, String location, String inputGcsUri) throws IOException {
    // 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);
        TableBoundHint tableBoundHints = TableBoundHint.newBuilder().setBoundingBox(// Each vertice coordinate must be a number between 0 and 1
        BoundingPoly.newBuilder().addNormalizedVertices(NormalizedVertex.newBuilder().setX(0).setX(0).build()).addNormalizedVertices(NormalizedVertex.newBuilder().setX(1).setX(0).build()).addNormalizedVertices(NormalizedVertex.newBuilder().setX(1).setX(1).build()).addNormalizedVertices(NormalizedVertex.newBuilder().setX(0).setX(1).build()).build()).setPageNumber(1).build();
        TableExtractionParams params = TableExtractionParams.newBuilder().setEnabled(true).addTableBoundHints(tableBoundHints).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).setTableExtractionParams(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();
        // Get the first table in the document
        if (response.getPagesCount() > 0) {
            Document.Page page1 = response.getPages(0);
            if (page1.getTablesCount() > 0) {
                Document.Page.Table table = page1.getTables(0);
                System.out.println("Results from first table processed:");
                List<Document.Page.DetectedLanguage> detectedLangs = page1.getDetectedLanguagesList();
                String langCode = detectedLangs.size() > 0 ? detectedLangs.get(0).getLanguageCode() : "NOT_FOUND";
                System.out.printf("First detected language: : %s", langCode);
                Document.Page.Table.TableRow headerRow = table.getHeaderRows(0);
                System.out.println("Header row:");
                for (Document.Page.Table.TableCell tableCell : headerRow.getCellsList()) {
                    if (tableCell.getLayout().getTextAnchor().getTextSegmentsList() != null) {
                        // Extract shards from the text field
                        // First shard in document doesn't have startIndex property
                        System.out.printf("\t%s", getText(tableCell.getLayout(), text));
                    }
                }
            }
        }
    }
}
Also used : DocumentUnderstandingServiceClient(com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient) GcsSource(com.google.cloud.documentai.v1beta2.GcsSource) Document(com.google.cloud.documentai.v1beta2.Document) TableBoundHint(com.google.cloud.documentai.v1beta2.TableBoundHint) TableExtractionParams(com.google.cloud.documentai.v1beta2.TableExtractionParams) InputConfig(com.google.cloud.documentai.v1beta2.InputConfig) ProcessDocumentRequest(com.google.cloud.documentai.v1beta2.ProcessDocumentRequest)

Aggregations

Document (com.google.cloud.documentai.v1beta2.Document)2 DocumentUnderstandingServiceClient (com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient)2 GcsSource (com.google.cloud.documentai.v1beta2.GcsSource)2 InputConfig (com.google.cloud.documentai.v1beta2.InputConfig)2 ProcessDocumentRequest (com.google.cloud.documentai.v1beta2.ProcessDocumentRequest)2 TableBoundHint (com.google.cloud.documentai.v1beta2.TableBoundHint)2 TableExtractionParams (com.google.cloud.documentai.v1beta2.TableExtractionParams)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