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);
}
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;
}
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);
}
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");
}
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");
}
Aggregations