Candy04/ImageGen
0
1import os2from io import BytesIO3from PIL import Image4import gradio as gr5from google import genai6from google.genai import types7import logging8 9# 設定 logging10logging.basicConfig(11 filename='app.log',12 level=logging.INFO,13 format='%(asctime)s - %(levelname)s - %(message)s'14)15 16# 設定 Gemini API 金鑰17# === 初始化 Google Gemini ===18GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")19client = genai.Client(api_key=GEMINI_API_KEY)20 21def generate_image(prompt):22 """23 使用 Gemini API 根據提示詞生成圖片,並返回 PIL 圖像物件。24 """25 response = client.models.generate_content(26 model="gemini-2.0-flash-exp-image-generation",27 contents=prompt,28 config=types.GenerateContentConfig(29 response_modalities=["TEXT", "IMAGE"]30 ),31 )32 33 # 處理回應中的圖片34 for part in response.candidates[0].content.parts:35 if part.inline_data is not None:36 image = Image.open(BytesIO(part.inline_data.data))37 logging.info("成功生成圖片。")38 return image39 40 logging.warning("未能生成圖片,請嘗試其他提示詞。")41 return None42 43# 建立 Gradio 介面44with gr.Blocks() as demo:45 gr.Markdown("## 🖼️ B10090012 吳宥錚 Gemini 圖片生成器")46 prompt_input = gr.Textbox(label="輸入提示詞", placeholder="例如:一隻戴著墨鏡的貓在沙灘上")47 generate_button = gr.Button("生成圖片")48 image_output = gr.Image(label="生成的圖片")49 50 def on_generate(prompt):51 image = generate_image(prompt)52 return image53 54 generate_button.click(fn=on_generate, inputs=prompt_input, outputs=image_output)55 56if __name__ == "__main__":57 demo.launch()58 