Spaces:
Sleeping

aiTOYAMA commited on
Commit
86b8136
·
verified ·
1 Parent(s): 3be3215

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -84
app.py CHANGED
@@ -98,7 +98,7 @@ def ask_paper(question, mode):
98
  instruction = "論文中の手法について説明してください。以下を含めること:・概要・特徴・利点・数式・初心者向け解説"
99
  elif mode == "実験":
100
  instruction = "論文中の実験内容を整理してください。以下を抽出:・データセット・評価指標・比較手法・結果・考察"
101
- elif mode == "表形式": # UIの表記に合わせて「表形式」に統一
102
  instruction = """論文からユーザーの指示に合う情報を抽出し、結果を必ずCSV形式のみで出力してください。
103
  例:
104
  項目,内容
@@ -112,7 +112,6 @@ def ask_paper(question, mode):
112
 
113
  prompt = f"{instruction}\n\n【論文情報】\n{knowledge[:120000]}\n\n【質問】\n{question}"
114
 
115
- # エラーハンドリング付きのAPIコール(3回までリトライ)
116
  for i in range(3):
117
  try:
118
  response = client.models.generate_content(
@@ -124,30 +123,32 @@ def ask_paper(question, mode):
124
  err_msg = str(e)
125
  if "429" in err_msg or "503" in err_msg:
126
  if i < 2:
127
- time.sleep(3) # 少し待って再試行
128
  continue
129
  return f"⚠️ API混雑または一時的な制限エラーが発生しました。数分後に再度お試しください。\nエラー詳細: {err_msg}"
130
  return f"エラーが発生しました: {err_msg}"
131
 
132
  # =====================================
133
- # メモ保存
134
  # =====================================
135
 
136
- def export_history(question, answer, table_data):
137
- filename = "research_history.txt"
 
 
 
138
  temp_dir = tempfile.gettempdir()
139
  file_path = os.path.join(temp_dir, filename)
140
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
141
 
142
  with open(file_path, "w", encoding="utf-8") as f:
143
  f.write("=" * 60 + "\n")
144
- f.write("研究支援アプリ 保存履歴\n")
145
  f.write("=" * 60 + "\n\n")
146
  f.write(f"保存日時: {now}\n\n")
147
  f.write(f"【質問】\n{question}\n\n")
148
 
149
- # 表形式データがある場合はそれも書き出す
150
- if table_data is not None and not table_data.empty:
151
  f.write("【回答(表形式データ)】\n")
152
  f.write(table_data.to_string(index=False))
153
  else:
@@ -157,44 +158,75 @@ def export_history(question, answer, table_data):
157
  return file_path
158
 
159
  # =====================================
160
- # 解析(表示の切り替えロジック)
161
  # =====================================
162
 
163
- def run_analysis(question, mode):
 
 
 
 
 
 
164
  result = ask_paper(question, mode)
165
 
166
- # エラーメッセージが返ってきた場合の処理
 
 
 
 
 
167
  if "⚠️" in result or "エラーが発生しました" in result:
168
- return result, gr.update(visible=False, value=None)
 
 
 
 
 
169
 
170
  if mode == "表形式":
171
  try:
172
- # Geminiが出力したCSVテキストをPandas DataFrameに変換
173
  df = pd.read_csv(StringIO(result.strip()))
174
- # テキストエリアを隠し、データフレームを表示する
175
- return gr.update(visible=False, value=""), gr.update(visible=True, value=df)
176
  except Exception as e:
177
- # CSV変換に失敗した場合は、テキストとしてエラーを表示
178
  err_df = pd.DataFrame({"エラー": ["CSV表への変換に失敗しました。Geminiの出力を確認してください。"]})
179
- return result, gr.update(visible=True, value=err_df)
180
- else:
181
- # 表形式以外はテキストを表示し、データフレームを隠す
182
- return gr.update(visible=True, value=result), gr.update(visible=False, value=None)
 
 
 
 
 
183
 
184
  # =====================================
185
- # 質問例(プレースホルダー切り替え)
186
  # =====================================
187
 
188
- def update_placeholder(mode):
189
- if mode == "手法":
190
- return gr.update(placeholder="例:この論文で提案されているアルゴリズムの独自の強みは何ですか? / 数式や理論の背景を教えてください。")
191
- elif mode == "実験":
192
- return gr.update(placeholder="例:実験で使用されたデータセットの規模は? / Baseline手法と比べてどの指標が向上していますか?")
193
- elif mode == "要約":
194
- return gr.update(placeholder="例:この論文の研究背景、目的、および今後の課題を要約してください。")
195
- elif mode == "表形式":
196
- return gr.update(placeholder="例:主要な実験結果を、データセット、評価指標、精度の項目でテーブルにまとめてください。")
197
- return gr.update(placeholder="論文への質問や指示を入力してください。")
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  # =====================================
200
  # UI
@@ -207,28 +239,15 @@ with gr.Blocks() as app:
207
  with gr.Row():
208
 
209
  with gr.Column():
210
- upload_files = gr.File(
211
- file_count="multiple",
212
- file_types=[".pdf"],
213
- label="論文追加"
214
- )
215
-
216
  upload_btn = gr.Button("PDF登録")
217
  upload_result = gr.Textbox(label="状態")
218
 
219
- upload_btn.click(
220
- add_pdfs,
221
- inputs=upload_files,
222
- outputs=upload_result
223
- )
224
 
225
  paper_list = gr.Textbox(label="登録論文")
226
  refresh_btn = gr.Button("論文一覧更新")
227
-
228
- refresh_btn.click(
229
- show_paper_list,
230
- outputs=paper_list
231
- )
232
 
233
  with gr.Column():
234
  mode = gr.Radio(
@@ -237,57 +256,56 @@ with gr.Blocks() as app:
237
  label="🔬 解析モードを選択"
238
  )
239
 
240
- question = gr.Textbox(
241
- label="📝 論文への質問・指示",
 
242
  placeholder="例:この論文で提案されているアルゴリズムの独自の強みは何ですか?",
243
- lines=2
244
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
 
246
  mode.change(
247
- fn=update_placeholder,
248
  inputs=mode,
249
- outputs=question,
250
  queue=False
251
  )
252
-
253
- answer = gr.Textbox(
254
- label="💡 AIアシスタントの分析・回答",
255
- placeholder="ここに論文の解析結果が出力されます。",
256
- lines=20,
257
- interactive=False,
258
- visible=True
259
- )
260
-
261
- # 初期状態では非表示にしておく
262
- table_output = gr.Dataframe(
263
- label="📊 解析結果(表形式)",
264
- visible=False
265
- )
266
 
267
- search_btn = gr.Button(
268
- "🚀 論文の解析を実行する",
269
- variant="primary"
270
- )
271
 
272
  search_btn.click(
273
  run_analysis,
274
- inputs=[question, mode],
275
- outputs=[answer, table_output]
276
  )
277
 
278
- download_btn = gr.Button(
279
- "💾 この対話をテキストファイル(.txt)で保存する",
280
- variant="secondary"
281
- )
282
-
283
- download_file = gr.File(
284
- label="📥 ダウンロード",
285
- visible=True
286
- )
287
 
288
  download_btn.click(
289
- export_history,
290
- inputs=[question, answer, table_output],
291
  outputs=download_file
292
  )
293
 
 
98
  instruction = "論文中の手法について説明してください。以下を含めること:・概要・特徴・利点・数式・初心者向け解説"
99
  elif mode == "実験":
100
  instruction = "論文中の実験内容を整理してください。以下を抽出:・データセット・評価指標・比較手法・結果・考察"
101
+ elif mode == "表形式":
102
  instruction = """論文からユーザーの指示に合う情報を抽出し、結果を必ずCSV形式のみで出力してください。
103
  例:
104
  項目,内容
 
112
 
113
  prompt = f"{instruction}\n\n【論文情報】\n{knowledge[:120000]}\n\n【質問】\n{question}"
114
 
 
115
  for i in range(3):
116
  try:
117
  response = client.models.generate_content(
 
123
  err_msg = str(e)
124
  if "429" in err_msg or "503" in err_msg:
125
  if i < 2:
126
+ time.sleep(3)
127
  continue
128
  return f"⚠️ API混雑または一時的な制限エラーが発生しました。数分後に再度お試しください。\nエラー詳細: {err_msg}"
129
  return f"エラーが発生しました: {err_msg}"
130
 
131
  # =====================================
132
+ # メモ保存 (ファイル名を動的に生成)
133
  # =====================================
134
 
135
+ def export_history(mode, question, answer, table_data):
136
+ # 保存した瞬間の日時をファイル名に組み込む (例: research_history_手法_20260624_173045.txt)
137
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
138
+ filename = f"research_history_{mode}_{timestamp}.txt"
139
+
140
  temp_dir = tempfile.gettempdir()
141
  file_path = os.path.join(temp_dir, filename)
142
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
143
 
144
  with open(file_path, "w", encoding="utf-8") as f:
145
  f.write("=" * 60 + "\n")
146
+ f.write(f"研究支援アプリ 保存履歴 ({mode}モード)\n")
147
  f.write("=" * 60 + "\n\n")
148
  f.write(f"保存日時: {now}\n\n")
149
  f.write(f"【質問】\n{question}\n\n")
150
 
151
+ if mode == "表形式" and table_data is not None and not table_data.empty:
 
152
  f.write("【回答(表形式データ)】\n")
153
  f.write(table_data.to_string(index=False))
154
  else:
 
158
  return file_path
159
 
160
  # =====================================
161
+ # 解析メイン処理 (モードごとに適切なコンポーネントへ出力)
162
  # =====================================
163
 
164
+ def run_analysis(mode, q_method, q_experiment, q_summary, q_table):
165
+ # 現在のモードに応じた質問を取得
166
+ if mode == "手法": question = q_method
167
+ elif mode == "実験": question = q_experiment
168
+ elif mode == "要約": question = q_summary
169
+ else: question = q_table
170
+
171
  result = ask_paper(question, mode)
172
 
173
+ # 初期値(すべて非表示、または更新なしの状態)
174
+ updates = {
175
+ "ans_method": gr.update(), "ans_experiment": gr.update(),
176
+ "ans_summary": gr.update(), "ans_table": gr.update()
177
+ }
178
+
179
  if "⚠️" in result or "エラーが発生しました" in result:
180
+ if mode == "表形式":
181
+ err_df = pd.DataFrame({"エラー": [result]})
182
+ updates["ans_table"] = gr.update(value=err_df)
183
+ else:
184
+ updates[f"ans_{'summary' if mode=='要約' else mode}"] = gr.update(value=result)
185
+ return list(updates.values())
186
 
187
  if mode == "表形式":
188
  try:
 
189
  df = pd.read_csv(StringIO(result.strip()))
190
+ updates["ans_table"] = gr.update(value=df)
 
191
  except Exception as e:
 
192
  err_df = pd.DataFrame({"エラー": ["CSV表への変換に失敗しました。Geminiの出力を確認してください。"]})
193
+ updates["ans_table"] = gr.update(value=err_df)
194
+ elif mode == "手法":
195
+ updates["ans_method"] = gr.update(value=result)
196
+ elif mode == "実験":
197
+ updates["ans_experiment"] = gr.update(value=result)
198
+ elif mode == "要約":
199
+ updates["ans_summary"] = gr.update(value=result)
200
+
201
+ return list(updates.values())
202
 
203
  # =====================================
204
+ # モード切り替え時の表示制御
205
  # =====================================
206
 
207
+ def toggle_mode_visibility(mode):
208
+ # すべての質問、回答、表コンポーネントの表示・非表示を切り替える辞書
209
+ return (
210
+ gr.update(visible=(mode == "手法")), # q_method
211
+ gr.update(visible=(mode == "実験")), # q_experiment
212
+ gr.update(visible=(mode == "要約")), # q_summary
213
+ gr.update(visible=(mode == "表形式")), # q_table
214
+ gr.update(visible=(mode == "手法")), # ans_method
215
+ gr.update(visible=(mode == "実験")), # ans_experiment
216
+ gr.update(visible=(mode == "要約")), # ans_summary
217
+ gr.update(visible=(mode == "表形式")) # ans_table
218
+ )
219
+
220
+ # =====================================
221
+ # 履歴保存ボタンのトリガー関数
222
+ # =====================================
223
+
224
+ def process_download(mode, q_method, q_experiment, q_summary, q_table, ans_method, ans_experiment, ans_summary, ans_table):
225
+ if mode == "手法": return export_history(mode, q_method, ans_method, None)
226
+ elif mode == "実験": return export_history(mode, q_experiment, ans_experiment, None)
227
+ elif mode == "要約": return export_history(mode, q_summary, ans_summary, None)
228
+ elif mode == "表形式": return export_history(mode, q_table, None, ans_table)
229
+ return None
230
 
231
  # =====================================
232
  # UI
 
239
  with gr.Row():
240
 
241
  with gr.Column():
242
+ upload_files = gr.File(file_count="multiple", file_types=[".pdf"], label="論文追加")
 
 
 
 
 
243
  upload_btn = gr.Button("PDF登録")
244
  upload_result = gr.Textbox(label="状態")
245
 
246
+ upload_btn.click(add_pdfs, inputs=upload_files, outputs=upload_result)
 
 
 
 
247
 
248
  paper_list = gr.Textbox(label="登録論文")
249
  refresh_btn = gr.Button("論文一覧更新")
250
+ refresh_btn.click(show_paper_list, outputs=paper_list)
 
 
 
 
251
 
252
  with gr.Column():
253
  mode = gr.Radio(
 
256
  label="🔬 解析モードを選択"
257
  )
258
 
259
+ # --- モードごとに独立した質問入力欄を用意 ---
260
+ q_method = gr.Textbox(
261
+ label="📝 【手法】論文への質問・指示",
262
  placeholder="例:この論文で提案されているアルゴリズムの独自の強みは何ですか?",
263
+ lines=2, visible=True
264
  )
265
+ q_experiment = gr.Textbox(
266
+ label="📝 【実験】論文への質問・指示",
267
+ placeholder="例:実験で使用されたデータセットの規模は?",
268
+ lines=2, visible=False
269
+ )
270
+ q_summary = gr.Textbox(
271
+ label="📝 【要約】論文への質問・指示",
272
+ placeholder="例:この論文の研究背景、目的、および今後の課題を要約してください。",
273
+ lines=2, visible=False
274
+ )
275
+ q_table = gr.Textbox(
276
+ label="📝 【表形式】論文への質問・指示",
277
+ placeholder="例:主要な実験結果を、データセット、評価指標、精度の項目でテーブルにまとめてください。",
278
+ lines=2, visible=False
279
+ )
280
+
281
+ # --- モードごとに独立した回答出力欄を用意 ---
282
+ ans_method = gr.Textbox(label="💡 【手法】AIの分析・回答", lines=15, interactive=False, visible=True)
283
+ ans_experiment = gr.Textbox(label="💡 【実験】AIの分析・回答", lines=15, interactive=False, visible=False)
284
+ ans_summary = gr.Textbox(label="💡 【要約】AIの分析・回答", lines=15, interactive=False, visible=False)
285
+ ans_table = gr.Dataframe(label="📊 【表形式】解析結果", visible=False)
286
 
287
+ # ラジオボタン変更時に表示をパッと切り替える
288
  mode.change(
289
+ fn=toggle_mode_visibility,
290
  inputs=mode,
291
+ outputs=[q_method, q_experiment, q_summary, q_table, ans_method, ans_experiment, ans_summary, ans_table],
292
  queue=False
293
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
+ search_btn = gr.Button("🚀 論文の解析を実行する", variant="primary")
 
 
 
296
 
297
  search_btn.click(
298
  run_analysis,
299
+ inputs=[mode, q_method, q_experiment, q_summary, q_table],
300
+ outputs=[ans_method, ans_experiment, ans_summary, ans_table]
301
  )
302
 
303
+ download_btn = gr.Button("💾 このモードの対話をファイルに保存する", variant="secondary")
304
+ download_file = gr.File(label="📥 ダウンロード", visible=True)
 
 
 
 
 
 
 
305
 
306
  download_btn.click(
307
+ process_download,
308
+ inputs=[mode, q_method, q_experiment, q_summary, q_table, ans_method, ans_experiment, ans_summary, ans_table],
309
  outputs=download_file
310
  )
311