baxin commited on
Commit
06b8797
·
verified ·
1 Parent(s): 85f9e0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -39
app.py CHANGED
@@ -1,47 +1,150 @@
 
 
1
  import gradio as gr
2
- from duckduckgo_search import DDGS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
 
 
4
 
5
- def news(
6
- keywords: str,
7
- region: str = "wt-wt",
8
- safesearch: str = "moderate",
9
- timelimit: str | None = None,
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
- keywords: keywords for query.
16
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
17
- safesearch: on, moderate, off. Defaults to "moderate".
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
- List of dictionaries with news search results.
 
23
  """
24
- # Fix: Use the keywords parameter instead of hardcoded "sun"
25
- results = DDGS().news(keywords=keywords, region=region,
26
- safesearch=safesearch, timelimit=timelimit, max_results=max_results)
27
- return list(results) # Convert generator to list and return it
28
-
29
-
30
- # Create a Gradio interface for the news function
31
- demo = gr.Interface(
32
- fn=news,
33
- inputs=[
34
- gr.Textbox(label="Keywords"),
35
- gr.Dropdown(["wt-wt", "us-en", "uk-en"],
36
- label="Region", value="wt-wt"),
37
- gr.Dropdown(["on", "moderate", "off"],
38
- label="Safe Search", value="moderate"),
39
- gr.Dropdown([None, "d", "w", "m"], label="Time Limit", value=None),
40
- gr.Number(label="Max Results", value=10)
41
- ],
42
- outputs=gr.JSON(),
43
- title="News Search",
44
- description="Search for news using DuckDuckGo"
45
- )
46
-
47
- demo.launch(mcp_server=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)