Skip to content

Commit c7d3878

Browse files
nnegreychingor13
authored andcommitted
samples: vision: move samples out of branch and add clarifying comments (#2297)
1 parent 6056b61 commit c7d3878

File tree

2 files changed

+178
-0
lines changed

2 files changed

+178
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.vision;
18+
19+
// [START vision_async_batch_annotate_images]
20+
import com.google.cloud.vision.v1.AnnotateImageRequest;
21+
import com.google.cloud.vision.v1.AsyncBatchAnnotateImagesRequest;
22+
import com.google.cloud.vision.v1.AsyncBatchAnnotateImagesResponse;
23+
import com.google.cloud.vision.v1.Feature;
24+
import com.google.cloud.vision.v1.GcsDestination;
25+
import com.google.cloud.vision.v1.Image;
26+
import com.google.cloud.vision.v1.ImageAnnotatorClient;
27+
import com.google.cloud.vision.v1.ImageSource;
28+
import com.google.cloud.vision.v1.OutputConfig;
29+
30+
import java.io.IOException;
31+
import java.util.concurrent.ExecutionException;
32+
33+
public class AsyncBatchAnnotateImages {
34+
35+
public static void asyncBatchAnnotateImages()
36+
throws InterruptedException, ExecutionException, IOException {
37+
String inputImageUri = "gs://cloud-samples-data/vision/label/wakeupcat.jpg";
38+
String outputUri = "gs://YOUR_BUCKET_ID/path/to/save/results/";
39+
asyncBatchAnnotateImages(inputImageUri, outputUri);
40+
}
41+
42+
public static void asyncBatchAnnotateImages(String inputImageUri, String outputUri)
43+
throws IOException, ExecutionException, InterruptedException {
44+
// Initialize client that will be used to send requests. This client only needs to be created
45+
// once, and can be reused for multiple requests. After completing all of your requests, call
46+
// the "close" method on the client to safely clean up any remaining background resources.
47+
try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) {
48+
49+
// You can send multiple images to be annotated, this sample demonstrates how to do this with
50+
// one image. If you want to use multiple images, you have to create a `AnnotateImageRequest`
51+
// object for each image that you want annotated.
52+
// First specify where the vision api can find the image
53+
ImageSource source = ImageSource.newBuilder().setImageUri(inputImageUri).build();
54+
Image image = Image.newBuilder().setSource(source).build();
55+
56+
// Set the type of annotation you want to perform on the image
57+
// https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type
58+
Feature feature = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build();
59+
60+
// Build the request object for that one image. Note: for additional images you have to create
61+
// additional `AnnotateImageRequest` objects and store them in a list to be used below.
62+
AnnotateImageRequest imageRequest =
63+
AnnotateImageRequest.newBuilder().setImage(image).addFeatures(feature).build();
64+
65+
// Set where to store the results for the images that will be annotated.
66+
GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(outputUri).build();
67+
OutputConfig outputConfig =
68+
OutputConfig.newBuilder()
69+
.setGcsDestination(gcsDestination)
70+
.setBatchSize(2) // The max number of responses to output in each JSON file
71+
.build();
72+
73+
// Add each `AnnotateImageRequest` object to the batch request and add the output config.
74+
AsyncBatchAnnotateImagesRequest request =
75+
AsyncBatchAnnotateImagesRequest.newBuilder()
76+
.addRequests(imageRequest)
77+
.setOutputConfig(outputConfig)
78+
.build();
79+
80+
// Make the asynchronous batch request.
81+
AsyncBatchAnnotateImagesResponse response =
82+
imageAnnotatorClient.asyncBatchAnnotateImagesAsync(request).get();
83+
84+
// The output is written to GCS with the provided output_uri as prefix
85+
String gcsOutputUri = response.getOutputConfig().getGcsDestination().getUri();
86+
System.out.printf("Output written to GCS with prefix: %s\n", gcsOutputUri);
87+
}
88+
}
89+
}
90+
// [END vision_async_batch_annotate_images]
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.vision;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static junit.framework.TestCase.assertNotNull;
21+
22+
import com.google.api.gax.paging.Page;
23+
import com.google.cloud.storage.Blob;
24+
import com.google.cloud.storage.Storage;
25+
import com.google.cloud.storage.StorageOptions;
26+
27+
import java.io.ByteArrayOutputStream;
28+
import java.io.IOException;
29+
import java.io.PrintStream;
30+
import java.util.UUID;
31+
import java.util.concurrent.ExecutionException;
32+
33+
import org.junit.After;
34+
import org.junit.Before;
35+
import org.junit.BeforeClass;
36+
import org.junit.Test;
37+
import org.junit.runner.RunWith;
38+
import org.junit.runners.JUnit4;
39+
40+
@RunWith(JUnit4.class)
41+
@SuppressWarnings("checkstyle:abbreviationaswordinname")
42+
public class AsyncBatchAnnotateImagesTest {
43+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
44+
private static final String INPUT_URI = "gs://cloud-samples-data/vision/label/wakeupcat.jpg";
45+
private static final String PREFIX = String.format("vision/%s/", UUID.randomUUID().toString());
46+
private static final String OUTPUT_URI = String.format("gs://%s/%s", PROJECT_ID, PREFIX);
47+
48+
private ByteArrayOutputStream bout;
49+
private PrintStream out;
50+
51+
private static void requireEnvVar(String varName) {
52+
assertNotNull(
53+
System.getenv(varName),
54+
"Environment variable '%s' is required to perform these tests.".format(varName));
55+
}
56+
57+
@BeforeClass
58+
public static void checkRequirements() {
59+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
60+
}
61+
62+
@Before
63+
public void setUp() {
64+
bout = new ByteArrayOutputStream();
65+
out = new PrintStream(bout);
66+
System.setOut(out);
67+
}
68+
69+
@After
70+
public void tearDown() {
71+
System.setOut(null);
72+
73+
Storage storage = StorageOptions.getDefaultInstance().getService();
74+
75+
Page<Blob> blobs = storage.list(PROJECT_ID, Storage.BlobListOption.currentDirectory(),
76+
Storage.BlobListOption.prefix(PREFIX));
77+
for (Blob blob : blobs.iterateAll()) {
78+
blob.delete();
79+
}
80+
}
81+
82+
@Test
83+
public void testSetEndpoint() throws IOException, ExecutionException, InterruptedException {
84+
AsyncBatchAnnotateImages.asyncBatchAnnotateImages(INPUT_URI, OUTPUT_URI);
85+
String got = bout.toString();
86+
assertThat(got).contains("Output written to GCS with prefix");
87+
}
88+
}

0 commit comments

Comments
 (0)