Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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"] = "
|
| 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}
|
| 27 |
-
|
| 28 |
-
# STEP 3. 텍스트 추출
|
| 29 |
-
def extract_texts_from_pdfs(
|
| 30 |
-
|
| 31 |
-
for path in
|
|
|
|
|
|
|
|
|
|
| 32 |
try:
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
print(f"✅ 추출
|
| 39 |
except Exception as e:
|
| 40 |
-
print(f"
|
| 41 |
-
|
|
|
|
| 42 |
|
| 43 |
docs = extract_texts_from_pdfs(pdf_paths)
|
| 44 |
|
| 45 |
-
# STEP 4. 임베딩 및 색인
|
| 46 |
embed_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
|
| 47 |
-
texts = [
|
| 48 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
# STEP 6. Groq 응답
|
| 61 |
def ask_with_groq(question, context):
|
| 62 |
-
|
| 63 |
model="llama3-8b-8192",
|
| 64 |
messages=[
|
| 65 |
-
{"role": "system", "content": "너는 문화 프로그램
|
| 66 |
-
{"role": "user", "content": f"{question}\n\n[관련 문서
|
| 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 |
-
|
| 86 |
-
chat_history.append((f"🙋♂️ {message}", f"🤖 {
|
| 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="📘
|
| 105 |
-
gr.Markdown("## 📘 오아시스 문
|
| 106 |
-
gr.Markdown("
|
| 107 |
|
| 108 |
-
|
| 109 |
|
| 110 |
with gr.Row():
|
| 111 |
-
|
| 112 |
-
user_input = gr.Textbox(label="✉️ 질문", placeholder="질문을 입력하세요", lines=1)
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
clear_btn = gr.Button("대화 초기화")
|
| 117 |
|
| 118 |
-
|
| 119 |
-
user_input.submit(chatbot_fn, inputs=[user_input,
|
| 120 |
-
|
| 121 |
|
| 122 |
with gr.Accordion("💡 추천 질문", open=False):
|
| 123 |
for q in suggested_questions:
|
| 124 |
-
|
| 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 |
-
|
|
|
|
|
|
| 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()
|