hallu11 commited on
Commit
a57731e
·
verified ·
1 Parent(s): a5a8380

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -57
app.py CHANGED
@@ -7,7 +7,7 @@ from sentence_transformers import SentenceTransformer
7
  from groq import Groq
8
 
9
  # STEP 1. Groq API 키
10
- os.environ["GROQ_API_KEY"] = "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"
11
  client = Groq(api_key=os.environ["GROQ_API_KEY"])
12
 
13
  # STEP 2. PDF 경로 리스트
@@ -20,53 +20,63 @@ pdf_paths = [
20
  "pdfs/어린이 문화학교 _ 의왕문화원.pdf"
21
  ]
22
 
23
- # STEP 2.1 현재 작업 디렉토리 및 파일 존재 여부 출력 (경로 확인용)
24
- print("현재 작업 디렉토리:", os.getcwd())
25
  for path in pdf_paths:
26
- print(f"{path} 존재 여부:", os.path.exists(path))
27
-
28
- # STEP 3. 텍스트 추출 함수
29
- def extract_texts_from_pdfs(pdf_paths):
30
- chunks = []
31
- for path in pdf_paths:
 
 
 
32
  try:
33
- with fitz.open(path) as doc:
34
- for i, page in enumerate(doc):
35
- text = page.get_text().strip()
36
- if len(text) > 30:
37
- chunks.append({"text": text, "source": os.path.basename(path)})
38
- print(f"✅ 추출 성공: {path}")
39
  except Exception as e:
40
- print(f"❌ 오류: {path} -> {e}")
41
- return chunks
 
42
 
43
  docs = extract_texts_from_pdfs(pdf_paths)
44
 
45
- # STEP 4. 임베딩 및 색인
46
  embed_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
47
- texts = [doc["text"] for doc in docs]
48
- sources = [doc["source"] for doc in docs]
 
 
49
  embeddings = embed_model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
50
 
51
  index = faiss.IndexFlatL2(embeddings.shape[1])
52
  index.add(np.array(embeddings))
 
53
 
54
  # STEP 5. 유사 문서 검색
55
  def search_similar_docs(query, top_k=3):
56
- query_emb = embed_model.encode([query])[0]
57
- scores, indices = index.search(np.array([query_emb]), top_k)
58
- return "\n\n".join([docs[idx]["text"] for idx in indices[0]])
 
 
 
 
59
 
60
  # STEP 6. Groq 응답
61
  def ask_with_groq(question, context):
62
- response = client.chat.completions.create(
63
  model="llama3-8b-8192",
64
  messages=[
65
- {"role": "system", "content": "너는 문화 프로그램 관련 문서 기반 한국어 Q&A 챗봇이야."},
66
- {"role": "user", "content": f"{question}\n\n[관련 문서 발췌]\n{context[:3000]}"}
67
  ]
68
- )
69
- return response.choices[0].message.content
70
 
71
  # STEP 7. 챗봇 함수
72
  chat_history = []
@@ -78,12 +88,12 @@ def chatbot_fn(message, keyword):
78
  return "", chat_history
79
 
80
  context = search_similar_docs(message)
81
- if not context:
82
  chat_history.append((f"🙋‍♂️ {message}", "❌ 관련 문서를 찾지 못했습니다."))
83
  return "", chat_history
84
 
85
- response = ask_with_groq(message, context)
86
- chat_history.append((f"🙋‍♂️ {message}", f"🤖 {response}"))
87
  return "", chat_history
88
 
89
  def clear_chat():
@@ -92,40 +102,29 @@ def clear_chat():
92
  return chat_history
93
 
94
  # STEP 8. 추천 질문
95
- suggested_questions = [
96
- "의왕단오축제는 언제 열리나요?",
97
- "성인 문화학교 교육 대상은 누구인가요?",
98
- "횡성문화원 문화학교는 어떤 수업이 있나요?",
99
- "꿈꾸는 마을 프로그램은 어떤 지원을 하나요?",
100
- "어린이 문화학교는 몇 세부터 참여 가능한가요?"
101
- ]
102
 
103
  # STEP 9. Gradio UI
104
- with gr.Blocks(title="📘 오아시스 문화 챗봇 🤖") as demo:
105
- gr.Markdown("## 📘 오아시스 문서 기반 문화 프로그램 챗봇 🤖 '뮤지스(Musesis)'")
106
- gr.Markdown("질문을 입력하면 유사 문서를 검색해 답변해줍니다. (PDF 업로드 없이 사용 가능)")
107
 
108
- chatbot = gr.Chatbot(label="🤖 챗봇 응답", height=400)
109
 
110
  with gr.Row():
111
- keyword_input = gr.Textbox(label="🔍 키워드 (선택)", placeholder="예: 단오축제, 문화학교")
112
- user_input = gr.Textbox(label="✉️ 질문", placeholder="질문을 입력하세요", lines=1)
113
 
114
- with gr.Row():
115
- send_btn = gr.Button("질문하기")
116
- clear_btn = gr.Button("대화 초기화")
117
 
118
- send_btn.click(chatbot_fn, inputs=[user_input, keyword_input], outputs=[user_input, chatbot])
119
- user_input.submit(chatbot_fn, inputs=[user_input, keyword_input], outputs=[user_input, chatbot])
120
- clear_btn.click(clear_chat, outputs=chatbot)
121
 
122
  with gr.Accordion("💡 추천 질문", open=False):
123
  for q in suggested_questions:
124
- q_btn = gr.Button(q)
125
-
126
- def ask_suggested(q=q):
127
- return chatbot_fn(q, "")
128
-
129
- q_btn.click(ask_suggested, outputs=[user_input, chatbot])
130
 
131
- demo.launch()
 
 
7
  from groq import Groq
8
 
9
  # STEP 1. Groq API 키
10
+ os.environ["GROQ_API_KEY"] = "YOUR_GROQ_KEY"
11
  client = Groq(api_key=os.environ["GROQ_API_KEY"])
12
 
13
  # STEP 2. PDF 경로 리스트
 
20
  "pdfs/어린이 문화학교 _ 의왕문화원.pdf"
21
  ]
22
 
23
+ # STEP 2.1. 디렉토리 및 파일 확인
24
+ print("🛠️ 현재 작업 디렉토리:", os.getcwd())
25
  for path in pdf_paths:
26
+ print(f"{path} -> exists? {os.path.exists(path)}")
27
+
28
+ # STEP 3. PDF 텍스트 추출
29
+ def extract_texts_from_pdfs(paths):
30
+ docs = []
31
+ for path in paths:
32
+ if not os.path.exists(path):
33
+ print(f"❌ 파일 누락: {path}")
34
+ continue
35
  try:
36
+ doc = fitz.open(path)
37
+ for pg in doc:
38
+ text = pg.get_text().strip()
39
+ if len(text) > 30:
40
+ docs.append({"text": text, "source": os.path.basename(path)})
41
+ print(f"✅ 추출 완료: {path} ({len(docs)} chunks so far)")
42
  except Exception as e:
43
+ print(f"❗ 오류({path}): {e}")
44
+ print(f"📚 총 추출 문서 조각 수: {len(docs)}")
45
+ return docs
46
 
47
  docs = extract_texts_from_pdfs(pdf_paths)
48
 
49
+ # STEP 4. 임베딩 및 FAISS 색인
50
  embed_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
51
+ texts = [d["text"] for d in docs]
52
+ if not texts:
53
+ raise RuntimeError("❌ 문서 조각이 없어서 임베딩을 진행할 수 없습니다.")
54
+ print("💡 임베딩 시작, 총 문장수:", len(texts))
55
  embeddings = embed_model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
56
 
57
  index = faiss.IndexFlatL2(embeddings.shape[1])
58
  index.add(np.array(embeddings))
59
+ print("📌 FAISS 색인 생성 완료 (entries:", index.ntotal, ")")
60
 
61
  # STEP 5. 유사 문서 검색
62
  def search_similar_docs(query, top_k=3):
63
+ print(f"🔍 검색 요청: '{query}'")
64
+ q_emb = embed_model.encode([query])[0]
65
+ scores, idxs = index.search(np.array([q_emb]), top_k)
66
+ results = [(texts[i], float(scores[0][j])) for j, i in enumerate(idxs[0])]
67
+ for txt, sc in results:
68
+ print(f" score: {sc:.4f}, text snippet: {txt[:50]}")
69
+ return "\n\n".join([txt for txt, _ in results])
70
 
71
  # STEP 6. Groq 응답
72
  def ask_with_groq(question, context):
73
+ return client.chat.completions.create(
74
  model="llama3-8b-8192",
75
  messages=[
76
+ {"role": "system", "content": "너는 문화 프로그램 기반 한국어 Q&A 챗봇이야."},
77
+ {"role": "user", "content": f"{question}\n\n[관련 문서]\n{context[:3000]}"}
78
  ]
79
+ ).choices[0].message.content
 
80
 
81
  # STEP 7. 챗봇 함수
82
  chat_history = []
 
88
  return "", chat_history
89
 
90
  context = search_similar_docs(message)
91
+ if not context.strip():
92
  chat_history.append((f"🙋‍♂️ {message}", "❌ 관련 문서를 찾지 못했습니다."))
93
  return "", chat_history
94
 
95
+ answer = ask_with_groq(message, context)
96
+ chat_history.append((f"🙋‍♂️ {message}", f"🤖 {answer}"))
97
  return "", chat_history
98
 
99
  def clear_chat():
 
102
  return chat_history
103
 
104
  # STEP 8. 추천 질문
105
+ suggested_questions = ["의왕단오축제는 언제 열리나요?", "성인 문화학교 교육 대상은 누구인가요?"]
 
 
 
 
 
 
106
 
107
  # STEP 9. Gradio UI
108
+ with gr.Blocks(title="📘 뮤지스 챗봇") as demo:
109
+ gr.Markdown("## 📘 오아시스 문화 챗봇 🤖 '뮤지스'")
110
+ gr.Markdown("(pdf 없이 실행, 유사 문서 검색 기반 응답)")
111
 
112
+ chatbot_widget = gr.Chatbot(label="Chat", height=400)
113
 
114
  with gr.Row():
115
+ user_input = gr.Textbox(placeholder="질문 입력...", lines=1)
 
116
 
117
+ send = gr.Button("질문하기")
118
+ clear = gr.Button("초기화")
 
119
 
120
+ send.click(chatbot_fn, inputs=[user_input, gr.State()], outputs=[user_input, chatbot_widget])
121
+ user_input.submit(chatbot_fn, inputs=[user_input, gr.State()], outputs=[user_input, chatbot_widget])
122
+ clear.click(clear_chat, outputs=chatbot_widget)
123
 
124
  with gr.Accordion("💡 추천 질문", open=False):
125
  for q in suggested_questions:
126
+ btn = gr.Button(q)
127
+ btn.click(lambda q=q: chatbot_fn(q, ""), outputs=[user_input, chatbot_widget])
 
 
 
 
128
 
129
+ if __name__ == "__main__":
130
+ demo.launch()