Search in sources :

Example 6 with Result

use of com.google.cloud.vision.v1.ProductSearchResults.Result in project java-vision by googleapis.

the class VisionController method extractLabels.

// [END spring_vision_autowire]
/**
 * This method downloads an image from a URL and sends its contents to the Vision API for label
 * detection.
 *
 * @param imageUrl the URL of the image
 * @param map the model map to use
 * @return a string with the list of labels and percentage of certainty
 */
@GetMapping("/extractLabels")
public ModelAndView extractLabels(String imageUrl, ModelMap map) {
    // [START spring_vision_image_labelling]
    AnnotateImageResponse response = this.cloudVisionTemplate.analyzeImage(this.resourceLoader.getResource(imageUrl), Type.LABEL_DETECTION);
    Map<String, Float> imageLabels = response.getLabelAnnotationsList().stream().collect(Collectors.toMap(EntityAnnotation::getDescription, EntityAnnotation::getScore, (u, v) -> {
        throw new IllegalStateException(String.format("Duplicate key %s", u));
    }, LinkedHashMap::new));
    // [END spring_vision_image_labelling]
    map.addAttribute("annotations", imageLabels);
    map.addAttribute("imageUrl", imageUrl);
    return new ModelAndView("result", map);
}
Also used : ResourceLoader(org.springframework.core.io.ResourceLoader) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) Type(com.google.cloud.vision.v1.Feature.Type) Autowired(org.springframework.beans.factory.annotation.Autowired) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) ModelMap(org.springframework.ui.ModelMap) LinkedHashMap(java.util.LinkedHashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) Map(java.util.Map) GetMapping(org.springframework.web.bind.annotation.GetMapping) EntityAnnotation(com.google.cloud.vision.v1.EntityAnnotation) CloudVisionTemplate(org.springframework.cloud.gcp.vision.CloudVisionTemplate) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ModelAndView(org.springframework.web.servlet.ModelAndView) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 7 with Result

use of com.google.cloud.vision.v1.ProductSearchResults.Result in project spring-cloud-gcp by GoogleCloudPlatform.

the class CloudVisionTemplate method extractTextFromImage.

/**
 * Extract the text out of an image and return the result as a String.
 *
 * @param imageResource the image one wishes to analyze
 * @param imageContext the image context to customize the text extraction request
 * @return the text extracted from the image aggregated to a String
 * @throws CloudVisionException if the image could not be read or if text extraction failed
 */
public String extractTextFromImage(Resource imageResource, ImageContext imageContext) {
    AnnotateImageResponse response = analyzeImage(imageResource, imageContext, Type.TEXT_DETECTION);
    String result = response.getFullTextAnnotation().getText();
    if (result.isEmpty() && response.getError().getCode() != Code.OK.getNumber()) {
        throw new CloudVisionException(response.getError().getMessage());
    }
    return result;
}
Also used : AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) ByteString(com.google.protobuf.ByteString)

Example 8 with Result

use of com.google.cloud.vision.v1.ProductSearchResults.Result in project spring-cloud-gcp by GoogleCloudPlatform.

the class DocumentOcrTemplate method runOcrForDocument.

/**
 * Runs OCR processing for a specified {@code document} and generates OCR output files under the
 * path specified by {@code outputFilePathPrefix}.
 *
 * <p>For example, if you specify an {@code outputFilePathPrefix} of
 * "gs://bucket_name/ocr_results/myDoc_", all the output files of OCR processing will be saved
 * under prefix, such as:
 *
 * <ul>
 *   <li>gs://bucket_name/ocr_results/myDoc_output-1-to-5.json
 *   <li>gs://bucket_name/ocr_results/myDoc_output-6-to-10.json
 *   <li>gs://bucket_name/ocr_results/myDoc_output-11-to-15.json
 * </ul>
 *
 * <p>Note: OCR processing operations may take several minutes to complete, so it may not be
 * advisable to block on the completion of the operation. One may use the returned {@link
 * ListenableFuture} to register callbacks or track the status of the operation.
 *
 * @param document The {@link GoogleStorageLocation} of the document to run OCR processing
 * @param outputFilePathPrefix The {@link GoogleStorageLocation} of a file, folder, or a bucket
 *     describing the path for which all output files shall be saved under
 * @return A {@link ListenableFuture} allowing you to register callbacks or wait for the
 *     completion of the operation.
 */
public ListenableFuture<DocumentOcrResultSet> runOcrForDocument(GoogleStorageLocation document, GoogleStorageLocation outputFilePathPrefix) {
    Assert.isTrue(document.isFile(), "Provided document location is not a valid file location: " + document);
    GcsSource gcsSource = GcsSource.newBuilder().setUri(document.uriString()).build();
    String contentType = extractContentType(document);
    InputConfig inputConfig = InputConfig.newBuilder().setMimeType(contentType).setGcsSource(gcsSource).build();
    GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(outputFilePathPrefix.uriString()).build();
    OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).setBatchSize(this.jsonOutputBatchSize).build();
    AsyncAnnotateFileRequest request = AsyncAnnotateFileRequest.newBuilder().addFeatures(DOCUMENT_OCR_FEATURE).setInputConfig(inputConfig).setOutputConfig(outputConfig).build();
    OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> result = imageAnnotatorClient.asyncBatchAnnotateFilesAsync(Collections.singletonList(request));
    return extractOcrResultFuture(result);
}
Also used : GcsSource(com.google.cloud.vision.v1.GcsSource) OutputConfig(com.google.cloud.vision.v1.OutputConfig) AsyncBatchAnnotateFilesResponse(com.google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse) InputConfig(com.google.cloud.vision.v1.InputConfig) AsyncAnnotateFileRequest(com.google.cloud.vision.v1.AsyncAnnotateFileRequest) GcsDestination(com.google.cloud.vision.v1.GcsDestination) OperationMetadata(com.google.cloud.vision.v1.OperationMetadata)

Example 9 with Result

use of com.google.cloud.vision.v1.ProductSearchResults.Result in project spring-cloud-gcp by GoogleCloudPlatform.

the class DocumentOcrTemplateIntegrationTests method testDocumentOcrTemplate.

@Test
void testDocumentOcrTemplate() throws ExecutionException, InterruptedException, InvalidProtocolBufferException, TimeoutException {
    GoogleStorageLocation document = GoogleStorageLocation.forFile("vision-integration-test-bucket", "test.pdf");
    GoogleStorageLocation outputLocationPrefix = GoogleStorageLocation.forFile("vision-integration-test-bucket", "it_output/test-");
    ListenableFuture<DocumentOcrResultSet> result = this.documentOcrTemplate.runOcrForDocument(document, outputLocationPrefix);
    DocumentOcrResultSet ocrPages = result.get(5, TimeUnit.MINUTES);
    String page1Text = ocrPages.getPage(1).getText();
    assertThat(page1Text).contains("Hello World. Is mayonnaise an instrument?");
    String page2Text = ocrPages.getPage(2).getText();
    assertThat(page2Text).contains("Page 2 stuff");
    ArrayList<String> pageContent = new ArrayList<>();
    Iterator<TextAnnotation> pageIterator = ocrPages.getAllPages();
    while (pageIterator.hasNext()) {
        pageContent.add(pageIterator.next().getText());
    }
    assertThat(pageContent).containsExactly("Hello World. Is mayonnaise an instrument?\n", "Page 2 stuff\n", "Page 3 stuff\n", "Page 4 stuff\n");
}
Also used : DocumentOcrResultSet(com.google.cloud.spring.vision.DocumentOcrResultSet) ArrayList(java.util.ArrayList) GoogleStorageLocation(com.google.cloud.spring.storage.GoogleStorageLocation) TextAnnotation(com.google.cloud.vision.v1.TextAnnotation) Test(org.junit.jupiter.api.Test)

Example 10 with Result

use of com.google.cloud.vision.v1.ProductSearchResults.Result in project spring-cloud-gcp by spring-cloud.

the class DocumentOcrTemplateIntegrationTests method testDocumentOcrTemplate.

@Test
public void testDocumentOcrTemplate() throws ExecutionException, InterruptedException, InvalidProtocolBufferException, TimeoutException {
    GoogleStorageLocation document = GoogleStorageLocation.forFile("vision-integration-test-bucket", "test.pdf");
    GoogleStorageLocation outputLocationPrefix = GoogleStorageLocation.forFile("vision-integration-test-bucket", "it_output/test-");
    ListenableFuture<DocumentOcrResultSet> result = this.documentOcrTemplate.runOcrForDocument(document, outputLocationPrefix);
    DocumentOcrResultSet ocrPages = result.get(5, TimeUnit.MINUTES);
    String page1Text = ocrPages.getPage(1).getText();
    assertThat(page1Text).contains("Hello World. Is mayonnaise an instrument?");
    String page2Text = ocrPages.getPage(2).getText();
    assertThat(page2Text).contains("Page 2 stuff");
    ArrayList<String> pageContent = new ArrayList<>();
    Iterator<TextAnnotation> pageIterator = ocrPages.getAllPages();
    while (pageIterator.hasNext()) {
        pageContent.add(pageIterator.next().getText());
    }
    assertThat(pageContent).containsExactly("Hello World. Is mayonnaise an instrument?\n", "Page 2 stuff\n", "Page 3 stuff\n", "Page 4 stuff\n");
}
Also used : DocumentOcrResultSet(org.springframework.cloud.gcp.vision.DocumentOcrResultSet) ArrayList(java.util.ArrayList) GoogleStorageLocation(org.springframework.cloud.gcp.storage.GoogleStorageLocation) TextAnnotation(com.google.cloud.vision.v1.TextAnnotation) Test(org.junit.Test)

Aggregations

AnnotateImageResponse (com.google.cloud.vision.v1.AnnotateImageResponse)8 ByteString (com.google.protobuf.ByteString)6 List (java.util.List)6 AsyncBatchAnnotateFilesResponse (com.google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse)5 EntityAnnotation (com.google.cloud.vision.v1.EntityAnnotation)5 Feature (com.google.cloud.vision.v1.Feature)5 ImageAnnotatorClient (com.google.cloud.vision.v1.ImageAnnotatorClient)5 Collectors (java.util.stream.Collectors)5 ModelAndView (org.springframework.web.servlet.ModelAndView)5 AnnotateImageRequest (com.google.cloud.vision.v1.AnnotateImageRequest)4 BatchAnnotateImagesResponse (com.google.cloud.vision.v1.BatchAnnotateImagesResponse)4 Image (com.google.cloud.vision.v1.Image)4 InputConfig (com.google.cloud.vision.v1.InputConfig)4 TextAnnotation (com.google.cloud.vision.v1.TextAnnotation)4 AsyncAnnotateFileRequest (com.google.cloud.vision.v1.AsyncAnnotateFileRequest)3 GcsDestination (com.google.cloud.vision.v1.GcsDestination)3 GcsSource (com.google.cloud.vision.v1.GcsSource)3 ImageContext (com.google.cloud.vision.v1.ImageContext)3 OperationMetadata (com.google.cloud.vision.v1.OperationMetadata)3 ArrayList (java.util.ArrayList)3