Search in sources :

Example 21 with InputConfig

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

the class Detect method detectDocumentsGcs.

// [END vision_fulltext_detection_gcs]
// [START vision_text_detection_pdf_gcs]
/**
 * Performs document text OCR with PDF/TIFF as source files on Google Cloud Storage.
 *
 * @param gcsSourcePath The path to the remote file on Google Cloud Storage to detect document
 *     text on.
 * @param gcsDestinationPath The path to the remote file on Google Cloud Storage to store the
 *     results on.
 * @throws Exception on errors while closing the client.
 */
public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinationPath) throws Exception {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        List<AsyncAnnotateFileRequest> requests = new ArrayList<>();
        // Set the GCS source path for the remote file.
        GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsSourcePath).build();
        // Create the configuration with the specified MIME (Multipurpose Internet Mail Extensions)
        // types
        InputConfig inputConfig = InputConfig.newBuilder().setMimeType(// Supported MimeTypes: "application/pdf", "image/tiff"
        "application/pdf").setGcsSource(gcsSource).build();
        // Set the GCS destination path for where to save the results.
        GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(gcsDestinationPath).build();
        // Create the configuration for the System.output with the batch size.
        // The batch size sets how many pages should be grouped into each json System.output file.
        OutputConfig outputConfig = OutputConfig.newBuilder().setBatchSize(2).setGcsDestination(gcsDestination).build();
        // Select the Feature required by the vision API
        Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build();
        // Build the OCR request
        AsyncAnnotateFileRequest request = AsyncAnnotateFileRequest.newBuilder().addFeatures(feature).setInputConfig(inputConfig).setOutputConfig(outputConfig).build();
        requests.add(request);
        // Perform the OCR request
        OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> response = client.asyncBatchAnnotateFilesAsync(requests);
        System.out.println("Waiting for the operation to finish.");
        // Wait for the request to finish. (The result is not used, since the API saves the result to
        // the specified location on GCS.)
        List<AsyncAnnotateFileResponse> result = response.get(180, TimeUnit.SECONDS).getResponsesList();
        // Once the request has completed and the System.output has been
        // written to GCS, we can list all the System.output files.
        Storage storage = StorageOptions.getDefaultInstance().getService();
        // Get the destination location from the gcsDestinationPath
        Pattern pattern = Pattern.compile("gs://([^/]+)/(.+)");
        Matcher matcher = pattern.matcher(gcsDestinationPath);
        if (matcher.find()) {
            String bucketName = matcher.group(1);
            String prefix = matcher.group(2);
            // Get the list of objects with the given prefix from the GCS bucket
            Bucket bucket = storage.get(bucketName);
            com.google.api.gax.paging.Page<Blob> pageList = bucket.list(BlobListOption.prefix(prefix));
            Blob firstOutputFile = null;
            // List objects with the given prefix.
            System.out.println("Output files:");
            for (Blob blob : pageList.iterateAll()) {
                System.out.println(blob.getName());
                // the first two pages of the input file.
                if (firstOutputFile == null) {
                    firstOutputFile = blob;
                }
            }
            // Get the contents of the file and convert the JSON contents to an AnnotateFileResponse
            // object. If the Blob is small read all its content in one request
            // (Note: the file is a .json file)
            // Storage guide: https://cloud.google.com/storage/docs/downloading-objects
            String jsonContents = new String(firstOutputFile.getContent());
            Builder builder = AnnotateFileResponse.newBuilder();
            JsonFormat.parser().merge(jsonContents, builder);
            // Build the AnnotateFileResponse object
            AnnotateFileResponse annotateFileResponse = builder.build();
            // Parse through the object to get the actual response for the first page of the input file.
            AnnotateImageResponse annotateImageResponse = annotateFileResponse.getResponses(0);
            // Here we print the full text from the first page.
            // The response contains more information:
            // annotation/pages/blocks/paragraphs/words/symbols
            // including confidence score and bounding boxes
            System.out.format("%nText: %s%n", annotateImageResponse.getFullTextAnnotation().getText());
        } else {
            System.out.println("No MATCH");
        }
    }
}
Also used : GcsSource(com.google.cloud.vision.v1.GcsSource) Matcher(java.util.regex.Matcher) AsyncAnnotateFileResponse(com.google.cloud.vision.v1.AsyncAnnotateFileResponse) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) Builder(com.google.cloud.vision.v1.AnnotateFileResponse.Builder) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) Feature(com.google.cloud.vision.v1.Feature) AsyncBatchAnnotateFilesResponse(com.google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse) AnnotateFileResponse(com.google.cloud.vision.v1.AnnotateFileResponse) AsyncAnnotateFileResponse(com.google.cloud.vision.v1.AsyncAnnotateFileResponse) InputConfig(com.google.cloud.vision.v1.InputConfig) OperationMetadata(com.google.cloud.vision.v1.OperationMetadata) Pattern(java.util.regex.Pattern) Blob(com.google.cloud.storage.Blob) OutputConfig(com.google.cloud.vision.v1.OutputConfig) Storage(com.google.cloud.storage.Storage) Bucket(com.google.cloud.storage.Bucket) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) AsyncAnnotateFileRequest(com.google.cloud.vision.v1.AsyncAnnotateFileRequest) GcsDestination(com.google.cloud.vision.v1.GcsDestination)

Example 22 with InputConfig

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

the class DetectBatchAnnotateFilesGcs method detectBatchAnnotateFilesGcs.

// Performs document feature detection on a remote PDF/TIFF/GIF file on Google Cloud Storage.
public static void detectBatchAnnotateFilesGcs(String gcsPath) {
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        // Annotate the first two pages and the last one (max 5 pages)
        // First page starts at 1, and not 0. Last page is -1.
        List<Integer> pages = Arrays.asList(1, 2, -1);
        GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsPath).build();
        Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build();
        // Other supported mime types : 'image/tiff' or 'image/gif'
        InputConfig inputConfig = InputConfig.newBuilder().setMimeType("application/pdf").setGcsSource(gcsSource).build();
        AnnotateFileRequest request = AnnotateFileRequest.newBuilder().addFeatures(feat).setInputConfig(inputConfig).addAllPages(pages).build();
        List<AnnotateFileRequest> requests = new ArrayList<>();
        requests.add(request);
        BatchAnnotateFilesRequest batchAnnotateFilesRequest = BatchAnnotateFilesRequest.newBuilder().addAllRequests(requests).build();
        ApiFuture<BatchAnnotateFilesResponse> future = client.batchAnnotateFilesCallable().futureCall(batchAnnotateFilesRequest);
        BatchAnnotateFilesResponse response = future.get();
        // Getting the first response
        AnnotateFileResponse annotateFileResponse = response.getResponses(0);
        // For full list of available annotations, see http://g.co/cloud/vision/docs
        TextAnnotation textAnnotation = annotateFileResponse.getResponses(0).getFullTextAnnotation();
        for (Page page : textAnnotation.getPagesList()) {
            String pageText = "";
            for (Block block : page.getBlocksList()) {
                String blockText = "";
                for (Paragraph para : block.getParagraphsList()) {
                    String paraText = "";
                    for (Word word : para.getWordsList()) {
                        String wordText = "";
                        for (Symbol symbol : word.getSymbolsList()) {
                            wordText = wordText + symbol.getText();
                            System.out.format("Symbol text: %s (Confidence: %f)\n", symbol.getText(), symbol.getConfidence());
                        }
                        System.out.format("Word text: %s (Confidence: %f)\n\n", wordText, word.getConfidence());
                        paraText = String.format("%s %s", paraText, wordText);
                    }
                    // Output Example using Paragraph:
                    System.out.println("\nParagraph: \n" + paraText);
                    System.out.format("Paragraph Confidence: %f\n", para.getConfidence());
                    blockText = blockText + paraText;
                }
                pageText = pageText + blockText;
            }
        }
        System.out.println("\nComplete annotation:");
        System.out.println(textAnnotation.getText());
    } catch (Exception e) {
        System.out.println("Error during detectPdfText: \n" + e.toString());
    }
}
Also used : GcsSource(com.google.cloud.vision.v1p4beta1.GcsSource) Word(com.google.cloud.vision.v1p4beta1.Word) BatchAnnotateFilesRequest(com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest) Symbol(com.google.cloud.vision.v1p4beta1.Symbol) ImageAnnotatorClient(com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient) ArrayList(java.util.ArrayList) Page(com.google.cloud.vision.v1p4beta1.Page) Feature(com.google.cloud.vision.v1p4beta1.Feature) Paragraph(com.google.cloud.vision.v1p4beta1.Paragraph) BatchAnnotateFilesResponse(com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse) AnnotateFileResponse(com.google.cloud.vision.v1p4beta1.AnnotateFileResponse) AnnotateFileRequest(com.google.cloud.vision.v1p4beta1.AnnotateFileRequest) Block(com.google.cloud.vision.v1p4beta1.Block) InputConfig(com.google.cloud.vision.v1p4beta1.InputConfig) TextAnnotation(com.google.cloud.vision.v1p4beta1.TextAnnotation)

Example 23 with InputConfig

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

the class DetectBatchAnnotateFiles method detectBatchAnnotateFiles.

// Performs document feature detection on a local PDF/TIFF/GIF file.
public static void detectBatchAnnotateFiles(String filePath) {
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        // Annotate the first two pages and the last one (max 5 pages)
        // First page starts at 1, and not 0. Last page is -1.
        List<Integer> pages = Arrays.asList(1, 2, -1);
        ByteString pdfBytes = ByteString.readFrom(new FileInputStream(filePath));
        Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build();
        // Other supported mime types : 'image/tiff' or 'image/gif'
        InputConfig inputConfig = InputConfig.newBuilder().setMimeType("application/pdf").setContent(pdfBytes).build();
        AnnotateFileRequest request = AnnotateFileRequest.newBuilder().addFeatures(feat).setInputConfig(inputConfig).addAllPages(pages).build();
        List<AnnotateFileRequest> requests = new ArrayList<>();
        requests.add(request);
        BatchAnnotateFilesRequest batchAnnotateFilesRequest = BatchAnnotateFilesRequest.newBuilder().addAllRequests(requests).build();
        ApiFuture<BatchAnnotateFilesResponse> future = client.batchAnnotateFilesCallable().futureCall(batchAnnotateFilesRequest);
        BatchAnnotateFilesResponse response = future.get();
        // Getting the first response
        AnnotateFileResponse annotateFileResponse = response.getResponses(0);
        // For full list of available annotations, see http://g.co/cloud/vision/docs
        TextAnnotation textAnnotation = annotateFileResponse.getResponses(0).getFullTextAnnotation();
        for (Page page : textAnnotation.getPagesList()) {
            String pageText = "";
            for (Block block : page.getBlocksList()) {
                String blockText = "";
                for (Paragraph para : block.getParagraphsList()) {
                    String paraText = "";
                    for (Word word : para.getWordsList()) {
                        String wordText = "";
                        for (Symbol symbol : word.getSymbolsList()) {
                            wordText = wordText + symbol.getText();
                            System.out.format("Symbol text: %s (Confidence: %f)\n", symbol.getText(), symbol.getConfidence());
                        }
                        System.out.format("Word text: %s (Confidence: %f)\n\n", wordText, word.getConfidence());
                        paraText = String.format("%s %s", paraText, wordText);
                    }
                    // Output Example using Paragraph:
                    System.out.println("\nParagraph: \n" + paraText);
                    System.out.format("Paragraph Confidence: %f\n", para.getConfidence());
                    blockText = blockText + paraText;
                }
                pageText = pageText + blockText;
            }
        }
        System.out.println("\nComplete annotation:");
        System.out.println(textAnnotation.getText());
    } catch (Exception e) {
        System.out.println("Error during detectPdfText: \n" + e.toString());
    }
}
Also used : Word(com.google.cloud.vision.v1p4beta1.Word) BatchAnnotateFilesRequest(com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest) ByteString(com.google.protobuf.ByteString) Symbol(com.google.cloud.vision.v1p4beta1.Symbol) ImageAnnotatorClient(com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient) ArrayList(java.util.ArrayList) Page(com.google.cloud.vision.v1p4beta1.Page) ByteString(com.google.protobuf.ByteString) Feature(com.google.cloud.vision.v1p4beta1.Feature) FileInputStream(java.io.FileInputStream) Paragraph(com.google.cloud.vision.v1p4beta1.Paragraph) BatchAnnotateFilesResponse(com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse) AnnotateFileResponse(com.google.cloud.vision.v1p4beta1.AnnotateFileResponse) AnnotateFileRequest(com.google.cloud.vision.v1p4beta1.AnnotateFileRequest) Block(com.google.cloud.vision.v1p4beta1.Block) InputConfig(com.google.cloud.vision.v1p4beta1.InputConfig) TextAnnotation(com.google.cloud.vision.v1p4beta1.TextAnnotation)

Example 24 with InputConfig

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

the class BatchAnnotateFiles method batchAnnotateFiles.

public static void batchAnnotateFiles(String filePath) throws IOException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) {
        // You can send multiple files to be annotated, this sample demonstrates how to do this with
        // one file. If you want to use multiple files, you have to create a `AnnotateImageRequest`
        // object for each file that you want annotated.
        // First read the files contents
        Path path = Paths.get(filePath);
        byte[] data = Files.readAllBytes(path);
        ByteString content = ByteString.copyFrom(data);
        // Specify the input config with the file's contents and its type.
        // Supported mime_type: application/pdf, image/tiff, image/gif
        // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#inputconfig
        InputConfig inputConfig = InputConfig.newBuilder().setMimeType("application/pdf").setContent(content).build();
        // Set the type of annotation you want to perform on the file
        // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type
        Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build();
        // Build the request object for that one file. Note: for additional file you have to create
        // additional `AnnotateFileRequest` objects and store them in a list to be used below.
        // Since we are sending a file of type `application/pdf`, we can use the `pages` field to
        // specify which pages to process. The service can process up to 5 pages per document file.
        // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.AnnotateFileRequest
        AnnotateFileRequest fileRequest = AnnotateFileRequest.newBuilder().setInputConfig(inputConfig).addFeatures(feature).addPages(// Process the first page
        1).addPages(// Process the second page
        2).addPages(// Process the last page
        -1).build();
        // Add each `AnnotateFileRequest` object to the batch request.
        BatchAnnotateFilesRequest request = BatchAnnotateFilesRequest.newBuilder().addRequests(fileRequest).build();
        // Make the synchronous batch request.
        BatchAnnotateFilesResponse response = imageAnnotatorClient.batchAnnotateFiles(request);
        // sample.
        for (AnnotateImageResponse imageResponse : response.getResponsesList().get(0).getResponsesList()) {
            System.out.format("Full text: %s%n", imageResponse.getFullTextAnnotation().getText());
            for (Page page : imageResponse.getFullTextAnnotation().getPagesList()) {
                for (Block block : page.getBlocksList()) {
                    System.out.format("%nBlock confidence: %s%n", block.getConfidence());
                    for (Paragraph par : block.getParagraphsList()) {
                        System.out.format("\tParagraph confidence: %s%n", par.getConfidence());
                        for (Word word : par.getWordsList()) {
                            System.out.format("\t\tWord confidence: %s%n", word.getConfidence());
                            for (Symbol symbol : word.getSymbolsList()) {
                                System.out.format("\t\t\tSymbol: %s, (confidence: %s)%n", symbol.getText(), symbol.getConfidence());
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : Path(java.nio.file.Path) Word(com.google.cloud.vision.v1.Word) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) ByteString(com.google.protobuf.ByteString) Symbol(com.google.cloud.vision.v1.Symbol) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) Page(com.google.cloud.vision.v1.Page) Feature(com.google.cloud.vision.v1.Feature) Paragraph(com.google.cloud.vision.v1.Paragraph) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) AnnotateFileRequest(com.google.cloud.vision.v1.AnnotateFileRequest) Block(com.google.cloud.vision.v1.Block) InputConfig(com.google.cloud.vision.v1.InputConfig)

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