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..29b2d562e634 --- /dev/null +++ b/sdks/python/apache_beam/examples/inference/gemini_image_generation.py @@ -0,0 +1,140 @@ +# +# 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 +from collections.abc import Iterable +from io import BytesIO + +import apache_beam as beam +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 +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): + """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 = element.inference + for part in response.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 ImageSink(FileSink): + def open(self, fh) -> None: + self._fh = fh + + def write(self, record): + record.save(self._fh, format='PNG') + + def flush(self): + self._fh.flush() + + +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" >> WriteToFiles( + path=known_args.output, + file_naming=default_file_naming("gemini-image", ".png"), + sink=ImageSink()) + + 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 b264467467cf..0072dfc50b2f 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[1][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}" + 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( diff --git a/sdks/python/apache_beam/ml/inference/gemini_inference.py b/sdks/python/apache_beam/ml/inference/gemini_inference.py index fd1a7b0f7ac9..a04ee2533a1b 100644 --- a/sdks/python/apache_beam/ml/inference/gemini_inference.py +++ b/sdks/python/apache_beam/ml/inference/gemini_inference.py @@ -21,13 +21,16 @@ 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 +from google.genai.types import Part 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") @@ -56,6 +59,41 @@ def generate_from_string( 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[Union[str, Image, Part]]], + 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-image model (AKA Nano Banana.) + + Args: + model_name: the Gemini model to use for the request. This model should be + 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 + inference_args: any additional arguments passed to the generate_content + call. + """ return model.models.generate_content( model=model_name, contents=batch, **inference_args) @@ -168,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..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 @@ -23,11 +23,13 @@ import pytest +from apache_beam.io.filesystem import MatchResult from apache_beam.io.filesystems import FileSystems from apache_beam.testing.test_pipeline import TestPipeline # 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 +54,29 @@ 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=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)) + 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) 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