damccorm commented on code in PR #36177: URL: https://github.com/apache/beam/pull/36177#discussion_r2437071643
########## 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 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 +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 _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) + + 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 expand(self, pcoll: beam.PCollection) -> beam.pvalue.PDone: + return ( + pcoll + | "WriteImageToFile" >> beam.ParDo( + _WriteImageFn(self._output_dir, self._filename_prefix))) Review Comment: We should probably use https://beam.apache.org/releases/pydoc/current/apache_beam.io.fileio.html#apache_beam.io.fileio.WriteToFiles ########## sdks/python/apache_beam/ml/inference/gemini_inference.py: ########## @@ -51,11 +54,46 @@ 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( Review Comment: Do we need this (breaking) change? ########## sdks/python/apache_beam/ml/inference/gemini_inference.py: ########## @@ -51,11 +54,46 @@ 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[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( Review Comment: This call is the exact same as the one to generate text - is the only difference in these apis that one accepts a list and one accepts a single text string? Or are there other things I'm missing? This is surprisingly subtle IMO -- 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. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
