From 34479ac70a53304ca30792f2d9b139e772dfd10b Mon Sep 17 00:00:00 2001 From: Mike Ganbold Date: Wed, 27 May 2020 12:09:12 -0700 Subject: [PATCH 1/4] chore: added comment on try/catch block --- .../vision/AsyncBatchAnnotateImages.java | 2 +- .../example/vision/BatchAnnotateFiles.java | 12 +- .../example/vision/BatchAnnotateFilesGcs.java | 12 +- .../main/java/com/example/vision/Detect.java | 277 ++++++++++++------ .../com/example/vision/QuickstartSample.java | 8 +- .../java/com/example/vision/SetEndpoint.java | 4 +- 6 files changed, 201 insertions(+), 114 deletions(-) diff --git a/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java b/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java index e9b31582051..032d6375dc5 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java +++ b/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java @@ -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/BatchAnnotateFiles.java index 0895ca7aa00..e12b5c795dc 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFiles.java +++ b/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFiles.java @@ -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/BatchAnnotateFilesGcs.java index dce825fd025..18c65d3755f 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFilesGcs.java +++ b/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFilesGcs.java @@ -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/Detect.java b/vision/cloud-client/src/main/java/com/example/vision/Detect.java index ae84a53ed70..7b9308b52d5 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 @@ -95,19 +95,19 @@ public static void main(String[] args) throws Exception, IOException { 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" + out.format( + "\tmvn exec:java -DDetect -Dexec.args=\" \"%n" + "\tmvn exec:java -DDetect -Dexec.args=\"ocr \"" - + "\n" - + "Commands:\n" + + "%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"); + + "| 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]; @@ -219,20 +219,23 @@ public static void detectFaces(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()); + 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()) { - out.printf( - "anger: %s\njoy: %s\nsurprise: %s\nposition: %s", + out.format( + "anger: %s%njoy: %s%nsurprise: %s%nposition: %s", annotation.getAngerLikelihood(), annotation.getJoyLikelihood(), annotation.getSurpriseLikelihood(), @@ -264,20 +267,23 @@ public static void detectFacesGcs(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()); + 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()) { - out.printf( - "anger: %s\njoy: %s\nsurprise: %s\nposition: %s", + out.format( + "anger: %s%njoy: %s%nsurprise: %s%nposition: %s", annotation.getAngerLikelihood(), annotation.getJoyLikelihood(), annotation.getSurpriseLikelihood(), @@ -308,19 +314,22 @@ public static void detectLabels(String filePath, 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()); + 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) -> out.printf("%s : %s\n", k, v.toString())); + annotation.getAllFields().forEach((k, v) -> out.format("%s : %s%n", k, v.toString())); } } } @@ -348,19 +357,22 @@ public static void detectLabelsGcs(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()); + 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) -> out.printf("%s : %s\n", k, v.toString())); + annotation.getAllFields().forEach((k, v) -> out.format("%s : %s%n", k, v.toString())); } } } @@ -387,20 +399,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()); + 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()); + out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } @@ -425,20 +440,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()); + 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()); + out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } @@ -465,20 +483,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()); + 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()); + out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } @@ -505,13 +526,16 @@ 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()); + out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -544,13 +568,16 @@ 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()); + out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -583,20 +610,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()); + 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()); + out.format("Text: %s%n", annotation.getDescription()); + out.format("Position : %s%n", annotation.getBoundingPoly()); } } } @@ -622,20 +652,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()); + 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()); + out.format("Text: %s%n", annotation.getDescription()); + out.format("Position : %s%n", annotation.getBoundingPoly()); } } } @@ -663,21 +696,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()); + 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", + out.format( + "fraction: %f%nr: %f, g: %f, b: %f%n", color.getPixelFraction(), color.getColor().getRed(), color.getColor().getGreen(), @@ -709,21 +745,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()); + 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", + out.format( + "fraction: %f%nr: %f, g: %f, b: %f%n", color.getPixelFraction(), color.getColor().getRed(), color.getColor().getGreen(), @@ -755,20 +794,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()); + 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", + out.format( + "adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n", annotation.getAdult(), annotation.getMedical(), annotation.getSpoof(), @@ -800,20 +842,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()); + 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", + out.format( + "adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n", annotation.getAdult(), annotation.getMedical(), annotation.getSpoof(), @@ -845,13 +890,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()); + out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -866,21 +914,21 @@ public static void detectWebDetections(String filePath, PrintStream out) entity.getDescription() + " : " + entity.getEntityId() + " : " + entity.getScore()); } for (WebLabel label : annotation.getBestGuessLabelsList()) { - out.format("\nBest guess label: %s", label.getLabel()); + out.format("%nBest guess label: %s", label.getLabel()); } - out.println("\nPages with matching images: Score\n=="); + out.println("%nPages with matching images: Score%n=="); for (WebPage page : annotation.getPagesWithMatchingImagesList()) { out.println(page.getUrl() + " : " + page.getScore()); } - out.println("\nPages with partially matching images: Score\n=="); + out.println("%nPages with partially matching images: Score%n=="); for (WebImage image : annotation.getPartialMatchingImagesList()) { out.println(image.getUrl() + " : " + image.getScore()); } - out.println("\nPages with fully matching images: Score\n=="); + out.println("%nPages with fully matching images: Score%n=="); for (WebImage image : annotation.getFullMatchingImagesList()) { out.println(image.getUrl() + " : " + image.getScore()); } - out.println("\nPages with visually similar images: Score\n=="); + out.println("%nPages with visually similar images: Score%n=="); for (WebImage image : annotation.getVisuallySimilarImagesList()) { out.println(image.getUrl() + " : " + image.getScore()); } @@ -910,13 +958,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()); + out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -931,21 +982,21 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) entity.getDescription() + " : " + entity.getEntityId() + " : " + entity.getScore()); } for (WebLabel label : annotation.getBestGuessLabelsList()) { - out.format("\nBest guess label: %s", label.getLabel()); + out.format("%nBest guess label: %s", label.getLabel()); } - out.println("\nPages with matching images: Score\n=="); + out.println("%nPages with matching images: Score%n=="); for (WebPage page : annotation.getPagesWithMatchingImagesList()) { out.println(page.getUrl() + " : " + page.getScore()); } - out.println("\nPages with partially matching images: Score\n=="); + out.println("%nPages with partially matching images: Score%n=="); for (WebImage image : annotation.getPartialMatchingImagesList()) { out.println(image.getUrl() + " : " + image.getScore()); } - out.println("\nPages with fully matching images: Score\n=="); + out.println("%nPages with fully matching images: Score%n=="); for (WebImage image : annotation.getFullMatchingImagesList()) { out.println(image.getUrl() + " : " + image.getScore()); } - out.println("\nPages with visually similar images: Score\n=="); + out.println("%nPages with visually similar images: Score%n=="); for (WebImage image : annotation.getVisuallySimilarImagesList()) { out.println(image.getUrl() + " : " + image.getScore()); } @@ -964,7 +1015,10 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) */ public static void detectWebEntities(String filePath, PrintStream out) 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)); @@ -993,8 +1047,8 @@ public static void detectWebEntities(String filePath, PrintStream out) .stream() .forEach( entity -> { - out.format("Description: %s\n", entity.getDescription()); - out.format("Score: %f\n", entity.getScore()); + out.format("Description: %s%n", entity.getDescription()); + out.format("Score: %f%n", entity.getScore()); })); } } @@ -1009,7 +1063,10 @@ public static void detectWebEntities(String filePath, PrintStream out) */ public static void detectWebEntitiesGcs(String gcsPath, PrintStream out) 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(); @@ -1037,8 +1094,8 @@ public static void detectWebEntitiesGcs(String gcsPath, PrintStream out) .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()); })); } } @@ -1054,7 +1111,10 @@ public static void detectWebEntitiesGcs(String gcsPath, PrintStream out) */ public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStream out) 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)); @@ -1092,8 +1152,8 @@ public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStre .stream() .forEach( entity -> { - out.format("Description: %s\n", entity.getDescription()); - out.format("Score: %f\n", entity.getScore()); + out.format("Description: %s%n", entity.getDescription()); + out.format("Score: %f%n", entity.getScore()); })); } } @@ -1111,7 +1171,10 @@ public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStre */ public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath, PrintStream out) 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(); @@ -1148,8 +1211,8 @@ public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath, PrintSt .stream() .forEach( entity -> { - out.format("Description: %s\n", entity.getDescription()); - out.format("Score: %f\n", entity.getScore()); + out.format("Description: %s%n", entity.getDescription()); + out.format("Score: %f%n", entity.getScore()); })); } } @@ -1176,13 +1239,16 @@ 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()); + out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -1216,13 +1282,16 @@ 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()); + out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -1257,6 +1326,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 +1336,7 @@ public static void detectDocumentText(String filePath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); + out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -1281,21 +1353,21 @@ public static void detectDocumentText(String filePath, PrintStream out) for (Symbol symbol : word.getSymbolsList()) { wordText = wordText + symbol.getText(); out.format( - "Symbol text: %s (confidence: %f)\n", + "Symbol text: %s (confidence: %f)%n", symbol.getText(), symbol.getConfidence()); } - out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence()); + out.format("Word text: %s (confidence: %f)%n%n", wordText, word.getConfidence()); paraText = String.format("%s %s", paraText, wordText); } // Output Example using Paragraph: - out.println("\nParagraph: \n" + paraText); - out.format("Paragraph Confidence: %f\n", para.getConfidence()); + out.println("%nParagraph: %n" + paraText); + out.format("Paragraph Confidence: %f%n", para.getConfidence()); blockText = blockText + paraText; } pageText = pageText + blockText; } } - out.println("\nComplete annotation:"); + out.println("%nComplete annotation:"); out.println(annotation.getText()); } } @@ -1322,6 +1394,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 +1404,7 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.printf("Error: %s\n", res.getError().getMessage()); + out.format("Error: %s%n", res.getError().getMessage()); return; } // For full list of available annotations, see http://g.co/cloud/vision/docs @@ -1345,21 +1420,21 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) for (Symbol symbol : word.getSymbolsList()) { wordText = wordText + symbol.getText(); out.format( - "Symbol text: %s (confidence: %f)\n", + "Symbol text: %s (confidence: %f)%n", symbol.getText(), symbol.getConfidence()); } - out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence()); + out.format("Word text: %s (confidence: %f)%n%n", wordText, word.getConfidence()); paraText = String.format("%s %s", paraText, wordText); } // Output Example using Paragraph: - out.println("\nParagraph: \n" + paraText); - out.format("Paragraph Confidence: %f\n", para.getConfidence()); + out.println("%nParagraph: %n" + paraText); + out.format("Paragraph Confidence: %f%n", para.getConfidence()); blockText = blockText + paraText; } pageText = pageText + blockText; } } - out.println("\nComplete annotation:"); + out.println("%nComplete annotation:"); out.println(annotation.getText()); } } @@ -1378,6 +1453,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<>(); @@ -1475,7 +1554,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"); } @@ -1506,21 +1585,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"); + out.format("Object name: %s%n", entity.getName()); + out.format("Confidence: %s%n", entity.getScore()); + out.format("Normalized Vertices:%n"); entity .getBoundingPoly() .getNormalizedVerticesList() - .forEach(vertex -> out.format("- (%s, %s)\n", vertex.getX(), vertex.getY())); + .forEach(vertex -> out.format("- (%s, %s)%n", vertex.getX(), vertex.getY())); } } } @@ -1551,21 +1633,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"); + out.format("Object name: %s%n", entity.getName()); + out.format("Confidence: %s%n", entity.getScore()); + out.format("Normalized Vertices:%n"); entity .getBoundingPoly() .getNormalizedVerticesList() - .forEach(vertex -> out.format("- (%s, %s)\n", vertex.getX(), vertex.getY())); + .forEach(vertex -> 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/QuickstartSample.java index b88233612d9..7d8c1f47e2c 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java +++ b/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java @@ -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/SetEndpoint.java b/vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java index 22eed6813d4..c6eaf8e4b31 100644 --- a/vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java +++ b/vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java @@ -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(); From de46cb13e23499b6c8d6038c4285fde62a19fd2f Mon Sep 17 00:00:00 2001 From: Mike Ganbold Date: Wed, 27 May 2020 18:14:02 -0700 Subject: [PATCH 2/4] started breaking down detect file --- vision/cloud-client/pom.xml | 2 +- .../main/java/com/example/vision/Detect.java | 548 ++++-------------- .../{ => quickstart}/QuickstartSample.java | 2 +- .../AsyncBatchAnnotateImages.java | 2 +- .../{ => snippets}/BatchAnnotateFiles.java | 2 +- .../{ => snippets}/BatchAnnotateFilesGcs.java | 2 +- .../example/vision/snippets/DetectFaces.java | 65 +++ .../vision/snippets/DetectFacesGcs.java | 64 ++ .../example/vision/snippets/DetectLabels.java | 60 ++ .../vision/snippets/DetectLabelsGcs.java | 59 ++ .../vision/{ => snippets}/SetEndpoint.java | 6 +- .../vision/AsyncBatchAnnotateImagesTest.java | 1 + .../vision/BatchAnnotateFilesGcsTest.java | 2 + .../vision/BatchAnnotateFilesTest.java | 2 + .../example/vision/DetectFacesGcsTest.java | 63 ++ .../com/example/vision/DetectFacesTest.java | 60 ++ .../java/com/example/vision/DetectIT.java | 130 +---- .../example/vision/DetectLabelsGcsTest.java | 61 ++ .../com/example/vision/DetectLabelsTest.java | 58 ++ .../com/example/vision/SetEndpointIT.java | 2 + 20 files changed, 641 insertions(+), 550 deletions(-) rename vision/cloud-client/src/main/java/com/example/vision/{ => quickstart}/QuickstartSample.java (98%) rename vision/cloud-client/src/main/java/com/example/vision/{ => snippets}/AsyncBatchAnnotateImages.java (99%) rename vision/cloud-client/src/main/java/com/example/vision/{ => snippets}/BatchAnnotateFiles.java (99%) rename vision/cloud-client/src/main/java/com/example/vision/{ => snippets}/BatchAnnotateFilesGcs.java (99%) create mode 100644 vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFaces.java create mode 100644 vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFacesGcs.java create mode 100644 vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabels.java create mode 100644 vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabelsGcs.java rename vision/cloud-client/src/main/java/com/example/vision/{ => snippets}/SetEndpoint.java (95%) create mode 100644 vision/cloud-client/src/test/java/com/example/vision/DetectFacesGcsTest.java create mode 100644 vision/cloud-client/src/test/java/com/example/vision/DetectFacesTest.java create mode 100644 vision/cloud-client/src/test/java/com/example/vision/DetectLabelsGcsTest.java create mode 100644 vision/cloud-client/src/test/java/com/example/vision/DetectLabelsTest.java 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 7b9308b52d5..f1da41642f7 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,319 +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.format( - "\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); - - // 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.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()) { - out.format( - "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); - - // 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.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()) { - out.format( - "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); - - // 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.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) -> out.format("%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); - - // 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.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) -> out.format("%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) + public static void detectLandmarks(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -408,14 +102,14 @@ public static void detectLandmarks(String filePath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); + System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } @@ -426,11 +120,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(); @@ -449,14 +142,14 @@ public static void detectLandmarksUrl(String uri, PrintStream out) throws Except for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); + System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } @@ -467,12 +160,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) + public static void detectLandmarksGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -492,14 +184,14 @@ public static void detectLandmarksGcs(String gcsPath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); + System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); } } } @@ -510,12 +202,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)); @@ -535,13 +226,13 @@ public static void detectLogos(String filePath, PrintStream out) throws Exceptio for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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()); } } } @@ -553,12 +244,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(); @@ -577,13 +267,13 @@ public static void detectLogosGcs(String gcsPath, PrintStream out) throws Except for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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()); } } } @@ -594,12 +284,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)); @@ -619,14 +308,14 @@ public static void detectText(String filePath, PrintStream out) throws Exception for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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.format("Text: %s%n", annotation.getDescription()); - out.format("Position : %s%n", annotation.getBoundingPoly()); + System.out.format("Text: %s%n", annotation.getDescription()); + System.out.format("Position : %s%n", annotation.getBoundingPoly()); } } } @@ -637,12 +326,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(); @@ -661,14 +349,14 @@ public static void detectTextGcs(String gcsPath, PrintStream out) throws Excepti for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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.format("Text: %s%n", annotation.getDescription()); - out.format("Position : %s%n", annotation.getBoundingPoly()); + System.out.format("Text: %s%n", annotation.getDescription()); + System.out.format("Position : %s%n", annotation.getBoundingPoly()); } } } @@ -679,12 +367,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) + public static void detectProperties(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -705,14 +392,14 @@ public static void detectProperties(String filePath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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.format( + System.out.format( "fraction: %f%nr: %f, g: %f, b: %f%n", color.getPixelFraction(), color.getColor().getRed(), @@ -729,12 +416,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) + public static void detectPropertiesGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -754,14 +440,14 @@ public static void detectPropertiesGcs(String gcsPath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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.format( + System.out.format( "fraction: %f%nr: %f, g: %f, b: %f%n", color.getPixelFraction(), color.getColor().getRed(), @@ -777,12 +463,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) + public static void detectSafeSearch(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -803,13 +488,13 @@ public static void detectSafeSearch(String filePath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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.format( + System.out.format( "adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n", annotation.getAdult(), annotation.getMedical(), @@ -826,12 +511,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) + public static void detectSafeSearchGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -851,13 +535,13 @@ public static void detectSafeSearchGcs(String gcsPath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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.format( + System.out.format( "adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n", annotation.getAdult(), annotation.getMedical(), @@ -874,11 +558,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) + public static void detectWebDetections(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -899,7 +582,7 @@ public static void detectWebDetections(String filePath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("Error: %s%n", res.getError().getMessage()); + System.out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -907,30 +590,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()); } } } @@ -943,11 +626,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) + public static void detectWebDetectionsGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -967,7 +649,7 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("Error: %s%n", res.getError().getMessage()); + System.out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -975,30 +657,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()); } } } @@ -1009,11 +691,10 @@ 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) + 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 @@ -1047,8 +728,8 @@ public static void detectWebEntities(String filePath, PrintStream out) .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()); })); } } @@ -1057,11 +738,10 @@ 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) + 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 @@ -1105,11 +785,10 @@ 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 { // Initialize client that will be used to send requests. This client only needs to be created @@ -1152,8 +831,8 @@ public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStre .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()); })); } } @@ -1165,11 +844,10 @@ 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 { // Initialize client that will be used to send requests. This client only needs to be created @@ -1211,8 +889,8 @@ public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath, PrintSt .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()); })); } } @@ -1222,12 +900,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) + public static void detectCropHints(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -1248,14 +925,14 @@ public static void detectCropHints(String filePath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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()); } } } @@ -1266,12 +943,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) + public static void detectCropHintsGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -1291,14 +967,14 @@ public static void detectCropHintsGcs(String gcsPath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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()); } } } @@ -1309,12 +985,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) + public static void detectDocumentText(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -1336,7 +1011,7 @@ public static void detectDocumentText(String filePath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("Error: %s%n", res.getError().getMessage()); + System.out.format("Error: %s%n", res.getError().getMessage()); return; } @@ -1352,23 +1027,23 @@ public static void detectDocumentText(String filePath, PrintStream out) String wordText = ""; for (Symbol symbol : word.getSymbolsList()) { wordText = wordText + symbol.getText(); - out.format( + 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,12 +1053,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) + public static void detectDocumentTextGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -1404,7 +1078,7 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) for (AnnotateImageResponse res : responses) { if (res.hasError()) { - out.format("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 @@ -1419,23 +1093,23 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) String wordText = ""; for (Symbol symbol : word.getSymbolsList()) { wordText = wordText + symbol.getText(); - out.format( + 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()); } } } @@ -1476,8 +1150,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(); @@ -1505,8 +1179,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 @@ -1528,7 +1202,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) { @@ -1567,11 +1241,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) + public static void detectLocalizedObjects(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -1596,13 +1269,13 @@ public static void detectLocalizedObjects(String filePath, PrintStream out) // 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())); } } } @@ -1615,11 +1288,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) + public static void detectLocalizedObjectsGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); @@ -1644,13 +1316,13 @@ public static void detectLocalizedObjectsGcs(String gcsPath, PrintStream out) // 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 98% 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 7d8c1f47e2c..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 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 99% 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 032d6375dc5..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; 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 99% 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 e12b5c795dc..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; 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 99% 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 18c65d3755f..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; 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..c78a7c6fa1a --- /dev/null +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFaces.java @@ -0,0 +1,65 @@ +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..41c125c5551 --- /dev/null +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectFacesGcs.java @@ -0,0 +1,64 @@ +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..6a5bc7fb203 --- /dev/null +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabels.java @@ -0,0 +1,60 @@ +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..e71cb6c0606 --- /dev/null +++ b/vision/cloud-client/src/main/java/com/example/vision/snippets/DetectLabelsGcs.java @@ -0,0 +1,59 @@ +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 95% 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 c6eaf8e4b31..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(); 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..a64dc0e2535 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 @@ -21,6 +21,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; + +import com.example.vision.snippets.BatchAnnotateFilesGcs; import org.junit.After; import org.junit.Before; import org.junit.Test; 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..edcb837c734 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 @@ -21,6 +21,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; + +import com.example.vision.snippets.BatchAnnotateFiles; import org.junit.After; import org.junit.Before; import org.junit.Test; 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..a5fdb199708 --- /dev/null +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectFacesGcsTest.java @@ -0,0 +1,63 @@ +/* + * 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 com.example.vision.snippets.DetectFacesGcs; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static com.google.common.truth.Truth.assertThat; + +@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..0951a48b622 --- /dev/null +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectFacesTest.java @@ -0,0 +1,60 @@ +/* + * 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 com.example.vision.snippets.DetectFaces; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static com.google.common.truth.Truth.assertThat; + +@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..53c2741ee73 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 @@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat; +import com.example.vision.snippets.DetectFaces; import com.google.api.gax.paging.Page; import com.google.cloud.storage.Blob; import com.google.cloud.storage.Storage; @@ -56,59 +57,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 +70,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 +82,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 +92,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 +102,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 +112,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 +122,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 +132,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 +143,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 +154,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 +167,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 +180,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 +191,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 +202,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 +212,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.detectWebDetectionsGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); String got = bout.toString().toLowerCase(); assertThat(got).contains("description"); @@ -283,8 +221,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 +232,7 @@ 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,8 @@ 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 +312,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 +322,7 @@ 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.detectLogosGcs("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..64a996e7770 --- /dev/null +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsGcsTest.java @@ -0,0 +1,61 @@ +/* + * 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 com.example.vision.snippets.DetectLabelsGcs; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static com.google.common.truth.Truth.assertThat; + +@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..419c0f9a5f5 --- /dev/null +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsTest.java @@ -0,0 +1,58 @@ +/* + * 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 com.example.vision.snippets.DetectLabels; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static com.google.common.truth.Truth.assertThat; + +@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..e0e2c46b2c8 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 @@ -21,6 +21,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; + +import com.example.vision.snippets.SetEndpoint; import org.junit.After; import org.junit.Before; import org.junit.Test; From 4998e311f478161f62dddd57e6860176257acf51 Mon Sep 17 00:00:00 2001 From: Mike Ganbold Date: Wed, 27 May 2020 18:19:19 -0700 Subject: [PATCH 3/4] nits --- .../src/test/java/com/example/vision/DetectIT.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 53c2741ee73..50ab90f8c6d 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 @@ -212,7 +212,7 @@ public void testDetectWebEntities() throws Exception { @Test public void testDetectWebEntitiesGcs() throws Exception { // Act - Detect.detectWebDetectionsGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); + Detect.detectWebEntitiesGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); String got = bout.toString().toLowerCase(); assertThat(got).contains("description"); @@ -322,7 +322,7 @@ public void testDetectLocalizedObjects() throws Exception { @Test public void testDetectLocalizedObjectsGcs() throws Exception { // Act - Detect.detectLogosGcs("gs://cloud-samples-data/vision/object_localization/puppies.jpg"); + Detect.detectLocalizedObjectsGcs("gs://cloud-samples-data/vision/object_localization/puppies.jpg"); // Assert String got = bout.toString().toLowerCase(); From 970aa006ff252b80e86b8df9fc08518464a81a23 Mon Sep 17 00:00:00 2001 From: Mike Ganbold Date: Thu, 28 May 2020 11:17:20 -0700 Subject: [PATCH 4/4] formatted new files --- .../main/java/com/example/vision/Detect.java | 86 ++++++------------- .../example/vision/snippets/DetectFaces.java | 29 +++++-- .../vision/snippets/DetectFacesGcs.java | 29 +++++-- .../example/vision/snippets/DetectLabels.java | 23 ++++- .../vision/snippets/DetectLabelsGcs.java | 26 ++++-- .../vision/BatchAnnotateFilesGcsTest.java | 3 +- .../vision/BatchAnnotateFilesTest.java | 3 +- .../example/vision/DetectFacesGcsTest.java | 9 +- .../com/example/vision/DetectFacesTest.java | 9 +- .../java/com/example/vision/DetectIT.java | 16 ++-- .../example/vision/DetectLabelsGcsTest.java | 12 ++- .../com/example/vision/DetectLabelsTest.java | 9 +- .../com/example/vision/SetEndpointIT.java | 3 +- 13 files changed, 142 insertions(+), 115 deletions(-) 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 f1da41642f7..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 @@ -82,8 +82,7 @@ public class Detect { * @throws IOException on Input/Output errors. */ // [START vision_landmark_detection] - public static void detectLandmarks(String filePath) - throws Exception, IOException { + public static void detectLandmarks(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -164,8 +163,7 @@ public static void detectLandmarksUrl(String uri) throws Exception, IOException * @throws IOException on Input/Output errors. */ // [START vision_landmark_detection_gcs] - public static void detectLandmarksGcs(String gcsPath) - throws Exception, IOException { + public static void detectLandmarksGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -371,8 +369,7 @@ public static void detectTextGcs(String gcsPath) throws Exception, IOException { * @throws IOException on Input/Output errors. */ // [START vision_image_property_detection] - public static void detectProperties(String filePath) - throws Exception, IOException { + public static void detectProperties(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -420,8 +417,7 @@ public static void detectProperties(String filePath) * @throws IOException on Input/Output errors. */ // [START vision_image_property_detection_gcs] - public static void detectPropertiesGcs(String gcsPath) - throws Exception, IOException { + public static void detectPropertiesGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -467,8 +463,7 @@ public static void detectPropertiesGcs(String gcsPath) * @throws IOException on Input/Output errors. */ // [START vision_safe_search_detection] - public static void detectSafeSearch(String filePath) - throws Exception, IOException { + public static void detectSafeSearch(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -515,8 +510,7 @@ public static void detectSafeSearch(String filePath) * @throws IOException on Input/Output errors. */ // [START vision_safe_search_detection_gcs] - public static void detectSafeSearchGcs(String gcsPath) - throws Exception, IOException { + public static void detectSafeSearchGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -561,8 +555,7 @@ public static void detectSafeSearchGcs(String gcsPath) * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectWebDetections(String filePath) - throws Exception, IOException { + public static void detectWebDetections(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -629,8 +622,7 @@ public static void detectWebDetections(String filePath) * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectWebDetectionsGcs(String gcsPath) - throws Exception, IOException { + public static void detectWebDetectionsGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -694,8 +686,7 @@ public static void detectWebDetectionsGcs(String gcsPath) * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectWebEntities(String filePath) - throws Exception, IOException { + 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 @@ -718,14 +709,10 @@ public static void detectWebEntities(String filePath) 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()); @@ -741,8 +728,7 @@ public static void detectWebEntities(String filePath) * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectWebEntitiesGcs(String gcsPath) - throws Exception, IOException { + 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 @@ -764,14 +750,10 @@ public static void detectWebEntitiesGcs(String gcsPath) 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()); @@ -821,14 +803,10 @@ public static void detectWebEntitiesIncludeGeoResults(String filePath) 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()); @@ -879,14 +857,10 @@ public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath) 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()); @@ -904,8 +878,7 @@ public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath) * @throws IOException on Input/Output errors. */ // [START vision_crop_hint_detection] - public static void detectCropHints(String filePath) - throws Exception, IOException { + public static void detectCropHints(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -947,8 +920,7 @@ public static void detectCropHints(String filePath) * @throws IOException on Input/Output errors. */ // [START vision_crop_hint_detection_gcs] - public static void detectCropHintsGcs(String gcsPath) - throws Exception, IOException { + public static void detectCropHintsGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -989,8 +961,7 @@ public static void detectCropHintsGcs(String gcsPath) * @throws IOException on Input/Output errors. */ // [START vision_fulltext_detection] - public static void detectDocumentText(String filePath) - throws Exception, IOException { + public static void detectDocumentText(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -1031,7 +1002,8 @@ public static void detectDocumentText(String filePath) "Symbol text: %s (confidence: %f)%n", symbol.getText(), symbol.getConfidence()); } - System.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: @@ -1057,8 +1029,7 @@ public static void detectDocumentText(String filePath) * @throws IOException on Input/Output errors. */ // [START vision_fulltext_detection_gcs] - public static void detectDocumentTextGcs(String gcsPath) - throws Exception, IOException { + public static void detectDocumentTextGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); @@ -1097,7 +1068,8 @@ public static void detectDocumentTextGcs(String gcsPath) "Symbol text: %s (confidence: %f)%n", symbol.getText(), symbol.getConfidence()); } - System.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: @@ -1244,8 +1216,7 @@ public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinatio * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLocalizedObjects(String filePath) - throws Exception, IOException { + public static void detectLocalizedObjects(String filePath) throws Exception, IOException { List requests = new ArrayList<>(); ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); @@ -1291,8 +1262,7 @@ public static void detectLocalizedObjects(String filePath) * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ - public static void detectLocalizedObjectsGcs(String gcsPath) - throws Exception, IOException { + public static void detectLocalizedObjectsGcs(String gcsPath) throws Exception, IOException { List requests = new ArrayList<>(); ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); 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 index c78a7c6fa1a..4c07fa08080 100644 --- 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 @@ -1,3 +1,19 @@ +/* + * 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] @@ -10,7 +26,6 @@ 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; @@ -33,7 +48,7 @@ public static void detectFaces(String filePath) throws IOException { 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(); + 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 @@ -52,11 +67,11 @@ public static void detectFaces(String filePath) throws IOException { // 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()); + "anger: %s%njoy: %s%nsurprise: %s%nposition: %s", + annotation.getAngerLikelihood(), + annotation.getJoyLikelihood(), + annotation.getSurpriseLikelihood(), + annotation.getBoundingPoly()); } } } 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 index 41c125c5551..b325623e761 100644 --- 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 @@ -1,3 +1,19 @@ +/* + * 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] @@ -10,7 +26,6 @@ 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; @@ -32,7 +47,7 @@ public static void detectFacesGcs(String gcsPath) throws IOException { Feature feat = Feature.newBuilder().setType(Feature.Type.FACE_DETECTION).build(); AnnotateImageRequest request = - AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); + 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 @@ -51,11 +66,11 @@ public static void detectFacesGcs(String gcsPath) throws IOException { // 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()); + "anger: %s%njoy: %s%nsurprise: %s%nposition: %s", + annotation.getAngerLikelihood(), + annotation.getJoyLikelihood(), + annotation.getSurpriseLikelihood(), + annotation.getBoundingPoly()); } } } 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 index 6a5bc7fb203..87563bb3ca6 100644 --- 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 @@ -1,3 +1,19 @@ +/* + * 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] @@ -10,7 +26,6 @@ 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; @@ -33,7 +48,7 @@ public static void detectLabels(String filePath) throws IOException { 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(); + 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 @@ -51,7 +66,9 @@ public static void detectLabels(String filePath) throws IOException { // 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())); + annotation + .getAllFields() + .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString())); } } } 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 index e71cb6c0606..53e8dfe5351 100644 --- 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 @@ -1,3 +1,19 @@ +/* + * 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] @@ -10,7 +26,6 @@ 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; @@ -24,15 +39,14 @@ public static void detectLabelsGcs() throws IOException { } // Detects labels in the specified remote image on Google Cloud Storage. - public static void detectLabelsGcs(String gcsPath) - throws IOException { + 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(); + 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 @@ -50,7 +64,9 @@ public static void detectLabelsGcs(String gcsPath) // 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())); + annotation + .getAllFields() + .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString())); } } } 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 a64dc0e2535..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,11 +18,10 @@ 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; - -import com.example.vision.snippets.BatchAnnotateFilesGcs; import org.junit.After; import org.junit.Before; import org.junit.Test; 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 edcb837c734..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,11 +18,10 @@ 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; - -import com.example.vision.snippets.BatchAnnotateFiles; import org.junit.After; import org.junit.Before; import org.junit.Test; 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 index a5fdb199708..8de0dac2d22 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/DetectFacesGcsTest.java +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectFacesGcsTest.java @@ -16,18 +16,17 @@ 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; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import static com.google.common.truth.Truth.assertThat; - @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class DetectFacesGcsTest { 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 index 0951a48b622..d009212739d 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/DetectFacesTest.java +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectFacesTest.java @@ -16,18 +16,17 @@ 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; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import static com.google.common.truth.Truth.assertThat; - @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class DetectFacesTest { 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 50ab90f8c6d..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 @@ -18,7 +18,6 @@ import static com.google.common.truth.Truth.assertThat; -import com.example.vision.snippets.DetectFaces; import com.google.api.gax.paging.Page; import com.google.cloud.storage.Blob; import com.google.cloud.storage.Storage; @@ -221,7 +220,7 @@ public void testDetectWebEntitiesGcs() throws Exception { @Test public void testDetectWebEntitiesIncludeGeoResults() throws Exception { // Act - Detect.detectWebEntitiesIncludeGeoResults( "./resources/city.jpg"); + Detect.detectWebEntitiesIncludeGeoResults("./resources/city.jpg"); // Assert String got = bout.toString().toLowerCase(); @@ -232,7 +231,8 @@ public void testDetectWebEntitiesIncludeGeoResults() throws Exception { @Test public void testDetectWebEntitiesIncludeGeoResultsGcs() throws Exception { // Act - Detect.detectWebEntitiesIncludeGeoResultsGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); + Detect.detectWebEntitiesIncludeGeoResultsGcs( + "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); String got = bout.toString().toLowerCase(); assertThat(got).contains("description"); @@ -289,8 +289,9 @@ public void testDocumentTextGcs() throws Exception { @Test public void testDetectDocumentsGcs() throws Exception { // Act - Detect.detectDocumentsGcs("gs://" + ASSET_BUCKET + "/vision/document/custom_0773375000.pdf", - "gs://" + OUTPUT_BUCKET + "/" + OUTPUT_PREFIX + "/"); + Detect.detectDocumentsGcs( + "gs://" + ASSET_BUCKET + "/vision/document/custom_0773375000.pdf", + "gs://" + OUTPUT_BUCKET + "/" + OUTPUT_PREFIX + "/"); // Assert String got = bout.toString(); @@ -312,7 +313,7 @@ public void testDetectDocumentsGcs() throws Exception { @Test public void testDetectLocalizedObjects() throws Exception { // Act - Detect.detectLocalizedObjects( "./resources/puppies.jpg"); + Detect.detectLocalizedObjects("./resources/puppies.jpg"); // Assert String got = bout.toString().toLowerCase(); @@ -322,7 +323,8 @@ public void testDetectLocalizedObjects() throws Exception { @Test public void testDetectLocalizedObjectsGcs() throws Exception { // Act - Detect.detectLocalizedObjectsGcs("gs://cloud-samples-data/vision/object_localization/puppies.jpg"); + 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 index 64a996e7770..9ddb0e2e515 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsGcsTest.java +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsGcsTest.java @@ -16,18 +16,17 @@ 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; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import static com.google.common.truth.Truth.assertThat; - @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class DetectLabelsGcsTest { @@ -48,11 +47,10 @@ public void tearDown() { System.setOut(null); } - @Test public void testLabelsGcs() throws Exception { // Act - DetectLabelsGcs.detectLabelsGcs( "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"); + DetectLabelsGcs.detectLabelsGcs("gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"); // Assert String got = bout.toString().toLowerCase(); 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 index 419c0f9a5f5..741b2f63142 100644 --- a/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsTest.java +++ b/vision/cloud-client/src/test/java/com/example/vision/DetectLabelsTest.java @@ -16,18 +16,17 @@ 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; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import static com.google.common.truth.Truth.assertThat; - @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class DetectLabelsTest { 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 e0e2c46b2c8..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,11 +18,10 @@ 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; - -import com.example.vision.snippets.SetEndpoint; import org.junit.After; import org.junit.Before; import org.junit.Test;