Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -8,11 +8,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:
|
@@ -21,26 +17,13 @@ else:
|
|
21 |
# 使用する画像生成モデル
|
22 |
IMAGE_MODEL = "black-forest-labs/FLUX.1-schnell-Free"
|
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 |
|
@@ -56,25 +39,36 @@ def generate_image_from_prompt(prompt: str, history: list):
|
|
56 |
width=1024
|
57 |
)
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
image = Image.open(BytesIO(image_data))
|
65 |
-
|
66 |
-
# 新しい画像とプロンプトを履歴リストの先頭に追加
|
67 |
-
# Galleryコンポーネントは (image, caption) のタプルのリストを期待します
|
68 |
-
new_history = [(image, prompt)] + history
|
69 |
-
|
70 |
-
print("画像の生成が完了しました。")
|
71 |
return new_history, new_history
|
72 |
|
73 |
except Exception as e:
|
74 |
-
|
|
|
|
|
|
|
75 |
raise gr.Error(f"画像の生成に失敗しました。エラー詳細: {e}")
|
76 |
|
77 |
-
|
78 |
# --- 3. Gradio UIの構築 ---
|
79 |
with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px; margin: auto;}") as app:
|
80 |
gr.Markdown(
|
@@ -85,39 +79,27 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px;
|
|
85 |
"""
|
86 |
)
|
87 |
gr.Markdown("---")
|
88 |
-
|
89 |
-
# 生成された画像の履歴を保持するためのState
|
90 |
-
# 履歴は [(PIL.Image, "プロンプト1"), (PIL.Image, "プロンプト2"), ...] のリスト
|
91 |
history_state = gr.State([])
|
92 |
|
93 |
with gr.Column():
|
94 |
-
# 入力コンポーネント
|
95 |
prompt_input = gr.Textbox(
|
96 |
label="画像生成プロンプト",
|
97 |
placeholder="例: 月面にいる、写真のようにリアルな猫の宇宙飛行士",
|
98 |
lines=4,
|
99 |
interactive=True,
|
100 |
)
|
101 |
-
|
102 |
-
# APIキーが設定されていない場合に警告を表示
|
103 |
if not together_client:
|
104 |
gr.Warning("環境変数 `TOGETHER_API_KEY` が見つかりません。画像生成機能を利用するにはAPIキーを設定してください。")
|
105 |
-
|
106 |
generate_btn = gr.Button(
|
107 |
-
"画像生成 ✨",
|
108 |
variant="primary",
|
109 |
-
# APIクライアントがなければボタンを無効化
|
110 |
interactive=(together_client is not None)
|
111 |
)
|
112 |
|
113 |
gr.Markdown("---")
|
114 |
-
|
115 |
-
# ▼▼▼ 修正箇所 ▼▼▼
|
116 |
-
# gr.subheader を gr.Markdown("## ...") に変更
|
117 |
gr.Markdown("## 生成された画像")
|
118 |
|
119 |
-
# 出力コンポーネント
|
120 |
-
# Galleryは、キャプション付きの画像リストを表示するのに最適です
|
121 |
image_gallery = gr.Gallery(
|
122 |
label="生成結果",
|
123 |
show_label=False,
|
@@ -128,16 +110,13 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px;
|
|
128 |
preview=True
|
129 |
)
|
130 |
|
131 |
-
# ボタンのクリックイベントと生成関数を接続
|
132 |
generate_btn.click(
|
133 |
fn=generate_image_from_prompt,
|
134 |
inputs=[prompt_input, history_state],
|
135 |
outputs=[image_gallery, history_state],
|
136 |
-
# API呼び出し中にプログレスインジケーターを表示
|
137 |
show_progress="full"
|
138 |
)
|
139 |
|
140 |
-
# ユーザーのための入力例
|
141 |
gr.Examples(
|
142 |
examples=[
|
143 |
"A high-resolution photo of a futuristic city with flying cars",
|
@@ -148,7 +127,5 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px;
|
|
148 |
inputs=prompt_input
|
149 |
)
|
150 |
|
151 |
-
# `app.launch()` はGradioアプリを起動します
|
152 |
-
# ローカルサーバーが立ち上がり、ブラウザでアクセスできるURLがターミナルに表示されます
|
153 |
if __name__ == "__main__":
|
154 |
app.launch(mcp_server=True)
|
|
|
8 |
from io import BytesIO
|
9 |
|
10 |
# --- 1. 設定: APIキーの読み込み ---
|
|
|
|
|
11 |
api_key = os.environ.get("TOGETHER_API_KEY")
|
|
|
|
|
12 |
if api_key:
|
13 |
together_client = together.Together(api_key=api_key)
|
14 |
else:
|
|
|
17 |
# 使用する画像生成モデル
|
18 |
IMAGE_MODEL = "black-forest-labs/FLUX.1-schnell-Free"
|
19 |
|
|
|
20 |
# --- 2. 中核機能: 画像生成関数 ---
|
21 |
def generate_image_from_prompt(prompt: str, history: list):
|
22 |
"""
|
23 |
TogetherAI APIを使用して画像を生成し、履歴リストの先頭に追加します。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
"""
|
|
|
25 |
if not together_client:
|
26 |
raise gr.Error("TogetherAIのAPIクライアントが設定されていません。環境変数 TOGETHER_API_KEY を確認してください。")
|
|
|
|
|
27 |
if not prompt or not prompt.strip():
|
28 |
raise gr.Error("画像を生成するには、プロンプトを入力してください。")
|
29 |
|
|
|
39 |
width=1024
|
40 |
)
|
41 |
|
42 |
+
generated_images = []
|
43 |
+
# response.data にはリクエストした全ての画像データが含まれる
|
44 |
+
for image_data_item in response.data:
|
45 |
+
image_b64 = image_data_item.b64_json
|
46 |
+
|
47 |
+
# ▼▼▼ 修正箇所: 安全チェックを追加 ▼▼▼
|
48 |
+
# image_b64がNoneでない(正常にデータが返された)場合のみ処理する
|
49 |
+
if image_b64:
|
50 |
+
image_data = base64.b64decode(image_b64)
|
51 |
+
image = Image.open(BytesIO(image_data))
|
52 |
+
# Gallery用に (image, caption) のタプルを作成
|
53 |
+
generated_images.append((image, prompt))
|
54 |
+
|
55 |
+
# 正常に生成された画像が1枚もなかった場合
|
56 |
+
if not generated_images:
|
57 |
+
raise gr.Error("画像の生成に失敗しました。プロンプトがコンテンツフィルターに抵触した可能性があります。別のプロンプトで試してください。")
|
58 |
+
|
59 |
+
# 新しい画像のリストを、既存の履歴の先頭に追加
|
60 |
+
new_history = generated_images + history
|
61 |
|
62 |
+
print(f"{len(generated_images)}枚の画像の生成が完了しました。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
return new_history, new_history
|
64 |
|
65 |
except Exception as e:
|
66 |
+
# 既にgr.Errorの場合はそのまま表示
|
67 |
+
if isinstance(e, gr.Error):
|
68 |
+
raise e
|
69 |
+
print(f"予期せぬエラーが発生しました: {e}")
|
70 |
raise gr.Error(f"画像の生成に失敗しました。エラー詳細: {e}")
|
71 |
|
|
|
72 |
# --- 3. Gradio UIの構築 ---
|
73 |
with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px; margin: auto;}") as app:
|
74 |
gr.Markdown(
|
|
|
79 |
"""
|
80 |
)
|
81 |
gr.Markdown("---")
|
82 |
+
|
|
|
|
|
83 |
history_state = gr.State([])
|
84 |
|
85 |
with gr.Column():
|
|
|
86 |
prompt_input = gr.Textbox(
|
87 |
label="画像生成プロンプト",
|
88 |
placeholder="例: 月面にいる、写真のようにリアルな猫の宇宙飛行士",
|
89 |
lines=4,
|
90 |
interactive=True,
|
91 |
)
|
|
|
|
|
92 |
if not together_client:
|
93 |
gr.Warning("環境変数 `TOGETHER_API_KEY` が見つかりません。画像生成機能を利用するにはAPIキーを設定してください。")
|
|
|
94 |
generate_btn = gr.Button(
|
95 |
+
"画像生成 ✨ (4枚)",
|
96 |
variant="primary",
|
|
|
97 |
interactive=(together_client is not None)
|
98 |
)
|
99 |
|
100 |
gr.Markdown("---")
|
|
|
|
|
|
|
101 |
gr.Markdown("## 生成された画像")
|
102 |
|
|
|
|
|
103 |
image_gallery = gr.Gallery(
|
104 |
label="生成結果",
|
105 |
show_label=False,
|
|
|
110 |
preview=True
|
111 |
)
|
112 |
|
|
|
113 |
generate_btn.click(
|
114 |
fn=generate_image_from_prompt,
|
115 |
inputs=[prompt_input, history_state],
|
116 |
outputs=[image_gallery, history_state],
|
|
|
117 |
show_progress="full"
|
118 |
)
|
119 |
|
|
|
120 |
gr.Examples(
|
121 |
examples=[
|
122 |
"A high-resolution photo of a futuristic city with flying cars",
|
|
|
127 |
inputs=prompt_input
|
128 |
)
|
129 |
|
|
|
|
|
130 |
if __name__ == "__main__":
|
131 |
app.launch(mcp_server=True)
|