Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,47 +1,150 @@
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
|
|
|
|
4 |
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
max_results: int | None = None,
|
11 |
-
) -> list[dict[str, str]]:
|
12 |
-
"""DuckDuckGo news search. Query params: https://duckduckgo.com/params.
|
13 |
|
14 |
Args:
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
timelimit: d, w, m. Defaults to None.
|
19 |
-
max_results: max number of results. If None, returns results only from the first response. Defaults to None.
|
20 |
|
21 |
Returns:
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
|
3 |
import gradio as gr
|
4 |
+
import together
|
5 |
+
import os
|
6 |
+
import base64
|
7 |
+
from PIL import Image
|
8 |
+
from io import BytesIO
|
9 |
+
|
10 |
+
# --- 1. 設定: APIキーの読み込み ---
|
11 |
+
# 環境変数 `TOGETHER_API_KEY` からAPIキーを読み込みます。
|
12 |
+
# 事前に `export TOGETHER_API_KEY="あなたのAPIキー"` のように設定してください。
|
13 |
+
api_key = os.environ.get("TOGETHER_API_KEY")
|
14 |
+
|
15 |
+
# APIキーがあればTogetherAIクライアントを初期化
|
16 |
+
if api_key:
|
17 |
+
together_client = together.Together(api_key=api_key)
|
18 |
+
else:
|
19 |
+
together_client = None
|
20 |
|
21 |
+
# 使用する画像生成モデル
|
22 |
+
IMAGE_MODEL = "stabilityai/stable-diffusion-xl-base-1.0"
|
23 |
|
24 |
+
|
25 |
+
# --- 2. 中核機能: 画像生成関数 ---
|
26 |
+
def generate_image_from_prompt(prompt: str, history: list):
|
27 |
+
"""
|
28 |
+
TogetherAI APIを使用して画像を生成し、履歴リストの先頭に追加します。
|
|
|
|
|
|
|
29 |
|
30 |
Args:
|
31 |
+
prompt (str): 画像生成のためのテキストプロンプト。
|
32 |
+
history (list): これまでの生成結果を格納したリスト。
|
33 |
+
各要素は (PIL.Image, "プロンプト") のタプルです。
|
|
|
|
|
34 |
|
35 |
Returns:
|
36 |
+
tuple: 更新された履歴リスト (Gallery表示用) と、
|
37 |
+
更新された履歴リスト (State保持用) のタプル。
|
38 |
"""
|
39 |
+
# APIクライアントが設定されていない場合はエラーを返す
|
40 |
+
if not together_client:
|
41 |
+
raise gr.Error("TogetherAIのAPIクライアントが設定されていません。環境変数 TOGETHER_API_KEY を確認してください。")
|
42 |
+
|
43 |
+
# プロンプトが空の場合はエラーを返す
|
44 |
+
if not prompt or not prompt.strip():
|
45 |
+
raise gr.Error("画像を生成するには、プロンプトを入力してください。")
|
46 |
+
|
47 |
+
print(f"プロンプトを元に画像を生成中: '{prompt}'")
|
48 |
+
try:
|
49 |
+
# TogetherAI APIを呼び出し
|
50 |
+
response = together_client.images.generate(
|
51 |
+
prompt=prompt,
|
52 |
+
model=IMAGE_MODEL,
|
53 |
+
n=1,
|
54 |
+
height=1024,
|
55 |
+
width=1024
|
56 |
+
)
|
57 |
+
|
58 |
+
# レスポンスにはbase64形式で画像データが含まれている
|
59 |
+
image_b64 = response.data[0].b64_json
|
60 |
+
image_data = base64.b64decode(image_b64)
|
61 |
+
|
62 |
+
# バイトデータからPILイメージオブジェクトを作成
|
63 |
+
image = Image.open(BytesIO(image_data))
|
64 |
+
|
65 |
+
# 新しい画像とプロンプトを履歴リストの先頭に追加
|
66 |
+
# Galleryコンポーネントは (image, caption) のタプルのリストを期待します
|
67 |
+
new_history = [(image, prompt)] + history
|
68 |
+
|
69 |
+
print("画像の生成が完了しました。")
|
70 |
+
return new_history, new_history
|
71 |
+
|
72 |
+
except Exception as e:
|
73 |
+
print(f"エラーが発生しました: {e}")
|
74 |
+
raise gr.Error(f"画像の生成に失敗しました。エラー詳細: {e}")
|
75 |
+
|
76 |
+
|
77 |
+
# --- 3. Gradio UIの構築 ---
|
78 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px; margin: auto;}") as app:
|
79 |
+
gr.Markdown(
|
80 |
+
"""
|
81 |
+
# 🖼️ TogetherAI 画像生成アプリ (Gradio版)
|
82 |
+
プロンプトを入力して、TogetherAIのAPIで画像を生成します。
|
83 |
+
最新の画像がギャラリーの先頭に表示されます。
|
84 |
+
"""
|
85 |
+
)
|
86 |
+
gr.Markdown("---")
|
87 |
+
|
88 |
+
# 生成された画像の履歴を保持するためのState
|
89 |
+
# 履歴は [(PIL.Image, "プロンプト1"), (PIL.Image, "プロンプト2"), ...] のリスト
|
90 |
+
history_state = gr.State([])
|
91 |
+
|
92 |
+
with gr.Column():
|
93 |
+
# 入力コンポーネント
|
94 |
+
prompt_input = gr.Textbox(
|
95 |
+
label="画像生成プロンプト",
|
96 |
+
placeholder="例: 月面にいる、写真のようにリアルな猫の宇宙飛行士",
|
97 |
+
lines=4,
|
98 |
+
interactive=True,
|
99 |
+
)
|
100 |
+
|
101 |
+
# APIキーが設定されていない場合に警告を表示
|
102 |
+
if not together_client:
|
103 |
+
gr.Warning("環境変数 `TOGETHER_API_KEY` が見つかりません。画像生成機能を利用するにはAPIキーを設定してください。")
|
104 |
+
|
105 |
+
generate_btn = gr.Button(
|
106 |
+
"画像生成 ✨",
|
107 |
+
variant="primary",
|
108 |
+
# APIクライアントがなければボタンを無効化
|
109 |
+
interactive=(together_client is not None)
|
110 |
+
)
|
111 |
+
|
112 |
+
gr.Markdown("---")
|
113 |
+
gr.subheader("生成された画像")
|
114 |
+
|
115 |
+
# 出力コンポーネント
|
116 |
+
# Galleryは、キャプション付きの画像リストを表示するのに最適です
|
117 |
+
image_gallery = gr.Gallery(
|
118 |
+
label="生成結果",
|
119 |
+
show_label=False,
|
120 |
+
columns=2,
|
121 |
+
height="auto",
|
122 |
+
object_fit="contain",
|
123 |
+
value=None,
|
124 |
+
preview=True
|
125 |
+
)
|
126 |
+
|
127 |
+
# ボタンのクリックイベントと生成関数を接続
|
128 |
+
generate_btn.click(
|
129 |
+
fn=generate_image_from_prompt,
|
130 |
+
inputs=[prompt_input, history_state],
|
131 |
+
outputs=[image_gallery, history_state],
|
132 |
+
# API呼び出し中にプログレスインジケーターを表示
|
133 |
+
show_progress="full"
|
134 |
+
)
|
135 |
+
|
136 |
+
# ユーザーのための入力例
|
137 |
+
gr.Examples(
|
138 |
+
examples=[
|
139 |
+
"A high-resolution photo of a futuristic city with flying cars",
|
140 |
+
"An oil painting of a serene landscape with a river and mountains",
|
141 |
+
"A cute, fluffy alien creature exploring a vibrant, magical forest",
|
142 |
+
"Logo for a coffee shop named 'The Daily Grind', minimalist, modern"
|
143 |
+
],
|
144 |
+
inputs=prompt_input
|
145 |
+
)
|
146 |
+
|
147 |
+
# `app.launch()` はGradioアプリを起動します
|
148 |
+
# ローカルサーバーが立ち上がり、ブラウザでアクセスできるURLがターミナルに表示されます
|
149 |
+
if __name__ == "__main__":
|
150 |
+
app.launch(mcp_server=True)
|