|
| 1 | +/* |
| 2 | + * Copyright 2019 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_beta] |
| 20 | +import com.google.api.core.ApiFuture; |
| 21 | +import com.google.api.gax.paging.Page; |
| 22 | +import com.google.cloud.storage.Blob; |
| 23 | +import com.google.cloud.storage.Bucket; |
| 24 | +import com.google.cloud.storage.Storage; |
| 25 | +import com.google.cloud.storage.Storage.BlobListOption; |
| 26 | +import com.google.cloud.storage.StorageOptions; |
| 27 | +import com.google.cloud.vision.v1p4beta1.AnnotateImageRequest; |
| 28 | +import com.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesRequest; |
| 29 | +import com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse.Builder; |
| 30 | +import com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse; |
| 31 | +import com.google.cloud.vision.v1p4beta1.Feature; |
| 32 | +import com.google.cloud.vision.v1p4beta1.Feature.Type; |
| 33 | +import com.google.cloud.vision.v1p4beta1.GcsDestination; |
| 34 | +import com.google.cloud.vision.v1p4beta1.Image; |
| 35 | +import com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient; |
| 36 | +import com.google.cloud.vision.v1p4beta1.ImageSource; |
| 37 | +import com.google.cloud.vision.v1p4beta1.OutputConfig; |
| 38 | + |
| 39 | +import com.google.longrunning.Operation; |
| 40 | +import com.google.protobuf.util.JsonFormat; |
| 41 | +import java.util.ArrayList; |
| 42 | +import java.util.List; |
| 43 | +import java.util.concurrent.TimeUnit; |
| 44 | +import java.util.regex.Matcher; |
| 45 | +import java.util.regex.Pattern; |
| 46 | + |
| 47 | +public class AsyncBatchAnnotateImagesGcs { |
| 48 | + |
| 49 | + // Performs asynchronous batch annotation of images on Google Cloud Storage |
| 50 | + public static void asyncBatchAnnotateImagesGcs(String gcsSourcePath, String gcsDestinationPath) |
| 51 | + throws Exception { |
| 52 | + // String gcsSourcePath = "gs://YOUR_BUCKET_ID/path_to_your_data"; |
| 53 | + // String gcsDestinationPath = "gs://YOUR_BUCKET_ID/path_to_store_annotation"; |
| 54 | + |
| 55 | + try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { |
| 56 | + List<AnnotateImageRequest> requests = new ArrayList<>(); |
| 57 | + |
| 58 | + ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsSourcePath).build(); |
| 59 | + |
| 60 | + Image image = Image.newBuilder().setSource(imgSource).build(); |
| 61 | + |
| 62 | + // Set the GCS destination path for where to save the results. |
| 63 | + GcsDestination gcsDestination = |
| 64 | + GcsDestination.newBuilder().setUri(gcsDestinationPath).build(); |
| 65 | + |
| 66 | + // Create the configuration for the output with the batch size. |
| 67 | + // The batch size sets how many pages should be grouped into each json output file. |
| 68 | + OutputConfig outputConfig = |
| 69 | + OutputConfig.newBuilder().setGcsDestination(gcsDestination).setBatchSize(2).build(); |
| 70 | + |
| 71 | + // Select the Features required by the vision API |
| 72 | + Feature features = |
| 73 | + Feature.newBuilder() |
| 74 | + .setType(Type.LABEL_DETECTION) |
| 75 | + .setType(Type.TEXT_DETECTION) |
| 76 | + .setType(Type.IMAGE_PROPERTIES) |
| 77 | + .build(); |
| 78 | + |
| 79 | + // Build the request |
| 80 | + AnnotateImageRequest annotateImageRequest = |
| 81 | + AnnotateImageRequest.newBuilder().setImage(image).addFeatures(features).build(); |
| 82 | + |
| 83 | + requests.add(annotateImageRequest); |
| 84 | + AsyncBatchAnnotateImagesRequest request = |
| 85 | + AsyncBatchAnnotateImagesRequest.newBuilder() |
| 86 | + .addAllRequests(requests) |
| 87 | + .setOutputConfig(outputConfig) |
| 88 | + .build(); |
| 89 | + |
| 90 | + ApiFuture<Operation> future = client.asyncBatchAnnotateImagesCallable().futureCall(request); |
| 91 | + // Wait for the request to finish. (The result is not used, since the API saves the result to |
| 92 | + // the specified location on GCS.) |
| 93 | + Operation response = future.get(180, TimeUnit.SECONDS); |
| 94 | + |
| 95 | + System.out.println("Waiting for the operation to finish."); |
| 96 | + |
| 97 | + // Once the request has completed and the output has been |
| 98 | + // written to GCS, we can list all the output files. |
| 99 | + Storage storage = StorageOptions.getDefaultInstance().getService(); |
| 100 | + |
| 101 | + // Get the destination location from the gcsDestinationPath |
| 102 | + Pattern pattern = Pattern.compile("gs://([^/]+)/(.+)"); |
| 103 | + Matcher matcher = pattern.matcher(gcsDestinationPath); |
| 104 | + |
| 105 | + if (matcher.find()) { |
| 106 | + String bucketName = matcher.group(1); |
| 107 | + String prefix = matcher.group(2); |
| 108 | + |
| 109 | + // Get the list of objects with the given prefix from the GCS bucket |
| 110 | + Bucket bucket = storage.get(bucketName); |
| 111 | + Page<Blob> pageList = bucket.list(BlobListOption.prefix(prefix)); |
| 112 | + |
| 113 | + Blob firstOutputFile = null; |
| 114 | + |
| 115 | + // List objects with the given prefix. |
| 116 | + System.out.println("Output files:"); |
| 117 | + for (Blob blob : pageList.iterateAll()) { |
| 118 | + System.out.println(blob.getName()); |
| 119 | + |
| 120 | + // Process the first output file from GCS. |
| 121 | + // Since we specified batch size = 2, the first response contains |
| 122 | + // the first two image requests |
| 123 | + if (firstOutputFile == null) { |
| 124 | + firstOutputFile = blob; |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + // Get the contents of the file and convert the JSON contents to an |
| 129 | + // BatchAnnotateImagesResponse |
| 130 | + // object. If the Blob is small read all its content in one request |
| 131 | + // (Note: the file is a .json file) |
| 132 | + // Storage guide: https://cloud.google.com/storage/docs/downloading-objects |
| 133 | + String jsonContents = new String(firstOutputFile.getContent()); |
| 134 | + Builder builder = BatchAnnotateImagesResponse.newBuilder(); |
| 135 | + JsonFormat.parser().merge(jsonContents, builder); |
| 136 | + |
| 137 | + // Build the AnnotateFileResponse object |
| 138 | + BatchAnnotateImagesResponse batchAnnotateImagesResponse = builder.build(); |
| 139 | + |
| 140 | + // Here we print the response for the first image |
| 141 | + // The response contains more information: |
| 142 | + // annotation/pages/blocks/paragraphs/words/symbols/colors |
| 143 | + // including confidence score and bounding boxes |
| 144 | + System.out.format("\nResponse: %s\n", batchAnnotateImagesResponse.getResponses(0)); |
| 145 | + |
| 146 | + } else { |
| 147 | + System.out.println("No MATCH"); |
| 148 | + } |
| 149 | + } catch (Exception e) { |
| 150 | + System.out.println("Error during asyncBatchAnnotateImagesGcs: \n" + e.toString()); |
| 151 | + } |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +// [END vision_async_batch_annotate_images_beta] |
0 commit comments