File size: 2,176 Bytes
4feb75c
 
 
 
 
ac7b414
 
01c2e26
 
 
 
 
 
 
 
4feb75c
 
612ea96
0099c0a
4feb75c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01c2e26
4feb75c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import uuid
from io import BytesIO
from PIL import Image
import gradio as gr
from google import genai
from google.genai import types
import logging

# 設定logging
logging.basicConfig(
    filename='app.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

# 設定 Gemini API 金鑰
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
client = genai.Client(api_key=GEMINI_API_KEY)

# 設定圖片儲存目錄
STATIC_IMAGE_PATH = "static/images"
os.makedirs(STATIC_IMAGE_PATH, exist_ok=True)

# 取得 Hugging Face Space 的主機名稱
SPACE_HOST = os.environ.get("SPACE_HOST", "your-space-name.hf.space")

def generate_image(prompt):
    """
    使用 Gemini API 根據提示詞生成圖片,並返回圖片的公開 URL。
    """
    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.inline_data is not None:
            image = Image.open(BytesIO(part.inline_data.data))
            filename = f"{uuid.uuid4().hex}.png"
            image_path = os.path.join(STATIC_IMAGE_PATH, filename)
            image.save(image_path)

            # 建立圖片的公開 URL
            image_url = f"https://{SPACE_HOST}/static/images/{filename}"
            logging.info(f"生成的圖片 URL: {image_url}")
            return image_url

    return "未能生成圖片,請嘗試其他提示詞。"

# 建立 Gradio 介面
with gr.Blocks() as demo:
    gr.Markdown("## 🖼️ Gemini 圖片生成器")
    prompt_input = gr.Textbox(label="輸入提示詞", placeholder="例如:一隻戴著墨鏡的貓在沙灘上")
    generate_button = gr.Button("生成圖片")
    image_output = gr.Image(label="生成的圖片")

    def on_generate(prompt):
        image_url = generate_image(prompt)
        return image_url

    generate_button.click(fn=on_generate, inputs=prompt_input, outputs=image_output)

if __name__ == "__main__":
    demo.launch()