diff --git a/vision/snippets/pom.xml b/vision/snippets/pom.xml new file mode 100644 index 00000000000..8e2b0315c26 --- /dev/null +++ b/vision/snippets/pom.xml @@ -0,0 +1,82 @@ + + + 4.0.0 + com.example.vision + vision-snippets + jar + Google Cloud Vision Snippets + https://github.com/GoogleCloudPlatform/java-docs-samples/tree/main/vision + + + + com.google.cloud.samples + shared-configuration + 1.2.0 + + + + 1.8 + 1.8 + UTF-8 + + + + + + + + com.google.cloud + libraries-bom + 26.1.3 + pom + import + + + + + + + com.google.cloud + google-cloud-vision + + + + com.google.cloud + google-cloud-storage + + + net.sourceforge.argparse4j + argparse4j + 0.9.0 + + + org.apache.commons + commons-csv + 1.9.0 + + + junit + junit + 4.13.2 + test + + + com.google.cloud + google-cloud-core + 2.8.21 + test + tests + + + com.google.truth + truth + 1.1.3 + test + + + + + diff --git a/vision/snippets/resources/city.jpg b/vision/snippets/resources/city.jpg new file mode 100644 index 00000000000..b14282e7539 Binary files /dev/null and b/vision/snippets/resources/city.jpg differ diff --git a/vision/snippets/resources/face_no_surprise.jpg b/vision/snippets/resources/face_no_surprise.jpg new file mode 100644 index 00000000000..0e2894adb83 Binary files /dev/null and b/vision/snippets/resources/face_no_surprise.jpg differ diff --git a/vision/snippets/resources/gcp-logos.png b/vision/snippets/resources/gcp-logos.png new file mode 100644 index 00000000000..dcfb4ac955f Binary files /dev/null and b/vision/snippets/resources/gcp-logos.png differ diff --git a/vision/snippets/resources/handwritten.jpg b/vision/snippets/resources/handwritten.jpg new file mode 100644 index 00000000000..50a9575b5ad Binary files /dev/null and b/vision/snippets/resources/handwritten.jpg differ diff --git a/vision/snippets/resources/indexed_product_sets.csv b/vision/snippets/resources/indexed_product_sets.csv new file mode 100644 index 00000000000..e31f99f44e3 --- /dev/null +++ b/vision/snippets/resources/indexed_product_sets.csv @@ -0,0 +1,2 @@ +"gs://java-docs-samples-testing/product-search/shoes_1.jpg","indexed_product_set_id_for_testing","indexed_product_id_for_testing_1","apparel","style=womens","0.1,0.1,0.9,0.1,0.9,0.9,0.1,0.9" +"gs://java-docs-samples-testing/product-search/shoes_2.jpg","indexed_product_set_id_for_testing","indexed_product_id_for_testing_2","apparel",, \ No newline at end of file diff --git a/vision/snippets/resources/kafka.pdf b/vision/snippets/resources/kafka.pdf new file mode 100644 index 00000000000..ffa2e2fac2f Binary files /dev/null and b/vision/snippets/resources/kafka.pdf differ diff --git a/vision/snippets/resources/landmark.jpg b/vision/snippets/resources/landmark.jpg new file mode 100644 index 00000000000..41c3d0fc935 Binary files /dev/null and b/vision/snippets/resources/landmark.jpg differ diff --git a/vision/snippets/resources/logos.png b/vision/snippets/resources/logos.png new file mode 100644 index 00000000000..5538eaed2bd Binary files /dev/null and b/vision/snippets/resources/logos.png differ diff --git a/vision/snippets/resources/product_sets.csv b/vision/snippets/resources/product_sets.csv new file mode 100644 index 00000000000..314cd030f6c --- /dev/null +++ b/vision/snippets/resources/product_sets.csv @@ -0,0 +1,2 @@ +"gs://java-docs-samples-testing/product-search/shoes_1.jpg","fake_product_set_id_for_testing","fake_product_id_for_testing_1","apparel","style=womens","0.1,0.1,0.9,0.1,0.9,0.9,0.1,0.9" +"gs://java-docs-samples-testing/product-search/shoes_2.jpg","fake_product_set_id_for_testing","fake_product_id_for_testing_2","apparel",, \ No newline at end of file diff --git a/vision/snippets/resources/puppies.jpg b/vision/snippets/resources/puppies.jpg new file mode 100644 index 00000000000..1bfbbc9c5e4 Binary files /dev/null and b/vision/snippets/resources/puppies.jpg differ diff --git a/vision/snippets/resources/shoes_1.jpg b/vision/snippets/resources/shoes_1.jpg new file mode 100644 index 00000000000..78318eeff66 Binary files /dev/null and b/vision/snippets/resources/shoes_1.jpg differ diff --git a/vision/snippets/resources/shoes_2.jpg b/vision/snippets/resources/shoes_2.jpg new file mode 100644 index 00000000000..cdfa80dd899 Binary files /dev/null and b/vision/snippets/resources/shoes_2.jpg differ diff --git a/vision/snippets/resources/text.jpg b/vision/snippets/resources/text.jpg new file mode 100644 index 00000000000..3b17d55de0e Binary files /dev/null and b/vision/snippets/resources/text.jpg differ diff --git a/vision/snippets/resources/wakeupcat.jpg b/vision/snippets/resources/wakeupcat.jpg new file mode 100644 index 00000000000..139cf461eca Binary files /dev/null and b/vision/snippets/resources/wakeupcat.jpg differ diff --git a/vision/snippets/src/main/java/com/example/vision/AsyncBatchAnnotateImagesGcs.java b/vision/snippets/src/main/java/com/example/vision/AsyncBatchAnnotateImagesGcs.java new file mode 100644 index 00000000000..c63d8a2993b --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/AsyncBatchAnnotateImagesGcs.java @@ -0,0 +1,154 @@ +/* + * Copyright 2019 Google LLC + * + * 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; + +// [START vision_async_batch_annotate_images_beta] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Bucket; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.Storage.BlobListOption; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.vision.v1p4beta1.AnnotateImageRequest; +import com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesRequest; +import com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesResponse; +import com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse.Builder; +import com.google.cloud.vision.v1p4beta1.Feature; +import com.google.cloud.vision.v1p4beta1.Feature.Type; +import com.google.cloud.vision.v1p4beta1.GcsDestination; +import com.google.cloud.vision.v1p4beta1.Image; +import com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient; +import com.google.cloud.vision.v1p4beta1.ImageSource; +import com.google.cloud.vision.v1p4beta1.OperationMetadata; +import com.google.cloud.vision.v1p4beta1.OutputConfig; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class AsyncBatchAnnotateImagesGcs { + + // Performs asynchronous batch annotation of images on Google Cloud Storage + public static void asyncBatchAnnotateImagesGcs(String gcsSourcePath, String gcsDestinationPath) + throws Exception { + // String gcsSourcePath = "gs://YOUR_BUCKET_ID/path_to_your_data"; + // String gcsDestinationPath = "gs://YOUR_BUCKET_ID/path_to_store_annotation"; + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + List requests = new ArrayList<>(); + + ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsSourcePath).build(); + + Image image = Image.newBuilder().setSource(imgSource).build(); + + // Set the GCS destination path for where to save the results. + GcsDestination gcsDestination = + GcsDestination.newBuilder().setUri(gcsDestinationPath).build(); + + // Create the configuration for the output with the batch size. + // The batch size sets how many pages should be grouped into each json output file. + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).setBatchSize(2).build(); + + // Select the Features required by the vision API + Feature features = + Feature.newBuilder() + .setType(Type.LABEL_DETECTION) + .setType(Type.TEXT_DETECTION) + .setType(Type.IMAGE_PROPERTIES) + .build(); + + // Build the request + AnnotateImageRequest annotateImageRequest = + AnnotateImageRequest.newBuilder().setImage(image).addFeatures(features).build(); + + requests.add(annotateImageRequest); + AsyncBatchAnnotateImagesRequest request = + AsyncBatchAnnotateImagesRequest.newBuilder() + .addAllRequests(requests) + .setOutputConfig(outputConfig) + .build(); + + OperationFuture response = + client.asyncBatchAnnotateImagesAsync(request); + System.out.println("Waiting for the operation to finish."); + + // we're not processing the response, since we'll be reading the output from GCS. + response.get(180, TimeUnit.SECONDS); + + // Once the request has completed and the output has been + // written to GCS, we can list all the output files. + Storage storage = StorageOptions.getDefaultInstance().getService(); + + // Get the destination location from the gcsDestinationPath + Pattern pattern = Pattern.compile("gs://([^/]+)/(.+)"); + Matcher matcher = pattern.matcher(gcsDestinationPath); + + if (matcher.find()) { + String bucketName = matcher.group(1); + String prefix = matcher.group(2); + + // Get the list of objects with the given prefix from the GCS bucket + Bucket bucket = storage.get(bucketName); + Page pageList = bucket.list(BlobListOption.prefix(prefix)); + + Blob firstOutputFile = null; + + // List objects with the given prefix. + System.out.println("Output files:"); + for (Blob blob : pageList.iterateAll()) { + System.out.println(blob.getName()); + + // Process the first output file from GCS. + // Since we specified batch size = 2, the first response contains + // the first two image requests + if (firstOutputFile == null) { + firstOutputFile = blob; + } + } + + // Get the contents of the file and convert the JSON contents to an + // BatchAnnotateImagesResponse + // object. If the Blob is small read all its content in one request + // (Note: the file is a .json file) + // Storage guide: https://cloud.google.com/storage/docs/downloading-objects + String jsonContents = new String(firstOutputFile.getContent()); + Builder builder = BatchAnnotateImagesResponse.newBuilder(); + JsonFormat.parser().merge(jsonContents, builder); + + // Build the AnnotateFileResponse object + BatchAnnotateImagesResponse batchAnnotateImagesResponse = builder.build(); + + // Here we print the response for the first image + // The response contains more information: + // annotation/pages/blocks/paragraphs/words/symbols/colors + // including confidence score and bounding boxes + System.out.format("\nResponse: %s\n", batchAnnotateImagesResponse.getResponses(0)); + + } else { + System.out.println("No MATCH"); + } + } catch (Exception e) { + System.out.println("Error during asyncBatchAnnotateImagesGcs: \n" + e.toString()); + } + } +} + +// [END vision_async_batch_annotate_images_beta] diff --git a/vision/snippets/src/main/java/com/example/vision/Detect.java b/vision/snippets/src/main/java/com/example/vision/Detect.java new file mode 100644 index 00000000000..5beb7d143a2 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/Detect.java @@ -0,0 +1,406 @@ +/* + * 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.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Bucket; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.Storage.BlobListOption; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.vision.v1.AnnotateFileResponse; +import com.google.cloud.vision.v1.AnnotateFileResponse.Builder; +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.AsyncAnnotateFileRequest; +import com.google.cloud.vision.v1.AsyncAnnotateFileResponse; +import com.google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.Block; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Feature.Type; +import com.google.cloud.vision.v1.GcsDestination; +import com.google.cloud.vision.v1.GcsSource; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageSource; +import com.google.cloud.vision.v1.InputConfig; +import com.google.cloud.vision.v1.LocalizedObjectAnnotation; +import com.google.cloud.vision.v1.OperationMetadata; +import com.google.cloud.vision.v1.OutputConfig; +import com.google.cloud.vision.v1.Page; +import com.google.cloud.vision.v1.Paragraph; +import com.google.cloud.vision.v1.Symbol; +import com.google.cloud.vision.v1.TextAnnotation; +import com.google.cloud.vision.v1.Word; +import com.google.protobuf.ByteString; +import com.google.protobuf.util.JsonFormat; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Detect { + /** + * Performs document text detection on a local image file. + * + * @param filePath The path to the local file to detect document text on. + * @throws Exception on errors while closing the client. + * @throws IOException on Input/Output errors. + */ + // [START vision_fulltext_detection] + public static void detectDocumentText(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(Type.DOCUMENT_TEXT_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(); + client.close(); + + 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 + TextAnnotation annotation = res.getFullTextAnnotation(); + for (Page page : annotation.getPagesList()) { + String pageText = ""; + for (Block block : page.getBlocksList()) { + String blockText = ""; + for (Paragraph para : block.getParagraphsList()) { + String paraText = ""; + for (Word word : para.getWordsList()) { + String wordText = ""; + for (Symbol symbol : word.getSymbolsList()) { + wordText = wordText + symbol.getText(); + System.out.format( + "Symbol text: %s (confidence: %f)%n", + symbol.getText(), symbol.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: + System.out.println("%nParagraph: %n" + paraText); + System.out.format("Paragraph Confidence: %f%n", para.getConfidence()); + blockText = blockText + paraText; + } + pageText = pageText + blockText; + } + } + System.out.println("%nComplete annotation:"); + System.out.println(annotation.getText()); + } + } + } + // [END vision_fulltext_detection] + + /** + * 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. + * @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) 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(Type.DOCUMENT_TEXT_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(); + client.close(); + + 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 + TextAnnotation annotation = res.getFullTextAnnotation(); + for (Page page : annotation.getPagesList()) { + String pageText = ""; + for (Block block : page.getBlocksList()) { + String blockText = ""; + for (Paragraph para : block.getParagraphsList()) { + String paraText = ""; + for (Word word : para.getWordsList()) { + String wordText = ""; + for (Symbol symbol : word.getSymbolsList()) { + wordText = wordText + symbol.getText(); + System.out.format( + "Symbol text: %s (confidence: %f)%n", + symbol.getText(), symbol.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: + System.out.println("%nParagraph: %n" + paraText); + System.out.format("Paragraph Confidence: %f%n", para.getConfidence()); + blockText = blockText + paraText; + } + pageText = pageText + blockText; + } + } + System.out.println("%nComplete annotation:"); + System.out.println(annotation.getText()); + } + } + } + // [END vision_fulltext_detection_gcs] + + // [START vision_text_detection_pdf_gcs] + /** + * Performs document text OCR with PDF/TIFF as source files on Google Cloud Storage. + * + * @param gcsSourcePath The path to the remote file on Google Cloud Storage to detect document + * text on. + * @param gcsDestinationPath The path to the remote file on Google Cloud Storage to store the + * results on. + * @throws Exception on errors while closing the client. + */ + public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinationPath) + throws Exception { + + // 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<>(); + + // Set the GCS source path for the remote file. + GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsSourcePath).build(); + + // Create the configuration with the specified MIME (Multipurpose Internet Mail Extensions) + // types + InputConfig inputConfig = + InputConfig.newBuilder() + .setMimeType( + "application/pdf") // Supported MimeTypes: "application/pdf", "image/tiff" + .setGcsSource(gcsSource) + .build(); + + // Set the GCS destination path for where to save the results. + GcsDestination gcsDestination = + GcsDestination.newBuilder().setUri(gcsDestinationPath).build(); + + // Create the configuration for the 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(); + + // Select the Feature required by the vision API + Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build(); + + // Build the OCR request + AsyncAnnotateFileRequest request = + AsyncAnnotateFileRequest.newBuilder() + .addFeatures(feature) + .setInputConfig(inputConfig) + .setOutputConfig(outputConfig) + .build(); + + requests.add(request); + + // Perform the OCR request + OperationFuture response = + client.asyncBatchAnnotateFilesAsync(requests); + + System.out.println("Waiting for the operation to finish."); + + // Wait for the request to finish. (The result is not used, since the API saves the result to + // the specified location on GCS.) + List result = + response.get(180, TimeUnit.SECONDS).getResponsesList(); + + // Once the request has completed and the 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 + Pattern pattern = Pattern.compile("gs://([^/]+)/(.+)"); + Matcher matcher = pattern.matcher(gcsDestinationPath); + + if (matcher.find()) { + String bucketName = matcher.group(1); + String prefix = matcher.group(2); + + // Get the list of objects with the given prefix from the GCS bucket + Bucket bucket = storage.get(bucketName); + com.google.api.gax.paging.Page pageList = bucket.list(BlobListOption.prefix(prefix)); + + Blob firstOutputFile = null; + + // List objects with the given prefix. + System.out.println("Output files:"); + for (Blob blob : pageList.iterateAll()) { + System.out.println(blob.getName()); + + // Process the first 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) { + firstOutputFile = blob; + } + } + + // Get the contents of the file and convert the JSON contents to an AnnotateFileResponse + // object. If the Blob is small read all its content in one request + // (Note: the file is a .json file) + // Storage guide: https://cloud.google.com/storage/docs/downloading-objects + String jsonContents = new String(firstOutputFile.getContent()); + Builder builder = AnnotateFileResponse.newBuilder(); + JsonFormat.parser().merge(jsonContents, builder); + + // Build the AnnotateFileResponse object + AnnotateFileResponse annotateFileResponse = builder.build(); + + // Parse through the object to get the actual response for the first page of the input file. + AnnotateImageResponse annotateImageResponse = annotateFileResponse.getResponses(0); + + // Here we print the full text from the first page. + // The response contains more information: + // annotation/pages/blocks/paragraphs/words/symbols + // including confidence score and bounding boxes + System.out.format("%nText: %s%n", annotateImageResponse.getFullTextAnnotation().getText()); + } else { + System.out.println("No MATCH"); + } + } + } + // [END vision_text_detection_pdf_gcs] + + // [START vision_localize_objects] + /** + * Detects localized objects in the specified local image. + * + * @param filePath The path to the file to perform localized object detection on. + * @throws Exception on errors while closing the client. + * @throws IOException on Input/Output errors. + */ + public static void detectLocalizedObjects(String filePath) throws IOException { + List requests = new ArrayList<>(); + + ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); + + Image img = Image.newBuilder().setContent(imgBytes).build(); + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(Feature.newBuilder().setType(Type.OBJECT_LOCALIZATION)) + .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()) { + // Perform the request + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + // Display the results + for (AnnotateImageResponse res : responses) { + for (LocalizedObjectAnnotation entity : res.getLocalizedObjectAnnotationsList()) { + 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 -> System.out.format("- (%s, %s)%n", vertex.getX(), vertex.getY())); + } + } + } + } + // [END vision_localize_objects] + + // [START vision_localize_objects_gcs] + /** + * Detects localized objects in a remote image on Google Cloud Storage. + * + * @param gcsPath The path to the remote file on Google Cloud Storage to detect localized objects + * on. + * @throws Exception on errors while closing the client. + * @throws IOException on Input/Output errors. + */ + public static void detectLocalizedObjectsGcs(String gcsPath) throws IOException { + List requests = new ArrayList<>(); + + ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); + Image img = Image.newBuilder().setSource(imgSource).build(); + + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(Feature.newBuilder().setType(Type.OBJECT_LOCALIZATION)) + .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()) { + // 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()) { + 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 -> System.out.format("- (%s, %s)%n", vertex.getX(), vertex.getY())); + } + } + } + } + // [END vision_localize_objects_gcs] +} diff --git a/vision/snippets/src/main/java/com/example/vision/DetectBatchAnnotateFiles.java b/vision/snippets/src/main/java/com/example/vision/DetectBatchAnnotateFiles.java new file mode 100644 index 00000000000..7ef3ac6f74d --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/DetectBatchAnnotateFiles.java @@ -0,0 +1,109 @@ +/* + * Copyright 2019 Google LLC + * + * 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; + +// [START vision_batch_annotate_files_beta] +import com.google.api.core.ApiFuture; +import com.google.cloud.vision.v1p4beta1.AnnotateFileRequest; +import com.google.cloud.vision.v1p4beta1.AnnotateFileResponse; +import com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest; +import com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse; +import com.google.cloud.vision.v1p4beta1.Block; +import com.google.cloud.vision.v1p4beta1.Feature; +import com.google.cloud.vision.v1p4beta1.Feature.Type; +import com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient; +import com.google.cloud.vision.v1p4beta1.InputConfig; +import com.google.cloud.vision.v1p4beta1.Page; +import com.google.cloud.vision.v1p4beta1.Paragraph; +import com.google.cloud.vision.v1p4beta1.Symbol; +import com.google.cloud.vision.v1p4beta1.TextAnnotation; +import com.google.cloud.vision.v1p4beta1.Word; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class DetectBatchAnnotateFiles { + + // Performs document feature detection on a local PDF/TIFF/GIF file. + public static void detectBatchAnnotateFiles(String filePath) { + // String filePath = "path/to/your_file"; + + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + // Annotate the first two pages and the last one (max 5 pages) + // First page starts at 1, and not 0. Last page is -1. + List pages = Arrays.asList(1, 2, -1); + ByteString pdfBytes = ByteString.readFrom(new FileInputStream(filePath)); + Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build(); + // Other supported mime types : 'image/tiff' or 'image/gif' + InputConfig inputConfig = + InputConfig.newBuilder().setMimeType("application/pdf").setContent(pdfBytes).build(); + AnnotateFileRequest request = + AnnotateFileRequest.newBuilder() + .addFeatures(feat) + .setInputConfig(inputConfig) + .addAllPages(pages) + .build(); + List requests = new ArrayList<>(); + requests.add(request); + + BatchAnnotateFilesRequest batchAnnotateFilesRequest = + BatchAnnotateFilesRequest.newBuilder().addAllRequests(requests).build(); + ApiFuture future = + client.batchAnnotateFilesCallable().futureCall(batchAnnotateFilesRequest); + BatchAnnotateFilesResponse response = future.get(); + + // Getting the first response + AnnotateFileResponse annotateFileResponse = response.getResponses(0); + + // For full list of available annotations, see http://g.co/cloud/vision/docs + TextAnnotation textAnnotation = annotateFileResponse.getResponses(0).getFullTextAnnotation(); + for (Page page : textAnnotation.getPagesList()) { + String pageText = ""; + for (Block block : page.getBlocksList()) { + String blockText = ""; + for (Paragraph para : block.getParagraphsList()) { + String paraText = ""; + for (Word word : para.getWordsList()) { + String wordText = ""; + for (Symbol symbol : word.getSymbolsList()) { + wordText = wordText + symbol.getText(); + System.out.format( + "Symbol text: %s (Confidence: %f)\n", symbol.getText(), symbol.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: + System.out.println("\nParagraph: \n" + paraText); + System.out.format("Paragraph Confidence: %f\n", para.getConfidence()); + blockText = blockText + paraText; + } + pageText = pageText + blockText; + } + } + System.out.println("\nComplete annotation:"); + System.out.println(textAnnotation.getText()); + + } catch (Exception e) { + System.out.println("Error during detectPdfText: \n" + e.toString()); + } + } +} +// [END vision_batch_annotate_files_beta] diff --git a/vision/snippets/src/main/java/com/example/vision/DetectBatchAnnotateFilesGcs.java b/vision/snippets/src/main/java/com/example/vision/DetectBatchAnnotateFilesGcs.java new file mode 100644 index 00000000000..3f8b9582018 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/DetectBatchAnnotateFilesGcs.java @@ -0,0 +1,108 @@ +/* + * Copyright 2019 Google LLC + * + * 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; + +// [START vision_batch_annotate_files_gcs_beta] +import com.google.api.core.ApiFuture; +import com.google.cloud.vision.v1p4beta1.AnnotateFileRequest; +import com.google.cloud.vision.v1p4beta1.AnnotateFileResponse; +import com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest; +import com.google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse; +import com.google.cloud.vision.v1p4beta1.Block; +import com.google.cloud.vision.v1p4beta1.Feature; +import com.google.cloud.vision.v1p4beta1.Feature.Type; +import com.google.cloud.vision.v1p4beta1.GcsSource; +import com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient; +import com.google.cloud.vision.v1p4beta1.InputConfig; +import com.google.cloud.vision.v1p4beta1.Page; +import com.google.cloud.vision.v1p4beta1.Paragraph; +import com.google.cloud.vision.v1p4beta1.Symbol; +import com.google.cloud.vision.v1p4beta1.TextAnnotation; +import com.google.cloud.vision.v1p4beta1.Word; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class DetectBatchAnnotateFilesGcs { + + // Performs document feature detection on a remote PDF/TIFF/GIF file on Google Cloud Storage. + public static void detectBatchAnnotateFilesGcs(String gcsPath) { + // String gcsPath = "gs://Your_BUCKET_ID/path_to_your_data"; + + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + // Annotate the first two pages and the last one (max 5 pages) + // First page starts at 1, and not 0. Last page is -1. + List pages = Arrays.asList(1, 2, -1); + GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsPath).build(); + Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build(); + // Other supported mime types : 'image/tiff' or 'image/gif' + InputConfig inputConfig = + InputConfig.newBuilder().setMimeType("application/pdf").setGcsSource(gcsSource).build(); + AnnotateFileRequest request = + AnnotateFileRequest.newBuilder() + .addFeatures(feat) + .setInputConfig(inputConfig) + .addAllPages(pages) + .build(); + List requests = new ArrayList<>(); + requests.add(request); + + BatchAnnotateFilesRequest batchAnnotateFilesRequest = + BatchAnnotateFilesRequest.newBuilder().addAllRequests(requests).build(); + ApiFuture future = + client.batchAnnotateFilesCallable().futureCall(batchAnnotateFilesRequest); + BatchAnnotateFilesResponse response = future.get(); + + // Getting the first response + AnnotateFileResponse annotateFileResponse = response.getResponses(0); + + // For full list of available annotations, see http://g.co/cloud/vision/docs + TextAnnotation textAnnotation = annotateFileResponse.getResponses(0).getFullTextAnnotation(); + for (Page page : textAnnotation.getPagesList()) { + String pageText = ""; + for (Block block : page.getBlocksList()) { + String blockText = ""; + for (Paragraph para : block.getParagraphsList()) { + String paraText = ""; + for (Word word : para.getWordsList()) { + String wordText = ""; + for (Symbol symbol : word.getSymbolsList()) { + wordText = wordText + symbol.getText(); + System.out.format( + "Symbol text: %s (Confidence: %f)\n", symbol.getText(), symbol.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: + System.out.println("\nParagraph: \n" + paraText); + System.out.format("Paragraph Confidence: %f\n", para.getConfidence()); + blockText = blockText + paraText; + } + pageText = pageText + blockText; + } + } + System.out.println("\nComplete annotation:"); + System.out.println(textAnnotation.getText()); + + } catch (Exception e) { + System.out.println("Error during detectPdfText: \n" + e.toString()); + } + } +} +// [END vision_batch_annotate_files_gcs_beta] diff --git a/vision/snippets/src/main/java/com/example/vision/DetectBeta.java b/vision/snippets/src/main/java/com/example/vision/DetectBeta.java new file mode 100644 index 00000000000..a62854e99fa --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/DetectBeta.java @@ -0,0 +1,329 @@ +/* + * Copyright 2018 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.google.cloud.vision.v1p3beta1.AnnotateImageRequest; +import com.google.cloud.vision.v1p3beta1.AnnotateImageResponse; +import com.google.cloud.vision.v1p3beta1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1p3beta1.Block; +import com.google.cloud.vision.v1p3beta1.Feature; +import com.google.cloud.vision.v1p3beta1.Feature.Type; +import com.google.cloud.vision.v1p3beta1.Image; +import com.google.cloud.vision.v1p3beta1.ImageAnnotatorClient; +import com.google.cloud.vision.v1p3beta1.ImageContext; +import com.google.cloud.vision.v1p3beta1.ImageSource; +import com.google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation; +import com.google.cloud.vision.v1p3beta1.Page; +import com.google.cloud.vision.v1p3beta1.Paragraph; +import com.google.cloud.vision.v1p3beta1.Symbol; +import com.google.cloud.vision.v1p3beta1.TextAnnotation; +import com.google.cloud.vision.v1p3beta1.Word; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; + +public class DetectBeta { + + /** + * Detects entities, sentiment, and syntax in a document using the Vision API. + * + * @throws Exception on errors while closing the client. + * @throws IOException on Input/Output errors. + */ + public static void main(String[] args) throws Exception, IOException { + argsHelper(args, System.out); + } + + /** + * Helper that handles the input passed to the program. + * + * @throws Exception on errors while closing the client. + * @throws IOException on Input/Output errors. + */ + public static void argsHelper(String[] args, PrintStream out) throws Exception, IOException { + if (args.length < 1) { + out.println("Usage:"); + out.printf( + "\tmvn exec:java -DDetect -Dexec.args=\" \"\n" + + "\tmvn exec:java -DDetect -Dexec.args=\"ocr \"" + + "\n" + + "Commands:\n" + + "\tobject-localization| handwritten-ocr\n" + + "Path:\n\tA file path (ex: ./resources/wakeupcat.jpg) or a URI for a Cloud Storage " + + "resource (gs://...)\n" + + "Path to File:\n\tA path to the remote file on Cloud Storage (gs://...)\n" + + "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("object-localization")) { + if (path.startsWith("gs://")) { + detectLocalizedObjectsGcs(path, out); + } else { + detectLocalizedObjects(path, out); + } + } else if (command.equals("handwritten-ocr")) { + if (path.startsWith("gs://")) { + detectHandwrittenOcrGcs(path, out); + } else { + detectHandwrittenOcr(path, out); + } + } + } + + // [START vision_localize_objects_beta] + /** + * Detects localized objects in the specified local image. + * + * @param filePath The path to the file to perform localized object detection on. + * @param out A {@link PrintStream} to write detected objects to. + * @throws Exception on errors while closing the client. + * @throws IOException on Input/Output errors. + */ + public static void detectLocalizedObjects(String filePath, PrintStream out) + throws Exception, IOException { + List requests = new ArrayList<>(); + + ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); + + Image img = Image.newBuilder().setContent(imgBytes).build(); + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(Feature.newBuilder().setType(Type.OBJECT_LOCALIZATION)) + .setImage(img) + .build(); + requests.add(request); + + // Perform the request + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + 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"); + entity + .getBoundingPoly() + .getNormalizedVerticesList() + .forEach(vertex -> out.format("- (%s, %s)\n", vertex.getX(), vertex.getY())); + } + } + } + } + // [END vision_localize_objects_beta] + + // [START vision_localize_objects_gcs_beta] + /** + * Detects localized objects in a remote image on Google Cloud Storage. + * + * @param gcsPath The path to the remote file on Google Cloud Storage to detect localized objects + * on. + * @param out A {@link PrintStream} to write detected objects to. + * @throws Exception on errors while closing the client. + * @throws IOException on Input/Output errors. + */ + public static void detectLocalizedObjectsGcs(String gcsPath, PrintStream out) + throws Exception, IOException { + List requests = new ArrayList<>(); + + ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); + Image img = Image.newBuilder().setSource(imgSource).build(); + + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(Feature.newBuilder().setType(Type.OBJECT_LOCALIZATION)) + .setImage(img) + .build(); + requests.add(request); + + // Perform the request + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + 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"); + entity + .getBoundingPoly() + .getNormalizedVerticesList() + .forEach(vertex -> out.format("- (%s, %s)\n", vertex.getX(), vertex.getY())); + } + } + } + } + // [END vision_localize_objects_gcs_beta] + + // [START vision_handwritten_ocr_beta] + /** + * Performs handwritten text detection on a local image file. + * + * @param filePath The path to the local file to detect handwritten text on. + * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. + * @throws IOException on Input/Output errors. + */ + public static void detectHandwrittenOcr(String filePath, PrintStream out) throws Exception { + List requests = new ArrayList<>(); + + ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); + + Image img = Image.newBuilder().setContent(imgBytes).build(); + Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build(); + // Set the Language Hint codes for handwritten OCR + ImageContext imageContext = + ImageContext.newBuilder().addLanguageHints("en-t-i0-handwrit").build(); + + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(feat) + .setImage(img) + .setImageContext(imageContext) + .build(); + requests.add(request); + + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + client.close(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } + + // For full list of available annotations, see http://g.co/cloud/vision/docs + TextAnnotation annotation = res.getFullTextAnnotation(); + for (Page page : annotation.getPagesList()) { + String pageText = ""; + for (Block block : page.getBlocksList()) { + String blockText = ""; + for (Paragraph para : block.getParagraphsList()) { + String paraText = ""; + for (Word word : para.getWordsList()) { + String wordText = ""; + for (Symbol symbol : word.getSymbolsList()) { + wordText = wordText + symbol.getText(); + out.format( + "Symbol text: %s (confidence: %f)\n", + symbol.getText(), symbol.getConfidence()); + } + out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence()); + paraText = String.format("%s %s", paraText, wordText); + } + // Output Example using Paragraph: + out.println("\nParagraph: \n" + paraText); + out.format("Paragraph Confidence: %f\n", para.getConfidence()); + blockText = blockText + paraText; + } + pageText = pageText + blockText; + } + } + out.println("\nComplete annotation:"); + out.println(annotation.getText()); + } + } + } + // [END vision_handwritten_ocr_beta] + + // [START vision_handwritten_ocr_gcs_beta] + /** + * Performs handwritten text detection on a remote image on Google Cloud Storage. + * + * @param gcsPath The path to the remote file on Google Cloud Storage to detect handwritten text + * on. + * @param out A {@link PrintStream} to write the results to. + * @throws Exception on errors while closing the client. + * @throws IOException on Input/Output errors. + */ + public static void detectHandwrittenOcrGcs(String gcsPath, PrintStream out) throws Exception { + List requests = new ArrayList<>(); + + ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); + Image img = Image.newBuilder().setSource(imgSource).build(); + + Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build(); + // Set the parameters for the image + ImageContext imageContext = + ImageContext.newBuilder().addLanguageHints("en-t-i0-handwrit").build(); + + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(feat) + .setImage(img) + .setImageContext(imageContext) + .build(); + requests.add(request); + + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + client.close(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + out.printf("Error: %s\n", res.getError().getMessage()); + return; + } + + // For full list of available annotations, see http://g.co/cloud/vision/docs + TextAnnotation annotation = res.getFullTextAnnotation(); + for (Page page : annotation.getPagesList()) { + String pageText = ""; + for (Block block : page.getBlocksList()) { + String blockText = ""; + for (Paragraph para : block.getParagraphsList()) { + String paraText = ""; + for (Word word : para.getWordsList()) { + String wordText = ""; + for (Symbol symbol : word.getSymbolsList()) { + wordText = wordText + symbol.getText(); + out.format( + "Symbol text: %s (confidence: %f)\n", + symbol.getText(), symbol.getConfidence()); + } + out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence()); + paraText = String.format("%s %s", paraText, wordText); + } + // Output Example using Paragraph: + out.println("\nParagraph: \n" + paraText); + out.format("Paragraph Confidence: %f\n", para.getConfidence()); + blockText = blockText + paraText; + } + pageText = pageText + blockText; + } + } + out.println("\nComplete annotation:"); + out.println(annotation.getText()); + } + } + } + // [END vision_handwritten_ocr_gcs_beta] +} diff --git a/vision/snippets/src/main/java/com/example/vision/ImportProductSets.java b/vision/snippets/src/main/java/com/example/vision/ImportProductSets.java new file mode 100644 index 00000000000..bc8c3a263cb --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/ImportProductSets.java @@ -0,0 +1,118 @@ +/* + * Copyright 2018 Google LLC + * + * 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; + +// [START vision_product_search_tutorial_import] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.vision.v1.BatchOperationMetadata; +import com.google.cloud.vision.v1.ImportProductSetsGcsSource; +import com.google.cloud.vision.v1.ImportProductSetsGcsSource.Builder; +import com.google.cloud.vision.v1.ImportProductSetsInputConfig; +import com.google.cloud.vision.v1.ImportProductSetsResponse; +import com.google.cloud.vision.v1.LocationName; +import com.google.cloud.vision.v1.ProductSearchClient; +import com.google.cloud.vision.v1.ReferenceImage; +import java.io.PrintStream; +import javax.swing.JPanel; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +// [END vision_product_search_tutorial_import] + +/** + * This application demonstrates how to Import Product Sets in Cloud Vision Product Search. + * + *

For more information, see the tutorial page at + * https://cloud.google.com/vision/product-search/docs/ + */ +public class ImportProductSets extends JPanel { + // [START vision_product_search_import_product_images] + /** + * Import images of different products in the product set. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param gcsUri - Google Cloud Storage URI.Target files must be in Product Search CSV format. + * @throws Exception - on client errors. + */ + public static void importProductSets(String projectId, String computeRegion, String gcsUri) + throws Exception { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // A resource that represents Google Cloud Platform location. + String formattedParent = LocationName.format(projectId, computeRegion); + Builder gcsSource = ImportProductSetsGcsSource.newBuilder().setCsvFileUri(gcsUri); + + // Set the input configuration along with Google Cloud Storage URI + ImportProductSetsInputConfig inputConfig = + ImportProductSetsInputConfig.newBuilder().setGcsSource(gcsSource).build(); + + // Import the product sets from the input URI. + OperationFuture response = + client.importProductSetsAsync(formattedParent, inputConfig); + + System.out.println(String.format("Processing operation name: %s", response.getName())); + ImportProductSetsResponse results = response.get(); + System.out.println("Processing done."); + System.out.println("Results of the processing:"); + + for (int i = 0; i < results.getStatusesCount(); i++) { + System.out.println( + String.format( + "Status of processing line %s of the csv: %s", i, results.getStatuses(i))); + // Check the status of reference image. + if (results.getStatuses(i).getCode() == 0) { + ReferenceImage referenceImage = results.getReferenceImages(i); + System.out.println(referenceImage); + } else { + System.out.println("No reference image."); + } + } + } + } + // [END vision_product_search_import_product_images] + + public static void main(String[] args) throws Exception { + ImportProductSets importProductSet = new ImportProductSets(); + importProductSet.argsHelper(args, System.out); + } + + public static void argsHelper(String[] args, PrintStream out) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("Import Product Sets").build(); + Subparsers subparsers = parser.addSubparsers().dest("command"); + + Subparser importProductSetsParser = subparsers.addParser("import_product_sets"); + importProductSetsParser.addArgument("gcsUri"); + + String projectId = System.getenv("PROJECT_ID"); + String computeRegion = System.getenv("REGION_NAME"); + + Namespace ns = null; + try { + ns = parser.parseArgs(args); + if (ns.get("command").equals("import_product_sets")) { + importProductSets(projectId, computeRegion, ns.getString("gcsUri")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/vision/snippets/src/main/java/com/example/vision/ProductInProductSetManagement.java b/vision/snippets/src/main/java/com/example/vision/ProductInProductSetManagement.java new file mode 100644 index 00000000000..8825520e41e --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/ProductInProductSetManagement.java @@ -0,0 +1,181 @@ +/* + * Copyright 2018 Google LLC + * + * 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.google.cloud.vision.v1.Product; +import com.google.cloud.vision.v1.ProductName; +import com.google.cloud.vision.v1.ProductSearchClient; +import com.google.cloud.vision.v1.ProductSet; +import com.google.cloud.vision.v1.ProductSetName; +import java.io.IOException; +import java.io.PrintStream; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +/** + * This application demonstrates how to perform basic operations with Products in a Product Set. + * + *

For more information, see the tutorial page at + * https://cloud.google.com/vision/product-search/docs/ + */ +public class ProductInProductSetManagement { + + // [START vision_product_search_add_product_to_product_set] + + /** + * Add a product to a product set. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId - Id of the product. + * @param productSetId - Id of the product set. + * @throws IOException - on I/O errors. + */ + public static void addProductToProductSet( + String projectId, String computeRegion, String productId, String productSetId) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product set. + String formattedName = ProductSetName.format(projectId, computeRegion, productSetId); + + // Get the full path of the product. + String productPath = ProductName.of(projectId, computeRegion, productId).toString(); + + // Add the product to the product set. + client.addProductToProductSet(formattedName, productPath); + + System.out.println(String.format("Product added to product set.")); + } + } + // [END vision_product_search_add_product_to_product_set] + + // [START vision_product_search_list_products_in_product_set] + + /** + * List all products in a product set. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productSetId - Id of the product set. + * @throws IOException - on I/O errors. + */ + public static void listProductsInProductSet( + String projectId, String computeRegion, String productSetId) throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product set. + String formattedName = ProductSetName.format(projectId, computeRegion, productSetId); + // List all the products available in the product set. + for (Product product : client.listProductsInProductSet(formattedName).iterateAll()) { + // Display the product information + System.out.println(String.format("Product name: %s", product.getName())); + System.out.println( + String.format( + "Product id: %s", + product.getName().substring(product.getName().lastIndexOf('/') + 1))); + System.out.println(String.format("Product display name: %s", product.getDisplayName())); + System.out.println(String.format("Product description: %s", product.getDescription())); + System.out.println(String.format("Product category: %s", product.getProductCategory())); + System.out.println("Product labels: "); + for (Product.KeyValue element : product.getProductLabelsList()) { + System.out.println(String.format("%s: %s", element.getKey(), element.getValue())); + } + } + } + } + // [END vision_product_search_list_products_in_product_set] + + // [START vision_product_search_remove_product_from_product_set] + + /** + * Remove a product from a product set. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId - Id of the product. + * @param productSetId - Id of the product set. + * @throws IOException - on I/O errors. + */ + public static void removeProductFromProductSet( + String projectId, String computeRegion, String productId, String productSetId) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product set. + String formattedParent = ProductSetName.format(projectId, computeRegion, productSetId); + + // Get the full path of the product. + String formattedName = ProductName.format(projectId, computeRegion, productId); + + // Remove the product from the product set. + client.removeProductFromProductSet(formattedParent, formattedName); + + System.out.println(String.format("Product removed from product set.")); + } + } + // [END vision_product_search_remove_product_from_product_set] + + public static void main(String[] args) throws Exception { + ProductInProductSetManagement productInProductSetManagement = + new ProductInProductSetManagement(); + productInProductSetManagement.argsHelper(args, System.out); + } + + public static void argsHelper(String[] args, PrintStream out) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("").build(); + Subparsers subparsers = parser.addSubparsers().dest("command"); + + Subparser addProductParser = subparsers.addParser("add_product_to_product_set"); + addProductParser.addArgument("productSetId"); + addProductParser.addArgument("productId"); + + Subparser listProductInProductSetParser = subparsers.addParser("list_products_in_product_set"); + listProductInProductSetParser.addArgument("productSetId"); + + Subparser removeProductFromProductSetParser = + subparsers.addParser("remove_product_from_product_set"); + removeProductFromProductSetParser.addArgument("productId"); + removeProductFromProductSetParser.addArgument("productSetId"); + + String projectId = System.getenv("PROJECT_ID"); + String computeRegion = System.getenv("REGION_NAME"); + + Namespace ns = null; + try { + ns = parser.parseArgs(args); + if (ns.get("command").equals("add_product_to_product_set")) { + addProductToProductSet( + projectId, computeRegion, ns.getString("productId"), ns.getString("productSetId")); + } + if (ns.get("command").equals("list_products_in_product_set")) { + listProductsInProductSet(projectId, computeRegion, ns.getString("productSetId")); + } + if (ns.get("command").equals("remove_product_from_product_set")) { + removeProductFromProductSet( + projectId, computeRegion, ns.getString("productId"), ns.getString("productSetId")); + } + + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/vision/snippets/src/main/java/com/example/vision/ProductManagement.java b/vision/snippets/src/main/java/com/example/vision/ProductManagement.java new file mode 100644 index 00000000000..25217f89858 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/ProductManagement.java @@ -0,0 +1,272 @@ +/* + * Copyright 2018 Google LLC + * + * 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.google.cloud.vision.v1.LocationName; +import com.google.cloud.vision.v1.Product; +import com.google.cloud.vision.v1.Product.KeyValue; +import com.google.cloud.vision.v1.ProductName; +import com.google.cloud.vision.v1.ProductSearchClient; +import com.google.protobuf.FieldMask; +import java.io.IOException; +import java.io.PrintStream; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +/** + * This application demonstrates how to perform basic operations on Products. + * + *

For more information, see the tutorial page at + * https://cloud.google.com/vision/product-search/docs/ + */ +public class ProductManagement { + + // [START vision_product_search_create_product] + /** + * Create one product. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId - Id of the product. + * @param productDisplayName - Display name of the product. + * @param productCategory - Category of the product. + * @throws IOException - on I/O errors. + */ + public static void createProduct( + String projectId, + String computeRegion, + String productId, + String productDisplayName, + String productCategory) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // A resource that represents Google Cloud Platform location. + String formattedParent = LocationName.format(projectId, computeRegion); + // Create a product with the product specification in the region. + // Multiple labels are also supported. + Product myProduct = + Product.newBuilder() + .setName(productId) + .setDisplayName(productDisplayName) + .setProductCategory(productCategory) + .build(); + Product product = client.createProduct(formattedParent, myProduct, productId); + // Display the product information + System.out.println(String.format("Product name: %s", product.getName())); + } + } + // [END vision_product_search_create_product] + + // [START vision_product_search_list_products] + /** + * List all products. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @throws IOException - on I/O errors. + */ + public static void listProducts(String projectId, String computeRegion) throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // A resource that represents Google Cloud Platform location. + String formattedParent = LocationName.format(projectId, computeRegion); + + // List all the products available in the region. + for (Product product : client.listProducts(formattedParent).iterateAll()) { + // Display the product information + System.out.println(String.format("\nProduct name: %s", product.getName())); + System.out.println( + String.format( + "Product id: %s", + product.getName().substring(product.getName().lastIndexOf('/') + 1))); + System.out.println(String.format("Product display name: %s", product.getDisplayName())); + System.out.println(String.format("Product category: %s", product.getProductCategory())); + System.out.println("Product labels:"); + System.out.println( + String.format("Product labels: %s", product.getProductLabelsList().toString())); + } + } + } + // [END vision_product_search_list_products] + + // [START vision_product_search_get_product] + /** + * Get information about a product. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId - Id of the product. + * @throws IOException - on I/O errors. + */ + public static void getProduct(String projectId, String computeRegion, String productId) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product. + String formattedName = ProductName.format(projectId, computeRegion, productId); + // Get complete detail of the product. + Product product = client.getProduct(formattedName); + // Display the product information + System.out.println(String.format("Product name: %s", product.getName())); + System.out.println( + String.format( + "Product id: %s", + product.getName().substring(product.getName().lastIndexOf('/') + 1))); + System.out.println(String.format("Product display name: %s", product.getDisplayName())); + System.out.println(String.format("Product description: %s", product.getDescription())); + System.out.println(String.format("Product category: %s", product.getProductCategory())); + System.out.println(String.format("Product labels: ")); + for (Product.KeyValue element : product.getProductLabelsList()) { + System.out.println(String.format("%s: %s", element.getKey(), element.getValue())); + } + } + } + // [END vision_product_search_get_product] + + // [START vision_product_search_update_product_labels] + /** + * Update the product labels. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId -Id of the product. + * @param productLabels - Labels of the product. + * @throws IOException - on I/O errors. + */ + public static void updateProductLabels( + String projectId, String computeRegion, String productId, String productLabels) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product. + String formattedName = ProductName.format(projectId, computeRegion, productId); + + // Set product name, product labels and product display name. + // Multiple labels are also supported. + Product product = + Product.newBuilder() + .setName(formattedName) + .addProductLabels( + KeyValue.newBuilder() + .setKey(productLabels.split(",")[0].split("=")[0]) + .setValue(productLabels.split(",")[0].split("=")[1]) + .build()) + .build(); + + // Set product update field name. + FieldMask updateMask = FieldMask.newBuilder().addPaths("product_labels").build(); + + // Update the product. + Product updatedProduct = client.updateProduct(product, updateMask); + // Display the product information + System.out.println(String.format("Product name: %s", updatedProduct.getName())); + System.out.println(String.format("Updated product labels: ")); + for (Product.KeyValue element : updatedProduct.getProductLabelsList()) { + System.out.println(String.format("%s: %s", element.getKey(), element.getValue())); + } + } + } + // [END vision_product_search_update_product_labels] + + // [START vision_product_search_delete_product] + /** + * Delete the product and all its reference images. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId - Id of the product. + * @throws IOException - on I/O errors. + */ + public static void deleteProduct(String projectId, String computeRegion, String productId) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product. + String formattedName = ProductName.format(projectId, computeRegion, productId); + + // Delete a product. + client.deleteProduct(formattedName); + System.out.println("Product deleted."); + } + } + // [END vision_product_search_delete_product] + + public static void main(String[] args) throws Exception { + ProductManagement productManagement = new ProductManagement(); + productManagement.argsHelper(args, System.out); + } + + public void argsHelper(String[] args, PrintStream out) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("Product Management").build(); + Subparsers subparsers = parser.addSubparsers().dest("command"); + + Subparser createProductParser = subparsers.addParser("create_product"); + createProductParser.addArgument("productId"); + createProductParser.addArgument("productDisplayName"); + createProductParser.addArgument("productCategory"); + createProductParser.addArgument("productDescription"); + createProductParser.addArgument("productLabels").nargs("?").setDefault(""); + + subparsers.addParser("list_products"); + + Subparser getProductParser = subparsers.addParser("get_product"); + getProductParser.addArgument("productId"); + + Subparser updateProductLabelsParser = subparsers.addParser("update_product_labels"); + updateProductLabelsParser.addArgument("productId"); + updateProductLabelsParser.addArgument("productLabels"); + + Subparser deleteProductParser = subparsers.addParser("delete_product"); + deleteProductParser.addArgument("productId"); + + String projectId = System.getenv("PROJECT_ID"); + String computeRegion = System.getenv("REGION_NAME"); + + Namespace ns = null; + try { + ns = parser.parseArgs(args); + if (ns.get("command").equals("create_product")) { + createProduct( + projectId, + computeRegion, + ns.getString("productId"), + ns.getString("productDisplayName"), + ns.getString("productCategory")); + } + if (ns.get("command").equals("list_products")) { + listProducts(projectId, computeRegion); + } + if (ns.get("command").equals("get_product")) { + getProduct(projectId, computeRegion, ns.getString("productId")); + } + if (ns.get("command").equals("update_product_labels")) { + updateProductLabels( + projectId, computeRegion, ns.getString("productId"), ns.getString("productLabels")); + } + if (ns.get("command").equals("delete_product")) { + deleteProduct(projectId, computeRegion, ns.getString("productId")); + } + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/vision/snippets/src/main/java/com/example/vision/ProductSearch.java b/vision/snippets/src/main/java/com/example/vision/ProductSearch.java new file mode 100644 index 00000000000..01496514425 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/ProductSearch.java @@ -0,0 +1,248 @@ +/* + * Copyright 2018 Google LLC + * + * 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.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Feature.Type; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageContext; +import com.google.cloud.vision.v1.ImageSource; +import com.google.cloud.vision.v1.ProductName; +import com.google.cloud.vision.v1.ProductSearchClient; +import com.google.cloud.vision.v1.ProductSearchParams; +import com.google.cloud.vision.v1.ProductSearchResults.Result; +import com.google.cloud.vision.v1.ProductSetName; +import com.google.protobuf.ByteString; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +/** + * This application demonstrates how to perform similar product search operation in Cloud Vision + * Product Search. + * + *

For more information, see the tutorial page at + * https://cloud.google.com/vision/product-search/docs/ + */ +public class ProductSearch { + + // [START vision_product_search_get_similar_products] + /** + * Search similar products to image in local file. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productSetId - Id of the product set. + * @param productCategory - Category of the product. + * @param filePath - Local file path of the image to be searched + * @param filter - Condition to be applied on the labels. Example for filter: (color = red OR + * color = blue) AND style = kids It will search on all products with the following labels: + * color:red AND style:kids color:blue AND style:kids + * @throws IOException - on I/O errors. + */ + public static void getSimilarProductsFile( + String projectId, + String computeRegion, + String productSetId, + String productCategory, + String filePath, + String filter) + throws IOException { + try (ImageAnnotatorClient queryImageClient = ImageAnnotatorClient.create()) { + + // Get the full path of the product set. + String productSetPath = ProductSetName.format(projectId, computeRegion, productSetId); + + // Read the image as a stream of bytes. + File imgPath = new File(filePath); + byte[] content = Files.readAllBytes(imgPath.toPath()); + + // Create annotate image request along with product search feature. + Feature featuresElement = Feature.newBuilder().setType(Type.PRODUCT_SEARCH).build(); + // The input image can be a HTTPS link or Raw image bytes. + // Example: + // To use HTTP link replace with below code + // ImageSource source = ImageSource.newBuilder().setImageUri(imageUri).build(); + // Image image = Image.newBuilder().setSource(source).build(); + Image image = Image.newBuilder().setContent(ByteString.copyFrom(content)).build(); + ImageContext imageContext = + ImageContext.newBuilder() + .setProductSearchParams( + ProductSearchParams.newBuilder() + .setProductSet(productSetPath) + .addProductCategories(productCategory) + .setFilter(filter)) + .build(); + + AnnotateImageRequest annotateImageRequest = + AnnotateImageRequest.newBuilder() + .addFeatures(featuresElement) + .setImage(image) + .setImageContext(imageContext) + .build(); + List requests = Arrays.asList(annotateImageRequest); + + // Search products similar to the image. + BatchAnnotateImagesResponse response = queryImageClient.batchAnnotateImages(requests); + + List similarProducts = + response.getResponses(0).getProductSearchResults().getResultsList(); + System.out.println("Similar Products: "); + for (Result product : similarProducts) { + System.out.println(String.format("\nProduct name: %s", product.getProduct().getName())); + System.out.println( + String.format("Product display name: %s", product.getProduct().getDisplayName())); + System.out.println( + String.format("Product description: %s", product.getProduct().getDescription())); + System.out.println(String.format("Score(Confidence): %s", product.getScore())); + System.out.println(String.format("Image name: %s", product.getImage())); + } + } + } + // [END vision_product_search_get_similar_products] + + // [START vision_product_search_get_similar_products_gcs] + /** + * Search similar products to image in Google Cloud Storage. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productSetId - Id of the product set. + * @param productCategory - Category of the product. + * @param gcsUri - GCS file path of the image to be searched + * @param filter - Condition to be applied on the labels. Example for filter: (color = red OR + * color = blue) AND style = kids It will search on all products with the following labels: + * color:red AND style:kids color:blue AND style:kids + * @throws Exception - on errors. + */ + public static void getSimilarProductsGcs( + String projectId, + String computeRegion, + String productSetId, + String productCategory, + String gcsUri, + String filter) + throws Exception { + try (ImageAnnotatorClient queryImageClient = ImageAnnotatorClient.create()) { + + // Get the full path of the product set. + String productSetPath = ProductSetName.of(projectId, computeRegion, productSetId).toString(); + + // Get the image from Google Cloud Storage + ImageSource source = ImageSource.newBuilder().setGcsImageUri(gcsUri).build(); + + // Create annotate image request along with product search feature. + Feature featuresElement = Feature.newBuilder().setType(Type.PRODUCT_SEARCH).build(); + Image image = Image.newBuilder().setSource(source).build(); + ImageContext imageContext = + ImageContext.newBuilder() + .setProductSearchParams( + ProductSearchParams.newBuilder() + .setProductSet(productSetPath) + .addProductCategories(productCategory) + .setFilter(filter)) + .build(); + + AnnotateImageRequest annotateImageRequest = + AnnotateImageRequest.newBuilder() + .addFeatures(featuresElement) + .setImage(image) + .setImageContext(imageContext) + .build(); + List requests = Arrays.asList(annotateImageRequest); + + // Search products similar to the image. + BatchAnnotateImagesResponse response = queryImageClient.batchAnnotateImages(requests); + + List similarProducts = + response.getResponses(0).getProductSearchResults().getResultsList(); + System.out.println("Similar Products: "); + for (Result product : similarProducts) { + System.out.println(String.format("\nProduct name: %s", product.getProduct().getName())); + System.out.println( + String.format("Product display name: %s", product.getProduct().getDisplayName())); + System.out.println( + String.format("Product description: %s", product.getProduct().getDescription())); + System.out.println(String.format("Score(Confidence): %s", product.getScore())); + System.out.println(String.format("Image name: %s", product.getImage())); + } + } + } + // [END vision_product_search_get_similar_products_gcs] + + public static void main(String[] args) throws Exception { + ProductSearch productSearch = new ProductSearch(); + productSearch.argsHelper(args, System.out); + } + + public static void argsHelper(String[] args, PrintStream out) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("Product Search").build(); + Subparsers subparsers = parser.addSubparsers().dest("command"); + + Subparser getSimilarProductsFileParser = subparsers.addParser("get_similar_products_file"); + getSimilarProductsFileParser.addArgument("productSetId"); + getSimilarProductsFileParser.addArgument("productCategory"); + getSimilarProductsFileParser.addArgument("filePath"); + getSimilarProductsFileParser.addArgument("filter").nargs("?").setDefault(""); + + Subparser getSimilarProductsGcsParser = subparsers.addParser("get_similar_products_gcs"); + getSimilarProductsGcsParser.addArgument("productSetId"); + getSimilarProductsGcsParser.addArgument("productCategory"); + getSimilarProductsGcsParser.addArgument("gcsUri"); + getSimilarProductsGcsParser.addArgument("filter").nargs("?").setDefault(""); + + String projectId = System.getenv("PROJECT_ID"); + String computeRegion = System.getenv("REGION_NAME"); + + Namespace ns = null; + try { + ns = parser.parseArgs(args); + if (ns.get("command").equals("get_similar_products_file")) { + getSimilarProductsFile( + projectId, + computeRegion, + ns.getString("productSetId"), + ns.getString("productCategory"), + ns.getString("filePath"), + ns.getString("filter")); + } else if (ns.get("command").equals("get_similar_products_gcs")) { + getSimilarProductsGcs( + projectId, + computeRegion, + ns.getString("productSetId"), + ns.getString("productCategory"), + ns.getString("gcsUri"), + ns.getString("filter")); + } + + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/vision/snippets/src/main/java/com/example/vision/ProductSetManagement.java b/vision/snippets/src/main/java/com/example/vision/ProductSetManagement.java new file mode 100644 index 00000000000..d277bc1c9e9 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/ProductSetManagement.java @@ -0,0 +1,208 @@ +/* + * Copyright 2018 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.google.cloud.vision.v1.CreateProductSetRequest; +import com.google.cloud.vision.v1.LocationName; +import com.google.cloud.vision.v1.ProductName; +import com.google.cloud.vision.v1.ProductSearchClient; +import com.google.cloud.vision.v1.ProductSet; +import com.google.cloud.vision.v1.ProductSetName; +import java.io.IOException; +import java.io.PrintStream; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +/** + * This application demonstrates how to perform basic operations on Product Sets. + * + *

For more information, see the tutorial page at + * https://cloud.google.com/vision/product-search/docs/ + */ +public class ProductSetManagement { + + // [START vision_product_search_create_product_set] + /** + * Create a product set + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productSetId - Id of the product set. + * @param productSetDisplayName - Display name of the product set. + * @throws IOException - on I/O errors. + */ + public static void createProductSet( + String projectId, String computeRegion, String productSetId, String productSetDisplayName) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // A resource that represents Google Cloud Platform location. + String formattedParent = LocationName.format(projectId, computeRegion); + + // Create a product set with the product set specification in the region. + ProductSet myProductSet = + ProductSet.newBuilder().setDisplayName(productSetDisplayName).build(); + CreateProductSetRequest request = + CreateProductSetRequest.newBuilder() + .setParent(formattedParent) + .setProductSet(myProductSet) + .setProductSetId(productSetId) + .build(); + ProductSet productSet = client.createProductSet(request); + // Display the product set information + System.out.println(String.format("Product set name: %s", productSet.getName())); + } + } + // [END vision_product_search_create_product_set] + + // [START vision_product_search_list_product_sets] + /** + * List all product sets + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @throws IOException - on I/O errors. + */ + public static void listProductSets(String projectId, String computeRegion) throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + // A resource that represents Google Cloud Platform location. + String formattedParent = LocationName.format(projectId, computeRegion); + // List all the product sets available in the region. + for (ProductSet productSet : client.listProductSets(formattedParent).iterateAll()) { + // Display the product set information + System.out.println(String.format("Product set name: %s", productSet.getName())); + System.out.println( + String.format( + "Product set id: %s", + productSet.getName().substring(productSet.getName().lastIndexOf('/') + 1))); + System.out.println( + String.format("Product set display name: %s", productSet.getDisplayName())); + System.out.println("Product set index time:"); + System.out.println(String.format("\tseconds: %s", productSet.getIndexTime().getSeconds())); + System.out.println(String.format("\tnanos: %s", productSet.getIndexTime().getNanos())); + } + } + } + // [END vision_product_search_list_product_sets] + + // [START vision_product_search_get_product_set] + /** + * Get info about the product set. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productSetId - Id of the product set. + * @throws IOException - on I/O errors. + */ + public static void getProductSet(String projectId, String computeRegion, String productSetId) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product set. + String formattedName = ProductSetName.format(projectId, computeRegion, productSetId); + // Get complete detail of the product set. + ProductSet productSet = client.getProductSet(formattedName); + // Display the product set information + System.out.println(String.format("Product set name: %s", productSet.getName())); + System.out.println( + String.format( + "Product set id: %s", + productSet.getName().substring(productSet.getName().lastIndexOf('/') + 1))); + System.out.println( + String.format("Product set display name: %s", productSet.getDisplayName())); + System.out.println("Product set index time:"); + System.out.println(String.format("\tseconds: %s", productSet.getIndexTime().getSeconds())); + System.out.println(String.format("\tnanos: %s", productSet.getIndexTime().getNanos())); + } + } + // [END vision_product_search_get_product_set] + + // [START vision_product_search_delete_product_set] + /** + * Delete a product set. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productSetId - Id of the product set. + * @throws IOException - on I/O errors. + */ + public static void deleteProductSet(String projectId, String computeRegion, String productSetId) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product set. + String formattedName = ProductSetName.format(projectId, computeRegion, productSetId); + // Delete the product set. + client.deleteProductSet(formattedName); + System.out.println(String.format("Product set deleted")); + } + } + // [END vision_product_search_delete_product_set] + + public static void main(String[] args) throws Exception { + ProductSetManagement productSetManagement = new ProductSetManagement(); + productSetManagement.argsHelper(args, System.out); + } + + public static void argsHelper(String[] args, PrintStream out) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("Product Set Management").build(); + Subparsers subparsers = parser.addSubparsers().dest("command"); + + Subparser createProductSetParser = subparsers.addParser("create_product_set"); + createProductSetParser.addArgument("productSetId"); + createProductSetParser.addArgument("productSetDisplayName"); + + subparsers.addParser("list_product_sets"); + + Subparser getProductSetParser = subparsers.addParser("get_product_set"); + getProductSetParser.addArgument("productSetId"); + + Subparser deleteProductSetParser = subparsers.addParser("delete_product_set"); + deleteProductSetParser.addArgument("productSetId"); + + String projectId = System.getenv("PROJECT_ID"); + String computeRegion = System.getenv("REGION_NAME"); + + Namespace ns = null; + try { + ns = parser.parseArgs(args); + if (ns.get("command").equals("create_product_set")) { + createProductSet( + projectId, + computeRegion, + ns.getString("productSetId"), + ns.getString("productSetDisplayName")); + } + if (ns.get("command").equals("list_product_sets")) { + listProductSets(projectId, computeRegion); + } + if (ns.get("command").equals("get_product_set")) { + getProductSet(projectId, computeRegion, ns.getString("productSetId")); + } + if (ns.get("command").equals("delete_product_set")) { + deleteProductSet(projectId, computeRegion, ns.getString("productSetId")); + } + + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/vision/snippets/src/main/java/com/example/vision/ReferenceImageManagement.java b/vision/snippets/src/main/java/com/example/vision/ReferenceImageManagement.java new file mode 100644 index 00000000000..50df7dbb8fe --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/ReferenceImageManagement.java @@ -0,0 +1,222 @@ +/* + * Copyright 2018 Google LLC + * + * 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.google.cloud.vision.v1.ImageName; +import com.google.cloud.vision.v1.ProductName; +import com.google.cloud.vision.v1.ProductSearchClient; +import com.google.cloud.vision.v1.ReferenceImage; +import java.io.IOException; +import java.io.PrintStream; +import net.sourceforge.argparse4j.ArgumentParsers; +import net.sourceforge.argparse4j.inf.ArgumentParser; +import net.sourceforge.argparse4j.inf.ArgumentParserException; +import net.sourceforge.argparse4j.inf.Namespace; +import net.sourceforge.argparse4j.inf.Subparser; +import net.sourceforge.argparse4j.inf.Subparsers; + +/** + * This application demonstrates how to perform basic operations on Reference Images in Cloud Vision + * Product Search. + * + *

For more information, see the tutorial page at + * https://cloud.google.com/vision/product-search/docs/ + */ +public class ReferenceImageManagement { + + // [START vision_product_search_create_reference_image] + /** + * Create a reference image. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId - Id of the product. + * @param referenceImageId - Id of the image. + * @param gcsUri - Google Cloud Storage path of the input image. + * @throws IOException - on I/O errors. + */ + public static void createReferenceImage( + String projectId, + String computeRegion, + String productId, + String referenceImageId, + String gcsUri) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product. + String formattedParent = ProductName.format(projectId, computeRegion, productId); + // Create a reference image. + ReferenceImage referenceImage = ReferenceImage.newBuilder().setUri(gcsUri).build(); + + ReferenceImage image = + client.createReferenceImage(formattedParent, referenceImage, referenceImageId); + // Display the reference image information. + System.out.println(String.format("Reference image name: %s", image.getName())); + System.out.println(String.format("Reference image uri: %s", image.getUri())); + } + } + // [END vision_product_search_create_reference_image] + + // [START vision_product_search_list_reference_images] + /** + * List all images in a product. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId - Id of the product. + * @throws IOException - on I/O errors. + */ + public static void listReferenceImagesOfProduct( + String projectId, String computeRegion, String productId) throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the product. + String formattedParent = ProductName.format(projectId, computeRegion, productId); + for (ReferenceImage image : client.listReferenceImages(formattedParent).iterateAll()) { + // Display the reference image information. + System.out.println(String.format("Reference image name: %s", image.getName())); + System.out.println( + String.format( + "Reference image id: %s", + image.getName().substring(image.getName().lastIndexOf('/') + 1))); + System.out.println(String.format("Reference image uri: %s", image.getUri())); + System.out.println( + String.format( + "Reference image bounding polygons: %s \n", + image.getBoundingPolysList().toString())); + } + } + } + // [END vision_product_search_list_reference_images] + + // [START vision_product_search_get_reference_image] + /** + * Get info about a reference image. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId - Id of the product. + * @param referenceImageId - Id of the image. + * @throws IOException - on I/O errors. + */ + public static void getReferenceImage( + String projectId, String computeRegion, String productId, String referenceImageId) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the reference image. + String formattedName = + ImageName.format(projectId, computeRegion, productId, referenceImageId); + // Get complete detail of the reference image. + ReferenceImage image = client.getReferenceImage(formattedName); + // Display the reference image information. + System.out.println(String.format("Reference image name: %s", image.getName())); + System.out.println( + String.format( + "Reference image id: %s", + image.getName().substring(image.getName().lastIndexOf('/') + 1))); + System.out.println(String.format("Reference image uri: %s", image.getUri())); + System.out.println( + String.format( + "Reference image bounding polygons: %s \n", image.getBoundingPolysList().toString())); + } + } + // [END vision_product_search_get_reference_image] + + // [START vision_product_search_delete_reference_image] + /** + * Delete a reference image. + * + * @param projectId - Id of the project. + * @param computeRegion - Region name. + * @param productId - Id of the product. + * @param referenceImageId - Id of the image. + * @throws IOException - on I/O errors. + */ + public static void deleteReferenceImage( + String projectId, String computeRegion, String productId, String referenceImageId) + throws IOException { + try (ProductSearchClient client = ProductSearchClient.create()) { + + // Get the full path of the reference image. + String formattedName = + ImageName.format(projectId, computeRegion, productId, referenceImageId); + // Delete the reference image. + client.deleteReferenceImage(formattedName); + System.out.println("Reference image deleted from product."); + } + } + // [END vision_product_search_delete_reference_image] + + public static void main(String[] args) throws Exception { + ReferenceImageManagement referenceImageManagement = new ReferenceImageManagement(); + referenceImageManagement.argsHelper(args, System.out); + } + + public static void argsHelper(String[] args, PrintStream out) throws Exception { + ArgumentParser parser = ArgumentParsers.newFor("Reference Image Management").build(); + Subparsers subparsers = parser.addSubparsers().dest("command"); + + Subparser createReferenceImageParser = subparsers.addParser("create_reference_image"); + createReferenceImageParser.addArgument("productId"); + createReferenceImageParser.addArgument("referenceImageId"); + createReferenceImageParser.addArgument("gcsUri"); + + Subparser listReferenceImagesOfProductParser = + subparsers.addParser("list_reference_images_of_product"); + listReferenceImagesOfProductParser.addArgument("productId"); + + Subparser getReferenceImageParser = subparsers.addParser("get_reference_image"); + getReferenceImageParser.addArgument("productId"); + getReferenceImageParser.addArgument("referenceImageId"); + + Subparser deleteReferenceImageParser = subparsers.addParser("delete_reference_image"); + deleteReferenceImageParser.addArgument("productId"); + deleteReferenceImageParser.addArgument("referenceImageId"); + + String projectId = System.getenv("PROJECT_ID"); + String computeRegion = System.getenv("REGION_NAME"); + + Namespace ns = null; + try { + ns = parser.parseArgs(args); + if (ns.get("command").equals("create_reference_image")) { + createReferenceImage( + projectId, + computeRegion, + ns.getString("productId"), + ns.getString("referenceImageId"), + ns.getString("gcsUri")); + } + if (ns.get("command").equals("list_reference_images_of_product")) { + listReferenceImagesOfProduct(projectId, computeRegion, ns.getString("productId")); + } + if (ns.get("command").equals("get_reference_image")) { + getReferenceImage( + projectId, computeRegion, ns.getString("productId"), ns.getString("referenceImageId")); + } + if (ns.get("command").equals("delete_reference_image")) { + deleteReferenceImage( + projectId, computeRegion, ns.getString("productId"), ns.getString("referenceImageId")); + } + + } catch (ArgumentParserException e) { + parser.handleError(e); + } + } +} diff --git a/vision/snippets/src/main/java/com/example/vision/quickstart/QuickstartSample.java b/vision/snippets/src/main/java/com/example/vision/quickstart/QuickstartSample.java new file mode 100644 index 00000000000..6e04f722e2f --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/quickstart/QuickstartSample.java @@ -0,0 +1,79 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.quickstart; + +// [START vision_quickstart] +// Imports the Google Cloud client library + +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.Feature.Type; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.protobuf.ByteString; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +public class QuickstartSample { + public static void main(String... args) 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 vision = ImageAnnotatorClient.create()) { + + // The path to the image file to annotate + String fileName = "./resources/wakeupcat.jpg"; + + // Reads the image file into memory + Path path = Paths.get(fileName); + byte[] data = Files.readAllBytes(path); + ByteString imgBytes = ByteString.copyFrom(data); + + // Builds the image annotation request + List requests = new ArrayList<>(); + 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); + + // Performs label detection on the image file + BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.format("Error: %s%n", res.getError().getMessage()); + return; + } + + for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { + annotation + .getAllFields() + .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString())); + } + } + } + } +} +// [END vision_quickstart] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/AsyncBatchAnnotateImages.java b/vision/snippets/src/main/java/com/example/vision/snippets/AsyncBatchAnnotateImages.java new file mode 100644 index 00000000000..025abc30594 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/AsyncBatchAnnotateImages.java @@ -0,0 +1,89 @@ +/* + * Copyright 2020 Google LLC + * + * 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_async_batch_annotate_images] +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AsyncBatchAnnotateImagesRequest; +import com.google.cloud.vision.v1.AsyncBatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.GcsDestination; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageSource; +import com.google.cloud.vision.v1.OutputConfig; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class AsyncBatchAnnotateImages { + + public static void asyncBatchAnnotateImages() + throws InterruptedException, ExecutionException, IOException { + String inputImageUri = "gs://cloud-samples-data/vision/label/wakeupcat.jpg"; + String outputUri = "gs://YOUR_BUCKET_ID/path/to/save/results/"; + asyncBatchAnnotateImages(inputImageUri, outputUri); + } + + public static void asyncBatchAnnotateImages(String inputImageUri, String outputUri) + throws IOException, ExecutionException, InterruptedException { + // 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 imageAnnotatorClient = ImageAnnotatorClient.create()) { + + // You can send multiple images to be annotated, this sample demonstrates how to do this with + // one image. If you want to use multiple images, you have to create a `AnnotateImageRequest` + // object for each image that you want annotated. + // First specify where the vision api can find the image + ImageSource source = ImageSource.newBuilder().setImageUri(inputImageUri).build(); + Image image = Image.newBuilder().setSource(source).build(); + + // Set the type of annotation you want to perform on the image + // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type + Feature feature = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build(); + + // Build the request object for that one image. Note: for additional images you have to create + // additional `AnnotateImageRequest` objects and store them in a list to be used below. + AnnotateImageRequest imageRequest = + AnnotateImageRequest.newBuilder().setImage(image).addFeatures(feature).build(); + + // Set where to store the results for the images that will be annotated. + GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder() + .setGcsDestination(gcsDestination) + .setBatchSize(2) // The max number of responses to output in each JSON file + .build(); + + // Add each `AnnotateImageRequest` object to the batch request and add the output config. + AsyncBatchAnnotateImagesRequest request = + AsyncBatchAnnotateImagesRequest.newBuilder() + .addRequests(imageRequest) + .setOutputConfig(outputConfig) + .build(); + + // Make the asynchronous batch request. + AsyncBatchAnnotateImagesResponse response = + imageAnnotatorClient.asyncBatchAnnotateImagesAsync(request).get(); + + // The output is written to GCS with the provided output_uri as prefix + String gcsOutputUri = response.getOutputConfig().getGcsDestination().getUri(); + System.out.format("Output written to GCS with prefix: %s%n", gcsOutputUri); + } + } +} +// [END vision_async_batch_annotate_images] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/BatchAnnotateFiles.java b/vision/snippets/src/main/java/com/example/vision/snippets/BatchAnnotateFiles.java new file mode 100644 index 00000000000..15a864ff5f3 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/BatchAnnotateFiles.java @@ -0,0 +1,114 @@ +/* + * Copyright 2020 Google LLC + * + * 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_batch_annotate_files] +import com.google.cloud.vision.v1.AnnotateFileRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateFilesRequest; +import com.google.cloud.vision.v1.BatchAnnotateFilesResponse; +import com.google.cloud.vision.v1.Block; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.InputConfig; +import com.google.cloud.vision.v1.Page; +import com.google.cloud.vision.v1.Paragraph; +import com.google.cloud.vision.v1.Symbol; +import com.google.cloud.vision.v1.Word; +import com.google.protobuf.ByteString; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class BatchAnnotateFiles { + + public static void batchAnnotateFiles() throws IOException { + String filePath = "path/to/your/file.pdf"; + batchAnnotateFiles(filePath); + } + + public static void batchAnnotateFiles(String filePath) throws IOException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) { + // You can send multiple files to be annotated, this sample demonstrates how to do this with + // one file. If you want to use multiple files, you have to create a `AnnotateImageRequest` + // object for each file that you want annotated. + // First read the files contents + Path path = Paths.get(filePath); + byte[] data = Files.readAllBytes(path); + ByteString content = ByteString.copyFrom(data); + + // Specify the input config with the file's contents and its type. + // Supported mime_type: application/pdf, image/tiff, image/gif + // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#inputconfig + InputConfig inputConfig = + InputConfig.newBuilder().setMimeType("application/pdf").setContent(content).build(); + + // Set the type of annotation you want to perform on the file + // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type + Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build(); + + // Build the request object for that one file. Note: for additional file you have to create + // additional `AnnotateFileRequest` objects and store them in a list to be used below. + // Since we are sending a file of type `application/pdf`, we can use the `pages` field to + // specify which pages to process. The service can process up to 5 pages per document file. + // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.AnnotateFileRequest + AnnotateFileRequest fileRequest = + AnnotateFileRequest.newBuilder() + .setInputConfig(inputConfig) + .addFeatures(feature) + .addPages(1) // Process the first page + .addPages(2) // Process the second page + .addPages(-1) // Process the last page + .build(); + + // Add each `AnnotateFileRequest` object to the batch request. + BatchAnnotateFilesRequest request = + BatchAnnotateFilesRequest.newBuilder().addRequests(fileRequest).build(); + + // Make the synchronous batch request. + BatchAnnotateFilesResponse response = imageAnnotatorClient.batchAnnotateFiles(request); + + // Process the results, just get the first result, since only one file was sent in this + // sample. + for (AnnotateImageResponse imageResponse : + response.getResponsesList().get(0).getResponsesList()) { + System.out.format("Full text: %s%n", imageResponse.getFullTextAnnotation().getText()); + for (Page page : imageResponse.getFullTextAnnotation().getPagesList()) { + for (Block block : page.getBlocksList()) { + System.out.format("%nBlock confidence: %s%n", block.getConfidence()); + for (Paragraph par : block.getParagraphsList()) { + System.out.format("\tParagraph confidence: %s%n", par.getConfidence()); + for (Word word : par.getWordsList()) { + System.out.format("\t\tWord confidence: %s%n", word.getConfidence()); + for (Symbol symbol : word.getSymbolsList()) { + System.out.format( + "\t\t\tSymbol: %s, (confidence: %s)%n", + symbol.getText(), symbol.getConfidence()); + } + } + } + } + } + } + } + } +} +// [END vision_batch_annotate_files] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/BatchAnnotateFilesGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/BatchAnnotateFilesGcs.java new file mode 100644 index 00000000000..f7d1ca4e52a --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/BatchAnnotateFilesGcs.java @@ -0,0 +1,109 @@ +/* + * Copyright 2020 Google LLC + * + * 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_batch_annotate_files_gcs] +import com.google.cloud.vision.v1.AnnotateFileRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateFilesRequest; +import com.google.cloud.vision.v1.BatchAnnotateFilesResponse; +import com.google.cloud.vision.v1.Block; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.GcsSource; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.InputConfig; +import com.google.cloud.vision.v1.Page; +import com.google.cloud.vision.v1.Paragraph; +import com.google.cloud.vision.v1.Symbol; +import com.google.cloud.vision.v1.Word; +import java.io.IOException; + +public class BatchAnnotateFilesGcs { + + public static void batchAnnotateFilesGcs() throws IOException { + String gcsUri = "gs://cloud-samples-data/vision/document_understanding/kafka.pdf"; + batchAnnotateFilesGcs(gcsUri); + } + + public static void batchAnnotateFilesGcs(String gcsUri) throws IOException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) { + // You can send multiple files to be annotated, this sample demonstrates how to do this with + // one file. If you want to use multiple files, you have to create a `AnnotateImageRequest` + // object for each file that you want annotated. + // First specify where the vision api can find the image + GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsUri).build(); + + // Specify the input config with the file's uri and its type. + // Supported mime_type: application/pdf, image/tiff, image/gif + // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#inputconfig + InputConfig inputConfig = + InputConfig.newBuilder().setMimeType("application/pdf").setGcsSource(gcsSource).build(); + + // Set the type of annotation you want to perform on the file + // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type + Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build(); + + // Build the request object for that one file. Note: for additional file you have to create + // additional `AnnotateFileRequest` objects and store them in a list to be used below. + // Since we are sending a file of type `application/pdf`, we can use the `pages` field to + // specify which pages to process. The service can process up to 5 pages per document file. + // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.AnnotateFileRequest + AnnotateFileRequest fileRequest = + AnnotateFileRequest.newBuilder() + .setInputConfig(inputConfig) + .addFeatures(feature) + .addPages(1) // Process the first page + .addPages(2) // Process the second page + .addPages(-1) // Process the last page + .build(); + + // Add each `AnnotateFileRequest` object to the batch request. + BatchAnnotateFilesRequest request = + BatchAnnotateFilesRequest.newBuilder().addRequests(fileRequest).build(); + + // Make the synchronous batch request. + BatchAnnotateFilesResponse response = imageAnnotatorClient.batchAnnotateFiles(request); + + // Process the results, just get the first result, since only one file was sent in this + // sample. + for (AnnotateImageResponse imageResponse : + response.getResponsesList().get(0).getResponsesList()) { + System.out.format("Full text: %s%n", imageResponse.getFullTextAnnotation().getText()); + for (Page page : imageResponse.getFullTextAnnotation().getPagesList()) { + for (Block block : page.getBlocksList()) { + System.out.format("%nBlock confidence: %s%n", block.getConfidence()); + for (Paragraph par : block.getParagraphsList()) { + System.out.format("\tParagraph confidence: %s%n", par.getConfidence()); + for (Word word : par.getWordsList()) { + System.out.format("\t\tWord confidence: %s%n", word.getConfidence()); + for (Symbol symbol : word.getSymbolsList()) { + System.out.format( + "\t\t\tSymbol: %s, (confidence: %s)%n", + symbol.getText(), symbol.getConfidence()); + } + } + } + } + } + } + } + } +} +// [END vision_batch_annotate_files_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectCropHints.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectCropHints.java new file mode 100644 index 00000000000..705a87ce0f8 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectCropHints.java @@ -0,0 +1,76 @@ +/* + * 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_crop_hint_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.CropHint; +import com.google.cloud.vision.v1.CropHintsAnnotation; +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 DetectCropHints { + public static void detectCropHints() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectCropHints(filePath); + } + + // Suggests a region to crop to for a local file. + public static void detectCropHints(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.CROP_HINTS).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 + CropHintsAnnotation annotation = res.getCropHintsAnnotation(); + for (CropHint hint : annotation.getCropHintsList()) { + System.out.println(hint.getBoundingPoly()); + } + } + } + } +} +// [END vision_crop_hint_detection] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectCropHintsGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectCropHintsGcs.java new file mode 100644 index 00000000000..9448a4612c7 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectCropHintsGcs.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_crop_hint_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.CropHint; +import com.google.cloud.vision.v1.CropHintsAnnotation; +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 DetectCropHintsGcs { + + public static void detectCropHintsGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectCropHintsGcs(filePath); + } + + // Suggests a region to crop to for a remote file on Google Cloud Storage. + public static void detectCropHintsGcs(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.CROP_HINTS).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 + CropHintsAnnotation annotation = res.getCropHintsAnnotation(); + for (CropHint hint : annotation.getCropHintsList()) { + System.out.println(hint.getBoundingPoly()); + } + } + } + } +} +// [END vision_crop_hint_detection_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectFaces.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectFaces.java new file mode 100644 index 00000000000..4c07fa08080 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectFaces.java @@ -0,0 +1,80 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_face_detection] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.FaceAnnotation; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectFaces { + + public static void detectFaces() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectFaces(filePath); + } + + // Detects faces in the specified local image. + public static void detectFaces(String filePath) throws IOException { + List requests = new ArrayList<>(); + + ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); + + Image img = Image.newBuilder().setContent(imgBytes).build(); + Feature feat = Feature.newBuilder().setType(Feature.Type.FACE_DETECTION).build(); + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); + requests.add(request); + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.format("Error: %s%n", res.getError().getMessage()); + return; + } + + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (FaceAnnotation annotation : res.getFaceAnnotationsList()) { + System.out.format( + "anger: %s%njoy: %s%nsurprise: %s%nposition: %s", + annotation.getAngerLikelihood(), + annotation.getJoyLikelihood(), + annotation.getSurpriseLikelihood(), + annotation.getBoundingPoly()); + } + } + } + } +} +// [END vision_face_detection] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectFacesGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectFacesGcs.java new file mode 100644 index 00000000000..b325623e761 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectFacesGcs.java @@ -0,0 +1,79 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_face_detection_gcs] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.FaceAnnotation; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageSource; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectFacesGcs { + + public static void detectFacesGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectFacesGcs(filePath); + } + + // Detects faces in the specified remote image on Google Cloud Storage. + public static void detectFacesGcs(String gcsPath) throws IOException { + List requests = new ArrayList<>(); + + ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); + Image img = Image.newBuilder().setSource(imgSource).build(); + Feature feat = Feature.newBuilder().setType(Feature.Type.FACE_DETECTION).build(); + + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); + requests.add(request); + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.format("Error: %s%n", res.getError().getMessage()); + return; + } + + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (FaceAnnotation annotation : res.getFaceAnnotationsList()) { + System.out.format( + "anger: %s%njoy: %s%nsurprise: %s%nposition: %s", + annotation.getAngerLikelihood(), + annotation.getJoyLikelihood(), + annotation.getSurpriseLikelihood(), + annotation.getBoundingPoly()); + } + } + } + } +} +// [END vision_face_detection_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectLabels.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLabels.java new file mode 100644 index 00000000000..87563bb3ca6 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLabels.java @@ -0,0 +1,77 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_label_detection] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.EntityAnnotation; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectLabels { + + public static void detectLabels() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectLabels(filePath); + } + + // Detects labels in the specified local image. + public static void detectLabels(String filePath) throws IOException { + List requests = new ArrayList<>(); + + ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath)); + + Image img = Image.newBuilder().setContent(imgBytes).build(); + Feature feat = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build(); + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); + requests.add(request); + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.format("Error: %s%n", res.getError().getMessage()); + return; + } + + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { + annotation + .getAllFields() + .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString())); + } + } + } + } +} +// [END vision_label_detection] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectLabelsGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLabelsGcs.java new file mode 100644 index 00000000000..53e8dfe5351 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLabelsGcs.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_label_detection_gcs] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.EntityAnnotation; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageSource; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectLabelsGcs { + + public static void detectLabelsGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectLabelsGcs(filePath); + } + + // Detects labels in the specified remote image on Google Cloud Storage. + public static void detectLabelsGcs(String gcsPath) throws IOException { + List requests = new ArrayList<>(); + + ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); + Image img = Image.newBuilder().setSource(imgSource).build(); + Feature feat = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build(); + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build(); + requests.add(request); + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); + List responses = response.getResponsesList(); + + for (AnnotateImageResponse res : responses) { + if (res.hasError()) { + System.out.format("Error: %s%n", res.getError().getMessage()); + return; + } + + // For full list of available annotations, see http://g.co/cloud/vision/docs + for (EntityAnnotation annotation : res.getLabelAnnotationsList()) { + annotation + .getAllFields() + .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString())); + } + } + } + } +} +// [END vision_label_detection_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectLandmarks.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLandmarks.java new file mode 100644 index 00000000000..5147e1e11dc --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLandmarks.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_landmark_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.cloud.vision.v1.LocationInfo; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectLandmarks { + public static void detectLandmarks() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectLandmarks(filePath); + } + + // Detects landmarks in the specified local image. + public static void detectLandmarks(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.LANDMARK_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.getLandmarkAnnotationsList()) { + LocationInfo info = annotation.getLocationsList().listIterator().next(); + System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); + } + } + } + } +} +// [END vision_landmark_detection] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectLandmarksGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLandmarksGcs.java new file mode 100644 index 00000000000..c5ff0c1e129 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLandmarksGcs.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_landmark_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 com.google.cloud.vision.v1.LocationInfo; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectLandmarksGcs { + + public static void detectLandmarksGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectLandmarksGcs(filePath); + } + + // Detects landmarks in the specified remote image on Google Cloud Storage. + public static void detectLandmarksGcs(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.LANDMARK_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.getLandmarkAnnotationsList()) { + LocationInfo info = annotation.getLocationsList().listIterator().next(); + System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); + } + } + } + } +} +// [END vision_landmark_detection_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectLandmarksUrl.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLandmarksUrl.java new file mode 100644 index 00000000000..ff52931863e --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLandmarksUrl.java @@ -0,0 +1,72 @@ +/* + * 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; + +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 com.google.cloud.vision.v1.LocationInfo; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectLandmarksUrl { + + public static void detectLandmarksUrl() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectLandmarksUrl(filePath); + } + + // Detects landmarks in the specified URI. + public static void detectLandmarksUrl(String uri) throws IOException { + List requests = new ArrayList<>(); + + ImageSource imgSource = ImageSource.newBuilder().setImageUri(uri).build(); + Image img = Image.newBuilder().setSource(imgSource).build(); + Feature feat = Feature.newBuilder().setType(Feature.Type.LANDMARK_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.getLandmarkAnnotationsList()) { + LocationInfo info = annotation.getLocationsList().listIterator().next(); + System.out.format("Landmark: %s%n %s%n", annotation.getDescription(), info.getLatLng()); + } + } + } + } +} diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectLogos.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLogos.java new file mode 100644 index 00000000000..22785a21dd0 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLogos.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_logo_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 DetectLogos { + public static void detectLogos() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectLogos(filePath); + } + + // Detects logos in the specified local image. + + public static void detectLogos(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.LOGO_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.getLogoAnnotationsList()) { + System.out.println(annotation.getDescription()); + } + } + } + } +} +// [END vision_logo_detection] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectLogosGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLogosGcs.java new file mode 100644 index 00000000000..e7e0c2002bd --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectLogosGcs.java @@ -0,0 +1,73 @@ +/* + * 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_logo_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 DetectLogosGcs { + + public static void detectLogosGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectLogosGcs(filePath); + } + + // Detects logos in the specified remote image on Google Cloud Storage. + public static void detectLogosGcs(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.LOGO_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.getLogoAnnotationsList()) { + System.out.println(annotation.getDescription()); + } + } + } + } +} +// [END vision_logo_detection_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectProperties.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectProperties.java new file mode 100644 index 00000000000..9fd022b6469 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectProperties.java @@ -0,0 +1,81 @@ +/* + * 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_image_property_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.ColorInfo; +import com.google.cloud.vision.v1.DominantColorsAnnotation; +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 DetectProperties { + public static void detectProperties() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectProperties(filePath); + } + + // Detects image properties such as color frequency from the specified local image. + public static void detectProperties(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.IMAGE_PROPERTIES).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 + DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors(); + for (ColorInfo color : colors.getColorsList()) { + System.out.format( + "fraction: %f%nr: %f, g: %f, b: %f%n", + color.getPixelFraction(), + color.getColor().getRed(), + color.getColor().getGreen(), + color.getColor().getBlue()); + } + } + } + } +} +// [END vision_image_property_detection] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectPropertiesGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectPropertiesGcs.java new file mode 100644 index 00000000000..2a974c63296 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectPropertiesGcs.java @@ -0,0 +1,81 @@ +/* + * 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_image_property_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.ColorInfo; +import com.google.cloud.vision.v1.DominantColorsAnnotation; +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 DetectPropertiesGcs { + + public static void detectPropertiesGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectPropertiesGcs(filePath); + } + + // Detects image properties such as color frequency from the specified remote image on Google + // Cloud Storage. + public static void detectPropertiesGcs(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.IMAGE_PROPERTIES).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 + DominantColorsAnnotation colors = res.getImagePropertiesAnnotation().getDominantColors(); + for (ColorInfo color : colors.getColorsList()) { + System.out.format( + "fraction: %f%nr: %f, g: %f, b: %f%n", + color.getPixelFraction(), + color.getColor().getRed(), + color.getColor().getGreen(), + color.getColor().getBlue()); + } + } + } + } +} +// [END vision_image_property_detection_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectSafeSearch.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectSafeSearch.java new file mode 100644 index 00000000000..351869f8172 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectSafeSearch.java @@ -0,0 +1,79 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_safe_search_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.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.SafeSearchAnnotation; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectSafeSearch { + public static void detectSafeSearch() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectSafeSearch(filePath); + } + + // Detects whether the specified image has features you would want to moderate. + public static void detectSafeSearch(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.SAFE_SEARCH_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 + SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); + System.out.format( + "adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n", + annotation.getAdult(), + annotation.getMedical(), + annotation.getSpoof(), + annotation.getViolence(), + annotation.getRacy()); + } + } + } +} +// [END vision_safe_search_detection] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectSafeSearchGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectSafeSearchGcs.java new file mode 100644 index 00000000000..619404b6753 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectSafeSearchGcs.java @@ -0,0 +1,80 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_safe_search_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.Feature; +import com.google.cloud.vision.v1.Feature.Type; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageSource; +import com.google.cloud.vision.v1.SafeSearchAnnotation; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectSafeSearchGcs { + + public static void detectSafeSearchGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectSafeSearchGcs(filePath); + } + + // Detects whether the specified image on Google Cloud Storage has features you would want to + // moderate. + public static void detectSafeSearchGcs(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(Type.SAFE_SEARCH_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 + SafeSearchAnnotation annotation = res.getSafeSearchAnnotation(); + System.out.format( + "adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n", + annotation.getAdult(), + annotation.getMedical(), + annotation.getSpoof(), + annotation.getViolence(), + annotation.getRacy()); + } + } + } +} +// [END vision_safe_search_detection_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectText.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectText.java new file mode 100644 index 00000000000..8cac7288a5e --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectText.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision.snippets; + +// [START vision_text_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 DetectText { + public static void detectText() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectText(filePath); + } + + // Detects text in the specified image. + public static void detectText(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.TEXT_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.getTextAnnotationsList()) { + System.out.format("Text: %s%n", annotation.getDescription()); + System.out.format("Position : %s%n", annotation.getBoundingPoly()); + } + } + } + } +} +// [END vision_text_detection] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectTextGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectTextGcs.java new file mode 100644 index 00000000000..18bedcdcf5c --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectTextGcs.java @@ -0,0 +1,74 @@ +/* + * 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_text_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 DetectTextGcs { + + public static void detectTextGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectTextGcs(filePath); + } + + // Detects text in the specified remote image on Google Cloud Storage. + public static void detectTextGcs(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.TEXT_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.getTextAnnotationsList()) { + System.out.format("Text: %s%n", annotation.getDescription()); + System.out.format("Position : %s%n", annotation.getBoundingPoly()); + } + } + } + } +} +// [END vision_text_detection_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebDetections.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebDetections.java new file mode 100644 index 00000000000..98a74f4d691 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebDetections.java @@ -0,0 +1,105 @@ +/* + * 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_web_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.Feature; +import com.google.cloud.vision.v1.Feature.Type; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.WebDetection; +import com.google.cloud.vision.v1.WebDetection.WebEntity; +import com.google.cloud.vision.v1.WebDetection.WebImage; +import com.google.cloud.vision.v1.WebDetection.WebLabel; +import com.google.cloud.vision.v1.WebDetection.WebPage; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectWebDetections { + + public static void detectWebDetections() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectWebDetections(filePath); + } + + // Finds references to the specified image on the web. + public static void detectWebDetections(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(Type.WEB_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; + } + + // Search the web for usages of the image. You could use these signals later + // for user input moderation or linking external references. + // For a full list of available annotations, see http://g.co/cloud/vision/docs + WebDetection annotation = res.getWebDetection(); + System.out.println("Entity:Id:Score"); + System.out.println("==============="); + for (WebEntity entity : annotation.getWebEntitiesList()) { + System.out.println( + entity.getDescription() + " : " + entity.getEntityId() + " : " + entity.getScore()); + } + for (WebLabel label : annotation.getBestGuessLabelsList()) { + System.out.format("%nBest guess label: %s", label.getLabel()); + } + System.out.println("%nPages with matching images: Score%n=="); + for (WebPage page : annotation.getPagesWithMatchingImagesList()) { + System.out.println(page.getUrl() + " : " + page.getScore()); + } + System.out.println("%nPages with partially matching images: Score%n=="); + for (WebImage image : annotation.getPartialMatchingImagesList()) { + System.out.println(image.getUrl() + " : " + image.getScore()); + } + System.out.println("%nPages with fully matching images: Score%n=="); + for (WebImage image : annotation.getFullMatchingImagesList()) { + System.out.println(image.getUrl() + " : " + image.getScore()); + } + System.out.println("%nPages with visually similar images: Score%n=="); + for (WebImage image : annotation.getVisuallySimilarImagesList()) { + System.out.println(image.getUrl() + " : " + image.getScore()); + } + } + } + } +} +// [END vision_web_detection] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebDetectionsGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebDetectionsGcs.java new file mode 100644 index 00000000000..484a6711cc6 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebDetectionsGcs.java @@ -0,0 +1,99 @@ +/* + * 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_web_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.Feature; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageSource; +import com.google.cloud.vision.v1.WebDetection; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class DetectWebDetectionsGcs { + + public static void detectWebDetectionsGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectWebDetectionsGcs(filePath); + } + + // Detects whether the remote image on Google Cloud Storage has features you would want to + // moderate. + public static void detectWebDetectionsGcs(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.WEB_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; + } + + // Search the web for usages of the image. You could use these signals later + // for user input moderation or linking external references. + // For a full list of available annotations, see http://g.co/cloud/vision/docs + WebDetection annotation = res.getWebDetection(); + System.out.println("Entity:Id:Score"); + System.out.println("==============="); + for (WebDetection.WebEntity entity : annotation.getWebEntitiesList()) { + System.out.println( + entity.getDescription() + " : " + entity.getEntityId() + " : " + entity.getScore()); + } + for (WebDetection.WebLabel label : annotation.getBestGuessLabelsList()) { + System.out.format("%nBest guess label: %s", label.getLabel()); + } + System.out.println("%nPages with matching images: Score%n=="); + for (WebDetection.WebPage page : annotation.getPagesWithMatchingImagesList()) { + System.out.println(page.getUrl() + " : " + page.getScore()); + } + System.out.println("%nPages with partially matching images: Score%n=="); + for (WebDetection.WebImage image : annotation.getPartialMatchingImagesList()) { + System.out.println(image.getUrl() + " : " + image.getScore()); + } + System.out.println("%nPages with fully matching images: Score%n=="); + for (WebDetection.WebImage image : annotation.getFullMatchingImagesList()) { + System.out.println(image.getUrl() + " : " + image.getScore()); + } + System.out.println("%nPages with visually similar images: Score%n=="); + for (WebDetection.WebImage image : annotation.getVisuallySimilarImagesList()) { + System.out.println(image.getUrl() + " : " + image.getScore()); + } + } + } + } +} +// [END vision_web_detection_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntities.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntities.java new file mode 100644 index 00000000000..1e3385bc7f2 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntities.java @@ -0,0 +1,76 @@ +/* + * 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_web_detection] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Feature.Type; +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.Arrays; + +public class DetectWebEntities { + + public static void detectWebEntities() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectWebEntities(filePath); + } + + // Find web entities given a local image. + public static void detectWebEntities(String filePath) throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + // Read in the local image + ByteString contents = ByteString.readFrom(new FileInputStream(filePath)); + + // Build the image + Image image = Image.newBuilder().setContent(contents).build(); + + // Create the request with the image and the specified feature: web detection + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION)) + .setImage(image) + .build(); + + // Perform the request + BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); + + // Display the results + response.getResponsesList().stream() + .forEach( + r -> + r.getWebDetection().getWebEntitiesList().stream() + .forEach( + entity -> { + System.out.format("Description: %s%n", entity.getDescription()); + System.out.format("Score: %f%n", entity.getScore()); + })); + } + } +} +// [END vision_web_detection] \ No newline at end of file diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntitiesGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntitiesGcs.java new file mode 100644 index 00000000000..5e4fab05bc9 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntitiesGcs.java @@ -0,0 +1,70 @@ +/* + * 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; + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +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.Arrays; + +public class DetectWebEntitiesGcs { + + public static void detectWebEntitiesGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectWebEntitiesGcs(filePath); + } + + // Find web entities given the remote image on Google Cloud Storage. + public static void detectWebEntitiesGcs(String gcsPath) throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + // Set the image source to the given gs uri + ImageSource imageSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); + // Build the image + Image image = Image.newBuilder().setSource(imageSource).build(); + + // Create the request with the image and the specified feature: web detection + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(Feature.newBuilder().setType(Feature.Type.WEB_DETECTION)) + .setImage(image) + .build(); + + // Perform the request + BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); + + // Display the results + response.getResponsesList().stream() + .forEach( + r -> + r.getWebDetection().getWebEntitiesList().stream() + .forEach( + entity -> { + System.out.format("Description: %s%n", entity.getDescription()); + System.out.format("Score: %f%n", entity.getScore()); + })); + } + } +} diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntitiesIncludeGeoResults.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntitiesIncludeGeoResults.java new file mode 100644 index 00000000000..f1a0f58c969 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntitiesIncludeGeoResults.java @@ -0,0 +1,87 @@ +/* + * 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_web_detection_include_geo] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +import com.google.cloud.vision.v1.Feature; +import com.google.cloud.vision.v1.Feature.Type; +import com.google.cloud.vision.v1.Image; +import com.google.cloud.vision.v1.ImageAnnotatorClient; +import com.google.cloud.vision.v1.ImageContext; +import com.google.cloud.vision.v1.WebDetectionParams; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Arrays; + +public class DetectWebEntitiesIncludeGeoResults { + + public static void detectWebEntitiesIncludeGeoResults() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "path/to/your/image/file.jpg"; + detectWebEntitiesIncludeGeoResults(filePath); + } + + // Find web entities given a local image. + public static void detectWebEntitiesIncludeGeoResults(String filePath) throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + // Read in the local image + ByteString contents = ByteString.readFrom(new FileInputStream(filePath)); + + // Build the image + Image image = Image.newBuilder().setContent(contents).build(); + + // Enable `IncludeGeoResults` + WebDetectionParams webDetectionParams = + WebDetectionParams.newBuilder().setIncludeGeoResults(true).build(); + + // Set the parameters for the image + ImageContext imageContext = + ImageContext.newBuilder().setWebDetectionParams(webDetectionParams).build(); + + // Create the request with the image, imageContext, and the specified feature: web detection + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION)) + .setImage(image) + .setImageContext(imageContext) + .build(); + + // Perform the request + BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); + + // Display the results + response.getResponsesList().stream() + .forEach( + r -> + r.getWebDetection().getWebEntitiesList().stream() + .forEach( + entity -> { + System.out.format("Description: %s%n", entity.getDescription()); + System.out.format("Score: %f%n", entity.getScore()); + })); + } + } +} +// [END vision_web_detection_include_geo] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntitiesIncludeGeoResultsGcs.java b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntitiesIncludeGeoResultsGcs.java new file mode 100644 index 00000000000..d6dc1941ea3 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/DetectWebEntitiesIncludeGeoResultsGcs.java @@ -0,0 +1,84 @@ +/* + * 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_web_detection_include_geo_gcs] + +import com.google.cloud.vision.v1.AnnotateImageRequest; +import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; +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.ImageContext; +import com.google.cloud.vision.v1.ImageSource; +import com.google.cloud.vision.v1.WebDetectionParams; +import java.io.IOException; +import java.util.Arrays; + +public class DetectWebEntitiesIncludeGeoResultsGcs { + + public static void detectWebEntitiesIncludeGeoResultsGcs() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg"; + detectWebEntitiesIncludeGeoResultsGcs(filePath); + } + + // Find web entities given the remote image on Google Cloud Storage. + public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath) throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { + // Set the image source to the given gs uri + ImageSource imageSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build(); + // Build the image + Image image = Image.newBuilder().setSource(imageSource).build(); + + // Enable `IncludeGeoResults` + WebDetectionParams webDetectionParams = + WebDetectionParams.newBuilder().setIncludeGeoResults(true).build(); + + // Set the parameters for the image + ImageContext imageContext = + ImageContext.newBuilder().setWebDetectionParams(webDetectionParams).build(); + + // Create the request with the image, imageContext, and the specified feature: web detection + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder() + .addFeatures(Feature.newBuilder().setType(Feature.Type.WEB_DETECTION)) + .setImage(image) + .setImageContext(imageContext) + .build(); + + // Perform the request + BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request)); + + // Display the results + response.getResponsesList().stream() + .forEach( + r -> + r.getWebDetection().getWebEntitiesList().stream() + .forEach( + entity -> { + System.out.format("Description: %s%n", entity.getDescription()); + System.out.format("Score: %f%n", entity.getScore()); + })); + } + } +} +// [END vision_web_detection_include_geo_gcs] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/PurgeProducts.java b/vision/snippets/src/main/java/com/example/vision/snippets/PurgeProducts.java new file mode 100644 index 00000000000..dc0fd2d3c86 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/PurgeProducts.java @@ -0,0 +1,57 @@ +/* + * Copyright 2019 Google LLC + * + * 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_product_search_purge_orphan_products] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.vision.v1.LocationName; +import com.google.cloud.vision.v1.ProductSearchClient; +import com.google.cloud.vision.v1.PurgeProductsRequest; +import java.util.concurrent.TimeUnit; + +public class PurgeProducts { + + // Delete the product and all its reference images. + public static void purgeOrphanProducts(String projectId, String computeRegion) throws Exception { + + // String projectId = "YOUR_PROJECT_ID"; + // String computeRegion = "us-central1"; + // boolean force = true; + + try (ProductSearchClient client = ProductSearchClient.create()) { + String parent = LocationName.format(projectId, computeRegion); + + // The purge operation is async. + PurgeProductsRequest request = + PurgeProductsRequest.newBuilder() + .setDeleteOrphanProducts(true) + // The operation is irreversible and removes multiple products. + // The user is required to pass in force=True to actually perform the + // purge. + // If force is not set to True, the service raises an exception. + .setForce(true) + .setParent(parent) + .build(); + + OperationFuture response = client.purgeProductsAsync(request); + response.getPollingFuture().get(180, TimeUnit.SECONDS); + + System.out.println("Orphan products deleted."); + } + } +} +// [END vision_product_search_purge_orphan_products] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/PurgeProductsInProductSet.java b/vision/snippets/src/main/java/com/example/vision/snippets/PurgeProductsInProductSet.java new file mode 100644 index 00000000000..8ed6906c2d3 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/PurgeProductsInProductSet.java @@ -0,0 +1,64 @@ +/* + * Copyright 2019 Google LLC + * + * 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_product_search_purge_products_in_product_set] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.vision.v1.BatchOperationMetadata; +import com.google.cloud.vision.v1.LocationName; +import com.google.cloud.vision.v1.ProductSearchClient; +import com.google.cloud.vision.v1.ProductSetPurgeConfig; +import com.google.cloud.vision.v1.PurgeProductsRequest; +import com.google.protobuf.Empty; +import java.util.concurrent.TimeUnit; + +public class PurgeProductsInProductSet { + + // Delete all products in a product set. + public static void purgeProductsInProductSet( + String projectId, String location, String productSetId) throws Exception { + + // String projectId = "YOUR_PROJECT_ID"; + // String location = "us-central1"; + // String productSetId = "YOUR_PRODUCT_SET_ID"; + // boolean force = true; + + try (ProductSearchClient client = ProductSearchClient.create()) { + + String parent = LocationName.format(projectId, location); + ProductSetPurgeConfig productSetPurgeConfig = + ProductSetPurgeConfig.newBuilder().setProductSetId(productSetId).build(); + + PurgeProductsRequest request = + PurgeProductsRequest.newBuilder() + .setParent(parent) + .setProductSetPurgeConfig(productSetPurgeConfig) + // The operation is irreversible and removes multiple products. + // The user is required to pass in force=True to actually perform the + // purge. + // If force is not set to True, the service raises an exception. + .setForce(true) + .build(); + + OperationFuture response = client.purgeProductsAsync(request); + response.getPollingFuture().get(180, TimeUnit.SECONDS); + + System.out.println("Products removed from product set."); + } + } +} +// [END vision_product_search_purge_products_in_product_set] diff --git a/vision/snippets/src/main/java/com/example/vision/snippets/SetEndpoint.java b/vision/snippets/src/main/java/com/example/vision/snippets/SetEndpoint.java new file mode 100644 index 00000000000..7aeb05abb70 --- /dev/null +++ b/vision/snippets/src/main/java/com/example/vision/snippets/SetEndpoint.java @@ -0,0 +1,68 @@ +/* + * Copyright 2019 Google LLC + * + * 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; + +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.ImageAnnotatorSettings; +import com.google.cloud.vision.v1.ImageSource; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class SetEndpoint { + + // Change your endpoint + public static void setEndpoint() throws IOException { + // [START vision_set_endpoint] + ImageAnnotatorSettings settings = + ImageAnnotatorSettings.newBuilder().setEndpoint("eu-vision.googleapis.com:443").build(); + + // 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. + ImageAnnotatorClient client = ImageAnnotatorClient.create(settings); + // [END vision_set_endpoint] + + ImageSource imgSource = + ImageSource.newBuilder() + .setGcsImageUri("gs://cloud-samples-data/vision/text/screen.jpg") + .build(); + Image image = Image.newBuilder().setSource(imgSource).build(); + Feature feature = Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION).build(); + AnnotateImageRequest request = + AnnotateImageRequest.newBuilder().addFeatures(feature).setImage(image).build(); + List requests = new ArrayList<>(); + requests.add(request); + + BatchAnnotateImagesResponse batchResponse = client.batchAnnotateImages(requests); + + for (AnnotateImageResponse response : batchResponse.getResponsesList()) { + for (EntityAnnotation annotation : response.getTextAnnotationsList()) { + System.out.format("Text: %s%n", annotation.getDescription()); + System.out.println("Position:"); + System.out.format("%s%n", annotation.getBoundingPoly()); + } + } + client.close(); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java b/vision/snippets/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java new file mode 100644 index 00000000000..9aa73d5754a --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java @@ -0,0 +1,93 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; +import 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; +import com.google.cloud.storage.StorageOptions; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class AsyncBatchAnnotateImagesTest { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = "gs://cloud-samples-data/vision/label/wakeupcat.jpg"; + private static final String PREFIX = String.format("vision/%s/", UUID.randomUUID().toString()); + private static final String OUTPUT_URI = String.format("gs://%s/%s", PROJECT_ID, PREFIX); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + System.getenv(varName), + "Environment variable '%s' is required to perform these tests.".format(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + + Storage storage = StorageOptions.getDefaultInstance().getService(); + + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + for (Blob blob : blobs.iterateAll()) { + blob.delete(); + } + } + + @Test + public void testSetEndpoint() throws IOException, ExecutionException, InterruptedException { + AsyncBatchAnnotateImages.asyncBatchAnnotateImages(INPUT_URI, OUTPUT_URI); + String got = bout.toString(); + assertThat(got).contains("Output written to GCS with prefix"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java b/vision/snippets/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java new file mode 100644 index 00000000000..0c0b183dadf --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.BatchAnnotateFilesGcs; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchAnnotateFilesGcsTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testSetEndpoint() throws IOException { + BatchAnnotateFilesGcs.batchAnnotateFilesGcs( + "gs://cloud-samples-data/vision/document_understanding/kafka.pdf"); + + String got = bout.toString(); + assertThat(got).contains("Word confidence"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/BatchAnnotateFilesTest.java b/vision/snippets/src/test/java/com/example/vision/BatchAnnotateFilesTest.java new file mode 100644 index 00000000000..03cea5c6847 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/BatchAnnotateFilesTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.BatchAnnotateFiles; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchAnnotateFilesTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testSetEndpoint() throws IOException { + BatchAnnotateFiles.batchAnnotateFiles("resources/kafka.pdf"); + + String got = bout.toString(); + assertThat(got).contains("Word confidence"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectBetaIT.java b/vision/snippets/src/test/java/com/example/vision/DetectBetaIT.java new file mode 100644 index 00000000000..d02ff9779d8 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectBetaIT.java @@ -0,0 +1,157 @@ +/* + * Copyright 2018 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.Storage.BlobListOption; +import com.google.cloud.storage.StorageOptions; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for vision "Detect" sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectBetaIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String BUCKET = "java-docs-samples-testing"; + private static final String OUTPUT_BUCKET = PROJECT_ID; + private static final String OUTPUT_PREFIX = "OUTPUT_VISION_BETA_" + UUID.randomUUID().toString(); + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + private DetectBeta app; + + @Before + public void setUp() throws IOException { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + app = new DetectBeta(); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDetectLocalizedObjects() throws Exception { + // Act + String[] args = {"object-localization", "./resources/puppies.jpg"}; + DetectBeta.argsHelper(args, out); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Dog"); + } + + @Test + public void testDetectHandwrittenOcr() throws Exception { + // Act + String[] args = {"handwritten-ocr", "./resources/handwritten.jpg"}; + DetectBeta.argsHelper(args, out); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Google"); + assertThat(got).contains("Cloud"); + assertThat(got).contains("Platform"); + } + + @Test + public void testDetectLocalizedObjectsGcs() throws Exception { + // Act + String[] args = {"object-localization", "gs://cloud-samples-data/vision/puppies.jpg"}; + DetectBeta.argsHelper(args, out); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Dog"); + } + + @Test + public void testDetectHandwrittenOcrGcs() throws Exception { + // Act + String[] args = { + "handwritten-ocr", "gs://cloud-samples-data/vision/handwritten.jpg", + }; + DetectBeta.argsHelper(args, out); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Google"); + assertThat(got).contains("Cloud"); + assertThat(got).contains("Platform"); + } + + @Test + public void testDetectDocumentFeatures() { + // Act + DetectBatchAnnotateFiles.detectBatchAnnotateFiles("./resources/kafka.pdf"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Samsa"); + } + + @Test + public void testDetectDocumentFeaturesGcs() throws Exception { + // Act + DetectBatchAnnotateFilesGcs.detectBatchAnnotateFilesGcs( + "gs://cloud-samples-data/video/kafka.pdf"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Samsa"); + } + + @Test + public void testAsyncBatchAnnotateImagesGcs() throws Exception { + // Act + AsyncBatchAnnotateImagesGcs.asyncBatchAnnotateImagesGcs( + "gs://cloud-samples-data/vision/label/wakeupcat.jpg", + "gs://" + OUTPUT_BUCKET + "/" + OUTPUT_PREFIX + "/"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("red:"); + + Storage storage = StorageOptions.getDefaultInstance().getService(); + + Page blobs = + storage.list( + OUTPUT_BUCKET, + BlobListOption.currentDirectory(), + BlobListOption.prefix(OUTPUT_PREFIX + "/")); + for (Blob blob : blobs.iterateAll()) { + blob.delete(); + } + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectCropHintsGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectCropHintsGcsTest.java new file mode 100644 index 00000000000..98b4259a8c2 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectCropHintsGcsTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectCropHintsGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.regex.Pattern; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectCropHintsGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testCropHintsGcs() throws Exception { + // Act + DetectCropHintsGcs.detectCropHintsGcs("gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("vertices {"); + assertThat(got).containsMatch(Pattern.compile("x: 2\\d{2}")); + assertThat(got).containsMatch(Pattern.compile("y: 4\\d{2}")); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectCropHintsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectCropHintsTest.java new file mode 100644 index 00000000000..664105e66f1 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectCropHintsTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectCropHints; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.regex.Pattern; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectCropHintsTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testCropHints() throws Exception { + // Act + DetectCropHints.detectCropHints("./resources/wakeupcat.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("vertices {"); + assertThat(got).containsMatch(Pattern.compile("x: 2\\d{2}")); + assertThat(got).containsMatch(Pattern.compile("y: 4\\d{2}")); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectFacesGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectFacesGcsTest.java new file mode 100644 index 00000000000..55cef3e5d8f --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectFacesGcsTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectFacesGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectFacesGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @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/snippets/src/test/java/com/example/vision/DetectFacesTest.java b/vision/snippets/src/test/java/com/example/vision/DetectFacesTest.java new file mode 100644 index 00000000000..105841906ee --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectFacesTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectFaces; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectFacesTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @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/snippets/src/test/java/com/example/vision/DetectIT.java b/vision/snippets/src/test/java/com/example/vision/DetectIT.java new file mode 100644 index 00000000000..dff4d75c376 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectIT.java @@ -0,0 +1,133 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.Storage.BlobListOption; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for vision "Detect" sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIT { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + private static final String ASSET_BUCKET = "cloud-samples-data"; + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String OUTPUT_BUCKET = PROJECT_ID; + private static final String OUTPUT_PREFIX = "OCR_PDF_TEST_OUTPUT_" + UUID.randomUUID().toString(); + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testDocumentText() throws Exception { + // Act + Detect.detectDocumentText("./resources/text.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("After preparation is complete, the "); + assertThat(got).contains("37%"); + assertThat(got).contains("Word text: class (confidence:"); + } + + @Test + public void testDocumentTextGcs() throws Exception { + // Act + Detect.detectDocumentTextGcs("gs://" + ASSET_BUCKET + "/vision/text/screen.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("After preparation is complete, the "); + assertThat(got).contains("37%"); + assertThat(got).contains("Word text: class (confidence:"); + } + + @Test + public void testDetectDocumentsGcs() throws Exception { + // Act + Detect.detectDocumentsGcs( + "gs://" + ASSET_BUCKET + "/vision/document/custom_0773375000.pdf", + "gs://" + OUTPUT_BUCKET + "/" + OUTPUT_PREFIX + "/"); + + // Assert + String got = bout.toString(); + + assertThat(got).contains("OIL, GAS AND MINERAL LEASE"); + + Storage storage = StorageOptions.getDefaultInstance().getService(); + + Page blobs = + storage.list( + OUTPUT_BUCKET, + BlobListOption.currentDirectory(), + BlobListOption.prefix(OUTPUT_PREFIX + "/")); + for (Blob blob : blobs.iterateAll()) { + blob.delete(); + } + } + + @Test + public void testDetectLocalizedObjects() throws Exception { + // Act + Detect.detectLocalizedObjects("./resources/puppies.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("dog"); + } + + @Test + public void testDetectLocalizedObjectsGcs() throws Exception { + // Act + Detect.detectLocalizedObjectsGcs( + "gs://cloud-samples-data/vision/object_localization/puppies.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("dog"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectLabelsGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectLabelsGcsTest.java new file mode 100644 index 00000000000..40da0e0e054 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectLabelsGcsTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectLabelsGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLabelsGcsTest { + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @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/snippets/src/test/java/com/example/vision/DetectLabelsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectLabelsTest.java new file mode 100644 index 00000000000..a2c1e548d2f --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectLabelsTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectLabels; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLabelsTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @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/snippets/src/test/java/com/example/vision/DetectLandmarksGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectLandmarksGcsTest.java new file mode 100644 index 00000000000..070e73cd63f --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectLandmarksGcsTest.java @@ -0,0 +1,80 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectLandmarksGcs; +import com.example.vision.snippets.DetectLandmarksUrl; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLandmarksGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testLandmarksUrl() throws Exception { + // Act + String uri = + "https://storage-download.googleapis.com/" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"; + DetectLandmarksUrl.detectLandmarksUrl(uri); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("palace of fine arts"); + } + + @Test + public void testLandmarksGcs() throws Exception { + // Act + DetectLandmarksGcs.detectLandmarksGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("palace of fine arts"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectLandmarksTest.java b/vision/snippets/src/test/java/com/example/vision/DetectLandmarksTest.java new file mode 100644 index 00000000000..bfcc18f0639 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectLandmarksTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectLandmarks; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLandmarksTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testLandmarks() throws Exception { + // Act + DetectLandmarks.detectLandmarks("./resources/landmark.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("palace of fine arts"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectLogosGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectLogosGcsTest.java new file mode 100644 index 00000000000..5f052ef7344 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectLogosGcsTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectLogosGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLogosGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testLogosGcs() throws Exception { + // Act + DetectLogosGcs.detectLogosGcs("gs://" + ASSET_BUCKET + "/vision/logo/logo_google.png"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("google"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectLogosTest.java b/vision/snippets/src/test/java/com/example/vision/DetectLogosTest.java new file mode 100644 index 00000000000..78f843578c2 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectLogosTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectLogos; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLogosTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testLogos() throws Exception { + // Act + DetectLogos.detectLogos("./resources/logos.png"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("google"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectPropertiesGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectPropertiesGcsTest.java new file mode 100644 index 00000000000..2a2f67bf4fe --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectPropertiesGcsTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectPropertiesGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectPropertiesGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testPropertiesGcs() throws Exception { + // Act + DetectPropertiesGcs.detectPropertiesGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("fraction:"); + assertThat(got).contains("r:"); + assertThat(got).contains("g:"); + assertThat(got).contains("b:"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectPropertiesTest.java b/vision/snippets/src/test/java/com/example/vision/DetectPropertiesTest.java new file mode 100644 index 00000000000..31b6e7582d4 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectPropertiesTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectProperties; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectPropertiesTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testProperties() throws Exception { + // Act + DetectProperties.detectProperties("./resources/landmark.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("fraction:"); + assertThat(got).contains("r:"); + assertThat(got).contains("g:"); + assertThat(got).contains("b:"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectSafeSearchGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectSafeSearchGcsTest.java new file mode 100644 index 00000000000..0ae890a5209 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectSafeSearchGcsTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectSafeSearchGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectSafeSearchGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testSafeSearchGcs() throws Exception { + // Act + DetectSafeSearchGcs.detectSafeSearchGcs("gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("adult:"); + assertThat(got).contains("racy:"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectSafeSearchTest.java b/vision/snippets/src/test/java/com/example/vision/DetectSafeSearchTest.java new file mode 100644 index 00000000000..dd0617e0e6d --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectSafeSearchTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectSafeSearch; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectSafeSearchTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testSafeSearch() throws Exception { + // Act + DetectSafeSearch.detectSafeSearch("./resources/wakeupcat.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("adult:"); + assertThat(got).contains("racy:"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectTextGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectTextGcsTest.java new file mode 100644 index 00000000000..f0693e76721 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectTextGcsTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectTextGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectTextGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTextGcs() throws Exception { + // Act + DetectTextGcs.detectTextGcs("gs://" + ASSET_BUCKET + "/vision/text/screen.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("37%"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectTextTest.java b/vision/snippets/src/test/java/com/example/vision/DetectTextTest.java new file mode 100644 index 00000000000..487694f6197 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectTextTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectText; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectTextTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testText() throws Exception { + // Act + DetectText.detectText("./resources/text.jpg"); + + // Assert + String got = bout.toString(); + assertThat(got).contains("37%"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectWebDetectionsGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectWebDetectionsGcsTest.java new file mode 100644 index 00000000000..ce73a2c4b0c --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectWebDetectionsGcsTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectWebDetectionsGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectWebDetectionsGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDetectWebAnnotationsGcs() throws Exception { + // Act + DetectWebDetectionsGcs.detectWebDetectionsGcs( + "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("entity:id:score"); + assertThat(got).contains("best guess label"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectWebDetectionsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectWebDetectionsTest.java new file mode 100644 index 00000000000..a0ea302cb65 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectWebDetectionsTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectWebDetections; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectWebDetectionsTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void detectWebAnnotations() throws Exception { + // Act + DetectWebDetections.detectWebDetections("./resources/landmark.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).contains("entity:id:score"); + assertThat(got).contains("best guess label"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesGcsTest.java new file mode 100644 index 00000000000..f205fc21a63 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesGcsTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2017 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectWebEntitiesGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectWebEntitiesGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDetectWebEntitiesGcs() throws Exception { + // Act + DetectWebEntitiesGcs.detectWebEntitiesGcs("gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); + + String got = bout.toString().toLowerCase(); + assertThat(got).contains("description"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesIncludeGeoResultsGcsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesIncludeGeoResultsGcsTest.java new file mode 100644 index 00000000000..3ebad977dd4 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesIncludeGeoResultsGcsTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectWebEntitiesIncludeGeoResultsGcs; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectWebEntitiesIncludeGeoResultsGcsTest { + + private static final String ASSET_BUCKET = "cloud-samples-data"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDetectWebEntitiesIncludeGeoResultsGcs() throws Exception { + // Act + DetectWebEntitiesIncludeGeoResultsGcs.detectWebEntitiesIncludeGeoResultsGcs( + "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"); + + String got = bout.toString().toLowerCase(); + assertThat(got).contains("description"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesIncludeGeoResultsTest.java b/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesIncludeGeoResultsTest.java new file mode 100644 index 00000000000..0dd66b71ee8 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesIncludeGeoResultsTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectWebEntitiesIncludeGeoResults; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectWebEntitiesIncludeGeoResultsTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDetectWebEntitiesIncludeGeoResults() throws Exception { + // Act + DetectWebEntitiesIncludeGeoResults.detectWebEntitiesIncludeGeoResults("./resources/city.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + // Note: entities and labels can change over time. + assertThat(got).doesNotContain("error"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesTest.java b/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesTest.java new file mode 100644 index 00000000000..fefce5aeab4 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/DetectWebEntitiesTest.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 static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.DetectWebEntities; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectWebEntitiesTest { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDetectWebEntities() throws Exception { + // Act + DetectWebEntities.detectWebEntities("./resources/city.jpg"); + + // Assert + String got = bout.toString().toLowerCase(); + assertThat(got).doesNotContain("zepra"); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/ImportProductSetsIT.java b/vision/snippets/src/test/java/com/example/vision/ImportProductSetsIT.java new file mode 100644 index 00000000000..2e5ac41f40f --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/ImportProductSetsIT.java @@ -0,0 +1,115 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.BlobId; +import com.google.cloud.storage.BlobInfo; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link ImportProductSets}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ImportProductSetsIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String COMPUTE_REGION = "us-west1"; + private static final String PRODUCT_SET_ID = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_ID_1 = String.format("test_%s", UUID.randomUUID().toString()); + private static final String IMAGE_URI_1 = "shoes_1.jpg"; + private static final String FILEPATH = + String.format("vision/%s.csv", UUID.randomUUID().toString()); + private static final String GCS_URI = String.format("gs://%s/%s", PROJECT_ID, FILEPATH); + private Blob blob; + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + // Create the product set csv file locally and upload it to GCS + // This is so that there is a unique product set ID for all java version tests. + Storage storage = StorageOptions.newBuilder().setProjectId(PROJECT_ID).build().getService(); + BlobId blobId = BlobId.of(PROJECT_ID, FILEPATH); + BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build(); + String csvContents = + "\"gs://cloud-samples-data/vision/product_search/shoes_1.jpg\"," + + String.format("\"%s\",", IMAGE_URI_1) + + String.format("\"%s\",", PRODUCT_SET_ID) + + String.format("\"%s\",", PRODUCT_ID_1) + + "\"apparel\",,\"style=womens\",\"0.1,0.1,0.9,0.1,0.9,0.9,0.1,0.9\""; + blob = storage.create(blobInfo, csvContents.getBytes()); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() throws IOException { + ProductManagement.deleteProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID_1); + ProductSetManagement.deleteProductSet(PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID); + Storage storage = StorageOptions.newBuilder().setProjectId(PROJECT_ID).build().getService(); + // Delete the created blob + storage.delete(blob.getBlobId()); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testImportProductSets() throws Exception { + // Act + ImportProductSets.importProductSets(PROJECT_ID, COMPUTE_REGION, GCS_URI); + ProductSetManagement.listProductSets(PROJECT_ID, COMPUTE_REGION); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_SET_ID); + + // Act + ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION); + + // Assert + assertThat(got).contains(PRODUCT_ID_1); + + // Act + ProductInProductSetManagement.listProductsInProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID); + + // Assert + assertThat(got).contains(PRODUCT_ID_1); + + // Act + ReferenceImageManagement.listReferenceImagesOfProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID_1); + + // Assert + assertThat(got).contains(IMAGE_URI_1); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/ProductInProductSetManagementIT.java b/vision/snippets/src/test/java/com/example/vision/ProductInProductSetManagementIT.java new file mode 100644 index 00000000000..7e9f42fd8f3 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/ProductInProductSetManagementIT.java @@ -0,0 +1,105 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link ProductInProductSetManagement}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ProductInProductSetManagementIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String COMPUTE_REGION = "us-west1"; + private static final String PRODUCT_SET_DISPLAY_NAME = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_SET_ID = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_DISPLAY_NAME = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_CATEGORY = "apparel"; + private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString()); + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws IOException { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + ProductSetManagement.createProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_SET_DISPLAY_NAME); + ProductManagement.createProduct( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY); + bout.reset(); + } + + @After + public void tearDown() throws IOException { + ProductManagement.deleteProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID); + ProductSetManagement.deleteProductSet(PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testAddProductToProductSet() throws Exception { + // Act + ProductInProductSetManagement.addProductToProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_SET_ID); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Product added to product set."); + } + + @Test + public void testRemoveProductFromProductSet() throws Exception { + // Act + ProductInProductSetManagement.addProductToProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_SET_ID); + ProductInProductSetManagement.listProductsInProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_ID); + + bout.reset(); + + // Act + ProductInProductSetManagement.removeProductFromProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_SET_ID); + ProductInProductSetManagement.listProductsInProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID); + + // Assert + got = bout.toString(); + assertThat(got).doesNotContain(PRODUCT_ID); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/ProductManagementIT.java b/vision/snippets/src/test/java/com/example/vision/ProductManagementIT.java new file mode 100644 index 00000000000..1392b1c1c68 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/ProductManagementIT.java @@ -0,0 +1,119 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link ProductManagement}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ProductManagementIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String COMPUTE_REGION = "us-west1"; + private static final String PRODUCT_DISPLAY_NAME = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_CATEGORY = "homegoods"; + private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString()); + private static final String KEY = String.format("test_%s", UUID.randomUUID().toString()); + private static final String VALUE = String.format("test_%s", UUID.randomUUID().toString()); + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws IOException { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() throws IOException { + ProductManagement.deleteProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testCreateProduct() throws Exception { + // Act + ProductManagement.createProduct( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY); + ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_ID); + } + + @Test + public void testDeleteProduct() throws Exception { + // Act + ProductManagement.createProduct( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY); + ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_ID); + + bout.reset(); + + // Act + ProductManagement.deleteProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID); + ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION); + + // Assert + got = bout.toString(); + assertThat(got).doesNotContain(PRODUCT_ID); + } + + @Test + public void testUpdateProductLabels() throws Exception { + // Act + ProductManagement.createProduct( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY); + ProductManagement.getProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID); + + // Assert + String got = bout.toString(); + assertThat(got).doesNotContain(KEY); + assertThat(got).doesNotContain(VALUE); + + bout.reset(); + + // Act + ProductManagement.updateProductLabels( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, KEY + "=" + VALUE); + + // Assert + got = bout.toString(); + assertThat(got).contains(KEY); + assertThat(got).contains(VALUE); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/ProductSearchIT.java b/vision/snippets/src/test/java/com/example/vision/ProductSearchIT.java new file mode 100644 index 00000000000..a06a39d62dc --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/ProductSearchIT.java @@ -0,0 +1,113 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import 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; + +/** + * Integration (system) tests for {@link ProductSearch}.Tests rely on pre-created product set that + * has been indexed. + */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ProductSearchIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String COMPUTE_REGION = "us-west1"; + private static final String PRODUCT_SET_ID = "indexed_product_set_id_for_testing"; + private static final String PRODUCT_CATEGORY = "apparel"; + private static final String PRODUCT_ID_1 = "indexed_product_id_for_testing_1"; + private static final String PRODUCT_ID_2 = "indexed_product_id_for_testing_2"; + private static final String IMAGE_URI_1 = + "gs://cloud-samples-data/vision/product_search/shoes_1.jpg"; + private static final String FILE_PATH_1 = "./resources/shoes_1.jpg"; + private static final String FILTER = "style=womens"; + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws Exception { + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + bout.reset(); + } + + @After + public void tearDown() throws Exception { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testGetSimilarProductsFile() throws Exception { + // Act + ProductSearch.getSimilarProductsFile( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_CATEGORY, FILE_PATH_1, ""); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_ID_1); + assertThat(got).contains(PRODUCT_ID_2); + } + + @Test + public void testGetSimilarProductsGcs() throws Exception { + // Act + ProductSearch.getSimilarProductsGcs( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_CATEGORY, IMAGE_URI_1, ""); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_ID_1); + assertThat(got).contains(PRODUCT_ID_2); + } + + @Test + public void testGetSimilarProductsFileWithFilter() throws Exception { + // Act + ProductSearch.getSimilarProductsFile( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_CATEGORY, FILE_PATH_1, FILTER); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_ID_1); + assertThat(got).doesNotContain(PRODUCT_ID_2); + } + + @Test + public void testGetSimilarProductsGcsWithFilter() throws Exception { + // Act + ProductSearch.getSimilarProductsGcs( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_CATEGORY, IMAGE_URI_1, FILTER); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_ID_1); + assertThat(got).doesNotContain(PRODUCT_ID_2); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/ProductSetManagementIT.java b/vision/snippets/src/test/java/com/example/vision/ProductSetManagementIT.java new file mode 100644 index 00000000000..556a7c43345 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/ProductSetManagementIT.java @@ -0,0 +1,72 @@ +/* + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link ProductSetManagement}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ProductSetManagementIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String COMPUTE_REGION = "us-west1"; + private static final String PRODUCT_SET_ID = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_SET_DISPLAY_NAME = + String.format("test_%s", UUID.randomUUID().toString()); + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testCreateDeleteProductSet() throws Exception { + ProductSetManagement.createProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_SET_DISPLAY_NAME); + String got = bout.toString(); + assertThat(got).contains(PRODUCT_SET_ID); + + bout.reset(); + + ProductSetManagement.deleteProductSet(PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID); + ProductSetManagement.listProductSets(PROJECT_ID, COMPUTE_REGION); + got = bout.toString(); + assertThat(got).doesNotContain(PRODUCT_SET_ID); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/ReferenceImageManagementIT.java b/vision/snippets/src/test/java/com/example/vision/ReferenceImageManagementIT.java new file mode 100644 index 00000000000..1b9d666349a --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/ReferenceImageManagementIT.java @@ -0,0 +1,87 @@ +/* + * Copyright 2018 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link ReferenceImageManagement}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ReferenceImageManagementIT { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String COMPUTE_REGION = "us-west1"; + private static final String PRODUCT_DISPLAY_NAME = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_CATEGORY = "apparel"; + private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString()); + private static final String REFERENCE_IMAGE_ID = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String GCS_URI = "gs://java-docs-samples-testing/product-search/shoes_1.jpg"; + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws IOException { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + ProductManagement.createProduct( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY); + } + + @After + public void tearDown() throws IOException { + ProductManagement.deleteProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testCreateReferenceImage() throws Exception { + // Act + ReferenceImageManagement.createReferenceImage( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, REFERENCE_IMAGE_ID, GCS_URI); + ReferenceImageManagement.listReferenceImagesOfProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID); + + // Assert + String got = bout.toString(); + assertThat(got).contains(REFERENCE_IMAGE_ID); + + bout.reset(); + + // Act + ReferenceImageManagement.deleteReferenceImage( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, REFERENCE_IMAGE_ID); + ReferenceImageManagement.listReferenceImagesOfProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID); + + // Assert + got = bout.toString(); + assertThat(got).doesNotContain(REFERENCE_IMAGE_ID); + } +} diff --git a/vision/snippets/src/test/java/com/example/vision/SetEndpointIT.java b/vision/snippets/src/test/java/com/example/vision/SetEndpointIT.java new file mode 100644 index 00000000000..eb33a7e7460 --- /dev/null +++ b/vision/snippets/src/test/java/com/example/vision/SetEndpointIT.java @@ -0,0 +1,65 @@ +/* + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.vision; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.snippets.SetEndpoint; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +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; + +/** Tests for Vision Set Endpoint */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class SetEndpointIT { + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testSetEndpoint() throws IOException { + // Act + SetEndpoint.setEndpoint(); + + // Assert + String got = bout.toString(); + assertThat(got).contains("System Software Update"); + assertThat(got).contains("x:"); + assertThat(got).contains("y:"); + } +} diff --git a/vision/snippets/src/test/java/vision/snippets/ProductInProductSetManagementTests.java b/vision/snippets/src/test/java/vision/snippets/ProductInProductSetManagementTests.java new file mode 100644 index 00000000000..34230fbf182 --- /dev/null +++ b/vision/snippets/src/test/java/vision/snippets/ProductInProductSetManagementTests.java @@ -0,0 +1,89 @@ +/* + * Copyright 2019 Google LLC + * + * 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 vision.snippets; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.ProductInProductSetManagement; +import com.example.vision.ProductManagement; +import com.example.vision.ProductSetManagement; +import com.example.vision.snippets.PurgeProductsInProductSet; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ProductInProductSetManagementTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String COMPUTE_REGION = "us-west1"; + private static final String PRODUCT_SET_DISPLAY_NAME = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_SET_ID = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_DISPLAY_NAME = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_CATEGORY = "apparel"; + private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString()); + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws IOException { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + ProductSetManagement.createProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_SET_DISPLAY_NAME); + ProductManagement.createProduct( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY); + bout.reset(); + } + + @After + public void tearDown() throws IOException { + ProductManagement.deleteProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID); + ProductSetManagement.deleteProductSet(PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testPurgeProductsInProductSet() throws Exception { + // Act + ProductInProductSetManagement.addProductToProductSet( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_SET_ID); + ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_ID); + + bout.reset(); + PurgeProductsInProductSet.purgeProductsInProductSet(PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID); + + ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION); + + // Assert + got = bout.toString(); + assertThat(got).doesNotContain(PRODUCT_ID); + } +} diff --git a/vision/snippets/src/test/java/vision/snippets/ProductManagementTests.java b/vision/snippets/src/test/java/vision/snippets/ProductManagementTests.java new file mode 100644 index 00000000000..36e6b2e9f0a --- /dev/null +++ b/vision/snippets/src/test/java/vision/snippets/ProductManagementTests.java @@ -0,0 +1,82 @@ +/* + * Copyright 2019 Google LLC + * + * 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 vision.snippets; + +import static com.google.common.truth.Truth.assertThat; + +import com.example.vision.ProductManagement; +import com.example.vision.snippets.PurgeProducts; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class ProductManagementTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String COMPUTE_REGION = "us-west1"; + private static final String PRODUCT_DISPLAY_NAME = + String.format("test_%s", UUID.randomUUID().toString()); + private static final String PRODUCT_CATEGORY = "homegoods"; + private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString()); + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws IOException { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() throws IOException { + ProductManagement.deleteProduct(PROJECT_ID, COMPUTE_REGION, PRODUCT_ID); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testPurgeOrphanProducts() throws Exception { + // Act + ProductManagement.createProduct( + PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY); + ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION); + + // Assert + String got = bout.toString(); + assertThat(got).contains(PRODUCT_ID); + + bout.reset(); + + // Act + PurgeProducts.purgeOrphanProducts(PROJECT_ID, COMPUTE_REGION); + + // Assert + got = bout.toString(); + ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION); + assertThat(got).doesNotContain(PRODUCT_ID); + } +} diff --git a/vision/spring-framework/README.md b/vision/spring-framework/README.md new file mode 100644 index 00000000000..2921d32b82d --- /dev/null +++ b/vision/spring-framework/README.md @@ -0,0 +1,35 @@ +# Cloud Vision on Spring Boot + +This sample demonstrates leveraging Cloud Vision APIs within a Spring Boot application by using +[Spring Cloud GCP libraries](https://github.com/spring-cloud/spring-cloud-gcp). + +The Spring Cloud GCP libraries for Cloud Vision offer [Spring Auto-configuration classes](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html) +and convenience libraries to allow you to more quickly start using Cloud Vision in Spring. + +## Overview + +This sample starts a [Spring Boot](https://spring.io/projects/spring-boot) application +containing a simple web interface that allows you submit image URLs and get the image's text or +classification labels through the Google Cloud Vision APIs. + +This application is built and run with [Maven](https://maven.apache.org/), a tool for building and +managing dependencies in Java projects. + +## Build and Run + +1. **Follow the set-up instructions in [the documentation](https://cloud.google.com/java/docs/setup).** + +2. Enable the Google Cloud Vision APIs for your Google Cloud Platform project. + [Click here](https://console.cloud.google.com/flows/enableapi?apiid=vision.googleapis.com) + to visit Cloud Platform Console and enable the Google Cloud Vision APIs. + +3. After following step 1, you should have the `gcloud` command line tool installed. + Open up a terminal and run the command `gcloud auth application-default login`. + This will provide the account authentication necessary to run the application. + +4. In this directory, run the following Maven command to start the Spring Boot application. + ``` + mvn clean spring-boot:run + ``` + +5. After running the command, the application can be visited at http://localhost:8080/. diff --git a/vision/spring-framework/pom.xml b/vision/spring-framework/pom.xml new file mode 100644 index 00000000000..b5cf0dd2fd6 --- /dev/null +++ b/vision/spring-framework/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + + + 1.8 + 1.8 + 2.7.4 + + + + + com.google.cloud.samples + shared-configuration + 1.2.0 + + + com.example.vision + spring-framework + Spring Framework with Cloud Vision Sample + + + + + + org.springframework.cloud + spring-cloud-gcp-dependencies + 1.2.8.RELEASE + pom + import + + + + + + + + + org.springframework.cloud + spring-cloud-gcp-starter-vision + + + + + org.springframework.boot + spring-boot-starter-web + ${spring.version} + + + + org.springframework.boot + spring-boot-starter-thymeleaf + ${spring.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.version} + + com.example.vision.Application + + + + + diff --git a/vision/spring-framework/src/main/java/com/example/vision/Application.java b/vision/spring-framework/src/main/java/com/example/vision/Application.java new file mode 100644 index 00000000000..a3c4841f803 --- /dev/null +++ b/vision/spring-framework/src/main/java/com/example/vision/Application.java @@ -0,0 +1,29 @@ +/* + * Copyright 2019 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 org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** Entry point to running the Spring Boot application. */ +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/vision/spring-framework/src/main/java/com/example/vision/VisionController.java b/vision/spring-framework/src/main/java/com/example/vision/VisionController.java new file mode 100644 index 00000000000..4780db242e2 --- /dev/null +++ b/vision/spring-framework/src/main/java/com/example/vision/VisionController.java @@ -0,0 +1,88 @@ +/* + * Copyright 2019 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.google.cloud.vision.v1.AnnotateImageResponse; +import com.google.cloud.vision.v1.EntityAnnotation; +import com.google.cloud.vision.v1.Feature.Type; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.gcp.vision.CloudVisionTemplate; +import org.springframework.core.io.ResourceLoader; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +/** + * Code sample demonstrating Cloud Vision usage within the context of Spring Framework using Spring + * Cloud GCP libraries. The sample is written as a Spring Boot application to demonstrate a + * practical application of this usage. + */ +@RestController +public class VisionController { + + @Autowired private ResourceLoader resourceLoader; + + // [START vision_spring_autowire] + @Autowired private CloudVisionTemplate cloudVisionTemplate; + // [END vision_spring_autowire] + + /** + * This method downloads an image from a URL and sends its contents to the Vision API for label + * detection. + * + * @param imageUrl the URL of the image + * @param map the model map to use + * @return a string with the list of labels and percentage of certainty + */ + @GetMapping("/extractLabels") + public ModelAndView extractLabels(String imageUrl, ModelMap map) { + // [START vision_spring_image_labelling] + AnnotateImageResponse response = + this.cloudVisionTemplate.analyzeImage( + this.resourceLoader.getResource(imageUrl), Type.LABEL_DETECTION); + + Map imageLabels = + response.getLabelAnnotationsList().stream() + .collect( + Collectors.toMap( + EntityAnnotation::getDescription, + EntityAnnotation::getScore, + (u, v) -> { + throw new IllegalStateException(String.format("Duplicate key %s", u)); + }, + LinkedHashMap::new)); + // [END vision_spring_image_labelling] + + map.addAttribute("annotations", imageLabels); + map.addAttribute("imageUrl", imageUrl); + + return new ModelAndView("result", map); + } + + @GetMapping("/extractText") + public String extractText(String imageUrl) { + // [START vision_spring_text_extraction] + String textFromImage = + this.cloudVisionTemplate.extractTextFromImage(this.resourceLoader.getResource(imageUrl)); + return "Text from image: " + textFromImage; + // [END vision_spring_text_extraction] + } +} diff --git a/vision/spring-framework/src/main/resources/static/index.html b/vision/spring-framework/src/main/resources/static/index.html new file mode 100644 index 00000000000..89513379087 --- /dev/null +++ b/vision/spring-framework/src/main/resources/static/index.html @@ -0,0 +1,34 @@ + + + + + Google Cloud Vision API with Spring code sample + + + +

+

Image Label Annotations

+

Returns labels classifying the content of the image:

+
+ Web URL of image to analyze: + + +
+
+ +
+

Text Extraction

+

Read and extract the text from the image:

+
+ Web URL of image to analyze: + + +
+
+ + + diff --git a/vision/spring-framework/src/main/resources/templates/result.html b/vision/spring-framework/src/main/resources/templates/result.html new file mode 100644 index 00000000000..161d9e4446f --- /dev/null +++ b/vision/spring-framework/src/main/resources/templates/result.html @@ -0,0 +1,24 @@ + + + + Google Cloud Vision Results + + + +

Annotations Produced for the Image

+ + + + + + + + + +
DescriptionScore
[[${entry.key}]][[${entry.value}]]
+ +

+ +

+ +