kimrang commited on
Commit
e8bd7a8
·
verified ·
1 Parent(s): 71d7cd2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -47
app.py CHANGED
@@ -12,6 +12,7 @@ GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
12
  # 전역 변수들
13
  vectorstores = {}
14
  embeddings = None
 
15
 
16
  def debug_file_system():
17
  """파일 시스템 상태를 자세히 확인하는 함수"""
@@ -97,8 +98,8 @@ def find_vectorstore_folders():
97
  return vectorstore_folders
98
 
99
  def load_all_vectorstores():
100
- """모든 벡터스토어를 로드하는 함수"""
101
- global vectorstores, embeddings
102
 
103
  if not embeddings:
104
  embeddings = HuggingFaceEmbeddings(
@@ -108,20 +109,33 @@ def load_all_vectorstores():
108
  # 벡터스토어 폴더들 찾기
109
  folders = find_vectorstore_folders()
110
 
 
 
111
  for folder_name in folders:
112
- if folder_name not in vectorstores:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  try:
114
- vectorstore = FAISS.load_local(
115
- f"./{folder_name}",
116
- embeddings,
117
- allow_dangerous_deserialization=True
118
- )
119
- vectorstores[folder_name] = vectorstore
120
- print(f"✅ {folder_name} 로드 완료")
121
  except Exception as e:
122
- print(f"❌ {folder_name} 로드 실패: {e}")
 
123
 
124
- return list(vectorstores.keys())
125
 
126
  # 질문 리스트 (기존과 동일)
127
  suggested_questions = [
@@ -167,7 +181,7 @@ prompt = PromptTemplate(
167
  input_variables=["context", "question"]
168
  )
169
 
170
- def respond_with_groq(question, selected_q, model, selected_vectorstore):
171
  """질문에 대한 답변을 생성하는 함수"""
172
 
173
  # 선택된 질문이 있으면 그것을 사용
@@ -180,18 +194,12 @@ def respond_with_groq(question, selected_q, model, selected_vectorstore):
180
  if not GROQ_API_KEY:
181
  return "❌ API 키가 설정되지 않았습니다. 관리자에게 문의하세요."
182
 
183
- # 벡터스토어가 로드되지 않은 경우
184
- if not vectorstores:
185
  return "❌ 사용 가능한 벡터스토어가 없습니다. 관리자에게 문의하세요."
186
 
187
  try:
188
- # 선택된 벡터스토어 확인
189
- if selected_vectorstore not in vectorstores:
190
- available_stores = list(vectorstores.keys())
191
- return f"❌ 선택된 벡터스토어({selected_vectorstore})를 찾을 수 없습니다. 사용 가능한 스토어: {available_stores}"
192
-
193
- current_vectorstore = vectorstores[selected_vectorstore]
194
- print(f"✅ 사용 중인 벡터스토어: {selected_vectorstore}")
195
 
196
  # LLM 설정
197
  llm = ChatGroq(
@@ -205,7 +213,7 @@ def respond_with_groq(question, selected_q, model, selected_vectorstore):
205
  qa_chain = RetrievalQA.from_chain_type(
206
  llm=llm,
207
  chain_type="stuff",
208
- retriever=current_vectorstore.as_retriever(search_kwargs={"k": 3}),
209
  chain_type_kwargs={"prompt": prompt},
210
  return_source_documents=True
211
  )
@@ -227,7 +235,7 @@ def update_question(selected):
227
  return ""
228
 
229
  # 앱 시작시 벡터스토어들 로드
230
- available_vectorstores = load_all_vectorstores()
231
 
232
  # Gradio 인터페이스 생성
233
  with gr.Blocks(title="한남대학교 Q&A") as interface:
@@ -240,28 +248,6 @@ with gr.Blocks(title="한남대학교 Q&A") as interface:
240
 
241
  with gr.Row():
242
  with gr.Column(scale=1):
243
- # 벡터스토어 선택 드롭다운 추가
244
- if available_vectorstores:
245
- # 사용자 친화적인 이름으로 매핑
246
- vectorstore_display_names = {
247
- 'vectorstore1': '📚 데이터베이스 1',
248
- 'vectorstore2': '📚 데이터베이스 2',
249
- 'vectorstore3': '📚 데이터베이스 3'
250
- }
251
- display_choices = [vectorstore_display_names.get(vs, vs) for vs in available_vectorstores]
252
-
253
- vectorstore_dropdown = gr.Dropdown(
254
- choices=list(zip(display_choices, available_vectorstores)),
255
- label="📚 데이터베이스 선택",
256
- value=available_vectorstores[0] if available_vectorstores else None
257
- )
258
- else:
259
- vectorstore_dropdown = gr.Dropdown(
260
- choices=[("벡터스토어 없음", "none")],
261
- label="📚 데이터베이스 선택",
262
- value="none"
263
- )
264
-
265
  question_dropdown = gr.Dropdown(
266
  choices=["직접 입력"] + suggested_questions,
267
  label="💡 자주 묻는 질문",
@@ -293,7 +279,7 @@ with gr.Blocks(title="한남대학교 Q&A") as interface:
293
  # 이벤트 연결
294
  submit_btn.click(
295
  fn=respond_with_groq,
296
- inputs=[question_input, question_dropdown, model_choice, vectorstore_dropdown],
297
  outputs=output
298
  )
299
 
 
12
  # 전역 변수들
13
  vectorstores = {}
14
  embeddings = None
15
+ combined_vectorstore = None
16
 
17
  def debug_file_system():
18
  """파일 시스템 상태를 자세히 확인하는 함수"""
 
98
  return vectorstore_folders
99
 
100
  def load_all_vectorstores():
101
+ """모든 벡터스토어를 로드하고 통합하는 함수"""
102
+ global vectorstores, embeddings, combined_vectorstore
103
 
104
  if not embeddings:
105
  embeddings = HuggingFaceEmbeddings(
 
109
  # 벡터스토어 폴더들 찾기
110
  folders = find_vectorstore_folders()
111
 
112
+ loaded_vectorstores = []
113
+
114
  for folder_name in folders:
115
+ try:
116
+ vectorstore = FAISS.load_local(
117
+ f"./{folder_name}",
118
+ embeddings,
119
+ allow_dangerous_deserialization=True
120
+ )
121
+ vectorstores[folder_name] = vectorstore
122
+ loaded_vectorstores.append(vectorstore)
123
+ print(f"✅ {folder_name} 로드 완료")
124
+ except Exception as e:
125
+ print(f"❌ {folder_name} 로드 실패: {e}")
126
+
127
+ # 벡터스토어들을 통합 (첫 번째를 기본으로 하고 나머지를 merge)
128
+ if loaded_vectorstores:
129
+ combined_vectorstore = loaded_vectorstores[0]
130
+ for vs in loaded_vectorstores[1:]:
131
  try:
132
+ combined_vectorstore.merge_from(vs)
133
+ print(f"✅ 벡터스토어 통합 완료")
 
 
 
 
 
134
  except Exception as e:
135
+ print(f"❌ 벡터스토어 통합 실패: {e}")
136
+ print(f"🎉 총 {len(loaded_vectorstores)}개의 벡터스토어가 통합되었습니다")
137
 
138
+ return len(loaded_vectorstores) > 0
139
 
140
  # 질문 리스트 (기존과 동일)
141
  suggested_questions = [
 
181
  input_variables=["context", "question"]
182
  )
183
 
184
+ def respond_with_groq(question, selected_q, model):
185
  """질문에 대한 답변을 생성하는 함수"""
186
 
187
  # 선택된 질문이 있으면 그것을 사용
 
194
  if not GROQ_API_KEY:
195
  return "❌ API 키가 설정되지 않았습니다. 관리자에게 문의하세요."
196
 
197
+ # 통합된 벡터스토어가 로드되지 않은 경우
198
+ if not combined_vectorstore:
199
  return "❌ 사용 가능한 벡터스토어가 없습니다. 관리자에게 문의하세요."
200
 
201
  try:
202
+ print(f"✅ 통합된 벡터스토어를 사용하여 검색 중...")
 
 
 
 
 
 
203
 
204
  # LLM 설정
205
  llm = ChatGroq(
 
213
  qa_chain = RetrievalQA.from_chain_type(
214
  llm=llm,
215
  chain_type="stuff",
216
+ retriever=combined_vectorstore.as_retriever(search_kwargs={"k": 5}),
217
  chain_type_kwargs={"prompt": prompt},
218
  return_source_documents=True
219
  )
 
235
  return ""
236
 
237
  # 앱 시작시 벡터스토어들 로드
238
+ vectorstores_loaded = load_all_vectorstores()
239
 
240
  # Gradio 인터페이스 생성
241
  with gr.Blocks(title="한남대학교 Q&A") as interface:
 
248
 
249
  with gr.Row():
250
  with gr.Column(scale=1):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  question_dropdown = gr.Dropdown(
252
  choices=["직접 입력"] + suggested_questions,
253
  label="💡 자주 묻는 질문",
 
279
  # 이벤트 연결
280
  submit_btn.click(
281
  fn=respond_with_groq,
282
+ inputs=[question_input, question_dropdown, model_choice],
283
  outputs=output
284
  )
285