Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,91 +6,105 @@ import numpy as np
|
|
| 6 |
from sentence_transformers import SentenceTransformer
|
| 7 |
from groq import Groq
|
| 8 |
|
| 9 |
-
# Groq API 키 설정
|
| 10 |
os.environ["GROQ_API_KEY"] = "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"
|
| 11 |
client = Groq(api_key=os.environ["GROQ_API_KEY"])
|
| 12 |
|
| 13 |
-
# PDF 파일
|
| 14 |
pdf_paths = [
|
| 15 |
-
"의왕단오축제 _ 의왕문화원.pdf",
|
| 16 |
-
"성인 문화학교 _ 의왕문화원.pdf",
|
| 17 |
-
"횡성문화원_문화학교.pdf",
|
| 18 |
-
"발달장애인 교육사업 _ 꿈꾸는 마을.pdf",
|
| 19 |
-
"횡성의지역축제 - 횡성축제소개.pdf",
|
| 20 |
-
"어린이 문화학교 _ 의왕문화원.pdf"
|
| 21 |
]
|
| 22 |
|
|
|
|
| 23 |
def extract_texts_from_pdfs(pdf_paths):
|
| 24 |
-
|
| 25 |
for path in pdf_paths:
|
| 26 |
try:
|
| 27 |
with fitz.open(path) as doc:
|
| 28 |
for page in doc:
|
| 29 |
text = page.get_text().strip()
|
| 30 |
if len(text) > 30:
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
| 33 |
except Exception as e:
|
| 34 |
-
print(f"❌ 오류: {path} -> {e}")
|
| 35 |
-
return
|
| 36 |
|
| 37 |
docs = extract_texts_from_pdfs(pdf_paths)
|
| 38 |
-
texts = [d["text"] for d in docs]
|
| 39 |
-
sources = [d["source"] for d in docs]
|
| 40 |
|
| 41 |
-
# 임베딩
|
| 42 |
embed_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
|
|
|
|
|
|
|
| 43 |
embeddings = embed_model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
|
|
|
|
| 44 |
index = faiss.IndexFlatL2(embeddings.shape[1])
|
| 45 |
-
index.add(embeddings)
|
| 46 |
|
|
|
|
| 47 |
def search_similar_docs(query, top_k=3):
|
| 48 |
-
|
| 49 |
-
scores,
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
| 51 |
|
|
|
|
| 52 |
def ask_with_groq(question, context):
|
| 53 |
-
|
| 54 |
model="llama3-8b-8192",
|
| 55 |
messages=[
|
| 56 |
-
{"role": "system", "content": "너는 문화
|
| 57 |
-
{"role": "user", "content": f"{question}\n\n[
|
| 58 |
]
|
| 59 |
)
|
| 60 |
-
return
|
| 61 |
-
|
| 62 |
-
chat_history = []
|
| 63 |
-
|
| 64 |
-
def chatbot_fn(message, keyword):
|
| 65 |
-
global chat_history
|
| 66 |
-
message = message.strip()
|
| 67 |
-
if not message:
|
| 68 |
-
return "", chat_history
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
resp = ask_with_groq(message, context)
|
| 76 |
-
chat_history.append(("🙋♂️ " + message, "🤖 " + resp))
|
| 77 |
-
return "", chat_history
|
| 78 |
-
|
| 79 |
-
def clear_chat():
|
| 80 |
-
global chat_history
|
| 81 |
-
chat_history = []
|
| 82 |
-
return chat_history
|
| 83 |
|
|
|
|
| 84 |
suggested_questions = [
|
| 85 |
"의왕단오축제는 언제 열리나요?",
|
| 86 |
-
"성인 문화학교
|
| 87 |
-
"
|
| 88 |
-
"
|
| 89 |
-
"
|
| 90 |
]
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
| 95 |
with gr.Row():
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from sentence_transformers import SentenceTransformer
|
| 7 |
from groq import Groq
|
| 8 |
|
| 9 |
+
# ✅ 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 |
+
# ✅ 2. PDF 파일 경로 리스트 (pdfs 폴더 기준)
|
| 14 |
pdf_paths = [
|
| 15 |
+
"pdfs/의왕단오축제 _ 의왕문화원.pdf",
|
| 16 |
+
"pdfs/성인 문화학교 _ 의왕문화원.pdf",
|
| 17 |
+
"pdfs/횡성문화원_문화학교.pdf",
|
| 18 |
+
"pdfs/발달장애인 교육사업 _ 꿈꾸는 마을.pdf",
|
| 19 |
+
"pdfs/횡성의지역축제 - 횡성축제소개.pdf",
|
| 20 |
+
"pdfs/어린이 문화학교 _ 의왕문화원.pdf"
|
| 21 |
]
|
| 22 |
|
| 23 |
+
# ✅ 3. PDF 텍스트 추출
|
| 24 |
def extract_texts_from_pdfs(pdf_paths):
|
| 25 |
+
chunks = []
|
| 26 |
for path in pdf_paths:
|
| 27 |
try:
|
| 28 |
with fitz.open(path) as doc:
|
| 29 |
for page in doc:
|
| 30 |
text = page.get_text().strip()
|
| 31 |
if len(text) > 30:
|
| 32 |
+
chunks.append({
|
| 33 |
+
"text": text,
|
| 34 |
+
"source": os.path.basename(path)
|
| 35 |
+
})
|
| 36 |
+
print(f"✅ 텍스트 추출 완료: {path}")
|
| 37 |
except Exception as e:
|
| 38 |
+
print(f"❌ 오류 발생: {path} -> {e}")
|
| 39 |
+
return chunks
|
| 40 |
|
| 41 |
docs = extract_texts_from_pdfs(pdf_paths)
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
# ✅ 4. 문서 임베딩 및 FAISS 색인 구축
|
| 44 |
embed_model = SentenceTransformer("jhgan/ko-sroberta-multitask")
|
| 45 |
+
texts = [doc["text"] for doc in docs]
|
| 46 |
+
sources = [doc["source"] for doc in docs]
|
| 47 |
embeddings = embed_model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
|
| 48 |
+
|
| 49 |
index = faiss.IndexFlatL2(embeddings.shape[1])
|
| 50 |
+
index.add(np.array(embeddings))
|
| 51 |
|
| 52 |
+
# ✅ 5. 유사 문서 검색 함수
|
| 53 |
def search_similar_docs(query, top_k=3):
|
| 54 |
+
query_emb = embed_model.encode([query])[0]
|
| 55 |
+
scores, indices = index.search(np.array([query_emb]), top_k)
|
| 56 |
+
results = []
|
| 57 |
+
for idx in indices[0]:
|
| 58 |
+
results.append(docs[idx]["text"])
|
| 59 |
+
return "\n\n".join(results)
|
| 60 |
|
| 61 |
+
# ✅ 6. Groq 기반 응답 생성
|
| 62 |
def ask_with_groq(question, context):
|
| 63 |
+
response = client.chat.completions.create(
|
| 64 |
model="llama3-8b-8192",
|
| 65 |
messages=[
|
| 66 |
+
{"role": "system", "content": "너는 문화 관련 문서를 기반으로 질문에 한국어로 답하는 도우미야."},
|
| 67 |
+
{"role": "user", "content": f"{question}\n\n[문서 내용]\n{context[:3000]}"}
|
| 68 |
]
|
| 69 |
)
|
| 70 |
+
return response.choices[0].message.content
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
# ✅ 7. Gradio 인터페이스 함수
|
| 73 |
+
def chatbot_interface(question):
|
| 74 |
+
context = search_similar_docs(question)
|
| 75 |
+
answer = ask_with_groq(question, context)
|
| 76 |
+
return answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
# ✅ 8. 예시 질문 리스트
|
| 79 |
suggested_questions = [
|
| 80 |
"의왕단오축제는 언제 열리나요?",
|
| 81 |
+
"성인 문화학교에서 제공하는 수업 종류는 무엇인가요?",
|
| 82 |
+
"꿈꾸는 마을 프로그램 참가 자격은 어떻게 되나요?",
|
| 83 |
+
"���린이 문화학교에서 진행하는 주요 프로그램은 무엇인가요?",
|
| 84 |
+
"횡성축제의 개최 시기와 일정은 어떻게 되나요?",
|
| 85 |
]
|
| 86 |
|
| 87 |
+
# ✅ 9. Gradio UI 구성
|
| 88 |
+
with gr.Blocks() as demo:
|
| 89 |
+
gr.Markdown("# 📚 문화 프로그램 문서 챗봇")
|
| 90 |
+
gr.Markdown("업로드된 문화 관련 문서를 기반으로 질문에 답합니다.")
|
| 91 |
+
|
| 92 |
with gr.Row():
|
| 93 |
+
question_box = gr.Textbox(placeholder="질문을 입력하세요", label="질문")
|
| 94 |
+
with gr.Row():
|
| 95 |
+
submit_btn = gr.Button("질문하기")
|
| 96 |
+
with gr.Row():
|
| 97 |
+
answer_box = gr.Textbox(label="답변", lines=10)
|
| 98 |
+
|
| 99 |
+
with gr.Row():
|
| 100 |
+
gr.Markdown("### 💡 추천 질문")
|
| 101 |
+
with gr.Column():
|
| 102 |
+
for q in suggested_questions:
|
| 103 |
+
btn = gr.Button(q)
|
| 104 |
+
btn.click(fn=chatbot_interface, inputs=gr.Textbox(value=q, visible=False), outputs=answer_box)
|
| 105 |
+
|
| 106 |
+
submit_btn.click(fn=chatbot_interface, inputs=question_box, outputs=answer_box)
|
| 107 |
+
|
| 108 |
+
# ✅ 10. 앱 실행
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
demo.launch()
|