From a2d05a50ea251df56dffb56fd79d0e262e9e8fb6 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 16 Sep 2025 15:36:58 -0400 Subject: [PATCH 01/20] [WIP] Add image generation code to Gemini Model Handler --- .../inference/gemini_text_classification.py | 4 +- .../ml/inference/gemini_inference.py | 37 ++++++++++++++++++- .../ml/inference/gemini_inference_test.py | 10 ++--- 3 files changed, 43 insertions(+), 8 deletions(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_text_classification.py b/sdks/python/apache_beam/examples/inference/gemini_text_classification.py index b264467467cf..da9abf39eeff 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_text_classification.py +++ b/sdks/python/apache_beam/examples/inference/gemini_text_classification.py @@ -29,7 +29,7 @@ from apache_beam.ml.inference.base import PredictionResult from apache_beam.ml.inference.base import RunInference from apache_beam.ml.inference.gemini_inference import GeminiModelHandler -from apache_beam.ml.inference.gemini_inference import generate_from_string +from apache_beam.ml.inference.gemini_inference import generate_text_from_string from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.runners.runner import PipelineResult @@ -87,7 +87,7 @@ def run( pipeline_options.view_as(SetupOptions).save_main_session = save_main_session model_handler = GeminiModelHandler( model_name='gemini-2.0-flash-001', - request_fn=generate_from_string, + request_fn=generate_text_from_string, api_key=known_args.api_key, project=known_args.project, location=known_args.location) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference.py b/sdks/python/apache_beam/ml/inference/gemini_inference.py index fd1a7b0f7ac9..d3a686177f7b 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference.py @@ -29,6 +29,8 @@ from apache_beam.ml.inference.base import PredictionResult from apache_beam.ml.inference.base import RemoteModelHandler +from PIL.Image import Image + LOGGER = logging.getLogger("GeminiModelHandler") @@ -51,11 +53,44 @@ def _retry_on_appropriate_service_error(exception: Exception) -> bool: return exception.code == 429 or exception.code >= 500 -def generate_from_string( +def generate_text_from_string( model_name: str, batch: Sequence[str], model: genai.Client, inference_args: dict[str, Any]): + """ Request function that expects inputs to be composed of strings, then + sends requests to Gemini to generate text responses based on the text + prompts. + + Args: + model_name: the Gemini model to use for the request. This model should be + a text generation model. + batch: the string inputs to be send to Gemini for text generation. + model: the genai Client + inference_args: any additional arguments passed to the generate_content call. + """ + return model.models.generate_content( + model=model_name, contents=batch, **inference_args) + + +def generate_image_from_strings_and_images( + model_name: str, + batch: Sequence[list[str | Image]], + model: genai.Client, + inference_args: dict[str, Any]): + """ Request function that expects inputs to be composed of lists of strings + and PIL Image instances, then sends requests to Gemini to generate images + based on the text prompts and contextual images. This is currently intended + to be used with the gemini-2.5-flash-preview model (AKA Nano Banana.) + + Args: + model_name: the Gemini model to use for the request. This model should be + an image generation model suchas gemini-2.5-flash-preview + batch: the inputs to be send to Gemini for image generation as prompts. + Composed of text prompts and contextual pillow Images. + model: the genai Client + inference_args: any additional arguments passed to the generate_content call. + """ return model.models.generate_content( model=model_name, contents=batch, **inference_args) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference_test.py b/sdks/python/apache_beam/ml/inference/gemini_inference_test.py index bb6127a32872..a8bd62b332d4 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference_test.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference_test.py @@ -21,7 +21,7 @@ try: from apache_beam.ml.inference.gemini_inference import _retry_on_appropriate_service_error from apache_beam.ml.inference.gemini_inference import GeminiModelHandler - from apache_beam.ml.inference.gemini_inference import generate_from_string + from apache_beam.ml.inference.gemini_inference import generate_text_from_string from google.genai import errors except ImportError: raise unittest.SkipTest('Gemini dependencies are not installed') @@ -47,7 +47,7 @@ def test_all_params_set(self): ValueError, GeminiModelHandler, model_name="gemini-model-123", - request_fn=generate_from_string, + request_fn=generate_text_from_string, api_key="123456789", project="testproject", location="us-central1", @@ -58,7 +58,7 @@ def test_missing_vertex_location_param(self): ValueError, GeminiModelHandler, model_name="gemini-model-123", - request_fn=generate_from_string, + request_fn=generate_text_from_string, project="testproject", ) @@ -67,7 +67,7 @@ def test_missing_vertex_project_param(self): ValueError, GeminiModelHandler, model_name="gemini-model-123", - request_fn=generate_from_string, + request_fn=generate_text_from_string, location="us-central1", ) @@ -76,7 +76,7 @@ def test_missing_all_params(self): ValueError, GeminiModelHandler, model_name="gemini-model-123", - request_fn=generate_from_string, + request_fn=generate_text_from_string, ) From 59d510cccfe1ba58f27fd369a7cf2b6cccf5b50b Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 16 Sep 2025 15:42:04 -0400 Subject: [PATCH 02/20] add pillow to gemini_tests_requirements.txt --- .../apache_beam/ml/inference/gemini_tests_requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdks/python/apache_beam/ml/inference/gemini_tests_requirements.txt b/sdks/python/apache_beam/ml/inference/gemini_tests_requirements.txt index 722ed40777b7..9628370b48ee 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_tests_requirements.txt +++ b/sdks/python/apache_beam/ml/inference/gemini_tests_requirements.txt @@ -15,4 +15,5 @@ # limitations under the License. # -google-genai>=1.16.1 \ No newline at end of file +google-genai>=1.16.1 +pillow>=11.3.0 \ No newline at end of file From 63c25fd302ff9a35d70b4efb0a84eb0a19b6c07f Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 16 Sep 2025 16:28:42 -0400 Subject: [PATCH 03/20] linting --- sdks/python/apache_beam/ml/inference/gemini_inference.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference.py b/sdks/python/apache_beam/ml/inference/gemini_inference.py index d3a686177f7b..9c25a5740907 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference.py @@ -67,7 +67,8 @@ def generate_text_from_string( a text generation model. batch: the string inputs to be send to Gemini for text generation. model: the genai Client - inference_args: any additional arguments passed to the generate_content call. + inference_args: any additional arguments passed to the generate_content + call. """ return model.models.generate_content( model=model_name, contents=batch, **inference_args) @@ -89,7 +90,8 @@ def generate_image_from_strings_and_images( batch: the inputs to be send to Gemini for image generation as prompts. Composed of text prompts and contextual pillow Images. model: the genai Client - inference_args: any additional arguments passed to the generate_content call. + inference_args: any additional arguments passed to the generate_content + call. """ return model.models.generate_content( model=model_name, contents=batch, **inference_args) From 272947b0d10ac4078e894ce4eb3e01a5dfd21974 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Wed, 17 Sep 2025 10:03:21 -0400 Subject: [PATCH 04/20] import spacing --- sdks/python/apache_beam/ml/inference/gemini_inference.py | 1 - 1 file changed, 1 deletion(-) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference.py b/sdks/python/apache_beam/ml/inference/gemini_inference.py index 9c25a5740907..7557d4cf3dbe 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference.py @@ -28,7 +28,6 @@ from apache_beam.ml.inference import utils from apache_beam.ml.inference.base import PredictionResult from apache_beam.ml.inference.base import RemoteModelHandler - from PIL.Image import Image LOGGER = logging.getLogger("GeminiModelHandler") From 9ae4bda3335d931c45d0c878c6d3a25b09c15a17 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Wed, 17 Sep 2025 10:56:42 -0400 Subject: [PATCH 05/20] explicit union --- sdks/python/apache_beam/ml/inference/gemini_inference.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference.py b/sdks/python/apache_beam/ml/inference/gemini_inference.py index 7557d4cf3dbe..e189aabdad79 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference.py @@ -21,6 +21,7 @@ from collections.abc import Sequence from typing import Any from typing import Optional +from typing import Union from google import genai from google.genai import errors @@ -75,7 +76,7 @@ def generate_text_from_string( def generate_image_from_strings_and_images( model_name: str, - batch: Sequence[list[str | Image]], + batch: Sequence[list[Union[str, Image]]], model: genai.Client, inference_args: dict[str, Any]): """ Request function that expects inputs to be composed of lists of strings From 3f7a4704152cef3d4f7a4c4b67613741eeb397a4 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Thu, 18 Sep 2025 10:16:38 -0400 Subject: [PATCH 06/20] add part support to gemini image code --- sdks/python/apache_beam/ml/inference/gemini_inference.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference.py b/sdks/python/apache_beam/ml/inference/gemini_inference.py index e189aabdad79..eb978c53a839 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference.py @@ -25,6 +25,7 @@ from google import genai from google.genai import errors +from google.genai.types import Part from apache_beam.ml.inference import utils from apache_beam.ml.inference.base import PredictionResult @@ -76,7 +77,7 @@ def generate_text_from_string( def generate_image_from_strings_and_images( model_name: str, - batch: Sequence[list[Union[str, Image]]], + batch: Sequence[list[Union[str, Image, Part]]], model: genai.Client, inference_args: dict[str, Any]): """ Request function that expects inputs to be composed of lists of strings From f871550530670726ad9011527416a53a77d9a7d6 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 14 Oct 2025 12:00:36 -0400 Subject: [PATCH 07/20] Add example, IT test, fix regression in base model handler --- .../inference/gemini_image_generation.py | 190 ++++++++++++++++++ .../inference/gemini_text_classification.py | 6 +- .../ml/inference/gemini_inference.py | 8 +- .../ml/inference/gemini_inference_it_test.py | 16 ++ 4 files changed, 214 insertions(+), 6 deletions(-) create mode 100644 sdks/python/apache_beam/examples/inference/gemini_image_generation.py diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py new file mode 100644 index 000000000000..49d82f5c6918 --- /dev/null +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -0,0 +1,190 @@ +# +# 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. +# + +""" A sample pipeline using the RunInference API to classify text using an LLM. +This pipeline creates a set of prompts and sends it to a Gemini service then +returns the predictions from the classifier model. This example uses the +gemini-2.0-flash-001 model. +""" + +import argparse +import logging +import os +import uuid +from collections.abc import Iterable +from io import BytesIO +from PIL import Image +from typing import Optional + +import apache_beam as beam +from apache_beam.ml.inference.base import PredictionResult +from apache_beam.ml.inference.base import RunInference +from apache_beam.ml.inference.gemini_inference import GeminiModelHandler +from apache_beam.ml.inference.gemini_inference import generate_image_from_strings_and_images +from apache_beam.options.pipeline_options import PipelineOptions +from apache_beam.options.pipeline_options import SetupOptions +from apache_beam.runners.runner import PipelineResult + +from google.genai.types import GenerateContentResponse + + +def parse_known_args(argv): + """Parses args for the workflow.""" + parser = argparse.ArgumentParser() + parser.add_argument( + '--output', + dest='output', + type=str, + required=True, + help='Path to save output predictions.') + parser.add_argument( + '--api_key', + dest='api_key', + type=str, + required=False, + help='Gemini Developer API key.') + parser.add_argument( + '--cloud_project', + dest='project', + type=str, + required=False, + help='GCP Project') + parser.add_argument( + '--cloud_region', + dest='location', + type=str, + required=False, + help='GCP location for the Endpoint') + return parser.parse_known_args(argv) + + +class PostProcessor(beam.DoFn): + def process(self, element: PredictionResult) -> Iterable[Image.Image]: + try: + response: GenerateContentResponse = element.inference + print("response is: ", response) + for part in response.candidates[0].content.parts: + if part.text is not None: + print(part.text) + elif part.inline_data is not None: + image = Image.open(BytesIO(part.inline_data.data)) + yield image + except Exception as e: + print(f"Can't decode inference for element: {element.example}, got {e}") + raise e + + +class _WriteImageFn(beam.DoFn): + """ + A DoFn that writes a single PIL.Image.Image object to a file. + + This DoFn is intended to be used internally by the WriteImages transform. + """ + def __init__(self, output_dir: str, filename_prefix: str): + """ + Initializes the _WriteImageFn. + + Args: + output_dir: The directory where the image files will be written. + filename_prefix: A prefix to use for the output filenames. A UUID + and the .png extension will be appended to this prefix. + """ + self._output_dir = output_dir + self._filename_prefix = filename_prefix + + def setup(self): + """ + Ensures the output directory exists on each worker. + """ + os.makedirs(self._output_dir, exist_ok=True) + + def process(self, image: Image.Image): + """ + Saves the given PIL Image to a PNG file. + + Args: + image: A PIL.Image.Image object. + """ + # Generate a unique filename to prevent collisions. + unique_id = uuid.uuid4() + filename = f"{self._filename_prefix}-{unique_id}.png" + output_path = os.path.join(self._output_dir, filename) + + try: + logging.debug("Writing image to %s", output_path) + image.save(output_path, "PNG") + except Exception as e: + logging.error("Failed to write image to %s: %s", output_path, e) + raise + + +class WriteImages(beam.PTransform): + """ + An Apache Beam PTransform for writing a PCollection of PIL Image objects + to individual PNG files in a specified directory. + """ + def __init__(self, output_dir: str, filename_prefix: Optional[str] = "image"): + self._output_dir = output_dir + self._filename_prefix = filename_prefix + + def expand(self, pcoll: beam.PCollection) -> beam.pvalue.PDone: + return ( + pcoll + | "WriteImageToFile" >> beam.ParDo( + _WriteImageFn(self._output_dir, self._filename_prefix))) + + +def run( + argv=None, save_main_session=True, test_pipeline=None) -> PipelineResult: + """ + Args: + argv: Command line arguments defined for this example. + save_main_session: Used for internal testing. + test_pipeline: Used for internal testing. + """ + known_args, pipeline_args = parse_known_args(argv) + pipeline_options = PipelineOptions(pipeline_args) + pipeline_options.view_as(SetupOptions).save_main_session = save_main_session + model_handler = GeminiModelHandler( + model_name='gemini-2.5-flash-image', + request_fn=generate_image_from_strings_and_images, + api_key=known_args.api_key, + project=known_args.project, + location=known_args.location) + + pipeline = test_pipeline + if not test_pipeline: + pipeline = beam.Pipeline(options=pipeline_options) + + prompts = [ + "Create a picture of a pineapple in the sand at a beach.", + ] + + read_prompts = pipeline | "Get prompt" >> beam.Create(prompts) + predictions = read_prompts | "RunInference" >> RunInference(model_handler) + processed = predictions | "PostProcess" >> beam.ParDo(PostProcessor()) + _ = processed | "WriteOutput" >> WriteImages( + output_dir=known_args.output, filename_prefix="gemini_image") + + result = pipeline.run() + result.wait_until_finish() + return result + + +if __name__ == '__main__': + logging.getLogger().setLevel(logging.INFO) + run() diff --git a/sdks/python/apache_beam/examples/inference/gemini_text_classification.py b/sdks/python/apache_beam/examples/inference/gemini_text_classification.py index da9abf39eeff..c9965c268d96 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_text_classification.py +++ b/sdks/python/apache_beam/examples/inference/gemini_text_classification.py @@ -68,10 +68,10 @@ def parse_known_args(argv): class PostProcessor(beam.DoFn): def process(self, element: PredictionResult) -> Iterable[str]: try: - output_text = element.inference[1][0].content.parts[0].text + output_text = element.inference.candidates[0].content.parts[0].text yield f"Input: {element.example}, Output: {output_text}" - except Exception: - yield f"Can't decode inference for element: {element.example}" + except Exception as e: + yield f"Can't decode inference for element: {element.example}, got {e}" def run( diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference.py b/sdks/python/apache_beam/ml/inference/gemini_inference.py index eb978c53a839..7e019e55e152 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference.py @@ -83,11 +83,11 @@ def generate_image_from_strings_and_images( """ Request function that expects inputs to be composed of lists of strings and PIL Image instances, then sends requests to Gemini to generate images based on the text prompts and contextual images. This is currently intended - to be used with the gemini-2.5-flash-preview model (AKA Nano Banana.) + to be used with the gemini-2.5-flash-image model (AKA Nano Banana.) Args: model_name: the Gemini model to use for the request. This model should be - an image generation model suchas gemini-2.5-flash-preview + an image generation model such as gemini-2.5-flash-image. batch: the inputs to be send to Gemini for image generation as prompts. Composed of text prompts and contextual pillow Images. model: the genai Client @@ -206,5 +206,7 @@ def request( """ if inference_args is None: inference_args = {} - responses = self.request_fn(self.model_name, batch, model, inference_args) + # Wrap the responses in a list to prevent zip() call from treating the response + # itself as an iterable of individual responses. + responses = [self.request_fn(self.model_name, batch, model, inference_args)] return utils._convert_to_result(batch, responses, self.model_name) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py b/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py index d0cd9c236d67..50b0bd8c7e2b 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py @@ -28,6 +28,7 @@ # pylint: disable=ungrouped-imports try: + from apache_beam.examples.inference import gemini_image_generation from apache_beam.examples.inference import gemini_text_classification except ImportError as e: raise unittest.SkipTest("Gemini model handler dependencies are not installed") @@ -52,6 +53,21 @@ def test_gemini_text_classification(self): test_pipeline.get_full_options_as_args(**extra_opts)) self.assertEqual(FileSystems().exists(output_file), True) + @pytest.mark.gemini_postcommit + def test_gemini_image_generation(self): + output_dir = '/'.join([_OUTPUT_DIR, str(uuid.uuid4())]) + test_pipeline = TestPipeline(is_integration_test=True) + extra_opts = { + 'output': output_dir, + 'cloud_project': _TEST_PROJECT, + 'cloud_region': _TEST_REGION + } + gemini_image_generation.run(test_pipeline.get_full_options_as_args(**extra_opts)) + files = FileSystems().match([output_dir + '/*']) + self.assertGreater(len(files), 0) + for filename in files: + self.assertTrue(filename.startswith("gemini_image")) + self.assertTrue(filename.endswith(".png")) if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) From dd1d8147942411e3cf8029cb0402f101fffee4df Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 14 Oct 2025 12:17:27 -0400 Subject: [PATCH 08/20] fix file match check --- .../ml/inference/gemini_inference_it_test.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py b/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py index 50b0bd8c7e2b..1bba47f3f67b 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py @@ -23,6 +23,7 @@ import pytest +from apache_beam.io.filesystem import MatchResult from apache_beam.io.filesystems import FileSystems from apache_beam.testing.test_pipeline import TestPipeline @@ -53,21 +54,27 @@ def test_gemini_text_classification(self): test_pipeline.get_full_options_as_args(**extra_opts)) self.assertEqual(FileSystems().exists(output_file), True) + def _flatten_match(self, match_results): + return [ + file_metadata for match_result in match_results + for file_metadata in match_result.metadata_list + ] + @pytest.mark.gemini_postcommit def test_gemini_image_generation(self): output_dir = '/'.join([_OUTPUT_DIR, str(uuid.uuid4())]) - test_pipeline = TestPipeline(is_integration_test=True) + test_pipeline = TestPipeline(is_integration_test=False) extra_opts = { 'output': output_dir, 'cloud_project': _TEST_PROJECT, 'cloud_region': _TEST_REGION } gemini_image_generation.run(test_pipeline.get_full_options_as_args(**extra_opts)) - files = FileSystems().match([output_dir + '/*']) - self.assertGreater(len(files), 0) - for filename in files: - self.assertTrue(filename.startswith("gemini_image")) - self.assertTrue(filename.endswith(".png")) + matches: MatchResult = FileSystems().match([output_dir + '/*']) + self.assertGreater(len(matches), 0) + for match in matches: + for file in match.metadata_list: + self.assertTrue(file.path.endswith(".png")) if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) From 1cea543bdd72f6f21d830476ebd0048cff23ac76 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 14 Oct 2025 13:48:03 -0400 Subject: [PATCH 09/20] fix IO to write using FileSystem() --- .../examples/inference/gemini_image_generation.py | 8 +++++--- .../apache_beam/ml/inference/gemini_inference_it_test.py | 4 +++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index 49d82f5c6918..d33aa1bf4df1 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -31,6 +31,7 @@ from typing import Optional import apache_beam as beam +from apache_beam.io.filesystems import FileSystems from apache_beam.ml.inference.base import PredictionResult from apache_beam.ml.inference.base import RunInference from apache_beam.ml.inference.gemini_inference import GeminiModelHandler @@ -108,9 +109,9 @@ def __init__(self, output_dir: str, filename_prefix: str): def setup(self): """ - Ensures the output directory exists on each worker. + Ensures the output directory exists. """ - os.makedirs(self._output_dir, exist_ok=True) + FileSystems().mkdirs(self._output_dir) def process(self, image: Image.Image): """ @@ -126,7 +127,8 @@ def process(self, image: Image.Image): try: logging.debug("Writing image to %s", output_path) - image.save(output_path, "PNG") + with FileSystems().create(output_path) as image_file: + image.save(image_file, "PNG") except Exception as e: logging.error("Failed to write image to %s: %s", output_path, e) raise diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py b/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py index 1bba47f3f67b..8587bc5403c6 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference_it_test.py @@ -69,13 +69,15 @@ def test_gemini_image_generation(self): 'cloud_project': _TEST_PROJECT, 'cloud_region': _TEST_REGION } - gemini_image_generation.run(test_pipeline.get_full_options_as_args(**extra_opts)) + gemini_image_generation.run( + test_pipeline.get_full_options_as_args(**extra_opts)) matches: MatchResult = FileSystems().match([output_dir + '/*']) self.assertGreater(len(matches), 0) for match in matches: for file in match.metadata_list: self.assertTrue(file.path.endswith(".png")) + if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) unittest.main() From 49525494d9ef383e4aea43dbc284a8940d3cf27c Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 14 Oct 2025 14:10:56 -0400 Subject: [PATCH 10/20] remove debugging logging --- .../apache_beam/examples/inference/gemini_image_generation.py | 1 - 1 file changed, 1 deletion(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index d33aa1bf4df1..f4fd81ac7fb9 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -77,7 +77,6 @@ class PostProcessor(beam.DoFn): def process(self, element: PredictionResult) -> Iterable[Image.Image]: try: response: GenerateContentResponse = element.inference - print("response is: ", response) for part in response.candidates[0].content.parts: if part.text is not None: print(part.text) From ca0b5b89f25896536c2f795788c34a6cb9b3e390 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 14 Oct 2025 14:45:25 -0400 Subject: [PATCH 11/20] linting --- sdks/python/apache_beam/ml/inference/gemini_inference.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference.py b/sdks/python/apache_beam/ml/inference/gemini_inference.py index 7e019e55e152..443f7dd499bd 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference.py @@ -206,7 +206,7 @@ def request( """ if inference_args is None: inference_args = {} - # Wrap the responses in a list to prevent zip() call from treating the response - # itself as an iterable of individual responses. + # Wrap the responses in a list to prevent zip() call from treating the + # response itself as an iterable of individual responses. responses = [self.request_fn(self.model_name, batch, model, inference_args)] return utils._convert_to_result(batch, responses, self.model_name) From ac57d7ed9b2d1ea054a39339a7ddbfa5c82c7408 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 14 Oct 2025 15:10:27 -0400 Subject: [PATCH 12/20] fix imports --- .../apache_beam/examples/inference/gemini_image_generation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index f4fd81ac7fb9..9e226659f7a2 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -27,7 +27,6 @@ import uuid from collections.abc import Iterable from io import BytesIO -from PIL import Image from typing import Optional import apache_beam as beam @@ -41,6 +40,7 @@ from apache_beam.runners.runner import PipelineResult from google.genai.types import GenerateContentResponse +from PIL import Image def parse_known_args(argv): From b49966df3e92fdc5fc20f0f3a14be11b86be832e Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 14 Oct 2025 15:32:00 -0400 Subject: [PATCH 13/20] isort --- .../examples/inference/gemini_image_generation.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index 9e226659f7a2..406794058228 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -26,22 +26,19 @@ import os import uuid from collections.abc import Iterable +from google.genai.types import GenerateContentResponse from io import BytesIO +from PIL import Image from typing import Optional import apache_beam as beam from apache_beam.io.filesystems import FileSystems -from apache_beam.ml.inference.base import PredictionResult -from apache_beam.ml.inference.base import RunInference +from apache_beam.ml.inference.base import PredictionResult, RunInference from apache_beam.ml.inference.gemini_inference import GeminiModelHandler from apache_beam.ml.inference.gemini_inference import generate_image_from_strings_and_images -from apache_beam.options.pipeline_options import PipelineOptions -from apache_beam.options.pipeline_options import SetupOptions +from apache_beam.options.pipeline_options import PipelineOptions, SetupOptions from apache_beam.runners.runner import PipelineResult -from google.genai.types import GenerateContentResponse -from PIL import Image - def parse_known_args(argv): """Parses args for the workflow.""" From 27e82bde58e17a32295738b92b1e2411c74c727b Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 14 Oct 2025 15:32:34 -0400 Subject: [PATCH 14/20] fix doubled imports --- .../apache_beam/examples/inference/gemini_image_generation.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index 406794058228..9bf3ba1d2981 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -36,7 +36,8 @@ from apache_beam.ml.inference.base import PredictionResult, RunInference from apache_beam.ml.inference.gemini_inference import GeminiModelHandler from apache_beam.ml.inference.gemini_inference import generate_image_from_strings_and_images -from apache_beam.options.pipeline_options import PipelineOptions, SetupOptions +from apache_beam.options.pipeline_options import PipelineOptions +from apache_beam.options.pipeline_options import SetupOptions from apache_beam.runners.runner import PipelineResult From 5f06ea2393568b8574716228def15d315cabe20e Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Tue, 14 Oct 2025 16:05:12 -0400 Subject: [PATCH 15/20] another attempt at import ordering --- .../examples/inference/gemini_image_generation.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index 9bf3ba1d2981..5501a0dcea0f 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -26,19 +26,21 @@ import os import uuid from collections.abc import Iterable -from google.genai.types import GenerateContentResponse from io import BytesIO -from PIL import Image from typing import Optional +from google.genai.types import GenerateContentResponse + import apache_beam as beam from apache_beam.io.filesystems import FileSystems -from apache_beam.ml.inference.base import PredictionResult, RunInference +from apache_beam.ml.inference.base import PredictionResult +from apache_beam.ml.inference.base import RunInference from apache_beam.ml.inference.gemini_inference import GeminiModelHandler from apache_beam.ml.inference.gemini_inference import generate_image_from_strings_and_images from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.runners.runner import PipelineResult +from PIL import Image def parse_known_args(argv): From e17d005999f5632956ae4f2c36230c3dfb7221f3 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Wed, 15 Oct 2025 11:34:09 -0400 Subject: [PATCH 16/20] Move to using response.parts property, raise exceptions for text parsing failures --- .../examples/inference/gemini_image_generation.py | 7 ++++--- .../examples/inference/gemini_text_classification.py | 12 +++++++----- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index 5501a0dcea0f..34774146a51d 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -76,8 +76,8 @@ def parse_known_args(argv): class PostProcessor(beam.DoFn): def process(self, element: PredictionResult) -> Iterable[Image.Image]: try: - response: GenerateContentResponse = element.inference - for part in response.candidates[0].content.parts: + response = element.inference + for part in response.parts: if part.text is not None: print(part.text) elif part.inline_data is not None: @@ -110,7 +110,8 @@ def setup(self): """ Ensures the output directory exists. """ - FileSystems().mkdirs(self._output_dir) + if not FileSystems().exists(self._output_dir): + FileSystems().mkdirs(self._output_dir) def process(self, image: Image.Image): """ diff --git a/sdks/python/apache_beam/examples/inference/gemini_text_classification.py b/sdks/python/apache_beam/examples/inference/gemini_text_classification.py index c9965c268d96..30356aee6081 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_text_classification.py +++ b/sdks/python/apache_beam/examples/inference/gemini_text_classification.py @@ -67,11 +67,13 @@ def parse_known_args(argv): class PostProcessor(beam.DoFn): def process(self, element: PredictionResult) -> Iterable[str]: - try: - output_text = element.inference.candidates[0].content.parts[0].text - yield f"Input: {element.example}, Output: {output_text}" - except Exception as e: - yield f"Can't decode inference for element: {element.example}, got {e}" + for part in element.inference.parts: + try: + output_text = part.text + yield f"Input: {element.example}, Output: {output_text}" + except Exception as e: + print(f"Can't decode inference for element: {element.example}, got {e}") + raise e def run( From 5f4a8497b1ccf41577b2d26cfda8021383193772 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Wed, 15 Oct 2025 12:15:31 -0400 Subject: [PATCH 17/20] remove unused import --- .../apache_beam/examples/inference/gemini_image_generation.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index 34774146a51d..2e6049a53d47 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -29,8 +29,6 @@ from io import BytesIO from typing import Optional -from google.genai.types import GenerateContentResponse - import apache_beam as beam from apache_beam.io.filesystems import FileSystems from apache_beam.ml.inference.base import PredictionResult From 3d894613adbe21c4ae87dcde6e4ef4eb212fe336 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Thu, 16 Oct 2025 14:52:30 -0400 Subject: [PATCH 18/20] revert breaking change to text generation fn --- .../examples/inference/gemini_text_classification.py | 4 ++-- .../apache_beam/ml/inference/gemini_inference.py | 2 +- .../apache_beam/ml/inference/gemini_inference_test.py | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_text_classification.py b/sdks/python/apache_beam/examples/inference/gemini_text_classification.py index 30356aee6081..0072dfc50b2f 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_text_classification.py +++ b/sdks/python/apache_beam/examples/inference/gemini_text_classification.py @@ -29,7 +29,7 @@ from apache_beam.ml.inference.base import PredictionResult from apache_beam.ml.inference.base import RunInference from apache_beam.ml.inference.gemini_inference import GeminiModelHandler -from apache_beam.ml.inference.gemini_inference import generate_text_from_string +from apache_beam.ml.inference.gemini_inference import generate_from_string from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.runners.runner import PipelineResult @@ -89,7 +89,7 @@ def run( pipeline_options.view_as(SetupOptions).save_main_session = save_main_session model_handler = GeminiModelHandler( model_name='gemini-2.0-flash-001', - request_fn=generate_text_from_string, + request_fn=generate_from_string, api_key=known_args.api_key, project=known_args.project, location=known_args.location) diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference.py b/sdks/python/apache_beam/ml/inference/gemini_inference.py index 443f7dd499bd..a04ee2533a1b 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference.py @@ -54,7 +54,7 @@ def _retry_on_appropriate_service_error(exception: Exception) -> bool: return exception.code == 429 or exception.code >= 500 -def generate_text_from_string( +def generate_from_string( model_name: str, batch: Sequence[str], model: genai.Client, diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference_test.py b/sdks/python/apache_beam/ml/inference/gemini_inference_test.py index a8bd62b332d4..bb6127a32872 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference_test.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference_test.py @@ -21,7 +21,7 @@ try: from apache_beam.ml.inference.gemini_inference import _retry_on_appropriate_service_error from apache_beam.ml.inference.gemini_inference import GeminiModelHandler - from apache_beam.ml.inference.gemini_inference import generate_text_from_string + from apache_beam.ml.inference.gemini_inference import generate_from_string from google.genai import errors except ImportError: raise unittest.SkipTest('Gemini dependencies are not installed') @@ -47,7 +47,7 @@ def test_all_params_set(self): ValueError, GeminiModelHandler, model_name="gemini-model-123", - request_fn=generate_text_from_string, + request_fn=generate_from_string, api_key="123456789", project="testproject", location="us-central1", @@ -58,7 +58,7 @@ def test_missing_vertex_location_param(self): ValueError, GeminiModelHandler, model_name="gemini-model-123", - request_fn=generate_text_from_string, + request_fn=generate_from_string, project="testproject", ) @@ -67,7 +67,7 @@ def test_missing_vertex_project_param(self): ValueError, GeminiModelHandler, model_name="gemini-model-123", - request_fn=generate_text_from_string, + request_fn=generate_from_string, location="us-central1", ) @@ -76,7 +76,7 @@ def test_missing_all_params(self): ValueError, GeminiModelHandler, model_name="gemini-model-123", - request_fn=generate_text_from_string, + request_fn=generate_from_string, ) From 421ea78bca4304ea7c25c7b3f2b01a1d6f687c8f Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Thu, 16 Oct 2025 15:11:17 -0400 Subject: [PATCH 19/20] use WriteToFiles() --- .../inference/gemini_image_generation.py | 78 ++++--------------- 1 file changed, 14 insertions(+), 64 deletions(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index 2e6049a53d47..ce966e1bea47 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -23,14 +23,13 @@ import argparse import logging -import os -import uuid from collections.abc import Iterable from io import BytesIO -from typing import Optional import apache_beam as beam -from apache_beam.io.filesystems import FileSystems +from apache_beam.io.fileio import default_file_naming +from apache_beam.io.fileio import FileSink +from apache_beam.io.fileio import WriteToFiles from apache_beam.ml.inference.base import PredictionResult from apache_beam.ml.inference.base import RunInference from apache_beam.ml.inference.gemini_inference import GeminiModelHandler @@ -86,66 +85,15 @@ def process(self, element: PredictionResult) -> Iterable[Image.Image]: raise e -class _WriteImageFn(beam.DoFn): - """ - A DoFn that writes a single PIL.Image.Image object to a file. - - This DoFn is intended to be used internally by the WriteImages transform. - """ - def __init__(self, output_dir: str, filename_prefix: str): - """ - Initializes the _WriteImageFn. - - Args: - output_dir: The directory where the image files will be written. - filename_prefix: A prefix to use for the output filenames. A UUID - and the .png extension will be appended to this prefix. - """ - self._output_dir = output_dir - self._filename_prefix = filename_prefix - - def setup(self): - """ - Ensures the output directory exists. - """ - if not FileSystems().exists(self._output_dir): - FileSystems().mkdirs(self._output_dir) - - def process(self, image: Image.Image): - """ - Saves the given PIL Image to a PNG file. - - Args: - image: A PIL.Image.Image object. - """ - # Generate a unique filename to prevent collisions. - unique_id = uuid.uuid4() - filename = f"{self._filename_prefix}-{unique_id}.png" - output_path = os.path.join(self._output_dir, filename) +class ImageSink(FileSink): + def open(self, fh) -> None: + self._fh = fh - try: - logging.debug("Writing image to %s", output_path) - with FileSystems().create(output_path) as image_file: - image.save(image_file, "PNG") - except Exception as e: - logging.error("Failed to write image to %s: %s", output_path, e) - raise - - -class WriteImages(beam.PTransform): - """ - An Apache Beam PTransform for writing a PCollection of PIL Image objects - to individual PNG files in a specified directory. - """ - def __init__(self, output_dir: str, filename_prefix: Optional[str] = "image"): - self._output_dir = output_dir - self._filename_prefix = filename_prefix + def write(self, record): + record.save(self._fh, format='PNG') - def expand(self, pcoll: beam.PCollection) -> beam.pvalue.PDone: - return ( - pcoll - | "WriteImageToFile" >> beam.ParDo( - _WriteImageFn(self._output_dir, self._filename_prefix))) + def flush(self): + self._fh.flush() def run( @@ -177,8 +125,10 @@ def run( read_prompts = pipeline | "Get prompt" >> beam.Create(prompts) predictions = read_prompts | "RunInference" >> RunInference(model_handler) processed = predictions | "PostProcess" >> beam.ParDo(PostProcessor()) - _ = processed | "WriteOutput" >> WriteImages( - output_dir=known_args.output, filename_prefix="gemini_image") + _ = processed | "WriteOutput" >> WriteToFiles( + path=known_args.output, + file_naming=default_file_naming("gemini-image", ".png"), + sink=ImageSink()) result = pipeline.run() result.wait_until_finish() From c7b4ebb5e9f9075db4445847ac3341d34209bd06 Mon Sep 17 00:00:00 2001 From: jrmccluskey Date: Mon, 20 Oct 2025 10:24:21 -0400 Subject: [PATCH 20/20] linting --- .../apache_beam/examples/inference/gemini_image_generation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py index ce966e1bea47..29b2d562e634 100644 --- a/sdks/python/apache_beam/examples/inference/gemini_image_generation.py +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -27,9 +27,9 @@ from io import BytesIO import apache_beam as beam -from apache_beam.io.fileio import default_file_naming from apache_beam.io.fileio import FileSink from apache_beam.io.fileio import WriteToFiles +from apache_beam.io.fileio import default_file_naming from apache_beam.ml.inference.base import PredictionResult from apache_beam.ml.inference.base import RunInference from apache_beam.ml.inference.gemini_inference import GeminiModelHandler