0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Gradio】画像生成

Last updated at Posted at 2025-05-27

graidoを使用して簡単にWebアプリを作成できるらしいので、作成してみました。

環境
・Windows10
・Docker(Ubuntu)
・Python3.11
・visual stadio code

■事前準備

・gradioのインストール
 pip install gradio

・画像生成
 APIはgemini-2.0-flash(無料)を使用

■API共通部品作成

APIキーを設定

# API-KEYの設定
GOOGLE_API_KEY='取得したAPIキー'
client = cenaiC.Client(api_key=GOOGLE_API_KEY)

プロンプトを指示して、所定のフォルダに保存する

from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO
import base64

# 画像出力
def getGenerateImage(text):

    contents = text

    # ファイルパスの設定
    path = 'image/gemini-generate' + Util.getDate('YYYYMMDD HHMMSS') + '.png'

    # 画像生成
    response = client.models.generate_content(
        model="gemini-2.0-flash-exp-image-generation",
        contents=contents,
        config=types.GenerateContentConfig(
        response_modalities=['TEXT', 'IMAGE']
        )
    )

    for part in response.candidates[0].content.parts:
        if part.text is not None:
            print(part.text)
        elif part.inline_data is not None:
            image = Image.open(BytesIO((part.inline_data.data)))
            image.save(path)
    
    return path

メイン処理

# 画像生成(複数)
def generateImageSeq(text):

    list = []
    prompt = text

    # 指定回数描画(固定指定ですが。。)
    for i in range(5):
        path = utilG.getGenerateImage(prompt)
        list.append(path)    

    return list

# インターフェースの作成
# fn: 実行する関数
# inputs: 入力のコンポーネントの種類
# outputs: 出力のコンポーネントの種類
with gr.Blocks() as demo:
    with gr.Row():
        input_text = gr.Textbox()
        button = gr.Button("execute", scale=1)
        imageList = []
        for i in range(5):
            # 出力用の箱を5つ用意
            imageList.append(gr.Image())
            
    # 出力には出力した画像のパス一覧
    button.click(generateImageSeq, inputs=input_text, outputs=imageList)
    # Web UIの起動

# 画面起動
demo.launch()

ローカルホストにあくせす

gradio.PNG

起動結果

ca.PNG

終わりに

簡単に画像生成結果をWebアプリに表示することができました。
Gradioには他のメディアにも対応しているようなので
色々試せそうです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?