Repository navigation
Add image generation code to Gemini Model Handler #36177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
a2d05a5
[WIP] Add image generation code to Gemini Model Handler
jrmccluskey 59d510c
add pillow to gemini_tests_requirements.txt
jrmccluskey 63c25fd
linting
jrmccluskey 272947b
import spacing
jrmccluskey 9ae4bda
explicit union
jrmccluskey 3f7a470
add part support to gemini image code
jrmccluskey f871550
Add example, IT test, fix regression in base model handler
jrmccluskey dd1d814
fix file match check
jrmccluskey 1cea543
fix IO to write using FileSystem()
jrmccluskey 4952549
remove debugging logging
jrmccluskey ca0b5b8
linting
jrmccluskey ac57d7e
fix imports
jrmccluskey b49966d
isort
jrmccluskey 27e82bd
fix doubled imports
jrmccluskey 5f06ea2
another attempt at import ordering
jrmccluskey e17d005
Move to using response.parts property, raise exceptions for text pars…
jrmccluskey 5f4a849
remove unused import
jrmccluskey 3d89461
revert breaking change to text generation fn
jrmccluskey 421ea78
use WriteToFiles()
jrmccluskey c7b4ebb
linting
jrmccluskey File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
140 changes: 140 additions & 0 deletions
140
sdks/python/apache_beam/examples/inference/gemini_image_generation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,4 +15,5 @@ | |
| # limitations under the License. | ||
| # | ||
|
|
||
| google-genai>=1.16.1 | ||
| google-genai>=1.16.1 | ||
| pillow>=11.3.0 | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The type hinting is the major distinction here, the actual generation call to gemini is largely distinguished by the model you're calling (the docstring covers this somewhat.) The API is pretty simple from a user standpoint, the distinguishing request functions are really just to make sure we get reasonable typing in here.