From 3d107e5c8d886b0959d0579b35ce03d9121c7fb1 Mon Sep 17 00:00:00 2001 From: Alix Hamilton Date: Wed, 5 Sep 2018 17:27:35 -0700 Subject: [PATCH 1/2] remove unused vision beta samples --- vision/beta/cloud-client/README.md | 67 - .../main/java/com/example/vision/Detect.java | 1350 +---------------- .../java/com/example/vision/DetectIT.java | 325 ---- 3 files changed, 2 insertions(+), 1740 deletions(-) diff --git a/vision/beta/cloud-client/README.md b/vision/beta/cloud-client/README.md index c69ee463e25..e8921cbdcee 100644 --- a/vision/beta/cloud-client/README.md +++ b/vision/beta/cloud-client/README.md @@ -28,73 +28,6 @@ You can then run `Detect` via: mvn exec:java -DDetect -Dexec.args="arg1 'arg 2' arg3" ``` -### Analyze an image - -``` -export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-project-credentials.json -``` - -#### Faces -``` -mvn exec:java -DDetect -Dexec.args="faces ./resources/face_no_surprise.jpg" -``` - -#### Labels -``` -mvn exec:java -DDetect -Dexec.args="labels ./resources/wakeupcat.jpg" -``` - -#### Landmarks -``` -mvn exec:java -DDetect -Dexec.args="landmarks ./resources/landmark.jpg" -``` - -#### Logos -``` -mvn exec:java -DDetect -Dexec.args="logos ./resources/logos.png" -``` - -#### Text -``` -mvn exec:java -DDetect -Dexec.args="text ./resources/text.jpg" -``` - -#### Safe Search -``` -mvn exec:java -DDetect -Dexec.args="safe-search ./resources/wakeupcat.jpg" -``` - -#### Properties -``` -mvn exec:java -DDetect -Dexec.args="properties ./resources/city.jpg" -``` - -#### Web -``` -mvn exec:java -DDetect -Dexec.args="web ./resources/landmark.jpg" -``` - -#### Web Entities -``` -mvn exec:java -DDetect -Dexec.args="web-entities ./resources/landmark.jpg" -``` - -#### Web Entities Include Geo -``` -mvn exec:java -DDetect -Dexec.args="web-entities-include-geo ./resources/landmark.jpg" -``` - -#### Crop -``` -mvn exec:java -DDetect -Dexec.args="crop ./resources/landmark.jpg" -``` - -#### OCR -``` -mvn exec:java -DDetect -Dexec.args="ocr gs://java-docs-samples-testing/vision/HodgeConj.pdf \ - gs:///" -``` - #### Localized Objects ``` mvn exec:java -DDetect -Dexec.args="object-localization ./resources/puppies.jpg" diff --git a/vision/beta/cloud-client/src/main/java/com/example/vision/Detect.java b/vision/beta/cloud-client/src/main/java/com/example/vision/Detect.java index cbae0f2b80b..ed449981a59 100644 --- a/vision/beta/cloud-client/src/main/java/com/example/vision/Detect.java +++ b/vision/beta/cloud-client/src/main/java/com/example/vision/Detect.java @@ -16,64 +16,29 @@ package com.example.vision; -import com.google.api.gax.longrunning.OperationFuture; -import com.google.cloud.storage.Blob; -import com.google.cloud.storage.Bucket; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.Storage.BlobListOption; -import com.google.cloud.storage.StorageOptions; -import com.google.cloud.vision.v1p3beta1.AnnotateFileResponse; -import com.google.cloud.vision.v1p3beta1.AnnotateFileResponse.Builder; import com.google.cloud.vision.v1p3beta1.AnnotateImageRequest; import com.google.cloud.vision.v1p3beta1.AnnotateImageResponse; -import com.google.cloud.vision.v1p3beta1.AsyncAnnotateFileRequest; -import com.google.cloud.vision.v1p3beta1.AsyncAnnotateFileResponse; -import com.google.cloud.vision.v1p3beta1.AsyncBatchAnnotateFilesResponse; import com.google.cloud.vision.v1p3beta1.BatchAnnotateImagesResponse; import com.google.cloud.vision.v1p3beta1.Block; -import com.google.cloud.vision.v1p3beta1.ColorInfo; -import com.google.cloud.vision.v1p3beta1.CropHint; -import com.google.cloud.vision.v1p3beta1.CropHintsAnnotation; -import com.google.cloud.vision.v1p3beta1.DominantColorsAnnotation; -import com.google.cloud.vision.v1p3beta1.EntityAnnotation; -import com.google.cloud.vision.v1p3beta1.FaceAnnotation; import com.google.cloud.vision.v1p3beta1.Feature; import com.google.cloud.vision.v1p3beta1.Feature.Type; -import com.google.cloud.vision.v1p3beta1.GcsDestination; -import com.google.cloud.vision.v1p3beta1.GcsSource; import com.google.cloud.vision.v1p3beta1.Image; import com.google.cloud.vision.v1p3beta1.ImageAnnotatorClient; import com.google.cloud.vision.v1p3beta1.ImageContext; import com.google.cloud.vision.v1p3beta1.ImageSource; -import com.google.cloud.vision.v1p3beta1.InputConfig; import com.google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation; -import com.google.cloud.vision.v1p3beta1.LocationInfo; -import com.google.cloud.vision.v1p3beta1.OperationMetadata; -import com.google.cloud.vision.v1p3beta1.OutputConfig; import com.google.cloud.vision.v1p3beta1.Page; import com.google.cloud.vision.v1p3beta1.Paragraph; -import com.google.cloud.vision.v1p3beta1.SafeSearchAnnotation; import com.google.cloud.vision.v1p3beta1.Symbol; import com.google.cloud.vision.v1p3beta1.TextAnnotation; -import com.google.cloud.vision.v1p3beta1.WebDetection; -import com.google.cloud.vision.v1p3beta1.WebDetection.WebEntity; -import com.google.cloud.vision.v1p3beta1.WebDetection.WebImage; -import com.google.cloud.vision.v1p3beta1.WebDetection.WebLabel; -import com.google.cloud.vision.v1p3beta1.WebDetection.WebPage; -import com.google.cloud.vision.v1p3beta1.WebDetectionParams; import com.google.cloud.vision.v1p3beta1.Word; import com.google.protobuf.ByteString; -import com.google.protobuf.util.JsonFormat; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; public class Detect { @@ -101,9 +66,7 @@ public static void argsHelper(String[] args, PrintStream out) throws Exception, + "\tmvn exec:java -DDetect -Dexec.args=\"ocr \"" + "\n" + "Commands:\n" - + "\tfaces | labels | landmarks | logos | text | safe-search | properties" - + "| web | web-entities | web-entities-include-geo | crop | ocr\n" - + "| object-localization| handwritten-ocr\n" + + "\tobject-localization| handwritten-ocr\n" + "Path:\n\tA file path (ex: ./resources/wakeupcat.jpg) or a URI for a Cloud Storage " + "resource (gs://...)\n" + "Path to File:\n\tA path to the remote file on Cloud Storage (gs://...)\n" @@ -114,84 +77,7 @@ public static void argsHelper(String[] args, PrintStream out) throws Exception, String command = args[0]; String path = args.length > 1 ? args[1] : ""; - if (command.equals("faces")) { - if (path.startsWith("gs://")) { - detectFacesGcs(path, out); - } else { - detectFaces(path, out); - } - } else if (command.equals("labels")) { - if (path.startsWith("gs://")) { - detectLabelsGcs(path, out); - } else { - detectLabels(path, out); - } - } else if (command.equals("landmarks")) { - if (path.startsWith("http")) { - detectLandmarksUrl(path, out); - } else if (path.startsWith("gs://")) { - detectLandmarksGcs(path, out); - } else { - detectLandmarks(path, out); - } - } else if (command.equals("logos")) { - if (path.startsWith("gs://")) { - detectLogosGcs(path, out); - } else { - detectLogos(path, out); - } - } else if (command.equals("text")) { - if (path.startsWith("gs://")) { - detectTextGcs(path, out); - } else { - detectText(path, out); - } - } else if (command.equals("properties")) { - if (path.startsWith("gs://")) { - detectPropertiesGcs(path, out); - } else { - detectProperties(path, out); - } - } else if (command.equals("safe-search")) { - if (path.startsWith("gs://")) { - detectSafeSearchGcs(path, out); - } else { - detectSafeSearch(path, out); - } - } else if (command.equals("web")) { - if (path.startsWith("gs://")) { - detectWebDetectionsGcs(path, out); - } else { - detectWebDetections(path, out); - } - } else if (command.equals("web-entities")) { - if (path.startsWith("gs://")) { - detectWebEntitiesGcs(path, out); - } else { - detectWebEntities(path, out); - } - } else if (command.equals("web-entities-include-geo")) { - if (path.startsWith("gs://")) { - detectWebEntitiesIncludeGeoResultsGcs(path, out); - } else { - detectWebEntitiesIncludeGeoResults(path, out); - } - } else if (command.equals("crop")) { - if (path.startsWith("gs://")) { - detectCropHintsGcs(path, out); - } else { - detectCropHints(path, out); - } - } else if (command.equals("fulltext")) { - if (path.startsWith("gs://")) { - detectDocumentTextGcs(path, out); - } else { - detectDocumentText(path, out); - } - } else if (command.equals("ocr")) { - String destPath = args.length > 2 ? args[2] : ""; - detectDocumentsGcs(path, destPath); - } else if (command.equals("object-localization")) { + if (command.equals("object-localization")) { if (path.startsWith("gs://")) { detectLocalizedObjectsGcs(path, out); } else { @@ -206,1238 +92,6 @@ public static void argsHelper(String[] args, PrintStream out) throws Exception, } } - /** - * Detects faces in the specified local image. - * - * @param filePath The path to the file to perform face detection on. - * @param out A {@link PrintStream} to write detected features to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectFaces(String filePath, PrintStream out) throws Exception, IOException { - List requests = new ArrayList<>(); - - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.FACE_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (FaceAnnotation annotation : res.getFaceAnnotationsList()) { - out.printf( - "anger: %s\njoy: %s\nsurprise: %s\nposition: %s", - annotation.getAngerLikelihood(), - annotation.getJoyLikelihood(), - annotation.getSurpriseLikelihood(), - annotation.getBoundingPoly()); - } - } - } - } - - /** - * Detects faces in the specified remote image on Google Cloud Storage. - * - * @param gcsPath The path to the remote file on Google Cloud Storage to perform face detection - * on. - * @param out A {@link PrintStream} to write detected features to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectFacesGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.FACE_DETECTION).build(); - - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (FaceAnnotation annotation : res.getFaceAnnotationsList()) { - out.printf( - "anger: %s\njoy: %s\nsurprise: %s\nposition: %s", - annotation.getAngerLikelihood(), - annotation.getJoyLikelihood(), - annotation.getSurpriseLikelihood(), - annotation.getBoundingPoly()); - } - } - } - } - - /** - * Detects labels in the specified local image. - * - * @param filePath The path to the file to perform label detection on. - * @param out A {@link PrintStream} to write detected labels to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectLabels(String filePath, PrintStream out) throws Exception, IOException { - List requests = new ArrayList<>(); - - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { - annotation.getAllFields().forEach((k, v) -> out.printf("%s : %s\n", k, v.toString())); - } - } - } - } - - /** - * Detects labels in the specified remote image on Google Cloud Storage. - * - * @param gcsPath The path to the remote file on Google Cloud Storage to perform label detection - * on. - * @param out A {@link PrintStream} to write detected features to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectLabelsGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { - annotation.getAllFields().forEach((k, v) -> - out.printf("%s : %s\n", k, v.toString())); - } - } - } - } - - /** - * Detects landmarks in the specified local image. - * - * @param filePath The path to the file to perform landmark detection on. - * @param out A {@link PrintStream} to write detected landmarks to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectLandmarks(String filePath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.LANDMARK_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLandmarkAnnotationsList()) { - LocationInfo info = annotation.getLocationsList().listIterator().next(); - out.printf("Landmark: %s\n %s\n", annotation.getDescription(), info.getLatLng()); - } - } - } - } - - /** - * Detects landmarks in the specified URI. - * - * @param uri The path to the file to perform landmark detection on. - * @param out A {@link PrintStream} to write detected landmarks to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectLandmarksUrl(String uri, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setImageUri(uri).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.LANDMARK_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLandmarkAnnotationsList()) { - LocationInfo info = annotation.getLocationsList().listIterator().next(); - out.printf("Landmark: %s\n %s\n", annotation.getDescription(), info.getLatLng()); - } - } - } - } - - /** - * Detects landmarks in the specified remote imageon Google Cloud Storage. - * - * @param gcsPath The path to the remote file on Google Cloud Storage to perform landmark - * detection on. - * @param out A {@link PrintStream} to write detected landmarks to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectLandmarksGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.LANDMARK_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLandmarkAnnotationsList()) { - LocationInfo info = annotation.getLocationsList().listIterator().next(); - out.printf("Landmark: %s\n %s\n", annotation.getDescription(), info.getLatLng()); - } - } - } - } - - /** - * Detects logos in the specified local image. - * - * @param filePath The path to the local file to perform logo detection on. - * @param out A {@link PrintStream} to write detected logos to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectLogos(String filePath, PrintStream out) throws Exception, IOException { - List requests = new ArrayList<>(); - - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.LOGO_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLogoAnnotationsList()) { - out.println(annotation.getDescription()); - } - } - } - } - - /** - * Detects logos in the specified remote image on Google Cloud Storage. - * - * @param gcsPath The path to the remote file on Google Cloud Storage to perform logo detection - * on. - * @param out A {@link PrintStream} to write detected logos to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectLogosGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.LOGO_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getLogoAnnotationsList()) { - out.println(annotation.getDescription()); - } - } - } - } - - /** - * Detects text in the specified image. - * - * @param filePath The path to the file to detect text in. - * @param out A {@link PrintStream} to write the detected text to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectText(String filePath, PrintStream out) throws Exception, IOException { - List requests = new ArrayList<>(); - - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.TEXT_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getTextAnnotationsList()) { - out.printf("Text: %s\n", annotation.getDescription()); - out.printf("Position : %s\n", annotation.getBoundingPoly()); - } - } - } - } - - /** - * Detects text in the specified remote image on Google Cloud Storage. - * - * @param gcsPath The path to the remote file on Google Cloud Storage to detect text in. - * @param out A {@link PrintStream} to write the detected text to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectTextGcs(String gcsPath, PrintStream out) throws Exception, IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.TEXT_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - for (EntityAnnotation annotation : res.getTextAnnotationsList()) { - out.printf("Text: %s\n", annotation.getDescription()); - out.printf("Position : %s\n", annotation.getBoundingPoly()); - } - } - } - } - - /** - * Detects image properties such as color frequency from the specified local image. - * - * @param filePath The path to the file to detect properties. - * @param out A {@link PrintStream} to write - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectProperties(String filePath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.IMAGE_PROPERTIES).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors(); - for (ColorInfo color : colors.getColorsList()) { - out.printf( - "fraction: %f\nr: %f, g: %f, b: %f\n", - color.getPixelFraction(), - color.getColor().getRed(), - color.getColor().getGreen(), - color.getColor().getBlue()); - } - } - } - } - - /** - * Detects image properties such as color frequency from the specified remote image on Google - * Cloud Storage. - * - * @param gcsPath The path to the remote file on Google Cloud Storage to detect properties on. - * @param out A {@link PrintStream} to write - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectPropertiesGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.IMAGE_PROPERTIES).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors(); - for (ColorInfo color : colors.getColorsList()) { - out.printf( - "fraction: %f\nr: %f, g: %f, b: %f\n", - color.getPixelFraction(), - color.getColor().getRed(), - color.getColor().getGreen(), - color.getColor().getBlue()); - } - } - } - } - - // [START vision_detect_safe_search] - /** - * Detects whether the specified image has features you would want to moderate. - * - * @param filePath The path to the local file used for safe search detection. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectSafeSearch(String filePath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); - out.printf( - "adult: %s\nmedical: %s\nspoofed: %s\nviolence: %s\nracy: %s\n", - annotation.getAdult(), - annotation.getMedical(), - annotation.getSpoof(), - annotation.getViolence(), - annotation.getRacy()); - } - } - } - // [END vision_detect_safe_search] - - // [START vision_detect_safe_search_uri] - /** - * Detects whether the specified image on Google Cloud Storage has features you would want - * to moderate. - * - * @param gcsPath The path to the remote file on Google Cloud Storage to detect safe-search on. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectSafeSearchGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); - out.printf( - "adult: %s\nmedical: %s\nspoofed: %s\nviolence: %s\nracy: %s\n", - annotation.getAdult(), - annotation.getMedical(), - annotation.getSpoof(), - annotation.getViolence(), - annotation.getRacy()); - } - } - } - // [END vision_detect_safe_search_uri] - - // [START vision_detect_web] - /** - * Finds references to the specified image on the web. - * - * @param filePath The path to the local file used for web annotation detection. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectWebDetections(String filePath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.WEB_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // Search the web for usages of the image. You could use these signals later - // for user input moderation or linking external references. - // For a full list of available annotations, see http://g.co/cloud/vision/docs - WebDetection annotation = res.getWebDetection(); - out.println("Entity:Id:Score"); - out.println("==============="); - for (WebEntity entity : annotation.getWebEntitiesList()) { - out.println(entity.getDescription() + " : " + entity.getEntityId() + " : " - + entity.getScore()); - } - for (WebLabel label : annotation.getBestGuessLabelsList()) { - out.format("\nBest guess label: %s", label.getLabel()); - } - out.println("\nPages with matching images: Score\n=="); - for (WebPage page : annotation.getPagesWithMatchingImagesList()) { - out.println(page.getUrl() + " : " + page.getScore()); - } - out.println("\nPages with partially matching images: Score\n=="); - for (WebImage image : annotation.getPartialMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); - } - out.println("\nPages with fully matching images: Score\n=="); - for (WebImage image : annotation.getFullMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); - } - out.println("\nPages with visually similar images: Score\n=="); - for (WebImage image : annotation.getVisuallySimilarImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); - } - } - } - } - // [END vision_detect_web] - - // [START vision_detect_web_uri] - /** - * Detects whether the remote image on Google Cloud Storage has features you would want to - * moderate. - * - * @param gcsPath The path to the remote on Google Cloud Storage file to detect web annotations. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.WEB_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // Search the web for usages of the image. You could use these signals later - // for user input moderation or linking external references. - // For a full list of available annotations, see http://g.co/cloud/vision/docs - WebDetection annotation = res.getWebDetection(); - out.println("Entity:Id:Score"); - out.println("==============="); - for (WebEntity entity : annotation.getWebEntitiesList()) { - out.println(entity.getDescription() + " : " + entity.getEntityId() + " : " - + entity.getScore()); - } - for (WebLabel label : annotation.getBestGuessLabelsList()) { - out.format("\nBest guess label: %s", label.getLabel()); - } - out.println("\nPages with matching images: Score\n=="); - for (WebPage page : annotation.getPagesWithMatchingImagesList()) { - out.println(page.getUrl() + " : " + page.getScore()); - } - out.println("\nPages with partially matching images: Score\n=="); - for (WebImage image : annotation.getPartialMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); - } - out.println("\nPages with fully matching images: Score\n=="); - for (WebImage image : annotation.getFullMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); - } - out.println("\nPages with visually similar images: Score\n=="); - for (WebImage image : annotation.getVisuallySimilarImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); - } - } - } - } - // [END vision_detect_web_uri] - - /** - * Find web entities given a local image. - * @param filePath The path of the image to detect. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectWebEntities(String filePath, PrintStream out) throws Exception, - IOException { - // Instantiates a client - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - // Read in the local image - ByteString contents = ByteString.readFrom(new FileInputStream(filePath)); - - // Build the image - Image image = Image.newBuilder().setContent(contents).build(); - - // Create the request with the image and the specified feature: web detection - AnnotateImageRequest request = AnnotateImageRequest.newBuilder() - .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION)) - .setImage(image) - .build(); - - // Perform the request - BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); - - // Display the results - response.getResponsesList().stream() - .forEach(r -> r.getWebDetection().getWebEntitiesList().stream() - .forEach(entity -> { - out.format("Description: %s\n", entity.getDescription()); - out.format("Score: %f\n", entity.getScore()); - })); - } - } - - /** - * Find web entities given the remote image on Google Cloud Storage. - * @param gcsPath The path to the remote file on Google Cloud Storage to detect web entities. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectWebEntitiesGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - // Instantiates a client - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - // Set the image source to the given gs uri - ImageSource imageSource = ImageSource.newBuilder() - .setGcsImageUri(gcsPath) - .build(); - // Build the image - Image image = Image.newBuilder().setSource(imageSource).build(); - - // Create the request with the image and the specified feature: web detection - AnnotateImageRequest request = AnnotateImageRequest.newBuilder() - .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION)) - .setImage(image) - .build(); - - // Perform the request - BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); - - // Display the results - response.getResponsesList().stream() - .forEach(r -> r.getWebDetection().getWebEntitiesList().stream() - .forEach(entity -> { - System.out.format("Description: %s\n", entity.getDescription()); - System.out.format("Score: %f\n", entity.getScore()); - })); - } - } - - // [START vision_web_entities_include_geo_results] - /** - * Find web entities given a local image. - * @param filePath The path of the image to detect. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStream out) throws - Exception, IOException { - // Instantiates a client - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - // Read in the local image - ByteString contents = ByteString.readFrom(new FileInputStream(filePath)); - - // Build the image - Image image = Image.newBuilder().setContent(contents).build(); - - // Enable `IncludeGeoResults` - WebDetectionParams webDetectionParams = WebDetectionParams.newBuilder() - .setIncludeGeoResults(true) - .build(); - - // Set the parameters for the image - ImageContext imageContext = ImageContext.newBuilder() - .setWebDetectionParams(webDetectionParams) - .build(); - - // Create the request with the image, imageContext, and the specified feature: web detection - AnnotateImageRequest request = AnnotateImageRequest.newBuilder() - .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION)) - .setImage(image) - .setImageContext(imageContext) - .build(); - - // Perform the request - BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); - - // Display the results - response.getResponsesList().stream() - .forEach(r -> r.getWebDetection().getWebEntitiesList().stream() - .forEach(entity -> { - out.format("Description: %s\n", entity.getDescription()); - out.format("Score: %f\n", entity.getScore()); - })); - } - } - // [END vision_web_entities_include_geo_results] - - // [START vision_web_entities_include_geo_results_uri] - /** - * Find web entities given the remote image on Google Cloud Storage. - * @param gcsPath The path to the remote file on Google Cloud Storage to detect web entities with - * geo results. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath, PrintStream out) throws - Exception, IOException { - // Instantiates a client - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - // Set the image source to the given gs uri - ImageSource imageSource = ImageSource.newBuilder() - .setGcsImageUri(gcsPath) - .build(); - // Build the image - Image image = Image.newBuilder().setSource(imageSource).build(); - - // Enable `IncludeGeoResults` - WebDetectionParams webDetectionParams = WebDetectionParams.newBuilder() - .setIncludeGeoResults(true) - .build(); - - // Set the parameters for the image - ImageContext imageContext = ImageContext.newBuilder() - .setWebDetectionParams(webDetectionParams) - .build(); - - // Create the request with the image, imageContext, and the specified feature: web detection - AnnotateImageRequest request = AnnotateImageRequest.newBuilder() - .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION)) - .setImage(image) - .setImageContext(imageContext) - .build(); - - // Perform the request - BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); - - // Display the results - response.getResponsesList().stream() - .forEach(r -> r.getWebDetection().getWebEntitiesList().stream() - .forEach(entity -> { - out.format("Description: %s\n", entity.getDescription()); - out.format("Score: %f\n", entity.getScore()); - })); - } - } - // [END vision_web_entities_include_geo_results_uri] - - /** - * Suggests a region to crop to for a local file. - * - * @param filePath The path to the local file used for web annotation detection. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectCropHints(String filePath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.CROP_HINTS).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - CropHintsAnnotation annotation = res.getCropHintsAnnotation(); - for (CropHint hint : annotation.getCropHintsList()) { - out.println(hint.getBoundingPoly()); - } - } - } - } - - /** - * Suggests a region to crop to for a remote file on Google Cloud Storage. - * - * @param gcsPath The path to the remote file on Google Cloud Storage to detect safe-search on. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectCropHintsGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.CROP_HINTS).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - CropHintsAnnotation annotation = res.getCropHintsAnnotation(); - for (CropHint hint : annotation.getCropHintsList()) { - out.println(hint.getBoundingPoly()); - } - } - } - } - - // [START vision_detect_document] - /** - * Performs document text detection on a local image file. - * - * @param filePath The path to the local file to detect document text on. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectDocumentText(String filePath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); - - Image img = Image.newBuilder().setContent(imgBytes).build(); - Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - - // For full list of available annotations, see http://g.co/cloud/vision/docs - TextAnnotation annotation = res.getFullTextAnnotation(); - for (Page page: annotation.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(); - out.format("Symbol text: %s (confidence: %f)\n", symbol.getText(), - symbol.getConfidence()); - } - out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence()); - paraText = String.format("%s %s", paraText, wordText); - } - // Output Example using Paragraph: - out.println("\nParagraph: \n" + paraText); - out.format("Paragraph Confidence: %f\n", para.getConfidence()); - blockText = blockText + paraText; - } - pageText = pageText + blockText; - } - } - out.println("\nComplete annotation:"); - out.println(annotation.getText()); - } - } - } - // [END vision_detect_document] - - // [START vision_detect_document_uri] - /** - * Performs document text detection on a remote image on Google Cloud Storage. - * - * @param gcsPath The path to the remote file on Google Cloud Storage to detect document text on. - * @param out A {@link PrintStream} to write the results to. - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void detectDocumentTextGcs(String gcsPath, PrintStream out) throws Exception, - IOException { - List requests = new ArrayList<>(); - - ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); - Image img = Image.newBuilder().setSource(imgSource).build(); - Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build(); - AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); - requests.add(request); - - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); - List responses = response.getResponsesList(); - client.close(); - - for (AnnotateImageResponse res : responses) { - if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); - return; - } - // For full list of available annotations, see http://g.co/cloud/vision/docs - TextAnnotation annotation = res.getFullTextAnnotation(); - for (Page page: annotation.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(); - out.format("Symbol text: %s (confidence: %f)\n", symbol.getText(), - symbol.getConfidence()); - } - out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence()); - paraText = String.format("%s %s", paraText, wordText); - } - // Output Example using Paragraph: - out.println("\nParagraph: \n" + paraText); - out.format("Paragraph Confidence: %f\n", para.getConfidence()); - blockText = blockText + paraText; - } - pageText = pageText + blockText; - } - } - out.println("\nComplete annotation:"); - out.println(annotation.getText()); - } - } - } - // [END vision_detect_document_uri] - - // [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 { - try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { - List 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("application/pdf") // Supported MimeTypes: "application/pdf", "image/tiff" - .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 output with the batch size. - // The batch size sets how many pages should be grouped into each json 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 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 result = response.get(180, TimeUnit.SECONDS) - .getResponsesList(); - - // Once the request has completed and the output has been - // written to GCS, we can list all the 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 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()); - - // Process the first output file from GCS. - // Since we specified batch size = 2, the first response contains - // 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"); - } - } - } - // [END vision_text_detection_pdf_gcs] - // [START vision_localize_objects_beta] /** * Detects localized objects in the specified local image. diff --git a/vision/beta/cloud-client/src/test/java/com/example/vision/DetectIT.java b/vision/beta/cloud-client/src/test/java/com/example/vision/DetectIT.java index f26ef93d4e8..89823c504bf 100644 --- a/vision/beta/cloud-client/src/test/java/com/example/vision/DetectIT.java +++ b/vision/beta/cloud-client/src/test/java/com/example/vision/DetectIT.java @@ -18,11 +18,6 @@ import static com.google.common.truth.Truth.assertThat; -import com.google.api.gax.paging.Page; -import com.google.cloud.storage.Blob; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.Storage.BlobListOption; -import com.google.cloud.storage.StorageOptions; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; @@ -58,122 +53,6 @@ public void tearDown() { System.setOut(null); } - @Test - public void testFaces() throws Exception { - // Act - String[] args = {"faces", "./resources/face_no_surprise.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("anger: POSSIBLE"); - assertThat(got).contains("joy: POSSIBLE"); - assertThat(got).contains("surprise: LIKELY"); - } - - @Test - public void testFacesGcs() throws Exception { - // Act - String[] args = {"faces", "gs://" + BUCKET + "/vision/face_no_surprise.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("anger: POSSIBLE"); - assertThat(got).contains("joy: POSSIBLE"); - assertThat(got).contains("surprise: LIKELY"); - } - - @Test - public void testLabels() throws Exception { - // Act - String[] args = {"labels", "./resources/wakeupcat.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("whiskers"); - } - - @Test - public void testLabelsGcs() throws Exception { - // Act - String[] args = {"labels", "gs://" + BUCKET + "/vision/wakeupcat.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("whiskers"); - } - - @Test - public void testLandmarks() throws Exception { - // Act - String[] args = {"landmarks", "./resources/landmark.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("Palace of Fine Arts"); - } - - @Test - public void testLandmarksGcs() throws Exception { - // Act - String[] args = {"landmarks", "gs://" + BUCKET + "/vision/landmark.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("Palace of Fine Arts"); - } - - @Test - public void testLandmarksUrl() throws Exception { - // Act - String uri = "https://storage-download.googleapis.com/" - + BUCKET + "/vision/landmark.jpg"; - String[] args = {"landmarks", uri}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("Palace of Fine Arts"); - } - - @Test - public void testLogos() throws Exception { - // Act - String[] args = {"logos", "./resources/logos.png"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("Google"); - } - - @Test - public void testLogosGcs() throws Exception { - // Act - String[] args = {"logos", "gs://" + BUCKET + "/vision/logos.png"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("Google"); - } - - @Test - public void testText() throws Exception { - // Act - String[] args = {"text", "./resources/text.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("37%"); - } - @Test public void testDetectLocalizedObjects() throws Exception { // Act @@ -196,210 +75,6 @@ public void testDetectHandwrittenOcr() throws Exception { assertThat(got).contains("Google Cloud Platform"); } - - @Test - public void testTextGcs() throws Exception { - // Act - String[] args = {"text", "gs://" + BUCKET + "/vision/text.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("37%"); - } - - @Test - public void testSafeSearch() throws Exception { - // Act - String[] args = {"safe-search", "./resources/wakeupcat.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("adult: VERY_UNLIKELY"); - assertThat(got).contains("racy: UNLIKELY"); - } - - @Test - public void testSafeSearchGcs() throws Exception { - // Act - String[] args = {"safe-search", "gs://" + BUCKET + "/vision/wakeupcat.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("adult: VERY_UNLIKELY"); - assertThat(got).contains("racy: UNLIKELY"); - } - - @Test - public void testProperties() throws Exception { - // Act - String[] args = {"properties", "./resources/landmark.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("fraction:"); - assertThat(got).contains("r:"); - assertThat(got).contains("g:"); - assertThat(got).contains("b:"); - } - - @Test - public void testPropertiesGcs() throws Exception { - // Act - String[] args = {"properties", "gs://" + BUCKET + "/vision/landmark.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("fraction:"); - assertThat(got).contains("r:"); - assertThat(got).contains("g:"); - assertThat(got).contains("b:"); - } - - @Test - public void detectWebAnnotations() throws Exception { - // Act - String[] args = {"web", "./resources/landmark.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("History"); - assertThat(got).contains("Best guess label: palace of fine arts"); - } - - @Test - public void detectWebAnnotationsGcs() throws Exception { - // Act - String[] args = {"web", "gs://" + BUCKET + "/vision/landmark.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("History"); - assertThat(got).contains("Best guess label: palace of fine arts"); - } - - @Test - public void testDetectWebEntities() throws Exception { - // Act - String[] args = {"web-entities", "./resources/city.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).doesNotContain("Zepra"); - } - - @Test - public void testDetectWebEntitiesGcs() throws Exception { - // Act - String[] args = {"web-entities", "gs://" + BUCKET + "/vision/landmark.jpg"}; - Detect.argsHelper(args, out); - - String got = bout.toString(); - assertThat(got).contains("Description:"); - } - - @Test - public void testDetectWebEntitiesIncludeGeoResults() throws Exception { - // Act - String[] args = {"web-entities-include-geo", "./resources/city.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - // Note: entities and labels can change over time. - assertThat(got).doesNotContain("Error"); - } - - @Test - public void testDetectWebEntitiesIncludeGeoResultsGcs() throws Exception { - // Act - String[] args = {"web-entities-include-geo", "gs://" + BUCKET + "/vision/landmark.jpg"}; - Detect.argsHelper(args, out); - - String got = bout.toString(); - assertThat(got).contains("Description:"); - } - - @Test - public void testCropHints() throws Exception { - // Act - String[] args = {"crop", "./resources/wakeupcat.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("vertices {"); - assertThat(got).contains("x: 599"); - assertThat(got).contains("y: 475"); - } - - @Test - public void testCropHintsGcs() throws Exception { - // Act - String[] args = {"crop", "gs://" + BUCKET + "/vision/wakeupcat.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("vertices {"); - assertThat(got).contains("x: 599"); - assertThat(got).contains("y: 475"); - } - - @Test - public void testDocumentText() throws Exception { - // Act - String[] args = {"fulltext", "./resources/text.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("After preparation is complete, the "); - assertThat(got).contains("37%"); - assertThat(got).contains("Word text: class (confidence:"); - } - - @Test - public void testDocumentTextGcs() throws Exception { - // Act - String[] args = {"fulltext", "gs://" + BUCKET + "/vision/text.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("After preparation is complete, the "); - assertThat(got).contains("37%"); - assertThat(got).contains("Word text: class (confidence:"); - } - - @Test - public void testDetectDocumentsGcs() throws Exception { - // Act - String[] args = {"ocr", "gs://" + BUCKET + "/vision/HodgeConj.pdf", - "gs://" + BUCKET + "/" + OUTPUT_PREFIX + "/"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("HODGE'S GENERAL CONJECTURE"); - - Storage storage = StorageOptions.getDefaultInstance().getService(); - - Page blobs = storage.list(BUCKET, BlobListOption.currentDirectory(), - BlobListOption.prefix(OUTPUT_PREFIX + "/")); - - for (Blob blob : blobs.iterateAll()) { - blob.delete(); - } - } - @Test public void testDetectLocalizedObjectsGcs() throws Exception { // Act From 1106834f6c545b347b978304da576370bb4ad313 Mon Sep 17 00:00:00 2001 From: Alix Hamilton Date: Wed, 5 Sep 2018 17:41:17 -0700 Subject: [PATCH 2/2] delete unused region tags --- .../google/cloud/vision/samples/label/LabelApp.java | 11 ----------- .../samples/landmarkdetection/DetectLandmark.java | 9 --------- 2 files changed, 20 deletions(-) diff --git a/vision/label/src/main/java/com/google/cloud/vision/samples/label/LabelApp.java b/vision/label/src/main/java/com/google/cloud/vision/samples/label/LabelApp.java index ac441e65c86..0cb02b804db 100644 --- a/vision/label/src/main/java/com/google/cloud/vision/samples/label/LabelApp.java +++ b/vision/label/src/main/java/com/google/cloud/vision/samples/label/LabelApp.java @@ -16,8 +16,6 @@ package com.google.cloud.vision.samples.label; -// [START import_libraries] - import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.json.JsonFactory; @@ -39,7 +37,6 @@ import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.util.List; -// [END import_libraries] /** * A sample application that uses the Vision API to label an image. @@ -54,7 +51,6 @@ public class LabelApp { private static final int MAX_LABELS = 3; - // [START run_application] /** * Annotates an image using the Vision API. */ @@ -86,9 +82,7 @@ public static void printLabels(PrintStream out, Path imagePath, List labelImage(Path path, int maxResults) throws IOException { - // [START construct_request] byte[] data = Files.readAllBytes(path); AnnotateImageRequest request = @@ -130,9 +122,7 @@ public List labelImage(Path path, int maxResults) throws IOExc .annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request))); // Due to a bug: requests to Vision API containing large images fail when GZipped. annotate.setDisableGZipContent(true); - // [END construct_request] - // [START parse_response] BatchAnnotateImagesResponse batchResponse = annotate.execute(); assert batchResponse.getResponses().size() == 1; AnnotateImageResponse response = batchResponse.getResponses().get(0); @@ -143,6 +133,5 @@ public List labelImage(Path path, int maxResults) throws IOExc : "Unknown error getting image annotations"); } return response.getLabelAnnotations(); - // [END parse_response] } } diff --git a/vision/landmark-detection/src/main/java/com/google/cloud/vision/samples/landmarkdetection/DetectLandmark.java b/vision/landmark-detection/src/main/java/com/google/cloud/vision/samples/landmarkdetection/DetectLandmark.java index dd99a52af15..a3866fd196c 100644 --- a/vision/landmark-detection/src/main/java/com/google/cloud/vision/samples/landmarkdetection/DetectLandmark.java +++ b/vision/landmark-detection/src/main/java/com/google/cloud/vision/samples/landmarkdetection/DetectLandmark.java @@ -16,8 +16,6 @@ package com.google.cloud.vision.samples.landmarkdetection; -// [START import_libraries] - import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.json.JsonFactory; @@ -36,7 +34,6 @@ import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; -// [END import_libraries] /** * A sample application that uses the Vision API to detect landmarks in an image that is hosted on @@ -52,7 +49,6 @@ public class DetectLandmark { private static final int MAX_RESULTS = 4; - // [START run_application] /** * Annotates an image using the Vision API. */ @@ -74,9 +70,7 @@ public static void main(String[] args) throws IOException, GeneralSecurityExcept System.out.printf("\t%s\n", annotation.getDescription()); } } - // [END run_application] - // [START authenticate] /** * Connects to the Vision API using Application Default Credentials. */ @@ -88,9 +82,7 @@ public static Vision getVisionService() throws IOException, GeneralSecurityExcep .setApplicationName(APPLICATION_NAME) .build(); } - // [END authenticate] - // [START detect_gcs_object] private final Vision vision; /** @@ -129,5 +121,4 @@ public List identifyLandmark(String uri, int maxResults) throw } return response.getLandmarkAnnotations(); } - // [END detect_gcs_object] }