diff --git a/vision/cloud-client/pom.xml b/vision/cloud-client/pom.xml index 89ea28891da..4322f728b45 100644 --- a/vision/cloud-client/pom.xml +++ b/vision/cloud-client/pom.xml @@ -129,7 +129,7 @@ - com.example.vision.QuickstartSample + com.example.vision.quickstart.QuickstartSample false diff --git a/vision/cloud-client/src/main/java/com/example/vision/Detect.java b/vision/cloud-client/src/main/java/com/example/vision/Detect.java index ae84a53ed70..26d3f44d9ec 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/Detect.java +++ b/vision/cloud-client/src/main/java/com/example/vision/Detect.java @@ -36,7 +36,6 @@ import com.google.cloud.vision.v1.CropHintsAnnotation; import com.google.cloud.vision.v1.DominantColorsAnnotation; import com.google.cloud.vision.v1.EntityAnnotation; -import com.google.cloud.vision.v1.FaceAnnotation; import com.google.cloud.vision.v1.Feature; import com.google.cloud.vision.v1.Feature.Type; import com.google.cloud.vision.v1.GcsDestination; @@ -66,7 +65,6 @@ 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; @@ -76,308 +74,15 @@ public class Detect { - /** - * Detects entities, sentiment, and syntax in a document using the Vision API. - * - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void main(String[] args) throws Exception, IOException { - argsHelper(args, System.out); - } - - /** - * Helper that handles the input passed to the program. - * - * @throws Exception on errors while closing the client. - * @throws IOException on Input/Output errors. - */ - public static void argsHelper(String[] args, PrintStream out) throws Exception, IOException { - if (args.length < 1) { - out.println("Usage:"); - out.printf( - "\tmvn exec:java -DDetect -Dexec.args=\" \"\n" - + "\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 \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" - + "Path to Destination\n\tA path to the remote destination on Cloud Storage for the" - + " file to be saved. (gs://BUCKET_NAME/PREFIX/)\n"); - return; - } - 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 (path.startsWith("gs://")) { - detectLocalizedObjectsGcs(path, out); - } else { - detectLocalizedObjects(path, out); - } - } - } - - /** - * 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. - */ - // [START vision_face_detection] - 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()); - } - } - } - } - // [END vision_face_detection] - - /** - * 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. - */ - // [START vision_face_detection_gcs] - 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()); - } - } - } - } - // [END vision_face_detection_gcs] - - /** - * 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. - */ - // [START vision_label_detection] - 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())); - } - } - } - } - // [END vision_label_detection] - - /** - * 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. - */ - // [START vision_label_detection_gcs] - 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())); - } - } - } - } - // [END vision_label_detection_gcs] - /** * 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. */ // [START vision_landmark_detection] - public static void detectLandmarks(String filePath, PrintStream out) - throws Exception, IOException { + public static void detectLandmarks(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -387,20 +92,23 @@ public static void detectLandmarks(String filePath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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()); + System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } @@ -411,11 +119,10 @@ public static void detectLandmarks(String filePath, PrintStream out) * 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 { + public static void detectLandmarksUrl(String uri) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setImageUri(uri).build(); @@ -425,20 +132,23 @@ public static void detectLandmarksUrl(String uri, PrintStream out) throws Except AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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()); + System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } @@ -449,13 +159,11 @@ public static void detectLandmarksUrl(String uri, PrintStream out) throws Except * * @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. */ // [START vision_landmark_detection_gcs] - public static void detectLandmarksGcs(String gcsPath, PrintStream out) - throws Exception, IOException { + public static void detectLandmarksGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -465,20 +173,23 @@ public static void detectLandmarksGcs(String gcsPath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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()); + System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } @@ -489,12 +200,11 @@ public static void detectLandmarksGcs(String gcsPath, PrintStream out) * 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. */ // [START vision_logo_detection] - public static void detectLogos(String filePath, PrintStream out) throws Exception, IOException { + public static void detectLogos(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -505,19 +215,22 @@ public static void detectLogos(String filePath, PrintStream out) throws Exceptio AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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()); + System.out.println(annotation.getDescription()); } } } @@ -529,12 +242,11 @@ public static void detectLogos(String filePath, PrintStream out) throws Exceptio * * @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. */ // [START vision_logo_detection_gcs] - public static void detectLogosGcs(String gcsPath, PrintStream out) throws Exception, IOException { + public static void detectLogosGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -544,19 +256,22 @@ public static void detectLogosGcs(String gcsPath, PrintStream out) throws Except AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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()); + System.out.println(annotation.getDescription()); } } } @@ -567,12 +282,11 @@ public static void detectLogosGcs(String gcsPath, PrintStream out) throws Except * 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. */ // [START vision_text_detection] - public static void detectText(String filePath, PrintStream out) throws Exception, IOException { + public static void detectText(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -583,20 +297,23 @@ public static void detectText(String filePath, PrintStream out) throws Exception AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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()); + System.out.format("Text: %s%n", annotation.getDescription()); + System.out.format("Position : %s%n", annotation.getBoundingPoly()); } } } @@ -607,12 +324,11 @@ public static void detectText(String filePath, PrintStream out) throws Exception * 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. */ // [START vision_text_detection_gcs] - public static void detectTextGcs(String gcsPath, PrintStream out) throws Exception, IOException { + public static void detectTextGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -622,20 +338,23 @@ public static void detectTextGcs(String gcsPath, PrintStream out) throws Excepti AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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()); + System.out.format("Text: %s%n", annotation.getDescription()); + System.out.format("Position : %s%n", annotation.getBoundingPoly()); } } } @@ -646,13 +365,11 @@ public static void detectTextGcs(String gcsPath, PrintStream out) throws Excepti * 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. */ // [START vision_image_property_detection] - public static void detectProperties(String filePath, PrintStream out) - throws Exception, IOException { + public static void detectProperties(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -663,21 +380,24 @@ public static void detectProperties(String filePath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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", + System.out.format( + "fraction: %f%nr: %f, g: %f, b: %f%n", color.getPixelFraction(), color.getColor().getRed(), color.getColor().getGreen(), @@ -693,13 +413,11 @@ public static void detectProperties(String filePath, PrintStream out) * 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. */ // [START vision_image_property_detection_gcs] - public static void detectPropertiesGcs(String gcsPath, PrintStream out) - throws Exception, IOException { + public static void detectPropertiesGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -709,21 +427,24 @@ public static void detectPropertiesGcs(String gcsPath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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", + System.out.format( + "fraction: %f%nr: %f, g: %f, b: %f%n", color.getPixelFraction(), color.getColor().getRed(), color.getColor().getGreen(), @@ -738,13 +459,11 @@ public static void detectPropertiesGcs(String gcsPath, PrintStream out) * 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. */ // [START vision_safe_search_detection] - public static void detectSafeSearch(String filePath, PrintStream out) - throws Exception, IOException { + public static void detectSafeSearch(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -755,20 +474,23 @@ public static void detectSafeSearch(String filePath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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", + System.out.format( + "adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n", annotation.getAdult(), annotation.getMedical(), annotation.getSpoof(), @@ -784,13 +506,11 @@ public static void detectSafeSearch(String filePath, PrintStream out) * 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. */ // [START vision_safe_search_detection_gcs] - public static void detectSafeSearchGcs(String gcsPath, PrintStream out) - throws Exception, IOException { + public static void detectSafeSearchGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -800,20 +520,23 @@ public static void detectSafeSearchGcs(String gcsPath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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", + System.out.format( + "adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n", annotation.getAdult(), annotation.getMedical(), annotation.getSpoof(), @@ -829,12 +552,10 @@ public static void detectSafeSearchGcs(String gcsPath, PrintStream out) * 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 { + public static void detectWebDetections(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -845,13 +566,16 @@ public static void detectWebDetections(String filePath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -859,30 +583,30 @@ public static void detectWebDetections(String filePath, PrintStream out) // 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("==============="); + System.out.println("Entity:Id:Score"); + System.out.println("==============="); for (WebEntity entity : annotation.getWebEntitiesList()) { - out.println( + System.out.println( entity.getDescription() + " : " + entity.getEntityId() + " : " + entity.getScore()); } for (WebLabel label : annotation.getBestGuessLabelsList()) { - out.format("\nBest guess label: %s", label.getLabel()); + System.out.format("%nBest guess label: %s", label.getLabel()); } - out.println("\nPages with matching images: Score\n=="); + System.out.println("%nPages with matching images: Score%n=="); for (WebPage page : annotation.getPagesWithMatchingImagesList()) { - out.println(page.getUrl() + " : " + page.getScore()); + System.out.println(page.getUrl() + " : " + page.getScore()); } - out.println("\nPages with partially matching images: Score\n=="); + System.out.println("%nPages with partially matching images: Score%n=="); for (WebImage image : annotation.getPartialMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); + System.out.println(image.getUrl() + " : " + image.getScore()); } - out.println("\nPages with fully matching images: Score\n=="); + System.out.println("%nPages with fully matching images: Score%n=="); for (WebImage image : annotation.getFullMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); + System.out.println(image.getUrl() + " : " + image.getScore()); } - out.println("\nPages with visually similar images: Score\n=="); + System.out.println("%nPages with visually similar images: Score%n=="); for (WebImage image : annotation.getVisuallySimilarImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); + System.out.println(image.getUrl() + " : " + image.getScore()); } } } @@ -895,12 +619,10 @@ public static void detectWebDetections(String filePath, PrintStream out) * 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 { + public static void detectWebDetectionsGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -910,13 +632,16 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -924,30 +649,30 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) // 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("==============="); + System.out.println("Entity:Id:Score"); + System.out.println("==============="); for (WebEntity entity : annotation.getWebEntitiesList()) { - out.println( + System.out.println( entity.getDescription() + " : " + entity.getEntityId() + " : " + entity.getScore()); } for (WebLabel label : annotation.getBestGuessLabelsList()) { - out.format("\nBest guess label: %s", label.getLabel()); + System.out.format("%nBest guess label: %s", label.getLabel()); } - out.println("\nPages with matching images: Score\n=="); + System.out.println("%nPages with matching images: Score%n=="); for (WebPage page : annotation.getPagesWithMatchingImagesList()) { - out.println(page.getUrl() + " : " + page.getScore()); + System.out.println(page.getUrl() + " : " + page.getScore()); } - out.println("\nPages with partially matching images: Score\n=="); + System.out.println("%nPages with partially matching images: Score%n=="); for (WebImage image : annotation.getPartialMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); + System.out.println(image.getUrl() + " : " + image.getScore()); } - out.println("\nPages with fully matching images: Score\n=="); + System.out.println("%nPages with fully matching images: Score%n=="); for (WebImage image : annotation.getFullMatchingImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); + System.out.println(image.getUrl() + " : " + image.getScore()); } - out.println("\nPages with visually similar images: Score\n=="); + System.out.println("%nPages with visually similar images: Score%n=="); for (WebImage image : annotation.getVisuallySimilarImagesList()) { - out.println(image.getUrl() + " : " + image.getScore()); + System.out.println(image.getUrl() + " : " + image.getScore()); } } } @@ -958,13 +683,14 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) * 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 + public static void detectWebEntities(String filePath) throws Exception, IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { // Read in the local image ByteString contents = ByteString.readFrom(new FileInputStream(filePath)); @@ -983,18 +709,14 @@ public static void detectWebEntities(String filePath, PrintStream out) BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); // Display the results - response - .getResponsesList() - .stream() + response.getResponsesList().stream() .forEach( r -> - r.getWebDetection() - .getWebEntitiesList() - .stream() + r.getWebDetection().getWebEntitiesList().stream() .forEach( entity -> { - out.format("Description: %s\n", entity.getDescription()); - out.format("Score: %f\n", entity.getScore()); + System.out.format("Description: %s%n", entity.getDescription()); + System.out.format("Score: %f%n", entity.getScore()); })); } } @@ -1003,13 +725,14 @@ public static void detectWebEntities(String filePath, PrintStream out) * 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 + public static void detectWebEntitiesGcs(String gcsPath) throws Exception, IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { // Set the image source to the given gs uri ImageSource imageSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -1027,18 +750,14 @@ public static void detectWebEntitiesGcs(String gcsPath, PrintStream out) BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); // Display the results - response - .getResponsesList() - .stream() + response.getResponsesList().stream() .forEach( r -> - r.getWebDetection() - .getWebEntitiesList() - .stream() + r.getWebDetection().getWebEntitiesList().stream() .forEach( entity -> { - System.out.format("Description: %s\n", entity.getDescription()); - System.out.format("Score: %f\n", entity.getScore()); + System.out.format("Description: %s%n", entity.getDescription()); + System.out.format("Score: %f%n", entity.getScore()); })); } } @@ -1048,13 +767,15 @@ public static void detectWebEntitiesGcs(String gcsPath, PrintStream out) * 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) + public static void detectWebEntitiesIncludeGeoResults(String filePath) throws Exception, IOException { - // Instantiates a client + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { // Read in the local image ByteString contents = ByteString.readFrom(new FileInputStream(filePath)); @@ -1082,18 +803,14 @@ public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStre BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); // Display the results - response - .getResponsesList() - .stream() + response.getResponsesList().stream() .forEach( r -> - r.getWebDetection() - .getWebEntitiesList() - .stream() + r.getWebDetection().getWebEntitiesList().stream() .forEach( entity -> { - out.format("Description: %s\n", entity.getDescription()); - out.format("Score: %f\n", entity.getScore()); + System.out.format("Description: %s%n", entity.getDescription()); + System.out.format("Score: %f%n", entity.getScore()); })); } } @@ -1105,13 +822,15 @@ public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStre * * @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) + public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath) throws Exception, IOException { - // Instantiates a client + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { // Set the image source to the given gs uri ImageSource imageSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -1138,18 +857,14 @@ public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath, PrintSt BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); // Display the results - response - .getResponsesList() - .stream() + response.getResponsesList().stream() .forEach( r -> - r.getWebDetection() - .getWebEntitiesList() - .stream() + r.getWebDetection().getWebEntitiesList().stream() .forEach( entity -> { - out.format("Description: %s\n", entity.getDescription()); - out.format("Score: %f\n", entity.getScore()); + System.out.format("Description: %s%n", entity.getDescription()); + System.out.format("Score: %f%n", entity.getScore()); })); } } @@ -1159,13 +874,11 @@ public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath, PrintSt * 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. */ // [START vision_crop_hint_detection] - public static void detectCropHints(String filePath, PrintStream out) - throws Exception, IOException { + public static void detectCropHints(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -1176,20 +889,23 @@ public static void detectCropHints(String filePath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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()); + System.out.println(hint.getBoundingPoly()); } } } @@ -1200,13 +916,11 @@ public static void detectCropHints(String filePath, PrintStream out) * 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. */ // [START vision_crop_hint_detection_gcs] - public static void detectCropHintsGcs(String gcsPath, PrintStream out) - throws Exception, IOException { + public static void detectCropHintsGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -1216,20 +930,23 @@ public static void detectCropHintsGcs(String gcsPath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. 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()); + System.out.format("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()); + System.out.println(hint.getBoundingPoly()); } } } @@ -1240,13 +957,11 @@ public static void detectCropHintsGcs(String gcsPath, PrintStream out) * 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. */ // [START vision_fulltext_detection] - public static void detectDocumentText(String filePath, PrintStream out) - throws Exception, IOException { + public static void detectDocumentText(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -1257,6 +972,9 @@ public static void detectDocumentText(String filePath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); @@ -1264,7 +982,7 @@ public static void detectDocumentText(String filePath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); + System.out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -1280,23 +998,24 @@ public static void detectDocumentText(String filePath, PrintStream out) String wordText = ""; for (Symbol symbol : word.getSymbolsList()) { wordText = wordText + symbol.getText(); - out.format( - "Symbol text: %s (confidence: %f)\n", + System.out.format( + "Symbol text: %s (confidence: %f)%n", symbol.getText(), symbol.getConfidence()); } - out.format("Word text: %s (confidence: %f)\n\n", wordText, word.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: - out.println("\nParagraph: \n" + paraText); - out.format("Paragraph Confidence: %f\n", para.getConfidence()); + System.out.println("%nParagraph: %n" + paraText); + System.out.format("Paragraph Confidence: %f%n", para.getConfidence()); blockText = blockText + paraText; } pageText = pageText + blockText; } } - out.println("\nComplete annotation:"); - out.println(annotation.getText()); + System.out.println("%nComplete annotation:"); + System.out.println(annotation.getText()); } } } @@ -1306,13 +1025,11 @@ public static void detectDocumentText(String filePath, PrintStream out) * 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. */ // [START vision_fulltext_detection_gcs] - public static void detectDocumentTextGcs(String gcsPath, PrintStream out) - throws Exception, IOException { + public static void detectDocumentTextGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -1322,6 +1039,9 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); requests.add(request); + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); @@ -1329,7 +1049,7 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); + System.out.format("Error: %s%n", res.getError().getMessage()); return; } // For full list of available annotations, see http://g.co/cloud/vision/docs @@ -1344,23 +1064,24 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) String wordText = ""; for (Symbol symbol : word.getSymbolsList()) { wordText = wordText + symbol.getText(); - out.format( - "Symbol text: %s (confidence: %f)\n", + System.out.format( + "Symbol text: %s (confidence: %f)%n", symbol.getText(), symbol.getConfidence()); } - out.format("Word text: %s (confidence: %f)\n\n", wordText, word.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: - out.println("\nParagraph: \n" + paraText); - out.format("Paragraph Confidence: %f\n", para.getConfidence()); + System.out.println("%nParagraph: %n" + paraText); + System.out.format("Paragraph Confidence: %f%n", para.getConfidence()); blockText = blockText + paraText; } pageText = pageText + blockText; } } - out.println("\nComplete annotation:"); - out.println(annotation.getText()); + System.out.println("%nComplete annotation:"); + System.out.println(annotation.getText()); } } } @@ -1378,6 +1099,10 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) */ public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinationPath) throws Exception { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { List requests = new ArrayList<>(); @@ -1397,8 +1122,8 @@ public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinatio 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. + // Create the configuration for the System.output with the batch size. + // The batch size sets how many pages should be grouped into each json System.output file. OutputConfig outputConfig = OutputConfig.newBuilder().setBatchSize(2).setGcsDestination(gcsDestination).build(); @@ -1426,8 +1151,8 @@ public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinatio 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. + // Once the request has completed and the System.output has been + // written to GCS, we can list all the System.output files. Storage storage = StorageOptions.getDefaultInstance().getService(); // Get the destination location from the gcsDestinationPath @@ -1449,7 +1174,7 @@ public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinatio for (Blob blob : pageList.iterateAll()) { System.out.println(blob.getName()); - // Process the first output file from GCS. + // Process the first System.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) { @@ -1475,7 +1200,7 @@ public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinatio // 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()); + System.out.format("%nText: %s%n", annotateImageResponse.getFullTextAnnotation().getText()); } else { System.out.println("No MATCH"); } @@ -1488,12 +1213,10 @@ public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinatio * Detects localized objects in the specified local image. * * @param filePath The path to the file to perform localized object detection on. - * @param out A {@link PrintStream} to write detected objects to. * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLocalizedObjects(String filePath, PrintStream out) - throws Exception, IOException { + public static void detectLocalizedObjects(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -1506,21 +1229,24 @@ public static void detectLocalizedObjects(String filePath, PrintStream out) .build(); requests.add(request); - // Perform the request + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + // Perform the request BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); // Display the results for (AnnotateImageResponse res : responses) { for (LocalizedObjectAnnotation entity : res.getLocalizedObjectAnnotationsList()) { - out.format("Object name: %s\n", entity.getName()); - out.format("Confidence: %s\n", entity.getScore()); - out.format("Normalized Vertices:\n"); + System.out.format("Object name: %s%n", entity.getName()); + System.out.format("Confidence: %s%n", entity.getScore()); + System.out.format("Normalized Vertices:%n"); entity .getBoundingPoly() .getNormalizedVerticesList() - .forEach(vertex -> out.format("- (%s, %s)\n", vertex.getX(), vertex.getY())); + .forEach(vertex -> System.out.format("- (%s, %s)%n", vertex.getX(), vertex.getY())); } } } @@ -1533,12 +1259,10 @@ public static void detectLocalizedObjects(String filePath, PrintStream out) * * @param gcsPath The path to the remote file on Google Cloud Storage to detect localized objects * on. - * @param out A {@link PrintStream} to write detected objects to. * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLocalizedObjectsGcs(String gcsPath, PrintStream out) - throws Exception, IOException { + public static void detectLocalizedObjectsGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -1551,21 +1275,24 @@ public static void detectLocalizedObjectsGcs(String gcsPath, PrintStream out) .build(); requests.add(request); - // Perform the request + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + // Perform the request BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List responses = response.getResponsesList(); client.close(); // Display the results for (AnnotateImageResponse res : responses) { for (LocalizedObjectAnnotation entity : res.getLocalizedObjectAnnotationsList()) { - out.format("Object name: %s\n", entity.getName()); - out.format("Confidence: %s\n", entity.getScore()); - out.format("Normalized Vertices:\n"); + System.out.format("Object name: %s%n", entity.getName()); + System.out.format("Confidence: %s%n", entity.getScore()); + System.out.format("Normalized Vertices:%n"); entity .getBoundingPoly() .getNormalizedVerticesList() - .forEach(vertex -> out.format("- (%s, %s)\n", vertex.getX(), vertex.getY())); + .forEach(vertex -> System.out.format("- (%s, %s)%n", vertex.getX(), vertex.getY())); } } } diff --git a/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java b/vision/cloud-client/src/main/java/com/example/vision/quickstart/QuickstartSample.java similarity index 85% rename from vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java rename to vision/cloud-client/src/main/java/com/example/vision/quickstart/QuickstartSample.java index b88233612d9..6e04f722e2f 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java +++ b/vision/cloud-client/src/main/java/com/example/vision/quickstart/QuickstartSample.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.example.vision; +package com.example.vision.quickstart; // [START vision_quickstart] // Imports the Google Cloud client library @@ -36,7 +36,9 @@ public class QuickstartSample { public static void main(String... args) throws Exception { - // Instantiates a client + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) { // The path to the image file to annotate @@ -61,14 +63,14 @@ public static void main(String... args) throws Exception { for (AnnotateImageResponse res : responses) { if (res.hasError()) { - System.out.printf("Error: %s\n", res.getError().getMessage()); + System.out.format("Error: %s%n", res.getError().getMessage()); return; } for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { annotation .getAllFields() - .forEach((k, v) -> System.out.printf("%s : %s\n", k, v.toString())); + .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString())); } } } diff --git a/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java b/vision/cloud-client/src/main/java/com/example/vision/snippets/AsyncBatchAnnotateImages.java similarity index 97% rename from vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java rename to vision/cloud-client/src/main/java/com/example/vision/snippets/AsyncBatchAnnotateImages.java index e9b31582051..025abc30594 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/AsyncBatchAnnotateImages.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.example.vision; +package com.example.vision.snippets; // [START vision_async_batch_annotate_images] import com.google.cloud.vision.v1.AnnotateImageRequest; @@ -82,7 +82,7 @@ public static void asyncBatchAnnotateImages(String inputImageUri, String outputU // The output is written to GCS with the provided output_uri as prefix String gcsOutputUri = response.getOutputConfig().getGcsDestination().getUri(); - System.out.printf("Output written to GCS with prefix: %s\n", gcsOutputUri); + System.out.format("Output written to GCS with prefix: %s%n", gcsOutputUri); } } } diff --git a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFiles.java b/vision/cloud-client/src/main/java/com/example/vision/snippets/BatchAnnotateFiles.java similarity index 92% rename from vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFiles.java rename to vision/cloud-client/src/main/java/com/example/vision/snippets/BatchAnnotateFiles.java index 0895ca7aa00..15a864ff5f3 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFiles.java +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/BatchAnnotateFiles.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.example.vision; +package com.example.vision.snippets; // [START vision_batch_annotate_files] import com.google.cloud.vision.v1.AnnotateFileRequest; @@ -90,17 +90,17 @@ public static void batchAnnotateFiles(String filePath) throws IOException { // sample. for (AnnotateImageResponse imageResponse : response.getResponsesList().get(0).getResponsesList()) { - System.out.printf("Full text: %s\n", imageResponse.getFullTextAnnotation().getText()); + System.out.format("Full text: %s%n", imageResponse.getFullTextAnnotation().getText()); for (Page page : imageResponse.getFullTextAnnotation().getPagesList()) { for (Block block : page.getBlocksList()) { - System.out.printf("\nBlock confidence: %s\n", block.getConfidence()); + System.out.format("%nBlock confidence: %s%n", block.getConfidence()); for (Paragraph par : block.getParagraphsList()) { - System.out.printf("\tParagraph confidence: %s\n", par.getConfidence()); + System.out.format("\tParagraph confidence: %s%n", par.getConfidence()); for (Word word : par.getWordsList()) { - System.out.printf("\t\tWord confidence: %s\n", word.getConfidence()); + System.out.format("\t\tWord confidence: %s%n", word.getConfidence()); for (Symbol symbol : word.getSymbolsList()) { - System.out.printf( - "\t\t\tSymbol: %s, (confidence: %s)\n", + System.out.format( + "\t\t\tSymbol: %s, (confidence: %s)%n", symbol.getText(), symbol.getConfidence()); } } diff --git a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFilesGcs.java b/vision/cloud-client/src/main/java/com/example/vision/snippets/BatchAnnotateFilesGcs.java similarity index 92% rename from vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFilesGcs.java rename to vision/cloud-client/src/main/java/com/example/vision/snippets/BatchAnnotateFilesGcs.java index dce825fd025..f7d1ca4e52a 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFilesGcs.java +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/BatchAnnotateFilesGcs.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.example.vision; +package com.example.vision.snippets; // [START vision_batch_annotate_files_gcs] import com.google.cloud.vision.v1.AnnotateFileRequest; @@ -85,17 +85,17 @@ public static void batchAnnotateFilesGcs(String gcsUri) throws IOException { // sample. for (AnnotateImageResponse imageResponse : response.getResponsesList().get(0).getResponsesList()) { - System.out.printf("Full text: %s\n", imageResponse.getFullTextAnnotation().getText()); + System.out.format("Full text: %s%n", imageResponse.getFullTextAnnotation().getText()); for (Page page : imageResponse.getFullTextAnnotation().getPagesList()) { for (Block block : page.getBlocksList()) { - System.out.printf("\nBlock confidence: %s\n", block.getConfidence()); + System.out.format("%nBlock confidence: %s%n", block.getConfidence()); for (Paragraph par : block.getParagraphsList()) { - System.out.printf("\tParagraph confidence: %s\n", par.getConfidence()); + System.out.format("\tParagraph confidence: %s%n", par.getConfidence()); for (Word word : par.getWordsList()) { - System.out.printf("\t\tWord confidence: %s\n", word.getConfidence()); + System.out.format("\t\tWord confidence: %s%n", word.getConfidence()); for (Symbol symbol : word.getSymbolsList()) { - System.out.printf( - "\t\t\tSymbol: %s, (confidence: %s)\n", + System.out.format( + "\t\t\tSymbol: %s, (confidence: %s)%n", symbol.getText(), symbol.getConfidence()); } } diff --git a/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFaces.java b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFaces.java new file mode 100644 index 00000000000..4c07fa08080 --- /dev/null +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFaces.java @@ -0,0 +1,80 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_face_detection] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.FaceAnnotation; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectFaces { + + public static void detectFaces() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectFaces(filePath); + } + + // Detects faces in the specified local image. + public static void detectFaces(String filePath) throws IOException { + List requests = new ArrayList<>(); + + ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); + + Image img = Image.newBuilder().setContent(imgBytes).build(); + Feature feat = Feature.newBuilder().setType(Feature.Type.FACE_DETECTION).build(); + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); + requests.add(request); + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.format("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()) { + System.out.format( + "anger: %s%njoy: %s%nsurprise: %s%nposition: %s", + annotation.getAngerLikelihood(), + annotation.getJoyLikelihood(), + annotation.getSurpriseLikelihood(), + annotation.getBoundingPoly()); + } + } + } + } +} +// [END vision_face_detection] diff --git a/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFacesGcs.java b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFacesGcs.java new file mode 100644 index 00000000000..b325623e761 --- /dev/null +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFacesGcs.java @@ -0,0 +1,79 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_face_detection_gcs] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.FaceAnnotation; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageSource; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectFacesGcs { + + public static void detectFacesGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectFacesGcs(filePath); + } + + // Detects faces in the specified remote image on Google Cloud Storage. + public static void detectFacesGcs(String gcsPath) throws IOException { + List requests = new ArrayList<>(); + + ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); + Image img = Image.newBuilder().setSource(imgSource).build(); + Feature feat = Feature.newBuilder().setType(Feature.Type.FACE_DETECTION).build(); + + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); + requests.add(request); + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.format("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()) { + System.out.format( + "anger: %s%njoy: %s%nsurprise: %s%nposition: %s", + annotation.getAngerLikelihood(), + annotation.getJoyLikelihood(), + annotation.getSurpriseLikelihood(), + annotation.getBoundingPoly()); + } + } + } + } +} +// [END vision_face_detection_gcs] diff --git a/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabels.java b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabels.java new file mode 100644 index 00000000000..87563bb3ca6 --- /dev/null +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabels.java @@ -0,0 +1,77 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_label_detection] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.EntityAnnotation; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectLabels { + + public static void detectLabels() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectLabels(filePath); + } + + // Detects labels in the specified local image. + public static void detectLabels(String filePath) throws IOException { + List requests = new ArrayList<>(); + + ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); + + Image img = Image.newBuilder().setContent(imgBytes).build(); + Feature feat = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build(); + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); + requests.add(request); + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.format("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) -> System.out.format("%s : %s%n", k, v.toString())); + } + } + } + } +} +// [END vision_label_detection] diff --git a/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabelsGcs.java b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabelsGcs.java new file mode 100644 index 00000000000..53e8dfe5351 --- /dev/null +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabelsGcs.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_label_detection_gcs] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.EntityAnnotation; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageSource; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectLabelsGcs { + + public static void detectLabelsGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectLabelsGcs(filePath); + } + + // Detects labels in the specified remote image on Google Cloud Storage. + public static void detectLabelsGcs(String gcsPath) throws IOException { + List requests = new ArrayList<>(); + + ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); + Image img = Image.newBuilder().setSource(imgSource).build(); + Feature feat = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build(); + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); + requests.add(request); + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.format("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) -> System.out.format("%s : %s%n", k, v.toString())); + } + } + } + } +} +// [END vision_label_detection_gcs] diff --git a/vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java b/vision/cloud-client/src/main/java/com/example/vision/snippets/SetEndpoint.java similarity index 91% rename from vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java rename to vision/cloud-client/src/main/java/com/example/vision/snippets/SetEndpoint.java index 22eed6813d4..7aeb05abb70 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/SetEndpoint.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.example.vision; +package com.example.vision.snippets; import com.google.cloud.vision.v1.AnnotateImageRequest; import com.google.cloud.vision.v1.AnnotateImageResponse; @@ -29,10 +29,10 @@ import java.util.ArrayList; import java.util.List; -class SetEndpoint { +public class SetEndpoint { // Change your endpoint - static void setEndpoint() throws IOException { + public static void setEndpoint() throws IOException { // [START vision_set_endpoint] ImageAnnotatorSettings settings = ImageAnnotatorSettings.newBuilder().setEndpoint("eu-vision.googleapis.com:443").build(); @@ -58,9 +58,9 @@ static void setEndpoint() throws IOException { for (AnnotateImageResponse response : batchResponse.getResponsesList()) { for (EntityAnnotation annotation : response.getTextAnnotationsList()) { - System.out.printf("Text: %s\n", annotation.getDescription()); + System.out.format("Text: %s%n", annotation.getDescription()); System.out.println("Position:"); - System.out.printf("%s\n", annotation.getBoundingPoly()); + System.out.format("%s%n", annotation.getBoundingPoly()); } } client.close(); diff --git a/vision/cloud-client/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java b/vision/cloud-client/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java index 8edc89828fb..aa05841ed45 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java +++ b/vision/cloud-client/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java @@ -19,6 +19,7 @@ import static com.google.common.truth.Truth.assertThat; import static junit.framework.TestCase.assertNotNull; +import com.example.vision.snippets.AsyncBatchAnnotateImages; import com.google.api.gax.paging.Page; import com.google.cloud.storage.Blob; import com.google.cloud.storage.Storage; diff --git a/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java b/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java index 5f1c1e043a3..f8ff793559d 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java +++ b/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java @@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat; +import com.example.vision.snippets.BatchAnnotateFilesGcs; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; diff --git a/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesTest.java b/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesTest.java index 621aba76798..f08718981ca 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesTest.java +++ b/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesTest.java @@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat; +import com.example.vision.snippets.BatchAnnotateFiles; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; diff --git a/vision/cloud-client/src/test/java/com/example/vision/DetectFacesGcsTest.java b/vision/cloud-client/src/test/java/com/example/vision/DetectFacesGcsTest.java new file mode 100644 index 00000000000..8de0dac2d22 --- /dev/null +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectFacesGcsTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectFacesGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectFacesGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testFaces() throws Exception { + // Act + DetectFacesGcs.detectFacesGcs("gs://" + ASSET_BUCKET + "/vision/face/face_no_surprise.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("anger:"); + assertThat(got).contains("joy:"); + assertThat(got).contains("surprise:"); + } +} diff --git a/vision/cloud-client/src/test/java/com/example/vision/DetectFacesTest.java b/vision/cloud-client/src/test/java/com/example/vision/DetectFacesTest.java new file mode 100644 index 00000000000..d009212739d --- /dev/null +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectFacesTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectFaces; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectFacesTest { + private ByteArrayOutputStream bout; + private PrintStream out; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testFaces() throws Exception { + // Act + DetectFaces.detectFaces("./resources/face_no_surprise.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("anger:"); + assertThat(got).contains("joy:"); + assertThat(got).contains("surprise:"); + } +} diff --git a/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java b/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java index ad3c19d85a5..0b4eb18ab40 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java @@ -56,59 +56,10 @@ 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:"); - assertThat(got).contains("joy:"); - assertThat(got).contains("surprise:"); - } - - @Test - public void testFacesGcs() throws Exception { - // Act - String[] args = {"faces", "gs://" + ASSET_BUCKET + "/vision/face/face_no_surprise.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString(); - assertThat(got).contains("anger:"); - assertThat(got).contains("joy:"); - assertThat(got).contains("surprise:"); - } - - @Test - public void testLabels() throws Exception { - // Act - String[] args = {"labels", "./resources/wakeupcat.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString().toLowerCase(); - assertThat(got).contains("whiskers"); - } - - @Test - public void testLabelsGcs() throws Exception { - // Act - String[] args = {"labels", "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"}; - Detect.argsHelper(args, out); - - // Assert - String got = bout.toString().toLowerCase(); - assertThat(got).contains("whiskers"); - } - @Test public void testLandmarks() throws Exception { // Act - String[] args = {"landmarks", "./resources/landmark.jpg"}; - Detect.argsHelper(args, out); + Detect.detectLandmarks("./resources/landmark.jpg"); // Assert String got = bout.toString().toLowerCase(); @@ -118,8 +69,7 @@ public void testLandmarks() throws Exception { @Test public void testLandmarksGcs() throws Exception { // Act - String[] args = {"landmarks", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"}; - Detect.argsHelper(args, out); + Detect.detectLandmarksGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); // Assert String got = bout.toString().toLowerCase(); @@ -131,8 +81,7 @@ public void testLandmarksUrl() throws Exception { // Act String uri = "https://storage-download.googleapis.com/" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"; - String[] args = {"landmarks", uri}; - Detect.argsHelper(args, out); + Detect.detectLandmarksUrl(uri); // Assert String got = bout.toString().toLowerCase(); @@ -142,8 +91,7 @@ public void testLandmarksUrl() throws Exception { @Test public void testLogos() throws Exception { // Act - String[] args = {"logos", "./resources/logos.png"}; - Detect.argsHelper(args, out); + Detect.detectLogos("./resources/logos.png"); // Assert String got = bout.toString().toLowerCase(); @@ -153,8 +101,7 @@ public void testLogos() throws Exception { @Test public void testLogosGcs() throws Exception { // Act - String[] args = {"logos", "gs://" + ASSET_BUCKET + "/vision/logo/logo_google.png"}; - Detect.argsHelper(args, out); + Detect.detectLogosGcs("gs://" + ASSET_BUCKET + "/vision/logo/logo_google.png"); // Assert String got = bout.toString().toLowerCase(); @@ -164,8 +111,7 @@ public void testLogosGcs() throws Exception { @Test public void testText() throws Exception { // Act - String[] args = {"text", "./resources/text.jpg"}; - Detect.argsHelper(args, out); + Detect.detectText("./resources/text.jpg"); // Assert String got = bout.toString(); @@ -175,8 +121,7 @@ public void testText() throws Exception { @Test public void testTextGcs() throws Exception { // Act - String[] args = {"text", "gs://" + ASSET_BUCKET + "/vision/text/screen.jpg"}; - Detect.argsHelper(args, out); + Detect.detectTextGcs("gs://" + ASSET_BUCKET + "/vision/text/screen.jpg"); // Assert String got = bout.toString(); @@ -186,8 +131,7 @@ public void testTextGcs() throws Exception { @Test public void testSafeSearch() throws Exception { // Act - String[] args = {"safe-search", "./resources/wakeupcat.jpg"}; - Detect.argsHelper(args, out); + Detect.detectSafeSearch("./resources/wakeupcat.jpg"); // Assert String got = bout.toString(); @@ -198,8 +142,7 @@ public void testSafeSearch() throws Exception { @Test public void testSafeSearchGcs() throws Exception { // Act - String[] args = {"safe-search", "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"}; - Detect.argsHelper(args, out); + Detect.detectSafeSearchGcs("gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"); // Assert String got = bout.toString(); @@ -210,8 +153,7 @@ public void testSafeSearchGcs() throws Exception { @Test public void testProperties() throws Exception { // Act - String[] args = {"properties", "./resources/landmark.jpg"}; - Detect.argsHelper(args, out); + Detect.detectProperties("./resources/landmark.jpg"); // Assert String got = bout.toString(); @@ -224,8 +166,7 @@ public void testProperties() throws Exception { @Test public void testPropertiesGcs() throws Exception { // Act - String[] args = {"properties", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"}; - Detect.argsHelper(args, out); + Detect.detectPropertiesGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); // Assert String got = bout.toString(); @@ -238,8 +179,7 @@ public void testPropertiesGcs() throws Exception { @Test public void detectWebAnnotations() throws Exception { // Act - String[] args = {"web", "./resources/landmark.jpg"}; - Detect.argsHelper(args, out); + Detect.detectWebDetections("./resources/landmark.jpg"); // Assert String got = bout.toString().toLowerCase(); @@ -250,8 +190,7 @@ public void detectWebAnnotations() throws Exception { @Test public void detectWebAnnotationsGcs() throws Exception { // Act - String[] args = {"web", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"}; - Detect.argsHelper(args, out); + Detect.detectWebDetectionsGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); // Assert String got = bout.toString().toLowerCase(); @@ -262,8 +201,7 @@ public void detectWebAnnotationsGcs() throws Exception { @Test public void testDetectWebEntities() throws Exception { // Act - String[] args = {"web-entities", "./resources/city.jpg"}; - Detect.argsHelper(args, out); + Detect.detectWebEntities("./resources/city.jpg"); // Assert String got = bout.toString().toLowerCase(); @@ -273,8 +211,7 @@ public void testDetectWebEntities() throws Exception { @Test public void testDetectWebEntitiesGcs() throws Exception { // Act - String[] args = {"web-entities", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"}; - Detect.argsHelper(args, out); + Detect.detectWebEntitiesGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); String got = bout.toString().toLowerCase(); assertThat(got).contains("description"); @@ -283,8 +220,7 @@ public void testDetectWebEntitiesGcs() throws Exception { @Test public void testDetectWebEntitiesIncludeGeoResults() throws Exception { // Act - String[] args = {"web-entities-include-geo", "./resources/city.jpg"}; - Detect.argsHelper(args, out); + Detect.detectWebEntitiesIncludeGeoResults("./resources/city.jpg"); // Assert String got = bout.toString().toLowerCase(); @@ -295,10 +231,8 @@ public void testDetectWebEntitiesIncludeGeoResults() throws Exception { @Test public void testDetectWebEntitiesIncludeGeoResultsGcs() throws Exception { // Act - String[] args = { - "web-entities-include-geo", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg" - }; - Detect.argsHelper(args, out); + Detect.detectWebEntitiesIncludeGeoResultsGcs( + "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); String got = bout.toString().toLowerCase(); assertThat(got).contains("description"); @@ -307,8 +241,7 @@ public void testDetectWebEntitiesIncludeGeoResultsGcs() throws Exception { @Test public void testCropHints() throws Exception { // Act - String[] args = {"crop", "./resources/wakeupcat.jpg"}; - Detect.argsHelper(args, out); + Detect.detectCropHints("./resources/wakeupcat.jpg"); // Assert String got = bout.toString(); @@ -320,8 +253,7 @@ public void testCropHints() throws Exception { @Test public void testCropHintsGcs() throws Exception { // Act - String[] args = {"crop", "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"}; - Detect.argsHelper(args, out); + Detect.detectCropHintsGcs("gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"); // Assert String got = bout.toString(); @@ -333,8 +265,7 @@ public void testCropHintsGcs() throws Exception { @Test public void testDocumentText() throws Exception { // Act - String[] args = {"fulltext", "./resources/text.jpg"}; - Detect.argsHelper(args, out); + Detect.detectDocumentText("./resources/text.jpg"); // Assert String got = bout.toString(); @@ -346,8 +277,7 @@ public void testDocumentText() throws Exception { @Test public void testDocumentTextGcs() throws Exception { // Act - String[] args = {"fulltext", "gs://" + ASSET_BUCKET + "/vision/text/screen.jpg"}; - Detect.argsHelper(args, out); + Detect.detectDocumentTextGcs("gs://" + ASSET_BUCKET + "/vision/text/screen.jpg"); // Assert String got = bout.toString(); @@ -359,12 +289,9 @@ public void testDocumentTextGcs() throws Exception { @Test public void testDetectDocumentsGcs() throws Exception { // Act - String[] args = { - "ocr", - "gs://" + ASSET_BUCKET + "/vision/document/custom_0773375000.pdf", - "gs://" + OUTPUT_BUCKET + "/" + OUTPUT_PREFIX + "/" - }; - Detect.argsHelper(args, out); + Detect.detectDocumentsGcs( + "gs://" + ASSET_BUCKET + "/vision/document/custom_0773375000.pdf", + "gs://" + OUTPUT_BUCKET + "/" + OUTPUT_PREFIX + "/"); // Assert String got = bout.toString(); @@ -386,8 +313,7 @@ public void testDetectDocumentsGcs() throws Exception { @Test public void testDetectLocalizedObjects() throws Exception { // Act - String[] args = {"object-localization", "./resources/puppies.jpg"}; - Detect.argsHelper(args, out); + Detect.detectLocalizedObjects("./resources/puppies.jpg"); // Assert String got = bout.toString().toLowerCase(); @@ -397,10 +323,8 @@ public void testDetectLocalizedObjects() throws Exception { @Test public void testDetectLocalizedObjectsGcs() throws Exception { // Act - String[] args = { - "object-localization", "gs://cloud-samples-data/vision/object_localization/puppies.jpg" - }; - Detect.argsHelper(args, out); + Detect.detectLocalizedObjectsGcs( + "gs://cloud-samples-data/vision/object_localization/puppies.jpg"); // Assert String got = bout.toString().toLowerCase(); diff --git a/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsGcsTest.java b/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsGcsTest.java new file mode 100644 index 00000000000..9ddb0e2e515 --- /dev/null +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsGcsTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectLabelsGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLabelsGcsTest { + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testLabelsGcs() throws Exception { + // Act + DetectLabelsGcs.detectLabelsGcs("gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("whiskers"); + } +} diff --git a/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsTest.java b/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsTest.java new file mode 100644 index 00000000000..741b2f63142 --- /dev/null +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectLabels; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLabelsTest { + private ByteArrayOutputStream bout; + private PrintStream out; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + System.setOut(out); + } + + @After + public void tearDown() { + System.setOut(null); + } + + @Test + public void testLabels() throws Exception { + // Act + DetectLabels.detectLabels("./resources/wakeupcat.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("whiskers"); + } +} diff --git a/vision/cloud-client/src/test/java/com/example/vision/SetEndpointIT.java b/vision/cloud-client/src/test/java/com/example/vision/SetEndpointIT.java index 9b27ea7d7de..1f648f54494 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/SetEndpointIT.java +++ b/vision/cloud-client/src/test/java/com/example/vision/SetEndpointIT.java @@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat; +import com.example.vision.snippets.SetEndpoint; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream;