Spaces:
Sleeping
Sleeping
| 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 | |
| # ่จญๅฎ 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() | |