|
import os |
|
import io |
|
import PIL.Image |
|
import tempfile |
|
from google import genai |
|
from google.genai import types |
|
from datetime import datetime |
|
|
|
|
|
client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"]) |
|
|
|
def generate_image_with_gemini(prompt): |
|
response = client.models.generate_content( |
|
model="gemini-2.0-flash-exp-image-generation", |
|
contents=prompt, |
|
config=types.GenerateContentConfig(response_modalities=['Text', 'Image']) |
|
) |
|
|
|
for part in response.candidates[0].content.parts: |
|
if part.text is not None: |
|
print(part.text) |
|
elif part.inline_data is not None: |
|
return part.inline_data.data |
|
|
|
return |
|
|
|
def upload_image_to_imgur(client, image_binary, album=None, name="gemini-image", title="gemini Generated Image"): |
|
|
|
image = PIL.Image.open(io.BytesIO(image_binary)) |
|
|
|
|
|
with tempfile.NamedTemporaryFile(suffix=".png", delete=True) as tmp: |
|
image.save(tmp.name, format='PNG') |
|
|
|
|
|
config = { |
|
'album': album, |
|
'name': name, |
|
'title': title, |
|
'description': f'Generated by gemini - {datetime.now()}' |
|
} |
|
|
|
|
|
uploaded_image = client.upload_from_path(tmp.name, config=config, anon=False) |
|
|
|
|
|
return uploaded_image['link'] |
|
|