tysonjh commented on a change in pull request #11331:
URL: https://github.com/apache/beam/pull/11331#discussion_r421689993



##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/AnnotateImages.java
##########
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+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.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageContext;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.GroupIntoBatches;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Parent class for transform utilizing Cloud Vision API.
+ *
+ * @param <T> Type of input PCollection.
+ */
+public abstract class AnnotateImages<T>
+    extends PTransform<PCollection<T>, 
PCollection<List<AnnotateImageResponse>>> {
+
+  private static final Long MIN_BATCH_SIZE = 1L;
+  private static final Long MAX_BATCH_SIZE = 5L;
+
+  protected final PCollectionView<Map<T, ImageContext>> contextSideInput;
+  protected final List<Feature> featureList;
+  private long batchSize;
+
+  public AnnotateImages(

Review comment:
       Would you please add comments to this as well? It would be useful for 
those implementing subclasses.

##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/AnnotateImages.java
##########
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+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.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageContext;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.GroupIntoBatches;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Parent class for transform utilizing Cloud Vision API.
+ *
+ * @param <T> Type of input PCollection.
+ */
+public abstract class AnnotateImages<T>
+    extends PTransform<PCollection<T>, 
PCollection<List<AnnotateImageResponse>>> {
+
+  private static final Long MIN_BATCH_SIZE = 1L;
+  private static final Long MAX_BATCH_SIZE = 5L;
+
+  protected final PCollectionView<Map<T, ImageContext>> contextSideInput;
+  protected final List<Feature> featureList;
+  private long batchSize;
+
+  public AnnotateImages(
+      PCollectionView<Map<T, ImageContext>> contextSideInput,
+      List<Feature> featureList,
+      long batchSize) {
+    this.contextSideInput = contextSideInput;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  public AnnotateImages(List<Feature> featureList, long batchSize) {
+    contextSideInput = null;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  private void checkBatchSizeCorrectness(long batchSize) {
+    if (batchSize > MAX_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Max batch size exceeded.\n" + "Batch size needs to be equal or 
smaller than %d",
+              MAX_BATCH_SIZE));
+    } else if (batchSize < MIN_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Min batch size not reached.\n" + "Batch size needs to be larger 
than %d",

Review comment:
       'larger or equal to %d'

##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/AnnotateImages.java
##########
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+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.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageContext;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.GroupIntoBatches;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Parent class for transform utilizing Cloud Vision API.
+ *
+ * @param <T> Type of input PCollection.
+ */
+public abstract class AnnotateImages<T>
+    extends PTransform<PCollection<T>, 
PCollection<List<AnnotateImageResponse>>> {
+
+  private static final Long MIN_BATCH_SIZE = 1L;
+  private static final Long MAX_BATCH_SIZE = 5L;

Review comment:
       Why was 5 chosen?

##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/AnnotateImages.java
##########
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+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.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageContext;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.GroupIntoBatches;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Parent class for transform utilizing Cloud Vision API.
+ *
+ * @param <T> Type of input PCollection.
+ */
+public abstract class AnnotateImages<T>
+    extends PTransform<PCollection<T>, 
PCollection<List<AnnotateImageResponse>>> {
+
+  private static final Long MIN_BATCH_SIZE = 1L;
+  private static final Long MAX_BATCH_SIZE = 5L;
+
+  protected final PCollectionView<Map<T, ImageContext>> contextSideInput;
+  protected final List<Feature> featureList;
+  private long batchSize;
+
+  public AnnotateImages(
+      PCollectionView<Map<T, ImageContext>> contextSideInput,
+      List<Feature> featureList,
+      long batchSize) {
+    this.contextSideInput = contextSideInput;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  public AnnotateImages(List<Feature> featureList, long batchSize) {
+    contextSideInput = null;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  private void checkBatchSizeCorrectness(long batchSize) {
+    if (batchSize > MAX_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Max batch size exceeded.\n" + "Batch size needs to be equal or 
smaller than %d",
+              MAX_BATCH_SIZE));
+    } else if (batchSize < MIN_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Min batch size not reached.\n" + "Batch size needs to be larger 
than %d",
+              MIN_BATCH_SIZE));
+    }
+  }
+
+  /**
+   * Applies all necessary transforms to call the Vision API. In order to 
group requests into
+   * batches, we assign keys to the requests, as {@link GroupIntoBatches} 
works only on {@link KV}s.
+   */
+  @Override
+  public PCollection<List<AnnotateImageResponse>> expand(PCollection<T> input) 
{
+    ParDo.SingleOutput<T, AnnotateImageRequest> inputToRequestMapper;
+    if (contextSideInput != null) {
+      inputToRequestMapper =
+          ParDo.of(new 
MapInputToRequest(contextSideInput)).withSideInputs(contextSideInput);
+    } else {
+      inputToRequestMapper = ParDo.of(new MapInputToRequest(null));
+    }
+    return input
+        .apply(inputToRequestMapper)
+        .apply(ParDo.of(new AssignRandomKeys()))
+        .apply(GroupIntoBatches.ofSize(batchSize))
+        .apply(ParDo.of(new ExtractValues()))
+        .apply(ParDo.of(new PerformImageAnnotation()));
+  }
+
+  /**
+   * Input type to {@link AnnotateImageRequest} mapper. Needs to be 
implemented by child classes
+   *
+   * @param input Input element.
+   * @param ctx optional image context.
+   * @return A valid {@link AnnotateImageRequest} object.
+   */
+  public abstract AnnotateImageRequest mapToRequest(T input, ImageContext ctx);

Review comment:
       What do you think about adding a CheckForNull annotation for ctx? 
Mentioning that the parameter may be null in the comments, and the significance 
of it, would be helpful.

##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/AnnotateImages.java
##########
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+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.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageContext;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.GroupIntoBatches;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Parent class for transform utilizing Cloud Vision API.
+ *
+ * @param <T> Type of input PCollection.
+ */
+public abstract class AnnotateImages<T>
+    extends PTransform<PCollection<T>, 
PCollection<List<AnnotateImageResponse>>> {
+
+  private static final Long MIN_BATCH_SIZE = 1L;
+  private static final Long MAX_BATCH_SIZE = 5L;
+
+  protected final PCollectionView<Map<T, ImageContext>> contextSideInput;
+  protected final List<Feature> featureList;
+  private long batchSize;
+
+  public AnnotateImages(
+      PCollectionView<Map<T, ImageContext>> contextSideInput,
+      List<Feature> featureList,
+      long batchSize) {
+    this.contextSideInput = contextSideInput;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  public AnnotateImages(List<Feature> featureList, long batchSize) {
+    contextSideInput = null;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  private void checkBatchSizeCorrectness(long batchSize) {
+    if (batchSize > MAX_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Max batch size exceeded.\n" + "Batch size needs to be equal or 
smaller than %d",
+              MAX_BATCH_SIZE));
+    } else if (batchSize < MIN_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Min batch size not reached.\n" + "Batch size needs to be larger 
than %d",
+              MIN_BATCH_SIZE));
+    }
+  }
+
+  /**
+   * Applies all necessary transforms to call the Vision API. In order to 
group requests into
+   * batches, we assign keys to the requests, as {@link GroupIntoBatches} 
works only on {@link KV}s.
+   */
+  @Override
+  public PCollection<List<AnnotateImageResponse>> expand(PCollection<T> input) 
{
+    ParDo.SingleOutput<T, AnnotateImageRequest> inputToRequestMapper;
+    if (contextSideInput != null) {
+      inputToRequestMapper =
+          ParDo.of(new 
MapInputToRequest(contextSideInput)).withSideInputs(contextSideInput);
+    } else {
+      inputToRequestMapper = ParDo.of(new MapInputToRequest(null));
+    }
+    return input
+        .apply(inputToRequestMapper)
+        .apply(ParDo.of(new AssignRandomKeys()))
+        .apply(GroupIntoBatches.ofSize(batchSize))
+        .apply(ParDo.of(new ExtractValues()))
+        .apply(ParDo.of(new PerformImageAnnotation()));
+  }
+
+  /**
+   * Input type to {@link AnnotateImageRequest} mapper. Needs to be 
implemented by child classes
+   *
+   * @param input Input element.
+   * @param ctx optional image context.
+   * @return A valid {@link AnnotateImageRequest} object.
+   */
+  public abstract AnnotateImageRequest mapToRequest(T input, ImageContext ctx);
+
+  /**
+   * The {@link DoFn} performing the calls to Cloud Vision API. Input 
PCollection contains lists of
+   * {@link AnnotateImageRequest}s ready for batching.
+   */
+  public static class PerformImageAnnotation
+      extends DoFn<List<AnnotateImageRequest>, List<AnnotateImageResponse>> {
+
+    private ImageAnnotatorClient imageAnnotatorClient;
+
+    public PerformImageAnnotation() {}
+
+    /**
+     * Parametrized constructor to make mock injection easier in testing.
+     *
+     * @param imageAnnotatorClient
+     */
+    public PerformImageAnnotation(ImageAnnotatorClient imageAnnotatorClient) {
+      this.imageAnnotatorClient = imageAnnotatorClient;
+    }
+
+    @StartBundle
+    public void startBundle() throws IOException {
+      imageAnnotatorClient = ImageAnnotatorClient.create();
+    }
+
+    @Teardown
+    public void teardown() {
+      imageAnnotatorClient.close();

Review comment:
       Should this be in finishBundle()?
   
   I would expect either a new ImageAnnotatorClient is created with each bundle 
and closed after processing a bundle, or that a single instance is used for the 
life of the DoFn using setup/teardown.

##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/AnnotateImages.java
##########
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+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.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageContext;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.GroupIntoBatches;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Parent class for transform utilizing Cloud Vision API.
+ *
+ * @param <T> Type of input PCollection.
+ */
+public abstract class AnnotateImages<T>
+    extends PTransform<PCollection<T>, 
PCollection<List<AnnotateImageResponse>>> {
+
+  private static final Long MIN_BATCH_SIZE = 1L;
+  private static final Long MAX_BATCH_SIZE = 5L;
+
+  protected final PCollectionView<Map<T, ImageContext>> contextSideInput;
+  protected final List<Feature> featureList;
+  private long batchSize;
+
+  public AnnotateImages(
+      PCollectionView<Map<T, ImageContext>> contextSideInput,
+      List<Feature> featureList,
+      long batchSize) {
+    this.contextSideInput = contextSideInput;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  public AnnotateImages(List<Feature> featureList, long batchSize) {
+    contextSideInput = null;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  private void checkBatchSizeCorrectness(long batchSize) {
+    if (batchSize > MAX_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Max batch size exceeded.\n" + "Batch size needs to be equal or 
smaller than %d",
+              MAX_BATCH_SIZE));
+    } else if (batchSize < MIN_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Min batch size not reached.\n" + "Batch size needs to be larger 
than %d",
+              MIN_BATCH_SIZE));
+    }
+  }
+
+  /**
+   * Applies all necessary transforms to call the Vision API. In order to 
group requests into
+   * batches, we assign keys to the requests, as {@link GroupIntoBatches} 
works only on {@link KV}s.
+   */
+  @Override
+  public PCollection<List<AnnotateImageResponse>> expand(PCollection<T> input) 
{
+    ParDo.SingleOutput<T, AnnotateImageRequest> inputToRequestMapper;
+    if (contextSideInput != null) {
+      inputToRequestMapper =
+          ParDo.of(new 
MapInputToRequest(contextSideInput)).withSideInputs(contextSideInput);
+    } else {
+      inputToRequestMapper = ParDo.of(new MapInputToRequest(null));
+    }
+    return input
+        .apply(inputToRequestMapper)
+        .apply(ParDo.of(new AssignRandomKeys()))
+        .apply(GroupIntoBatches.ofSize(batchSize))
+        .apply(ParDo.of(new ExtractValues()))
+        .apply(ParDo.of(new PerformImageAnnotation()));
+  }
+
+  /**
+   * Input type to {@link AnnotateImageRequest} mapper. Needs to be 
implemented by child classes
+   *
+   * @param input Input element.
+   * @param ctx optional image context.
+   * @return A valid {@link AnnotateImageRequest} object.
+   */
+  public abstract AnnotateImageRequest mapToRequest(T input, ImageContext ctx);
+
+  /**
+   * The {@link DoFn} performing the calls to Cloud Vision API. Input 
PCollection contains lists of
+   * {@link AnnotateImageRequest}s ready for batching.
+   */
+  public static class PerformImageAnnotation
+      extends DoFn<List<AnnotateImageRequest>, List<AnnotateImageResponse>> {
+
+    private ImageAnnotatorClient imageAnnotatorClient;
+
+    public PerformImageAnnotation() {}
+
+    /**
+     * Parametrized constructor to make mock injection easier in testing.
+     *
+     * @param imageAnnotatorClient
+     */
+    public PerformImageAnnotation(ImageAnnotatorClient imageAnnotatorClient) {
+      this.imageAnnotatorClient = imageAnnotatorClient;
+    }
+
+    @StartBundle
+    public void startBundle() throws IOException {
+      imageAnnotatorClient = ImageAnnotatorClient.create();
+    }
+
+    @Teardown
+    public void teardown() {
+      imageAnnotatorClient.close();
+    }
+
+    @ProcessElement
+    public void processElement(ProcessContext context) {
+      context.output(getResponse(context.element()));
+    }
+
+    /**
+     * Performs the call itself. Default access for testing.

Review comment:
       Nit: 'the call itself' doesn't describe what this method does. Consider 
rephrasing.

##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/AnnotateImages.java
##########
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+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.ImageAnnotatorClient;
+import com.google.cloud.vision.v1.ImageContext;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.GroupIntoBatches;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.ParDo;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollection;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Parent class for transform utilizing Cloud Vision API.
+ *
+ * @param <T> Type of input PCollection.
+ */
+public abstract class AnnotateImages<T>
+    extends PTransform<PCollection<T>, 
PCollection<List<AnnotateImageResponse>>> {
+
+  private static final Long MIN_BATCH_SIZE = 1L;
+  private static final Long MAX_BATCH_SIZE = 5L;
+
+  protected final PCollectionView<Map<T, ImageContext>> contextSideInput;
+  protected final List<Feature> featureList;
+  private long batchSize;
+
+  public AnnotateImages(
+      PCollectionView<Map<T, ImageContext>> contextSideInput,
+      List<Feature> featureList,
+      long batchSize) {
+    this.contextSideInput = contextSideInput;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  public AnnotateImages(List<Feature> featureList, long batchSize) {
+    contextSideInput = null;
+    this.featureList = featureList;
+    checkBatchSizeCorrectness(batchSize);
+    this.batchSize = batchSize;
+  }
+
+  private void checkBatchSizeCorrectness(long batchSize) {
+    if (batchSize > MAX_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Max batch size exceeded.\n" + "Batch size needs to be equal or 
smaller than %d",
+              MAX_BATCH_SIZE));
+    } else if (batchSize < MIN_BATCH_SIZE) {
+      throw new IllegalArgumentException(
+          String.format(
+              "Min batch size not reached.\n" + "Batch size needs to be larger 
than %d",
+              MIN_BATCH_SIZE));
+    }
+  }
+
+  /**
+   * Applies all necessary transforms to call the Vision API. In order to 
group requests into
+   * batches, we assign keys to the requests, as {@link GroupIntoBatches} 
works only on {@link KV}s.
+   */
+  @Override
+  public PCollection<List<AnnotateImageResponse>> expand(PCollection<T> input) 
{
+    ParDo.SingleOutput<T, AnnotateImageRequest> inputToRequestMapper;
+    if (contextSideInput != null) {
+      inputToRequestMapper =
+          ParDo.of(new 
MapInputToRequest(contextSideInput)).withSideInputs(contextSideInput);
+    } else {
+      inputToRequestMapper = ParDo.of(new MapInputToRequest(null));
+    }
+    return input
+        .apply(inputToRequestMapper)
+        .apply(ParDo.of(new AssignRandomKeys()))
+        .apply(GroupIntoBatches.ofSize(batchSize))
+        .apply(ParDo.of(new ExtractValues()))
+        .apply(ParDo.of(new PerformImageAnnotation()));
+  }
+
+  /**
+   * Input type to {@link AnnotateImageRequest} mapper. Needs to be 
implemented by child classes
+   *
+   * @param input Input element.
+   * @param ctx optional image context.
+   * @return A valid {@link AnnotateImageRequest} object.
+   */
+  public abstract AnnotateImageRequest mapToRequest(T input, ImageContext ctx);
+
+  /**
+   * The {@link DoFn} performing the calls to Cloud Vision API. Input 
PCollection contains lists of
+   * {@link AnnotateImageRequest}s ready for batching.
+   */
+  public static class PerformImageAnnotation
+      extends DoFn<List<AnnotateImageRequest>, List<AnnotateImageResponse>> {
+
+    private ImageAnnotatorClient imageAnnotatorClient;
+
+    public PerformImageAnnotation() {}
+
+    /**
+     * Parametrized constructor to make mock injection easier in testing.
+     *
+     * @param imageAnnotatorClient
+     */
+    public PerformImageAnnotation(ImageAnnotatorClient imageAnnotatorClient) {
+      this.imageAnnotatorClient = imageAnnotatorClient;
+    }
+
+    @StartBundle
+    public void startBundle() throws IOException {
+      imageAnnotatorClient = ImageAnnotatorClient.create();
+    }
+
+    @Teardown
+    public void teardown() {
+      imageAnnotatorClient.close();
+    }
+
+    @ProcessElement
+    public void processElement(ProcessContext context) {
+      context.output(getResponse(context.element()));
+    }
+
+    /**
+     * Performs the call itself. Default access for testing.
+     *
+     * @param requests request list.
+     * @return response list.
+     */
+    List<AnnotateImageResponse> getResponse(List<AnnotateImageRequest> 
requests) {
+      BatchAnnotateImagesResponse batchAnnotateImagesResponse =
+          imageAnnotatorClient.batchAnnotateImages(requests);
+      return batchAnnotateImagesResponse.getResponsesList();
+    }
+  }
+
+  /** A transform that converts input elements to {@link KV}s for grouping. */
+  private static class AssignRandomKeys
+      extends DoFn<AnnotateImageRequest, KV<Long, AnnotateImageRequest>> {
+    private Random random;
+
+    @Setup
+    public void setup() {
+      random = new Random();
+    }
+
+    @ProcessElement
+    public void processElement(ProcessContext context) {
+      context.output(KV.of(random.nextLong(), context.element()));

Review comment:
       From what I read, GroupIntoBatches only batches elements within a key. 
If keys are random, won't this result in very little batching?

##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/CloudVision.java
##########
@@ -0,0 +1,238 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+import com.google.cloud.vision.v1.AnnotateImageRequest;
+import com.google.cloud.vision.v1.Feature;
+import com.google.cloud.vision.v1.Image;
+import com.google.cloud.vision.v1.ImageContext;
+import com.google.cloud.vision.v1.ImageSource;
+import com.google.protobuf.ByteString;
+import java.util.List;
+import java.util.Map;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Factory class for implementations of {@link AnnotateImages}.
+ *
+ * <p>Example usage:
+ *
+ * <pre>
+ * pipeline
+ *  .apply(Create.of(IMAGE_URI))
+ *  .apply(CloudVision.annotateImagesFromGcsUri(sideInputWithContext,
+ *         features, 1));
+ * </pre>
+ */
+public class CloudVision {
+
+  /**
+   * Creates a {@link org.apache.beam.sdk.transforms.PTransform} that 
annotates images from their
+   * GCS addresses.
+   *
+   * @param contextSideInput optional side input with contexts for select 
images.
+   * @param features annotation features that should be passed to the API
+   * @param batchSize request batch size to be sent to API. Max 5.

Review comment:
       Since there is a max and min for this parameter it would be good to 
mention both requirements. There are a couple places in this file where this 
applies.

##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/CloudVision.java
##########
@@ -0,0 +1,238 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+import com.google.cloud.vision.v1.AnnotateImageRequest;
+import com.google.cloud.vision.v1.Feature;
+import com.google.cloud.vision.v1.Image;
+import com.google.cloud.vision.v1.ImageContext;
+import com.google.cloud.vision.v1.ImageSource;
+import com.google.protobuf.ByteString;
+import java.util.List;
+import java.util.Map;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Factory class for implementations of {@link AnnotateImages}.

Review comment:
       It would be helpful to describe the effects of including/excluding a 
contextSideInput, either here or in the method comments within this class.

##########
File path: 
sdks/java/extensions/ml/src/main/java/org/apache/beam/sdk/extensions/ml/CloudVision.java
##########
@@ -0,0 +1,238 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.beam.sdk.extensions.ml;
+
+import com.google.cloud.vision.v1.AnnotateImageRequest;
+import com.google.cloud.vision.v1.Feature;
+import com.google.cloud.vision.v1.Image;
+import com.google.cloud.vision.v1.ImageContext;
+import com.google.cloud.vision.v1.ImageSource;
+import com.google.protobuf.ByteString;
+import java.util.List;
+import java.util.Map;
+import org.apache.beam.sdk.values.KV;
+import org.apache.beam.sdk.values.PCollectionView;
+
+/**
+ * Factory class for implementations of {@link AnnotateImages}.
+ *
+ * <p>Example usage:
+ *
+ * <pre>
+ * pipeline
+ *  .apply(Create.of(IMAGE_URI))
+ *  .apply(CloudVision.annotateImagesFromGcsUri(sideInputWithContext,
+ *         features, 1));
+ * </pre>
+ */
+public class CloudVision {
+
+  /**
+   * Creates a {@link org.apache.beam.sdk.transforms.PTransform} that 
annotates images from their
+   * GCS addresses.
+   *
+   * @param contextSideInput optional side input with contexts for select 
images.
+   * @param features annotation features that should be passed to the API
+   * @param batchSize request batch size to be sent to API. Max 5.
+   * @return the PTransform.
+   */
+  public static AnnotateImagesFromGcsUri annotateImagesFromGcsUri(
+      PCollectionView<Map<String, ImageContext>> contextSideInput,
+      List<Feature> features,
+      long batchSize) {
+    return new AnnotateImagesFromGcsUri(contextSideInput, features, batchSize);
+  }
+
+  /**
+   * Creates a {@link org.apache.beam.sdk.transforms.PTransform} that 
annotates images from their
+   * contents encoded in {@link ByteString}s.
+   *
+   * @param contextSideInput optional side input with contexts for select 
images.
+   * @param features annotation features that should be passed to the API
+   * @param batchSize request batch size to be sent to API. Max 5.
+   * @return the PTransform.
+   */
+  public static AnnotateImagesFromBytes annotateImagesFromBytes(
+      PCollectionView<Map<ByteString, ImageContext>> contextSideInput,
+      List<Feature> features,
+      long batchSize) {
+    return new AnnotateImagesFromBytes(contextSideInput, features, batchSize);
+  }
+
+  /**
+   * Creates a {@link org.apache.beam.sdk.transforms.PTransform} that 
annotates images from KVs of
+   * their GCS addresses in Strings and {@link ImageContext} for each image.
+   *
+   * @param features annotation features that should be passed to the API
+   * @param batchSize request batch size to be sent to API. Max 5.
+   * @return the PTransform.
+   */
+  public static AnnotateImagesFromBytesWithContext 
annotateImagesFromBytesWithContext(
+      List<Feature> features, long batchSize) {
+    return new AnnotateImagesFromBytesWithContext(features, batchSize);
+  }
+
+  /**
+   * Creates a {@link org.apache.beam.sdk.transforms.PTransform} that 
annotates images from KVs of
+   * their String-encoded contents and {@link ImageContext} for each image.
+   *
+   * @param features annotation features that should be passed to the API
+   * @param batchSize request batch size to be sent to API. Max 5.
+   * @return the PTransform.
+   */
+  public static AnnotateImagesFromGcsUriWithContext 
annotateImagesFromGcsUriWithContext(
+      List<Feature> features, long batchSize) {
+    return new AnnotateImagesFromGcsUriWithContext(features, batchSize);
+  }
+
+  /**
+   * Implementation of {@link AnnotateImages} that accepts {@link String} 
(image URI on GCS) with

Review comment:
       I think you can drop 'Implementaiton of' since we get this information 
from the class signature. It would be helpful to know what this implementation 
does differently than other implementations. The name of the class is very 
descriptive which is great, you could even start the comment with it to the 
effect of 'Annotates images from a GCS URI. (then a bit more detail)'.
   
   

##########
File path: settings.gradle
##########
@@ -167,3 +167,6 @@ include "beam-test-infra-metrics"
 project(":beam-test-infra-metrics").dir = file(".test-infra/metrics")
 include "beam-test-tools"
 project(":beam-test-tools").dir = file(".test-infra/tools")
+include 'sdks:java:extensions:ml'
+findProject(':sdks:java:extensions:ml')?.name = 'ml'

Review comment:
       I don't see names being set elsewhere, why is this project different?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to