aiTOYAMA commited on
Commit
c0763b4
·
verified ·
1 Parent(s): dbcea0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -164
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import os
2
  import shutil
3
  from datetime import datetime
4
- from google import genai
5
  import gradio as gr
6
  from langchain_chroma import Chroma
7
  from langchain_community.document_loaders import PyPDFLoader
@@ -11,25 +10,25 @@ from langchain_google_genai import ChatGoogleGenerativeAI
11
  from huggingface_hub import snapshot_download
12
 
13
  # ==================================================
14
- # 設定
15
  # ==================================================
16
 
17
  PAPER_DIR = "papers"
18
- DB_DIR = "chroma_db"
19
  NOTE_FILE = "research_notes.txt"
20
 
21
  os.makedirs(PAPER_DIR, exist_ok=True)
22
 
23
 
24
  # ==================================================
25
- # Gemini
26
  # ==================================================
27
 
28
  API_KEY = os.getenv("GEMINI_API_KEY")
29
 
30
  if API_KEY is None:
31
  raise ValueError(
32
- "GEMINI_API_KEY が設定されていません"
33
  )
34
 
35
  embedding_model = HuggingFaceEmbeddings(
@@ -42,11 +41,10 @@ llm = ChatGoogleGenerativeAI(
42
  )
43
 
44
  # ==================================================
45
- # PDF → DB
46
  # ==================================================
47
 
48
  def rebuild_database():
49
-
50
  pdf_files = [
51
  os.path.join(PAPER_DIR, f)
52
  for f in os.listdir(PAPER_DIR)
@@ -59,31 +57,31 @@ def rebuild_database():
59
  all_docs = []
60
 
61
  for pdf in pdf_files:
62
-
63
  try:
64
-
65
  loader = PyPDFLoader(pdf)
66
-
67
  docs = loader.load()
68
-
69
  all_docs.extend(docs)
70
-
71
  except Exception as e:
 
72
 
73
- print(e)
 
74
 
75
  splitter = RecursiveCharacterTextSplitter(
76
  chunk_size=1000,
77
  chunk_overlap=200
78
  )
79
 
80
- chunks = splitter.split_documents(
81
- all_docs
82
- )
83
 
 
84
  if os.path.exists(DB_DIR):
85
- shutil.rmtree(DB_DIR)
 
 
 
86
 
 
87
  Chroma.from_documents(
88
  documents=chunks,
89
  embedding=embedding_model,
@@ -98,11 +96,8 @@ def rebuild_database():
98
  # ==================================================
99
 
100
  def get_db():
101
-
102
  if not os.path.exists(DB_DIR):
103
-
104
  return None
105
-
106
  return Chroma(
107
  persist_directory=DB_DIR,
108
  embedding_function=embedding_model
@@ -110,33 +105,23 @@ def get_db():
110
 
111
 
112
  # ==================================================
113
- # PDF追加
114
  # ==================================================
115
 
116
  def upload_pdfs(files):
117
-
118
  if files is None:
119
-
120
  return "PDF未選択"
121
 
122
  count = 0
123
-
124
  for file in files:
125
-
126
  dst = os.path.join(
127
  PAPER_DIR,
128
  os.path.basename(file.name)
129
  )
130
-
131
- shutil.copy(
132
- file.name,
133
- dst
134
- )
135
-
136
  count += 1
137
 
138
  msg = rebuild_database()
139
-
140
  return f"{count}件アップロード\n{msg}"
141
 
142
 
@@ -145,21 +130,12 @@ def upload_pdfs(files):
145
  # ==================================================
146
 
147
  def search_method(question):
148
-
149
  db = get_db()
150
-
151
  if db is None:
152
-
153
  return "PDFを登録してください"
154
 
155
- docs = db.similarity_search(
156
- question,
157
- k=5
158
- )
159
-
160
- context = "\n\n".join(
161
- [d.page_content for d in docs]
162
- )
163
 
164
  prompt = f"""
165
  あなたは研究指導教員です。
@@ -176,42 +152,42 @@ def search_method(question):
176
 
177
  【回答】
178
  """
179
-
180
- response = llm.invoke(prompt)
181
-
182
- return response.content
 
183
 
184
 
185
  # ==================================================
186
- # 実験検索
187
  # ==================================================
188
 
189
- snapshot_download(
190
- repo_id="aiTOYAMA/papers",
191
- repo_type="dataset",
192
- local_dir=PAPER_DIR
193
- )
194
- print(os.listdir(PAPER_DIR))
 
 
 
195
 
196
  if not os.path.exists(DB_DIR):
197
  print(rebuild_database())
198
 
199
- def search_experiment(question):
200
 
201
- db = get_db()
 
 
202
 
 
 
203
  if db is None:
204
-
205
  return "PDFを登録してください"
206
 
207
- docs = db.similarity_search(
208
- question,
209
- k=5
210
- )
211
-
212
- context = "\n\n".join(
213
- [d.page_content for d in docs]
214
- )
215
 
216
  prompt = f"""
217
  以下の論文内容を参考に、
@@ -222,7 +198,7 @@ def search_experiment(question):
222
  ・データセット
223
  ・学習率
224
  ・Epoch数
225
- ・評価指標
226
  ・比較手法
227
  ・実験結果
228
 
@@ -234,72 +210,50 @@ def search_experiment(question):
234
 
235
  【回答】
236
  """
237
-
238
- response = llm.invoke(prompt)
239
-
240
- return response.content
 
241
 
242
 
243
  # ==================================================
244
- # 保存
245
  # ==================================================
246
 
247
  def save_note(question, answer):
 
 
248
 
249
- now = datetime.now().strftime(
250
- "%Y-%m-%d %H:%M:%S"
251
- )
252
-
253
- with open(
254
- NOTE_FILE,
255
- "a",
256
- encoding="utf-8"
257
- ) as f:
258
-
259
- f.write("\n")
260
- f.write("=" * 60)
261
- f.write("\n")
262
-
263
- f.write(f"日時: {now}\n\n")
264
-
265
- f.write(
266
- f"質問:\n{question}\n\n"
267
- )
268
-
269
- f.write(
270
- f"回答:\n{answer}\n"
271
- )
272
 
273
- f.write("\n")
274
-
275
- return "保存完了"
 
 
 
 
 
 
276
 
277
 
278
  # ==================================================
279
- # UI
280
  # ==================================================
281
 
282
  with gr.Blocks() as demo:
 
283
 
284
- gr.Markdown(
285
- "# 研究支援RAGアプリ"
286
- )
287
-
288
  with gr.Tab("論文追加"):
289
-
290
  pdf_input = gr.File(
291
  file_count="multiple",
292
  file_types=[".pdf"],
293
  label="論文PDF"
294
  )
295
-
296
- upload_btn = gr.Button(
297
- "登録"
298
- )
299
-
300
- upload_status = gr.Textbox(
301
- label="状態"
302
- )
303
 
304
  upload_btn.click(
305
  fn=upload_pdfs,
@@ -307,80 +261,42 @@ with gr.Blocks() as demo:
307
  outputs=upload_status
308
  )
309
 
 
310
  with gr.Tab("手法・専門用語検索"):
311
-
312
- method_question = gr.Textbox(
313
- label="質問"
314
- )
315
-
316
- method_answer = gr.Textbox(
317
- label="回答",
318
- lines=15
319
- )
320
-
321
- method_btn = gr.Button(
322
- "検索"
323
- )
324
-
325
- method_save = gr.Button(
326
- "保存"
327
- )
328
-
329
- method_status = gr.Textbox(
330
- label="保存状態"
331
- )
332
 
333
  method_btn.click(
334
  fn=search_method,
335
  inputs=method_question,
336
  outputs=method_answer
337
  )
338
-
339
  method_save.click(
340
  fn=save_note,
341
- inputs=[
342
- method_question,
343
- method_answer
344
- ],
345
  outputs=method_status
346
  )
347
 
 
348
  with gr.Tab("実験内容検索"):
349
-
350
- exp_question = gr.Textbox(
351
- label="質問"
352
- )
353
-
354
- exp_answer = gr.Textbox(
355
- label="回答",
356
- lines=15
357
- )
358
-
359
- exp_btn = gr.Button(
360
- "検索"
361
- )
362
-
363
- exp_save = gr.DownloadButton(
364
- "保存"
365
- )
366
-
367
- exp_status = gr.Textbox(
368
- label="保存状態"
369
- )
370
 
371
  exp_btn.click(
372
  fn=search_experiment,
373
  inputs=exp_question,
374
  outputs=exp_answer
375
  )
376
-
377
  exp_save.click(
378
  fn=save_note,
379
- inputs=[
380
- exp_question,
381
- exp_answer
382
- ],
383
  outputs=exp_status
384
  )
385
 
386
- demo.launch()
 
1
  import os
2
  import shutil
3
  from datetime import datetime
 
4
  import gradio as gr
5
  from langchain_chroma import Chroma
6
  from langchain_community.document_loaders import PyPDFLoader
 
10
  from huggingface_hub import snapshot_download
11
 
12
  # ==================================================
13
+ # 設定(DBの保存先を/tmpに変更してエラーを回避)
14
  # ==================================================
15
 
16
  PAPER_DIR = "papers"
17
+ DB_DIR = "/tmp/chroma_db" # HF Spaces等での書き込みエラー対策
18
  NOTE_FILE = "research_notes.txt"
19
 
20
  os.makedirs(PAPER_DIR, exist_ok=True)
21
 
22
 
23
  # ==================================================
24
+ # Gemini / 埋め込みモデルの設定
25
  # ==================================================
26
 
27
  API_KEY = os.getenv("GEMINI_API_KEY")
28
 
29
  if API_KEY is None:
30
  raise ValueError(
31
+ "GEMINI_API_KEY が設定されていません。環境変数を確認してください。"
32
  )
33
 
34
  embedding_model = HuggingFaceEmbeddings(
 
41
  )
42
 
43
  # ==================================================
44
+ # PDF → DB 登録処理
45
  # ==================================================
46
 
47
  def rebuild_database():
 
48
  pdf_files = [
49
  os.path.join(PAPER_DIR, f)
50
  for f in os.listdir(PAPER_DIR)
 
57
  all_docs = []
58
 
59
  for pdf in pdf_files:
 
60
  try:
 
61
  loader = PyPDFLoader(pdf)
 
62
  docs = loader.load()
 
63
  all_docs.extend(docs)
 
64
  except Exception as e:
65
+ print(f"PDF読み込みエラー ({pdf}): {e}")
66
 
67
+ if not all_docs:
68
+ return "読み込み可能なPDFテキストがありませんでした。"
69
 
70
  splitter = RecursiveCharacterTextSplitter(
71
  chunk_size=1000,
72
  chunk_overlap=200
73
  )
74
 
75
+ chunks = splitter.split_documents(all_docs)
 
 
76
 
77
+ # 既存のDBディレクトリがあれば一度削除(初期化)
78
  if os.path.exists(DB_DIR):
79
+ try:
80
+ shutil.rmtree(DB_DIR)
81
+ except Exception as e:
82
+ print(f"DB削除エラー: {e}")
83
 
84
+ # 新しくベクトルDBを構築
85
  Chroma.from_documents(
86
  documents=chunks,
87
  embedding=embedding_model,
 
96
  # ==================================================
97
 
98
  def get_db():
 
99
  if not os.path.exists(DB_DIR):
 
100
  return None
 
101
  return Chroma(
102
  persist_directory=DB_DIR,
103
  embedding_function=embedding_model
 
105
 
106
 
107
  # ==================================================
108
+ # PDF追加(画面からのアップロード用)
109
  # ==================================================
110
 
111
  def upload_pdfs(files):
 
112
  if files is None:
 
113
  return "PDF未選択"
114
 
115
  count = 0
 
116
  for file in files:
 
117
  dst = os.path.join(
118
  PAPER_DIR,
119
  os.path.basename(file.name)
120
  )
121
+ shutil.copy(file.name, dst)
 
 
 
 
 
122
  count += 1
123
 
124
  msg = rebuild_database()
 
125
  return f"{count}件アップロード\n{msg}"
126
 
127
 
 
130
  # ==================================================
131
 
132
  def search_method(question):
 
133
  db = get_db()
 
134
  if db is None:
 
135
  return "PDFを登録してください"
136
 
137
+ docs = db.similarity_search(question, k=5)
138
+ context = "\n\n".join([d.page_content for d in docs])
 
 
 
 
 
 
139
 
140
  prompt = f"""
141
  あなたは研究指導教員です。
 
152
 
153
  【回答】
154
  """
155
+ try:
156
+ response = llm.invoke(prompt)
157
+ return response.content
158
+ except Exception as e:
159
+ return f"Geminiの呼び出し中にエラーが発生しました: {e}"
160
 
161
 
162
  # ==================================================
163
+ # データダウンロード & 初期DB構築
164
  # ==================================================
165
 
166
+ try:
167
+ snapshot_download(
168
+ repo_id="aiTOYAMA/papers",
169
+ repo_type="dataset",
170
+ local_dir=PAPER_DIR
171
+ )
172
+ print("データセットのダウンロードに成功しました:", os.listdir(PAPER_DIR))
173
+ except Exception as e:
174
+ print(f"データセットのダウンロードに失敗しました (手動アップロードを試みてくださ���): {e}")
175
 
176
  if not os.path.exists(DB_DIR):
177
  print(rebuild_database())
178
 
 
179
 
180
+ # ==================================================
181
+ # 実験検索
182
+ # ==================================================
183
 
184
+ def search_experiment(question):
185
+ db = get_db()
186
  if db is None:
 
187
  return "PDFを登録してください"
188
 
189
+ docs = db.similarity_search(question, k=5)
190
+ context = "\n\n".join([d.page_content for d in docs])
 
 
 
 
 
 
191
 
192
  prompt = f"""
193
  以下の論文内容を参考に、
 
198
  ・データセット
199
  ・学習率
200
  ・Epoch数
201
+ * 評価指標
202
  ・比較手法
203
  ・実験結果
204
 
 
210
 
211
  【回答】
212
  """
213
+ try:
214
+ response = llm.invoke(prompt)
215
+ return response.content
216
+ except Exception as e:
217
+ return f"Geminiの呼び出し中にエラーが発生しました: {e}"
218
 
219
 
220
  # ==================================================
221
+ # 保存処理
222
  # ==================================================
223
 
224
  def save_note(question, answer):
225
+ if not question or not answer:
226
+ return "質問または回答が空のため保存できません"
227
 
228
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
+ try:
231
+ with open(NOTE_FILE, "a", encoding="utf-8") as f:
232
+ f.write("\n" + "=" * 60 + "\n")
233
+ f.write(f"日時: {now}\n\n")
234
+ f.write(f"質問:\n{question}\n\n")
235
+ f.write(f"回答:\n{answer}\n\n")
236
+ return "保存完了"
237
+ except Exception as e:
238
+ return f"ファイル保存エラー: {e}"
239
 
240
 
241
  # ==================================================
242
+ # UI (Gradio)
243
  # ==================================================
244
 
245
  with gr.Blocks() as demo:
246
+ gr.Markdown("# 研究支援RAGアプリ")
247
 
248
+ # タブ1: 論文追加
 
 
 
249
  with gr.Tab("論文追加"):
 
250
  pdf_input = gr.File(
251
  file_count="multiple",
252
  file_types=[".pdf"],
253
  label="論文PDF"
254
  )
255
+ upload_btn = gr.Button("登録")
256
+ upload_status = gr.Textbox(label="状態")
 
 
 
 
 
 
257
 
258
  upload_btn.click(
259
  fn=upload_pdfs,
 
261
  outputs=upload_status
262
  )
263
 
264
+ # タブ2: 手法・専門用語検索
265
  with gr.Tab("手法・専門用語検索"):
266
+ method_question = gr.Textbox(label="質問")
267
+ method_answer = gr.Textbox(label="回答", lines=15)
268
+ method_btn = gr.Button("検索")
269
+ method_save = gr.Button("ノートへ保存")
270
+ method_status = gr.Textbox(label="保存状態")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
  method_btn.click(
273
  fn=search_method,
274
  inputs=method_question,
275
  outputs=method_answer
276
  )
 
277
  method_save.click(
278
  fn=save_note,
279
+ inputs=[method_question, method_answer],
 
 
 
280
  outputs=method_status
281
  )
282
 
283
+ # タブ3: 実験内容検索
284
  with gr.Tab("実験内容検索"):
285
+ exp_question = gr.Textbox(label="質問")
286
+ exp_answer = gr.Textbox(label="回答", lines=15)
287
+ exp_btn = gr.Button("検索")
288
+ exp_save = gr.Button("ノートへ保存") # gr.DownloadButton から変更
289
+ exp_status = gr.Textbox(label="保存状態")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
 
291
  exp_btn.click(
292
  fn=search_experiment,
293
  inputs=exp_question,
294
  outputs=exp_answer
295
  )
 
296
  exp_save.click(
297
  fn=save_note,
298
+ inputs=[exp_question, exp_answer],
 
 
 
299
  outputs=exp_status
300
  )
301
 
302
+ demo.launch()