Search in sources :

Example 1 with BatchAnnotateFilesRequest

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest in project java-vision by googleapis.

the class BatchAnnotateFilesGcs method batchAnnotateFilesGcs.

public static void batchAnnotateFilesGcs(String gcsUri) 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 specify where the vision api can find the image
        GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsUri).build();
        // Specify the input config with the file's uri 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").setGcsSource(gcsSource).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 : GcsSource(com.google.cloud.vision.v1.GcsSource) Word(com.google.cloud.vision.v1.Word) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) 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)

Example 2 with BatchAnnotateFilesRequest

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest 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)

Example 3 with BatchAnnotateFilesRequest

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest in project spring-cloud-gcp by GoogleCloudPlatform.

the class CloudVisionTemplateTests method testAddInputConfig_extractText.

@Test
public void testAddInputConfig_extractText() throws IOException {
    when(this.imageAnnotatorClient.batchAnnotateFiles(any(BatchAnnotateFilesRequest.class))).thenReturn(DEFAULT_FILES_API_RESPONSE);
    this.cloudVisionTemplate.extractTextFromPdf(FAKE_PDF);
    BatchAnnotateFilesRequest expectedRequest = BatchAnnotateFilesRequest.newBuilder().addRequests(AnnotateFileRequest.newBuilder().addFeatures(Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION)).setInputConfig(InputConfig.newBuilder().setMimeType("application/pdf").setContent(ByteString.readFrom(FAKE_PDF.getInputStream())).build()).build()).build();
    verify(this.imageAnnotatorClient, times(1)).batchAnnotateFiles(expectedRequest);
}
Also used : BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) Test(org.junit.Test)

Example 4 with BatchAnnotateFilesRequest

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest 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 5 with BatchAnnotateFilesRequest

use of com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest 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)

Aggregations

BatchAnnotateFilesRequest (com.google.cloud.vision.v1.BatchAnnotateFilesRequest)4 AnnotateFileRequest (com.google.cloud.vision.v1.AnnotateFileRequest)3 AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)3 BatchAnnotateFilesResponse (com.google.cloud.vision.v1.BatchAnnotateFilesResponse)3 Feature (com.google.cloud.vision.v1.Feature)3 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)3 InputConfig (com.google.cloud.vision.v1.InputConfig)3 ByteString (com.google.protobuf.ByteString)3 Block (com.google.cloud.vision.v1.Block)2 Page (com.google.cloud.vision.v1.Page)2 Paragraph (com.google.cloud.vision.v1.Paragraph)2 Symbol (com.google.cloud.vision.v1.Symbol)2 Word (com.google.cloud.vision.v1.Word)2 AnnotateFileRequest (com.google.cloud.vision.v1p4beta1.AnnotateFileRequest)2 AnnotateFileResponse (com.google.cloud.vision.v1p4beta1.AnnotateFileResponse)2 BatchAnnotateFilesRequest (com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest)2 BatchAnnotateFilesResponse (com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse)2 Block (com.google.cloud.vision.v1p4beta1.Block)2 Feature (com.google.cloud.vision.v1p4beta1.Feature)2 ImageAnnotatorClient (com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient)2