Spaces:
Running
Running
Create gemini.py
Browse files
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()
|