Spaces:
Paused
Paused
File size: 2,373 Bytes
3f4aae4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# To run this code you need to install the following dependencies:
# pip install google-genai
import base64
import mimetypes
import os
from google import genai
from google.genai import types
def save_binary_file(file_name, data):
f = open(file_name, "wb")
f.write(data)
f.close()
print(f"File saved to to: {file_name}")
def generate():
client = genai.Client(
api_key=os.environ.get("GEMINI_API_KEY"),
)
model = "gemini-2.0-flash-preview-image-generation"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text="""筋トレ中の女性
"""),
],
),
types.Content(
role="model",
parts=[
types.Part.from_bytes(
mime_type="image/png",
data=base64.b64decode(
""" <画像データが入ります> """
),
),
],
),
types.Content(
role="user",
parts=[
types.Part.from_text(text="""INSERT_INPUT_HERE"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
response_modalities=[
"IMAGE",
"TEXT",
],
response_mime_type="text/plain",
)
file_index = 0
for chunk in client.models.generate_content_stream(
model=model,
contents=contents,
config=generate_content_config,
):
if (
chunk.candidates is None
or chunk.candidates[0].content is None
or chunk.candidates[0].content.parts is None
):
continue
if chunk.candidates[0].content.parts[0].inline_data and chunk.candidates[0].content.parts[0].inline_data.data:
file_name = f"ENTER_FILE_NAME_{file_index}"
file_index += 1
inline_data = chunk.candidates[0].content.parts[0].inline_data
data_buffer = inline_data.data
file_extension = mimetypes.guess_extension(inline_data.mime_type)
save_binary_file(f"{file_name}{file_extension}", data_buffer)
else:
print(chunk.text)
if __name__ == "__main__":
generate()
|