File size: 1,960 Bytes
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
import os
import uuid
from io import BytesIO
from PIL import Image
import gradio as gr
import google.generativeai as genai
from google.generativeai import types

# ่จญๅฎš Gemini API ้‡‘้‘ฐ
genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
client = genai.Client()

# ่จญๅฎšๅœ–็‰‡ๅ„ฒๅญ˜็›ฎ้Œ„
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}"
            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()