Search in sources :

Example 16 with InputConfig

use of com.google.cloud.automl.v1.InputConfig in project java-document-ai by googleapis.

the class SetEndPointBeta method setEndpoint.

public static void setEndpoint(String projectId, String location, String inputGcsUri) throws IOException {
    DocumentUnderstandingServiceSettings settings = DocumentUnderstandingServiceSettings.newBuilder().setEndpoint("eu-documentai.googleapis.com:443").build();
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DocumentUnderstandingServiceClient client = DocumentUnderstandingServiceClient.create(settings)) {
        // Configure the request for processing the PDF
        String parent = String.format("projects/%s/locations/%s", projectId, location);
        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).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
        for (Document.Entity entity : response.getEntitiesList()) {
            System.out.printf("Entity text: %s\n", getText(entity, text));
            System.out.printf("Entity type: %s\n", entity.getType());
            System.out.printf("Entity mention text: %s\n", entity.getMentionText());
        }
    }
}
Also used : DocumentUnderstandingServiceClient(com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient) GcsSource(com.google.cloud.documentai.v1beta2.GcsSource) InputConfig(com.google.cloud.documentai.v1beta2.InputConfig) Document(com.google.cloud.documentai.v1beta2.Document) DocumentUnderstandingServiceSettings(com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceSettings) ProcessDocumentRequest(com.google.cloud.documentai.v1beta2.ProcessDocumentRequest)

Example 17 with InputConfig

use of com.google.cloud.automl.v1.InputConfig 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 18 with InputConfig

use of com.google.cloud.automl.v1.InputConfig 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)

Example 19 with InputConfig

use of com.google.cloud.automl.v1.InputConfig in project java-document-ai by googleapis.

the class QuickStart method quickStart.

public static void quickStart(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 a single document
        String parent = String.format("projects/%s/locations/%s", projectId, location);
        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).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
        for (Document.Entity entity : response.getEntitiesList()) {
            System.out.printf("Entity text: %s\n", getText(entity, text));
            System.out.printf("Entity type: %s\n", entity.getType());
            System.out.printf("Entity mention text: %s\n", entity.getMentionText());
        }
    }
}
Also used : DocumentUnderstandingServiceClient(com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient) GcsSource(com.google.cloud.documentai.v1beta2.GcsSource) InputConfig(com.google.cloud.documentai.v1beta2.InputConfig) Document(com.google.cloud.documentai.v1beta2.Document) ProcessDocumentRequest(com.google.cloud.documentai.v1beta2.ProcessDocumentRequest)

Example 20 with InputConfig

use of com.google.cloud.automl.v1.InputConfig in project spring-cloud-gcp by GoogleCloudPlatform.

the class CloudVisionTemplate method analyzeFile.

/**
 * Analyze a file and extract the features of the image specified by {@code featureTypes}.
 *
 * <p>A feature describes the kind of Cloud Vision analysis one wishes to perform on a file, such
 * as text detection, image labelling, facial detection, etc. A full list of feature types can be
 * found in {@link Feature.Type}.
 *
 * @param fileResource the file one wishes to analyze. The Cloud Vision APIs support image formats
 *     described here: https://cloud.google.com/vision/docs/supported-files. Documents with more
 *     than 5 pages are not supported.
 * @param mimeType the mime type of the fileResource. Currently, only "application/pdf",
 *     "image/tiff" and "image/gif" are supported.
 * @param featureTypes the types of image analysis to perform on the image
 * @return the results of file analyse
 * @throws CloudVisionException if the file could not be read or if a malformed response is
 *     received from the Cloud Vision APIs
 */
public AnnotateFileResponse analyzeFile(Resource fileResource, String mimeType, Feature.Type... featureTypes) {
    ByteString imgBytes;
    try {
        imgBytes = ByteString.readFrom(fileResource.getInputStream());
    } catch (IOException ex) {
        throw new CloudVisionException(READ_BYTES_ERROR_MESSAGE, ex);
    }
    InputConfig inputConfig = InputConfig.newBuilder().setMimeType(mimeType).setContent(imgBytes).build();
    List<Feature> featureList = Arrays.stream(featureTypes).map(featureType -> Feature.newBuilder().setType(featureType).build()).collect(Collectors.toList());
    BatchAnnotateFilesRequest request = BatchAnnotateFilesRequest.newBuilder().addRequests(AnnotateFileRequest.newBuilder().addAllFeatures(featureList).setInputConfig(inputConfig).build()).build();
    BatchAnnotateFilesResponse response = this.imageAnnotatorClient.batchAnnotateFiles(request);
    List<AnnotateFileResponse> annotateFileResponses = response.getResponsesList();
    if (!annotateFileResponses.isEmpty()) {
        return annotateFileResponses.get(0);
    } else {
        throw new CloudVisionException(EMPTY_RESPONSE_ERROR_MESSAGE);
    }
}
Also used : AnnotateFileRequest(com.google.cloud.vision.v1.AnnotateFileRequest) Arrays(java.util.Arrays) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) Type(com.google.cloud.vision.v1.Feature.Type) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) IOException(java.io.IOException) InputConfig(com.google.cloud.vision.v1.InputConfig) Collectors(java.util.stream.Collectors) Feature(com.google.cloud.vision.v1.Feature) ByteString(com.google.protobuf.ByteString) List(java.util.List) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) Image(com.google.cloud.vision.v1.Image) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) ImageContext(com.google.cloud.vision.v1.ImageContext) AnnotateImageRequest(com.google.cloud.vision.v1.AnnotateImageRequest) BatchAnnotateImagesResponse(com.google.cloud.vision.v1.BatchAnnotateImagesResponse) BatchAnnotateImagesRequest(com.google.cloud.vision.v1.BatchAnnotateImagesRequest) Code(com.google.rpc.Code) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) ByteString(com.google.protobuf.ByteString) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) InputConfig(com.google.cloud.vision.v1.InputConfig) IOException(java.io.IOException) Feature(com.google.cloud.vision.v1.Feature)

Aggregations

Document (com.google.cloud.documentai.v1beta2.Document)7 DocumentUnderstandingServiceClient (com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient)7 GcsSource (com.google.cloud.documentai.v1beta2.GcsSource)7 InputConfig (com.google.cloud.documentai.v1beta2.InputConfig)7 ProcessDocumentRequest (com.google.cloud.documentai.v1beta2.ProcessDocumentRequest)7 InputConfig (com.google.cloud.vision.v1.InputConfig)6 BatchTranslateMetadata (com.google.cloud.translate.v3.BatchTranslateMetadata)4 BatchTranslateResponse (com.google.cloud.translate.v3.BatchTranslateResponse)4 BatchTranslateTextRequest (com.google.cloud.translate.v3.BatchTranslateTextRequest)4 GcsDestination (com.google.cloud.translate.v3.GcsDestination)4 GcsSource (com.google.cloud.translate.v3.GcsSource)4 InputConfig (com.google.cloud.translate.v3.InputConfig)4 LocationName (com.google.cloud.translate.v3.LocationName)4 OutputConfig (com.google.cloud.translate.v3.OutputConfig)4 TranslationServiceClient (com.google.cloud.translate.v3.TranslationServiceClient)4 ByteString (com.google.protobuf.ByteString)4 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)3 Feature (com.google.cloud.vision.v1.Feature)3 GcsSource (com.google.cloud.vision.v1.GcsSource)3 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)3