aiTOYAMA commited on
Commit
03f5a91
·
verified ·
1 Parent(s): c093ec1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +192 -133
app.py CHANGED
@@ -31,7 +31,7 @@ PDF_FOLDER = "papers"
31
  os.makedirs(PDF_FOLDER, exist_ok=True)
32
 
33
  # =====================================
34
- # PDF・論文データ処理
35
  # =====================================
36
 
37
  def extract_pdf_text(filepath):
@@ -44,6 +44,10 @@ def extract_pdf_text(filepath):
44
  print(e)
45
  return text
46
 
 
 
 
 
47
  def load_papers():
48
  texts = []
49
  files = []
@@ -55,43 +59,58 @@ def load_papers():
55
  texts.append(f"\n\n### {file}\n{paper_text}")
56
  return files, "\n".join(texts)
57
 
 
 
 
 
58
  def show_paper_list():
59
  files, _ = load_papers()
60
  if len(files) == 0:
61
- return "📚 登録論文なし (上の「論文を追加する」からPDFをドロップしてください)"
62
- return "【読込済み】\n" + "\n".join([f"・ {f}" for f in files])
 
 
 
 
63
 
64
  def add_pdfs(files):
65
  if files is None:
66
- return "PDFが選択されていません"
67
  count = 0
68
  for file in files:
69
  dst = os.path.join(PDF_FOLDER, os.path.basename(file.name))
70
- with open(file.name, "rb") as src, open(dst, "wb") as out:
71
- out.write(src.read())
 
72
  count += 1
73
- return f"✅ {count}件の論文を新しく登録しました!"
74
 
75
  # =====================================
76
- # 解析・プロンプトコア
77
  # =====================================
78
 
79
  def ask_paper(question, mode):
80
  files, knowledge = load_papers()
81
  if len(files) == 0:
82
- return "⚠️ 論文が登録されていません。まずは上の管理パネルからPDFを登録してください。"
83
 
84
  if mode == "手法":
85
- instruction = "論文中の手法について、概要、特徴、利点、数式、初心者向け解説を整理してください。"
86
  elif mode == "実験":
87
- instruction = "論文中の実験内容について、データセット、評価指標、比較手法、結果、考察を抽出してください。"
88
  elif mode == "表形式":
89
  instruction = """論文からユーザーの指示に合う情報を抽出し、結果を必ずCSV形式のみで出力してください。
90
- 列名は「項目,内容」とし、余計な挨拶、説明、コードブロックのバッククォート(```)などは一切出力しないでください。純粋なCSVの文字列のみを返してください。"""
 
 
 
 
 
 
91
  else:
92
- instruction = "論文内容の全体像を要約してください(研究背景、目的、提案手法、結果、今後の課題)。"
93
 
94
- prompt = f"{instruction}\n\n【論文情報】\n{knowledge[:120000]}\n\n【ユーザーからの指示・質問】\n{question}"
95
 
96
  for i in range(3):
97
  try:
@@ -106,149 +125,189 @@ def ask_paper(question, mode):
106
  if i < 2:
107
  time.sleep(3)
108
  continue
109
- return f"⚠️ APIが混雑しています。少し待ってから再実行してください。"
110
- return f"エラー: {err_msg}"
111
 
112
  # =====================================
113
- # バックエンド制御 (動的表示の切り替え)
114
  # =====================================
115
 
116
- def run_analysis(question, mode):
117
- result = ask_paper(question, mode)
118
-
119
- if "⚠️" in result or "エラー" in result:
120
- if mode == "表形式":
121
- return gr.update(visible=False), gr.update(visible=True, value=pd.DataFrame({"エラー": [result]}))
122
- return gr.update(visible=True, value=result), gr.update(visible=False)
123
-
124
- if mode == "表形式":
125
- try:
126
- df = pd.read_csv(StringIO(result.strip()))
127
- return gr.update(visible=False), gr.update(visible=True, value=df)
128
- except:
129
- err_df = pd.DataFrame({"エラー": ["CSV表への自動変換に失敗しました。指示内容を具体的にするか、もう一度お試しください。"]})
130
- return gr.update(visible=False), gr.update(visible=True, value=err_df)
131
- else:
132
- return gr.update(visible=True, value=result), gr.update(visible=False)
133
-
134
- # モード選択時にラベルやプレースホルダーを「1つのボックス」に対して動的に切り替える
135
- def handle_mode_change(mode):
136
- placeholders = {
137
- "手法": "例:提案されているアルゴリズムの強みや数式ベースの背景は?",
138
- "実験": "例:使用されたデータセットや、Baselineと比べた精度向上幅は?",
139
- "要約": "例:この論文全体の主要な貢献(Contribution)を3点に要約して。",
140
- "表形式": "例:主要な実験結果を、データセット、評価指標、精度の項目でテーブルにして。"
141
- }
142
-
143
- # 質問欄の枠タイトル(label)とヒント(placeholder)を同時にアップデート
144
- return (
145
- gr.update(label=f"📝 【{mode}モード】 論文への質問・指示", placeholder=placeholders[mode]),
146
- gr.update(label=f"💡 【{mode}モード】 AIの分析結果")
147
- )
148
-
149
- def handle_download(mode, question, txt_answer, df_answer):
150
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
151
- filename = f"paper_analysis_{mode}_{timestamp}.txt"
152
 
153
  temp_dir = tempfile.gettempdir()
154
  file_path = os.path.join(temp_dir, filename)
155
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
156
 
157
  with open(file_path, "w", encoding="utf-8") as f:
158
- f.write("=" * 50 + "\n")
159
- f.write(f" 論文インサイト・ログ ({mode}分析)\n")
160
- f.write("=" * 50 + "\n\n")
161
- f.write(f"実行日時: {now}\n")
162
- f.write(f"入力質問: {question}\n\n")
163
- f.write("-" * 50 + "\n")
164
 
165
- if mode == "表形式" and df_answer is not None:
166
- f.write("【抽出データ】\n")
167
- f.write(df_answer.to_string(index=False))
168
  else:
169
- f.write(f"【AI回答】\n{txt_answer}")
170
  f.write("\n")
171
 
172
  return file_path
173
 
174
  # =====================================
175
- # UI 構築 (コンパクト設計)
176
  # =====================================
177
 
178
- with gr.Blocks(theme=gr.themes.Soft()) as app:
 
 
 
 
 
179
 
180
- gr.Markdown("## 🎓 PaperInsight Mini")
181
- gr.Markdown("論文から欲しい情報だけを即座に抜き出すコンパクトツール")
182
 
183
- # 1. 論文管理エリア(初期状態はアコーディオンを閉じて画面をすっきりさせる)
184
- with gr.Accordion("📚 文献ライブラリ管理(PDF登録・確認ならここをクリック)", open=False):
185
- with gr.Row():
186
- upload_files = gr.File(file_count="multiple", file_types=[".pdf"], label="論文を追加する")
187
- with gr.Column():
188
- upload_btn = gr.Button("📤 ライブラリに登録", variant="secondary")
189
- upload_result = gr.Textbox(label="処理ステータス", placeholder="結果がここに表示されます", interactive=False)
190
-
191
- paper_list = gr.Textbox(value=show_paper_list(), label="現在読み込み済みの文献", lines=4, interactive=False)
192
-
193
- upload_btn.click(add_pdfs, inputs=upload_files, outputs=upload_result).then(
194
- show_paper_list, outputs=paper_list
195
- )
196
-
197
- # 2. メイン解析エリア
198
- with gr.Group():
199
- mode = gr.Radio(
200
- choices=["手法", "実験", "要約", "表形式"],
201
- value="手法",
202
- label="🔬 解析アプロ��チ"
203
- )
204
-
205
- question = gr.Textbox(
206
- label="📝 【手法モード】 論文への質問・指示",
207
- placeholder="例:提案されているアルゴリズムの強みや数式ベースの背景は?",
208
- lines=2
209
- )
210
-
211
- search_btn = gr.Button("🚀 論文を解析する", variant="primary")
212
-
213
- # 3. リザルトエリア(テキスト用と表形式用を、結果に応じて自動で隠しあう)
214
- with gr.Group():
215
- answer_text = gr.Textbox(
216
- label="💡 【手法モード】 AIの分析結果",
217
- lines=12,
218
- interactive=False,
219
- visible=True
220
- )
221
-
222
- answer_table = gr.Dataframe(
223
- label="📊 抽出データ(表形式)",
224
- visible=False
225
- )
226
-
227
- # 4. ユーティリティ(保存)
228
- with gr.Row():
229
- download_btn = gr.Button("💾 今回の分析内容をファイルに保存する")
230
- download_file = gr.File(label="📥 ダウンロードリンク", visible=True)
231
-
232
- # --- インタラクション・トリガー ---
233
- # モード切り替え時にテキストボックスのラベルとヒントを瞬時に書き換える
234
- mode.change(
235
- fn=handle_mode_change,
236
- inputs=mode,
237
- outputs=[question, answer_text],
238
- queue=False
239
- )
240
 
241
- search_btn.click(
242
- fn=run_analysis,
243
- inputs=[question, mode],
244
- outputs=[answer_text, answer_table]
245
- )
 
 
246
 
247
- download_btn.click(
248
- fn=handle_download,
249
- inputs=[mode, question, answer_text, answer_table],
250
- outputs=download_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  )
252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  if __name__ == "__main__":
254
- app.launch()
 
31
  os.makedirs(PDF_FOLDER, exist_ok=True)
32
 
33
  # =====================================
34
+ # PDF読み込み
35
  # =====================================
36
 
37
  def extract_pdf_text(filepath):
 
44
  print(e)
45
  return text
46
 
47
+ # =====================================
48
+ # 論文DB
49
+ # =====================================
50
+
51
  def load_papers():
52
  texts = []
53
  files = []
 
59
  texts.append(f"\n\n### {file}\n{paper_text}")
60
  return files, "\n".join(texts)
61
 
62
+ # =====================================
63
+ # 論文一覧
64
+ # =====================================
65
+
66
  def show_paper_list():
67
  files, _ = load_papers()
68
  if len(files) == 0:
69
+ return "登録論文なし"
70
+ return "\n".join(files)
71
+
72
+ # =====================================
73
+ # PDF追加
74
+ # =====================================
75
 
76
  def add_pdfs(files):
77
  if files is None:
78
+ return "PDF未選択"
79
  count = 0
80
  for file in files:
81
  dst = os.path.join(PDF_FOLDER, os.path.basename(file.name))
82
+ with open(file.name, "rb") as src:
83
+ with open(dst, "wb") as out:
84
+ out.write(src.read())
85
  count += 1
86
+ return f"{count}件登録完了"
87
 
88
  # =====================================
89
+ # Gemini質問
90
  # =====================================
91
 
92
  def ask_paper(question, mode):
93
  files, knowledge = load_papers()
94
  if len(files) == 0:
95
+ return "論文が登録されていません"
96
 
97
  if mode == "手法":
98
+ instruction = "論文中の手法について説明してください。以下を含めること:・概要・特徴・利点・数式・初心者向け解説"
99
  elif mode == "実験":
100
+ instruction = "論文中の実験内容を整理してください。以下を抽出:・データセット・評価指標・比較手法・結果・考察"
101
  elif mode == "表形式":
102
  instruction = """論文からユーザーの指示に合う情報を抽出し、結果を必ずCSV形式のみで出力してください。
103
+ 例:
104
+ 項目,内容
105
+ データセット,MNIST
106
+ 評価指標,Accuracy
107
+ 精度,98.3%
108
+
109
+ 余計な挨拶や説明文は一切禁止です。純粋なCSVデータのみを返してください。"""
110
  else:
111
+ instruction = "論文内容を要約してください。・研究背景・目的・提案手法・結果・今後の課題"
112
 
113
+ prompt = f"{instruction}\n\n【論文情報】\n{knowledge[:120000]}\n\n【質問】\n{question}"
114
 
115
  for i in range(3):
116
  try:
 
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:
155
+ f.write(f"【回答】\n{answer}")
156
  f.write("\n")
157
 
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
233
+ # =====================================
234
+
235
+ with gr.Blocks() as app:
236
+
237
+ gr.Markdown("# 研究論文サポートシステム")
238
+
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(
254
+ choices=["手法", "実験", "要約", "表形式"],
255
+ value="手法",
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
+
312
  if __name__ == "__main__":
313
+ app.launch()