huchiahsi commited on
Commit
4feb75c
·
verified ·
1 Parent(s): 2ddda29

Create gemini.py

Browse files
Files changed (1) hide show
  1. gemini.py +60 -0
gemini.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ from io import BytesIO
4
+ from PIL import Image
5
+ import gradio as gr
6
+ import google.generativeai as genai
7
+ from google.generativeai import types
8
+
9
+ # 設定 Gemini API 金鑰
10
+ genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
11
+ client = genai.Client()
12
+
13
+ # 設定圖片儲存目錄
14
+ STATIC_IMAGE_PATH = "static/images"
15
+ os.makedirs(STATIC_IMAGE_PATH, exist_ok=True)
16
+
17
+ # 取得 Hugging Face Space 的主機名稱
18
+ SPACE_HOST = os.environ.get("SPACE_HOST", "your-space-name.hf.space")
19
+
20
+ def generate_image(prompt):
21
+ """
22
+ 使用 Gemini API 根據提示詞生成圖片,並返回圖片的公開 URL。
23
+ """
24
+ response = client.models.generate_content(
25
+ model="gemini-2.0-flash-exp-image-generation",
26
+ contents=prompt,
27
+ config=types.GenerateContentConfig(
28
+ response_modalities=["TEXT", "IMAGE"]
29
+ ),
30
+ )
31
+
32
+ # 處理回應中的圖片
33
+ for part in response.candidates[0].content.parts:
34
+ if part.inline_data is not None:
35
+ image = Image.open(BytesIO(part.inline_data.data))
36
+ filename = f"{uuid.uuid4().hex}.png"
37
+ image_path = os.path.join(STATIC_IMAGE_PATH, filename)
38
+ image.save(image_path)
39
+
40
+ # 建立圖片的公開 URL
41
+ image_url = f"https://{SPACE_HOST}/static/images/{filename}"
42
+ return image_url
43
+
44
+ return "未能生成圖片,請嘗試其他提示詞。"
45
+
46
+ # 建立 Gradio 介面
47
+ with gr.Blocks() as demo:
48
+ gr.Markdown("## 🖼️ Gemini 圖片生成器")
49
+ prompt_input = gr.Textbox(label="輸入提示詞", placeholder="例如:一隻戴著墨鏡的貓在沙灘上")
50
+ generate_button = gr.Button("生成圖片")
51
+ image_output = gr.Image(label="生成的圖片")
52
+
53
+ def on_generate(prompt):
54
+ image_url = generate_image(prompt)
55
+ return image_url
56
+
57
+ generate_button.click(fn=on_generate, inputs=prompt_input, outputs=image_output)
58
+
59
+ if __name__ == "__main__":
60
+ demo.launch()