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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -43
app.py CHANGED
@@ -1,63 +1,151 @@
1
- import gradio as gr
2
- import fitz # PyMuPDF
3
- from openai import OpenAI
4
  import os
 
 
 
5
 
6
- # Groq API 키 환경변수 설정 (본인 키로 변경)
7
  os.environ["GROQ_API_KEY"] = "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"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- # Groq 클라이언트 초
10
- client = OpenAI(
11
- base_url="https://api.groq.com/openai/v1",
12
- api_key=os.environ["GROQ_API_KEY"]
13
- )
14
-
15
- def extract_text_from_pdf(file):
16
- """업로드된 PDF 파일에서 텍스트 추출"""
17
- doc = fitz.open(file.name)
18
- text = ""
19
- for page in doc:
20
- text += page.get_text()
21
- return text
22
-
23
- def ask_question(question, context):
24
- """Groq API 호출로 질문에 답변 생성"""
25
  response = client.chat.completions.create(
26
  model="llama3-8b-8192",
27
  messages=[
28
- {"role": "system", "content": "너는 업로드한 문서를 설명하는 한국어 도우미야. 항상 한국어로 답변해."},
29
- {"role": "user", "content": f"{question}\n\n[문서 내용 일부]\n{context[:3000]}"}
30
  ]
31
  )
32
  return response.choices[0].message.content
33
 
34
- # 상태 유지용 전역 변수 (추출된 문서 텍스트)
35
- global_document_text = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- def upload_and_extract(pdf_file):
38
- global global_document_text
39
- text = extract_text_from_pdf(pdf_file)
40
- global_document_text = text
41
- return "PDF 텍스트가 성공적으로 추출되었습니다. 질문을 입력하세요."
42
 
43
- def answer_question(question):
44
- global global_document_text
45
- if not global_document_text:
46
- return "먼저 PDF를 업로드해서 텍스트를 추출해주세요."
47
- return ask_question(question, global_document_text)
48
 
49
- with gr.Blocks() as demo:
50
- gr.Markdown("# 📄 PDF 기반 한국어 답변 챗봇 (Groq API)")
 
51
 
52
- pdf_input = gr.File(label="PDF 파일 업로드", file_types=[".pdf"])
53
- upload_btn = gr.Button("PDF 텍스트 추출")
54
- upload_status = gr.Textbox(label="상태", interactive=False)
55
 
56
- question_input = gr.Textbox(label="질문 입력", placeholder="질문을 입력하세요")
57
- answer_output = gr.Textbox(label="챗봇 답변", interactive=False)
 
58
 
59
- upload_btn.click(upload_and_extract, inputs=pdf_input, outputs=upload_status)
60
- question_input.submit(answer_question, inputs=question_input, outputs=answer_output)
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  if __name__ == "__main__":
63
  demo.launch()
 
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:
26
+ try:
27
+ with fitz.open(path) as doc:
28
+ text = "".join(page.get_text() for page in doc)
29
+ docs.append({"filename": path, "text": text})
30
+ print(f"✅ 텍스트 추출 성공: {path}")
31
+ except Exception as e:
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:
42
+ if keyword.lower() in doc["text"].lower():
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 "❌ 관련 키워드를 포함하는 문서를 찾을 수 없습니다."
 
 
 
 
50
  response = client.chat.completions.create(
51
  model="llama3-8b-8192",
52
  messages=[
53
+ {"role": "system", "content": "너는 업로드한 문서를 바탕으로 설명하는 한국어 도우미야."},
54
+ {"role": "user", "content": f"{question}\n\n[문서 내용]\n{context[:3000]}"}
55
  ]
56
  )
57
  return response.choices[0].message.content
58
 
59
+ # 자동 키워드 추출
60
+ def auto_keyword_extraction(message):
61
+ keywords = ["단오축제", "문화학교", "횡성축제", "꿈꾸는 마을", "발달장애인", "의왕문화원", "횡성문화원"]
62
+ for k in keywords:
63
+ if k in message:
64
+ return k
65
+ return ""
66
+
67
+ # Gradio 챗봇 상태 저장용
68
+ chat_history = []
69
+
70
+ def chatbot_fn(message, keyword):
71
+ global chat_history
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))
86
+ return "", chat_history
87
+
88
+ def clear_history():
89
+ global chat_history
90
+ chat_history = []
91
+ return chat_history
92
+
93
+ # 추천 질문 리스트
94
+ suggested_questions = [
95
+ '의왕단오축제는 언제 열리나요?',
96
+ '의왕단오축제 주요 프로그램은 무엇인가요?',
97
+ '의왕문화원의 성인 문화학교 교육 대상은 누구인가요?',
98
+ '성인 문화학교에서 제공하는 수업 종류는 무엇인가요?',
99
+ '횡성문화원의 문화학교는 어떤 교육을 진행하나요?',
100
+ '발달장애인 교육사업 "꿈꾸는 마을"의 주요 목표는 무엇인가요?',
101
+ '꿈꾸는 마을 프로그램 참가 자격은 어떻게 되나요?',
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("업로드된 문서를 바탕으로 질문에 답변합니다. 키워드를 입력하지 않아도 자동으로 인식됩니다.")
 
121
 
122
+ chatbot = gr.Chatbot(label="🤖 챗봇 응답", height=400)
 
 
 
 
123
 
124
+ with gr.Row():
125
+ keyword_input = gr.Textbox(label="🔍 키워드 (선택)", placeholder="예: 단오축제,화학교")
126
+ user_input = gr.Textbox(label="✉️ 질문", placeholder="질문을 입력하세요", lines=1)
127
 
128
+ with gr.Row():
129
+ send_btn = gr.Button("질문하기")
130
+ clear_btn = gr.Button("대화 초기화")
131
 
132
+ send_btn.click(chatbot_fn, inputs=[user_input, keyword_input], outputs=[user_input, chatbot])
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()