hallu11 commited on
Commit
e57fda0
·
verified ·
1 Parent(s): ac5ac07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -46
app.py CHANGED
@@ -1,25 +1,24 @@
1
- # app.py
2
-
3
  import os
4
  from groq import Groq
5
  import fitz # PyMuPDF
6
  import gradio as gr
7
 
8
- # 환경변수Groq API 키 설정 (로컬 실행 시 미리 설정하거나 직접 변경 필요)
9
- os.environ["GROQ_API_KEY"] = "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"
10
- client = Groq(api_key=os.environ["GROQ_API_KEY"])
 
 
11
 
12
- # PDF 파일 경로 리스트
13
  pdf_paths = [
14
- "./pdf/의왕단오축제 _ 의왕문화원.pdf",
15
- "./pdf/성인 문화학교 _ 의왕문화원.pdf",
16
- "./pdf/횡성문화원_문화학교.pdf",
17
- "./pdf/발달장애인 교육사업 _ 꿈꾸는 마을.pdf",
18
- "./pdf/횡성의지역축제 - 횡성축제소개.pdf",
19
- "./pdf/어린이 문화학교 _ 의왕문화원.pdf"
20
  ]
21
 
22
- # PDF 텍스트 추출 함수
23
  def extract_texts_from_pdfs(pdf_paths):
24
  docs = []
25
  for path in pdf_paths:
@@ -32,10 +31,8 @@ def extract_texts_from_pdfs(pdf_paths):
32
  print(f"❌ 오류: {path} -> {e}")
33
  return docs
34
 
35
- # 문서 데이터 로드
36
  all_documents = extract_texts_from_pdfs(pdf_paths)
37
 
38
- # 키워드 기반 문서 검색
39
  def get_documents_by_keyword(documents, keyword):
40
  matches = []
41
  for doc in documents:
@@ -43,7 +40,6 @@ def get_documents_by_keyword(documents, keyword):
43
  matches.append(doc["text"])
44
  return "\n\n".join(matches)
45
 
46
- # Groq API로 질문 답변
47
  def ask_question_with_context(question, context):
48
  if not context:
49
  return "❌ 관련 키워드를 포함하는 문서를 찾을 수 없습니다."
@@ -56,7 +52,6 @@ def ask_question_with_context(question, context):
56
  )
57
  return response.choices[0].message.content
58
 
59
- # 자동 키워드 추출
60
  def auto_keyword_extraction(message):
61
  keywords = ["단오축제", "문화학교", "횡성축제", "꿈꾸는 마을", "발달장애인", "의왕문화원", "횡성문화원"]
62
  for k in keywords:
@@ -64,7 +59,6 @@ def auto_keyword_extraction(message):
64
  return k
65
  return ""
66
 
67
- # Gradio 챗봇 상태 저장용
68
  chat_history = []
69
 
70
  def chatbot_fn(message, keyword):
@@ -72,14 +66,12 @@ def chatbot_fn(message, keyword):
72
  message = message.strip()
73
  keyword = keyword.strip()
74
 
75
- # 키워드 자동 추출
76
  if not keyword:
77
  keyword = auto_keyword_extraction(message)
78
  if not keyword:
79
  chat_history.append(("🙋‍♂️ " + message, "❌ 키워드를 입력하지 않았고 자동 추출도 실패했습니다. 키워드를 입력해주세요."))
80
  return "", chat_history
81
 
82
- # 문서 검색 및 응답
83
  context = get_documents_by_keyword(all_documents, keyword)
84
  response = ask_question_with_context(message, context)
85
  chat_history.append(("🙋‍♂️ " + message, "🤖 " + response))
@@ -90,7 +82,6 @@ def clear_history():
90
  chat_history = []
91
  return chat_history
92
 
93
- # 추천 질문 리스트
94
  suggested_questions = [
95
  '의왕단오축제는 언제 열리나요?',
96
  '의왕단오축제 주요 프로그램은 무엇인가요?',
@@ -102,19 +93,8 @@ suggested_questions = [
102
  '횡성지역축제의 대표 축제는 무엇인가요?',
103
  '횡성축제의 개최 시기와 일정은 어떻게 되나요?',
104
  '의왕문화원의 어린이 문화학교는 몇 세부터 참여 가능한가요?',
105
- '어린이 문화학교에서 진행하는 주요 프로그램은 무엇인가요?',
106
- '의왕문화원 문화 프로그램은 어디에서 진행되나요?',
107
- '각 프로그램의 참가 신청 방법과 일정은 어떻게 되나요?',
108
- '발달장애인 교육사업에서 제공하는 지원 서비스는 무엇인가요?',
109
- '의왕단오축제 참가비는 얼마인가요?',
110
- '횡성문화원 문화학교는 몇 개의 과정을 운영하나요?',
111
- '어린이 문화학교 행사 일정은 어떻게 되나요?',
112
- '문화 프로그램이 지역사회에 미치는 긍정적 영향은 무엇인가요?',
113
- '프로그램 안전관리 및 코로나 방역 대책은 어떻게 되어 있나요?',
114
- '문화 프로그램 참여 후 제공되는 피드백 절차가 있나요?'
115
  ]
116
 
117
- # Gradio UI 구성
118
  with gr.Blocks(title="🤖 뮤지스 챗봇(Musesis)") as demo:
119
  gr.Markdown("## 📘 오아시스 문서 기반 문화 프로그램 챗봇 🤖 '뮤지스(Musesis)'")
120
  gr.Markdown("업로드된 문서를 바탕으로 질문에 답변합니다. 키워드를 입력하지 않아도 자동으로 인식됩니다.")
@@ -133,19 +113,10 @@ with gr.Blocks(title="🤖 뮤지스 챗봇(Musesis)") as demo:
133
  user_input.submit(chatbot_fn, inputs=[user_input, keyword_input], outputs=[user_input, chatbot])
134
  clear_btn.click(clear_history, outputs=chatbot)
135
 
136
- with gr.Accordion("💡 추천 질문 목록 (클릭 시 바로 질문)", open=False):
137
  for q in suggested_questions:
138
  btn = gr.Button(q)
139
- btn.click(
140
- fn=lambda x=q: chatbot_fn(x, ""),
141
- inputs=[],
142
- outputs=[user_input, chatbot]
143
- )
144
- btn.click(
145
- fn=lambda x=q: x,
146
- inputs=None,
147
- outputs=user_input
148
- )
149
-
150
- if __name__ == "__main__":
151
- demo.launch()
 
 
 
1
  import os
2
  from groq import Groq
3
  import fitz # PyMuPDF
4
  import gradio as gr
5
 
6
+ # Hugging Face 제공하는 Secrets로 API 키 가져오기
7
+ api_key = os.environ.get("GROQ_API_KEY")
8
+ if not api_key:
9
+ raise ValueError("❌ GROQ_API_KEY가 환경변수로 설정되어 있지 않습니다.")
10
+ client = Groq(api_key=api_key)
11
 
12
+ # PDF 파일 리스트 (Spaces의 Files 탭에서 파일 직접 업로드 필요)
13
  pdf_paths = [
14
+ "의왕단오축제 _ 의왕문화원.pdf",
15
+ "성인 문화학교 _ 의왕문화원.pdf",
16
+ "횡성문화원_문화학교.pdf",
17
+ "발달장애인 교육사업 _ 꿈꾸는 마을.pdf",
18
+ "횡성의지역축제 - 횡성축제소개.pdf",
19
+ "어린이 문화학교 _ 의왕문화원.pdf"
20
  ]
21
 
 
22
  def extract_texts_from_pdfs(pdf_paths):
23
  docs = []
24
  for path in pdf_paths:
 
31
  print(f"❌ 오류: {path} -> {e}")
32
  return docs
33
 
 
34
  all_documents = extract_texts_from_pdfs(pdf_paths)
35
 
 
36
  def get_documents_by_keyword(documents, keyword):
37
  matches = []
38
  for doc in documents:
 
40
  matches.append(doc["text"])
41
  return "\n\n".join(matches)
42
 
 
43
  def ask_question_with_context(question, context):
44
  if not context:
45
  return "❌ 관련 키워드를 포함하는 문서를 찾을 수 없습니다."
 
52
  )
53
  return response.choices[0].message.content
54
 
 
55
  def auto_keyword_extraction(message):
56
  keywords = ["단오축제", "문화학교", "횡성축제", "꿈꾸는 마을", "발달장애인", "의왕문화원", "횡성문화원"]
57
  for k in keywords:
 
59
  return k
60
  return ""
61
 
 
62
  chat_history = []
63
 
64
  def chatbot_fn(message, keyword):
 
66
  message = message.strip()
67
  keyword = keyword.strip()
68
 
 
69
  if not keyword:
70
  keyword = auto_keyword_extraction(message)
71
  if not keyword:
72
  chat_history.append(("🙋‍♂️ " + message, "❌ 키워드를 입력하지 않았고 자동 추출도 실패했습니다. 키워드를 입력해주세요."))
73
  return "", chat_history
74
 
 
75
  context = get_documents_by_keyword(all_documents, keyword)
76
  response = ask_question_with_context(message, context)
77
  chat_history.append(("🙋‍♂️ " + message, "🤖 " + response))
 
82
  chat_history = []
83
  return chat_history
84
 
 
85
  suggested_questions = [
86
  '의왕단오축제는 언제 열리나요?',
87
  '의왕단오축제 주요 프로그램은 무엇인가요?',
 
93
  '횡성지역축제의 대표 축제는 무엇인가요?',
94
  '횡성축제의 개최 시기와 일정은 어떻게 되나요?',
95
  '의왕문화원의 어린이 문화학교는 몇 세부터 참여 가능한가요?',
 
 
 
 
 
 
 
 
 
 
96
  ]
97
 
 
98
  with gr.Blocks(title="🤖 뮤지스 챗봇(Musesis)") as demo:
99
  gr.Markdown("## 📘 오아시스 문서 기반 문화 프로그램 챗봇 🤖 '뮤지스(Musesis)'")
100
  gr.Markdown("업로드된 문서를 바탕으로 질문에 답변합니다. 키워드를 입력하지 않아도 자동으로 인식됩니다.")
 
113
  user_input.submit(chatbot_fn, inputs=[user_input, keyword_input], outputs=[user_input, chatbot])
114
  clear_btn.click(clear_history, outputs=chatbot)
115
 
116
+ with gr.Accordion("💡 추천 질문 목록", open=False):
117
  for q in suggested_questions:
118
  btn = gr.Button(q)
119
+ btn.click(fn=lambda x=q: chatbot_fn(x, ""), inputs=[], outputs=[user_input, chatbot])
120
+ btn.click(fn=lambda x=q: x, inputs=None, outputs=user_input)
121
+
122
+ demo.launch()