baxin commited on
Commit
bf6edf9
·
verified ·
1 Parent(s): 546f79e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -49
app.py CHANGED
@@ -1,13 +1,12 @@
1
  # app.py
2
 
3
  import gradio as gr
4
- #from together import Together
5
  import together
6
-
7
  import os
8
  import base64
9
  from PIL import Image
10
  from io import BytesIO
 
11
 
12
  # --- 1. 設定: APIキーの読み込み ---
13
  api_key = os.environ.get("TOGETHER_API_KEY")
@@ -21,9 +20,6 @@ IMAGE_MODEL = "black-forest-labs/FLUX.1-schnell-Free"
21
 
22
  # --- 2. 中核機能: 画像生成関数 ---
23
  def generate_image_from_prompt(prompt: str, history: list):
24
- """
25
- TogetherAI APIを使用して画像を生成し、履歴リストの先頭に追加します。
26
- """
27
  if not together_client:
28
  raise gr.Error("TogetherAIのAPIクライアントが設定されていません。環境変数 TOGETHER_API_KEY を確認してください。")
29
  if not prompt or not prompt.strip():
@@ -31,7 +27,6 @@ def generate_image_from_prompt(prompt: str, history: list):
31
 
32
  print(f"プロンプトを元に画像を生成中: '{prompt}'")
33
  try:
34
- # TogetherAI APIを呼び出し
35
  response = together_client.images.generate(
36
  prompt=prompt,
37
  model=IMAGE_MODEL,
@@ -40,43 +35,50 @@ def generate_image_from_prompt(prompt: str, history: list):
40
  height=1024,
41
  width=1024
42
  )
43
-
44
- # ▼▼▼ デバッグのためにこの行を追加 ▼▼▼
45
- print("---------- API Response ----------")
46
- print(response)
47
- print("--------------------------------")
48
 
49
  generated_images = []
50
- # response.data にはリクエストした全ての画像データが含まれる
 
51
  for image_data_item in response.data:
52
- image_b64 = image_data_item.b64_json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- # ▼▼▼ 修正箇所: 安全チェックを追加 ▼▼▼
55
- # image_b64がNoneでない(正常にデータが返された)場合のみ処理する
56
- if image_b64:
57
  image_data = base64.b64decode(image_b64)
58
  image = Image.open(BytesIO(image_data))
59
- # Gallery用に (image, caption) のタプルを作成
60
  generated_images.append((image, prompt))
61
 
62
- # 正常に生成された画像が1枚もなかった場合
63
  if not generated_images:
64
- raise gr.Error("画像の生成に失敗しました。プロンプトがコンテンツフィルターに抵触した可能性があります。別のプロンプトで試してください。")
65
 
66
- # 新しい画像のリストを、既存の履歴の先頭に追加
67
  new_history = generated_images + history
68
-
69
  print(f"{len(generated_images)}枚の画像の生成が完了しました。")
70
  return new_history, new_history
71
 
72
  except Exception as e:
73
- # 既にgr.Errorの場合はそのまま表示
74
  if isinstance(e, gr.Error):
75
  raise e
76
  print(f"予期せぬエラーが発生しました: {e}")
77
  raise gr.Error(f"画像の生成に失敗しました。エラー詳細: {e}")
78
 
79
- # --- 3. Gradio UIの構築 ---
80
  with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px; margin: auto;}") as app:
81
  gr.Markdown(
82
  """
@@ -86,9 +88,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px;
86
  """
87
  )
88
  gr.Markdown("---")
89
-
90
  history_state = gr.State([])
91
-
92
  with gr.Column():
93
  prompt_input = gr.Textbox(
94
  label="画像生成プロンプト",
@@ -98,32 +98,11 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px;
98
  )
99
  if not together_client:
100
  gr.Warning("環境変数 `TOGETHER_API_KEY` が見つかりません。画像生成機能を利用するにはAPIキーを設定してください。")
101
- generate_btn = gr.Button(
102
- "画像生成 ✨",
103
- variant="primary",
104
- interactive=(together_client is not None)
105
- )
106
-
107
  gr.Markdown("---")
108
  gr.Markdown("## 生成された画像")
109
-
110
- image_gallery = gr.Gallery(
111
- label="生成結果",
112
- show_label=False,
113
- columns=2,
114
- height="auto",
115
- object_fit="contain",
116
- value=None,
117
- preview=True
118
- )
119
-
120
- generate_btn.click(
121
- fn=generate_image_from_prompt,
122
- inputs=[prompt_input, history_state],
123
- outputs=[image_gallery, history_state],
124
- show_progress="full"
125
- )
126
-
127
  gr.Examples(
128
  examples=[
129
  "A high-resolution photo of a futuristic city with flying cars",
 
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
+ import requests # ▼▼▼ 修正箇所: requestsライブラリをインポート ▼▼▼
10
 
11
  # --- 1. 設定: APIキーの読み込み ---
12
  api_key = os.environ.get("TOGETHER_API_KEY")
 
20
 
21
  # --- 2. 中核機能: 画像生成関数 ---
22
  def generate_image_from_prompt(prompt: str, history: list):
 
 
 
23
  if not together_client:
24
  raise gr.Error("TogetherAIのAPIクライアントが設定されていません。環境変数 TOGETHER_API_KEY を確認してください。")
25
  if not prompt or not prompt.strip():
 
27
 
28
  print(f"プロンプトを元に画像を生成中: '{prompt}'")
29
  try:
 
30
  response = together_client.images.generate(
31
  prompt=prompt,
32
  model=IMAGE_MODEL,
 
35
  height=1024,
36
  width=1024
37
  )
 
 
 
 
 
38
 
39
  generated_images = []
40
+
41
+ # ▼▼▼ 修正箇所: URLから画像をダウンロードするロジックに変更 ▼▼▼
42
  for image_data_item in response.data:
43
+ # APIの応答に 'url' が含まれているかチェック
44
+ if hasattr(image_data_item, 'url') and image_data_item.url:
45
+ try:
46
+ image_url = image_data_item.url
47
+ print(f"URLから画像をダウンロード中: {image_url}")
48
+
49
+ # URLにアクセスして画像データを取得
50
+ image_response = requests.get(image_url)
51
+ image_response.raise_for_status() # エラーがあれば例外を発生させる
52
+
53
+ # ダウンロードしたバイトデータからPILイメージを作成
54
+ image = Image.open(BytesIO(image_response.content))
55
+ generated_images.append((image, prompt))
56
+
57
+ except requests.exceptions.RequestException as e:
58
+ print(f"画像のダウンロードに失敗しました: {e}")
59
+ continue # この画像の処理をスキップして次に進む
60
 
61
+ # (参考) b64_jsonが返ってくるモデルのためのフォールバック処理
62
+ elif image_data_item.b64_json:
63
+ image_b64 = image_data_item.b64_json
64
  image_data = base64.b64decode(image_b64)
65
  image = Image.open(BytesIO(image_data))
 
66
  generated_images.append((image, prompt))
67
 
 
68
  if not generated_images:
69
+ raise gr.Error("画像の生成に失敗しました。APIから有効な画像データやURLが返されませんでした。")
70
 
 
71
  new_history = generated_images + history
 
72
  print(f"{len(generated_images)}枚の画像の生成が完了しました。")
73
  return new_history, new_history
74
 
75
  except Exception as e:
 
76
  if isinstance(e, gr.Error):
77
  raise e
78
  print(f"予期せぬエラーが発生しました: {e}")
79
  raise gr.Error(f"画像の生成に失敗しました。エラー詳細: {e}")
80
 
81
+ # --- 3. Gradio UIの構築 (変更なし) ---
82
  with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px; margin: auto;}") as app:
83
  gr.Markdown(
84
  """
 
88
  """
89
  )
90
  gr.Markdown("---")
 
91
  history_state = gr.State([])
 
92
  with gr.Column():
93
  prompt_input = gr.Textbox(
94
  label="画像生成プロンプト",
 
98
  )
99
  if not together_client:
100
  gr.Warning("環境変数 `TOGETHER_API_KEY` が見つかりません。画像生成機能を利用するにはAPIキーを設定してください。")
101
+ generate_btn = gr.Button("画像生成 ✨ (4枚)", variant="primary", interactive=(together_client is not None))
 
 
 
 
 
102
  gr.Markdown("---")
103
  gr.Markdown("## 生成された画像")
104
+ image_gallery = gr.Gallery(label="生成結果", show_label=False, columns=2, height="auto", object_fit="contain", value=None, preview=True)
105
+ generate_btn.click(fn=generate_image_from_prompt, inputs=[prompt_input, history_state], outputs=[image_gallery, history_state], show_progress="full")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  gr.Examples(
107
  examples=[
108
  "A high-resolution photo of a futuristic city with flying cars",