File size: 1,709 Bytes
4feb75c c3f33ac 01c2e26 95645e7 01c2e26 4feb75c 9cb4e4d 612ea96 9cb4e4d 4feb75c 95645e7 4feb75c 95645e7 4feb75c 95645e7 4feb75c 95645e7 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 |
import os
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 ้้ฐ
# === ๅๅงๅ Google Gemini ===
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
client = genai.Client(api_key=GEMINI_API_KEY)
def generate_image(prompt):
"""
ไฝฟ็จ Gemini API ๆ นๆๆ็คบ่ฉ็ๆๅ็๏ผไธฆ่ฟๅ PIL ๅๅ็ฉไปถใ
"""
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))
logging.info("ๆๅ็ๆๅ็ใ")
return image
logging.warning("ๆช่ฝ็ๆๅ็๏ผ่ซๅ่ฉฆๅ
ถไปๆ็คบ่ฉใ")
return None
# ๅปบ็ซ 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 = generate_image(prompt)
return image
generate_button.click(fn=on_generate, inputs=prompt_input, outputs=image_output)
if __name__ == "__main__":
demo.launch()
|