JirasakJo commited on
Commit
be01a92
·
verified ·
1 Parent(s): 3e05e6a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -293
app.py CHANGED
@@ -1,97 +1,30 @@
1
  import streamlit as st
2
  import json
3
  import os
4
- import time
5
  from datetime import datetime, timedelta
6
- import subprocess
7
  from huggingface_hub import HfApi
8
  from pathlib import Path
9
  from calendar_rag import (
10
  create_default_config,
11
  AcademicCalendarRAG,
12
- PipelineConfig
13
  )
14
 
15
  # Custom CSS for enhanced styling
16
  def load_custom_css():
17
  st.markdown("""
18
  <style>
19
- /* General body styling */
20
- body {
21
- font-family: "Arial", sans-serif !important;
22
- color: #000000 !important;
23
- background-color: white !important;
24
- line-height: 1.7 !important;
25
- }
26
-
27
- /* Main container styling */
28
- .main {
29
- padding: 2rem;
30
- color: #000000;
31
- background-color: white;
32
- }
33
-
34
- /* Headers styling */
35
- h1 {
36
- color: #000000;
37
- font-size: 2.8rem !important;
38
- font-weight: 700 !important;
39
- margin-bottom: 1.5rem !important;
40
- text-align: center;
41
- padding: 1rem 0;
42
- border-bottom: 3px solid #1E3A8A;
43
- }
44
-
45
- h3, h4 {
46
- color: #000000;
47
- font-weight: 600 !important;
48
- font-size: 1.6rem !important;
49
- margin-top: 1.5rem !important;
50
- }
51
-
52
- /* Chat message styling */
53
- .chat-message {
54
- padding: 1.5rem;
55
- border-radius: 10px;
56
- margin: 1rem 0;
57
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
58
- font-size: 1.1rem !important;
59
- line-height: 1.6 !important;
60
- font-family: "Arial", sans-serif !important;
61
- color: #000000 !important;
62
- }
63
-
64
- .user-message {
65
- background-color: #F3F4F6 !important;
66
- }
67
-
68
- .assistant-message {
69
- background-color: #EFF6FF !important;
70
- }
71
-
72
- /* Status indicators */
73
- .status-indicator {
74
- padding: 0.5rem 1rem;
75
- border-radius: 6px;
76
- font-weight: 500;
77
- font-size: 1.2rem;
78
- color: #000000;
79
- }
80
-
81
- .status-online {
82
- background-color: #DEF7EC;
83
- color: #03543F;
84
- }
85
-
86
- .status-offline {
87
- background-color: #FDE8E8;
88
- color: rgb(255, 255, 255);
89
- }
90
  </style>
91
  """, unsafe_allow_html=True)
92
 
93
  def initialize_pipeline():
94
- """Initialize RAG pipeline with configurations"""
95
  try:
96
  openai_api_key = os.getenv('OPENAI_API_KEY') or st.secrets['OPENAI_API_KEY']
97
  config = create_default_config(openai_api_key)
@@ -99,56 +32,26 @@ def initialize_pipeline():
99
  config.retriever.top_k = 5
100
  config.model.temperature = 0.3
101
  pipeline = AcademicCalendarRAG(config)
102
-
103
  with open("calendar.json", "r", encoding="utf-8") as f:
104
  calendar_data = json.load(f)
105
  pipeline.load_data(calendar_data)
106
-
107
  return pipeline
108
-
109
  except Exception as e:
110
  st.error(f"Error initializing pipeline: {str(e)}")
111
  return None
112
 
113
- def load_qa_history():
114
- """Load QA history from local JSON file"""
115
- try:
116
- history_file = Path("qa_history.json")
117
- if history_file.exists():
118
- with open(history_file, "r", encoding="utf-8") as f:
119
- return json.load(f)
120
- return []
121
- except Exception as e:
122
- st.error(f"Error loading QA history: {str(e)}")
123
- return []
124
-
125
-
126
  def save_qa_history(history_entry):
127
- """Save QA history entry to local JSON file and push to Hugging Face"""
128
  try:
129
  history_file = Path("qa_history.json")
130
-
131
- # Initialize or load existing history
132
  if history_file.exists():
133
  with open(history_file, "r", encoding="utf-8") as f:
134
- try:
135
- history_data = json.load(f)
136
- except json.JSONDecodeError:
137
- history_data = []
138
  else:
139
  history_data = []
140
-
141
- # Append new entry
142
  history_data.append(history_entry)
143
-
144
- # Save updated history
145
- with open("qa_history.json", "w", encoding="utf-8") as f:
146
  json.dump(history_data, f, ensure_ascii=False, indent=2)
147
-
148
- # Introduce a delay before pushing to Hugging Face
149
- time.sleep(30) # Sleep for 30 seconds
150
-
151
- # Push to Hugging Face
152
  hf_token = os.getenv('HF_TOKEN') or st.secrets['HF_TOKEN']
153
  api = HfApi(token=hf_token)
154
  api.upload_file(
@@ -160,222 +63,75 @@ def save_qa_history(history_entry):
160
  except Exception as e:
161
  st.error(f"Error saving QA history: {str(e)}")
162
 
163
- def add_to_qa_history(query: str, answer: str):
164
- """Add new QA pair to history"""
165
  history_entry = {
166
  "timestamp": (datetime.now() + timedelta(hours=7)).isoformat(),
167
  "query": query,
168
- "answer": answer
169
  }
170
  save_qa_history(history_entry)
171
- return history_entry
172
 
173
- def clear_qa_history():
174
- """Clear QA history file"""
175
- try:
176
- # Write empty list to history file
177
- with open("qa_history.json", "w", encoding="utf-8") as f:
178
- json.dump([], f, ensure_ascii=False, indent=2)
179
-
180
- # Push to Hugging Face
181
- hf_token = os.getenv('HF_TOKEN') or st.secrets['HF_TOKEN']
182
- api = HfApi(token=hf_token)
183
- api.upload_file(
184
- path_or_fileobj="qa_history.json",
185
- path_in_repo="qa_history.json",
186
- repo_id="JirasakJo/Questions_Graduate_Studies_Calendar_2024",
187
- repo_type="space"
188
- )
189
- except Exception as e:
190
- st.error(f"Error clearing QA history: {str(e)}")
191
-
192
- def add_to_history(role: str, message: str):
193
- """Add message to chat history and save if it's a complete QA pair"""
194
  st.session_state.chat_history.append((role, message))
195
-
196
- # If this is an assistant response, save the QA pair
197
- if role == "assistant" and len(st.session_state.chat_history) >= 2:
198
- # Get the corresponding user query (previous message)
199
- user_query = st.session_state.chat_history[-2][1]
200
- add_to_qa_history(user_query, message)
201
-
202
  def display_chat_history():
203
- """Display chat history with enhanced styling"""
204
- for i, (role, message) in enumerate(st.session_state.chat_history):
205
  if role == "user":
206
  st.markdown(f"""
207
  <div class="chat-message user-message">
208
- <strong>🧑 คำถาม:</strong><br>
209
- {message}
210
  </div>
211
  """, unsafe_allow_html=True)
212
- else:
213
  st.markdown(f"""
214
  <div class="chat-message assistant-message">
215
- <strong>🤖 คำตอบ:</strong><br>
216
- {message}
217
  </div>
218
  """, unsafe_allow_html=True)
219
 
220
  def main():
221
- # Page config
222
  st.set_page_config(
223
  page_title="Academic Calendar Assistant",
224
  page_icon="📅",
225
  layout="wide",
226
- initial_sidebar_state="collapsed"
227
  )
228
-
229
- # Load custom CSS
230
  load_custom_css()
231
 
232
  # Initialize session state
233
  if 'pipeline' not in st.session_state:
234
- st.session_state.pipeline = None
235
-
236
  if 'chat_history' not in st.session_state:
237
  st.session_state.chat_history = []
238
 
239
- # Load QA history at startup
240
- if 'qa_history_loaded' not in st.session_state:
241
- st.session_state.qa_history_loaded = True
242
- load_qa_history()
243
-
244
- # Header
245
- st.markdown("""
246
- <div style="text-align: center; padding: 2rem 0;">
247
- <h1>🎓 ระบบค้นหาข้อมูลปฏิทินการศึกษา</h1>
248
- </div>
249
- """, unsafe_allow_html=True)
250
-
251
- # Initialize pipeline
252
- if st.session_state.pipeline is None:
253
- with st.spinner("กำลังเริ่มต้นระบบ..."):
254
- st.session_state.pipeline = initialize_pipeline()
255
-
256
- chat_col, info_col = st.columns([7, 3])
257
-
258
- with chat_col:
259
- with st.container():
260
- # Display chat history
261
- display_chat_history()
262
-
263
- # Query input section
264
- st.markdown("""
265
- <label for="query_input" style="font-size: 1.2rem; font-weight: bold; color: black;">
266
- <span style="color: white; background-color: yellow; padding: 0 0.2rem;">โปรดระบุคำถามเกี่ยวกับ ปฏ���ทินการศึกษา:</span>
267
- </label>
268
- """, unsafe_allow_html=True)
269
-
270
- query = st.text_input(
271
- "",
272
- placeholder="เช่น: วันสุดท้ายของการสอบปากเปล่าในภาคเรียนที่ 1/2567 คือวันที่เท่าไร?",
273
- key="query_input"
274
- )
275
-
276
- # Button layout
277
- col1, col2, col3 = st.columns([1, 1, 4])
278
-
279
- with col1:
280
- send_query = st.button(
281
- "📤 ส่งคำถาม",
282
- type="primary",
283
- use_container_width=True,
284
- key="send_query_button"
285
- )
286
-
287
- with col2:
288
- clear_history = st.button(
289
- "🗑️ ล้างประวัติ",
290
- type="secondary",
291
- use_container_width=True,
292
- key="clear_history_button"
293
- )
294
-
295
- # Process query
296
- if send_query and query:
297
- if st.session_state.pipeline is None:
298
- st.error("❌ ไม่สามารถเชื่อมต่อกับระบบได้ กรุณาลองใหม่อีกครั้ง")
299
- return
300
-
301
- # Add the user query to the chat history
302
- add_to_history("user", query)
303
-
304
- try:
305
- with st.spinner("🔍 กำลังค้นหาคำตอบ..."):
306
- result = st.session_state.pipeline.process_query(query)
307
- add_to_history("assistant", result["answer"])
308
-
309
- # Save to history without reloading
310
- with st.expander("📚 แสดงข้อมูลอ้างอิง", expanded=False):
311
- for i, doc in enumerate(result["documents"], 1):
312
- st.markdown(f"""
313
- <div style="padding: 1rem; background-color: #F9FAFB; border-radius: 8px; margin: 0.5rem 0;">
314
- <strong>เอกสารที่ {i}:</strong><br>
315
- {doc.content}
316
- </div>
317
- """, unsafe_allow_html=True)
318
-
319
- with st.expander("🔍 รายละเอียดการวิเคราะห์คำถาม", expanded=False):
320
- st.json(result["query_info"])
321
-
322
- except Exception as e:
323
- st.error(f"❌ เกิดข้อผิดพลาด: {str(e)}")
324
-
325
- elif send_query and not query:
326
- st.warning("⚠️ กรุณาระบุคำถาม")
327
-
328
- # Clear history
329
- if clear_history:
330
- st.session_state.chat_history = []
331
- save_qa_history([]) # Clear saved history
332
- st.rerun()
333
-
334
- with info_col:
335
- # System information
336
- st.markdown("""
337
- <div style="background-color: #F9FAFB; padding: 1.5rem; border-radius: 12px; margin-bottom: 2rem;">
338
- <h3 style="color: #1E3A8A;">ℹ️ เกี่ยวกับระบบ</h3>
339
- <p style="color: #ff0015;">
340
- ระบบนี้ใช้เทคโนโลยี <strong>RAG (Retrieval-Augmented Generation)</strong>
341
- ในการค้นหาและตอบคำถามเกี่ยวกับปฏิทินการศึกษา
342
- </p>
343
- <h4 style="color: #1E3A8A; margin-top: 1rem;">สามารถสอบถามข้อมูลเกี่ยวกับ:</h4>
344
- <ul style="list-style-type: none; padding-left: 0;">
345
- <li>📅 กำหนดการต่างๆ ในปฏิทินการศึกษา</li>
346
- <li>🎯 วันสำคัญและกิจกรรม</li>
347
- <li>📝 การลงทะเบียนเรียน</li>
348
- <li>📚 กำหนดการสอบ</li>
349
- <li>🏖️ วันหยุดการศึกษา</li>
350
- </ul>
351
- </div>
352
- """, unsafe_allow_html=True)
353
-
354
- # System status
355
- st.markdown("""
356
- <div style="background-color: #f9fafb; padding: 1.5rem; border-radius: 12px;">
357
- <h3 style="color: #1E3A8A;">🔄 สถานะระบบ</h3>
358
- <div style="margin-top: 1rem;">
359
- <p><strong>⏰ เวลาปัจจุบัน:</strong><br>
360
- {}</p>
361
- <p><strong>📡 สถานะระบบ:</strong><br>
362
- <span class="status-indicator {}">
363
- {} {}
364
- </span></p>
365
- </div>
366
- </div>
367
- """.format(
368
- (datetime.now() + timedelta(hours=6)).strftime('%Y-%m-%d %H:%M:%S'),
369
- "status-online" if st.session_state.pipeline else "status-offline",
370
- "🟢" if st.session_state.pipeline else "🔴",
371
- "พร้อมใช้งาน" if st.session_state.pipeline else "ไม่พร้อมใช้งาน"
372
- ), unsafe_allow_html=True)
373
 
374
- # Handle clear history action
375
- if clear_history:
376
- st.session_state.chat_history = []
377
- clear_qa_history()
378
- st.rerun()
379
 
380
  if __name__ == "__main__":
381
- main()
 
1
  import streamlit as st
2
  import json
3
  import os
 
4
  from datetime import datetime, timedelta
 
5
  from huggingface_hub import HfApi
6
  from pathlib import Path
7
  from calendar_rag import (
8
  create_default_config,
9
  AcademicCalendarRAG,
 
10
  )
11
 
12
  # Custom CSS for enhanced styling
13
  def load_custom_css():
14
  st.markdown("""
15
  <style>
16
+ /* General styling */
17
+ body { font-family: "Arial", sans-serif; line-height: 1.6; }
18
+ .main { padding: 2rem; }
19
+ h1 { text-align: center; border-bottom: 3px solid #1E3A8A; padding-bottom: 1rem; }
20
+ .chat-message { padding: 1rem; margin: 1rem 0; border-radius: 8px; }
21
+ .user-message { background-color: #F3F4F6; }
22
+ .assistant-message { background-color: #EFF6FF; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  </style>
24
  """, unsafe_allow_html=True)
25
 
26
  def initialize_pipeline():
27
+ """Initialize the RAG pipeline."""
28
  try:
29
  openai_api_key = os.getenv('OPENAI_API_KEY') or st.secrets['OPENAI_API_KEY']
30
  config = create_default_config(openai_api_key)
 
32
  config.retriever.top_k = 5
33
  config.model.temperature = 0.3
34
  pipeline = AcademicCalendarRAG(config)
 
35
  with open("calendar.json", "r", encoding="utf-8") as f:
36
  calendar_data = json.load(f)
37
  pipeline.load_data(calendar_data)
 
38
  return pipeline
 
39
  except Exception as e:
40
  st.error(f"Error initializing pipeline: {str(e)}")
41
  return None
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  def save_qa_history(history_entry):
44
+ """Save QA history to file and upload to Hugging Face."""
45
  try:
46
  history_file = Path("qa_history.json")
 
 
47
  if history_file.exists():
48
  with open(history_file, "r", encoding="utf-8") as f:
49
+ history_data = json.load(f) or []
 
 
 
50
  else:
51
  history_data = []
 
 
52
  history_data.append(history_entry)
53
+ with open(history_file, "w", encoding="utf-8") as f:
 
 
54
  json.dump(history_data, f, ensure_ascii=False, indent=2)
 
 
 
 
 
55
  hf_token = os.getenv('HF_TOKEN') or st.secrets['HF_TOKEN']
56
  api = HfApi(token=hf_token)
57
  api.upload_file(
 
63
  except Exception as e:
64
  st.error(f"Error saving QA history: {str(e)}")
65
 
66
+ def add_to_qa_history(query, answer):
67
+ """Add a QA pair to history and save it."""
68
  history_entry = {
69
  "timestamp": (datetime.now() + timedelta(hours=7)).isoformat(),
70
  "query": query,
71
+ "answer": answer,
72
  }
73
  save_qa_history(history_entry)
 
74
 
75
+ def add_to_history(role, message):
76
+ """Update the chat history dynamically."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  st.session_state.chat_history.append((role, message))
78
+
 
 
 
 
 
 
79
  def display_chat_history():
80
+ """Display chat history dynamically."""
81
+ for role, message in st.session_state.chat_history:
82
  if role == "user":
83
  st.markdown(f"""
84
  <div class="chat-message user-message">
85
+ <strong>🧑 คำถาม:</strong><br>{message}
 
86
  </div>
87
  """, unsafe_allow_html=True)
88
+ elif role == "assistant":
89
  st.markdown(f"""
90
  <div class="chat-message assistant-message">
91
+ <strong>🤖 คำตอบ:</strong><br>{message}
 
92
  </div>
93
  """, unsafe_allow_html=True)
94
 
95
  def main():
96
+ # Page setup
97
  st.set_page_config(
98
  page_title="Academic Calendar Assistant",
99
  page_icon="📅",
100
  layout="wide",
 
101
  )
 
 
102
  load_custom_css()
103
 
104
  # Initialize session state
105
  if 'pipeline' not in st.session_state:
106
+ st.session_state.pipeline = initialize_pipeline()
 
107
  if 'chat_history' not in st.session_state:
108
  st.session_state.chat_history = []
109
 
110
+ st.title("🎓 ระบบค้นหาข้อมูลปฏิทินการศึกษา")
111
+
112
+ # Chat interface
113
+ query = st.text_input("โปรดระบุคำถามเกี่ยวกับปฏิทินการศึกษา:", "")
114
+ send_query = st.button("📤 ส่งคำถาม")
115
+ clear_history = st.button("🗑️ ล้างประวัติ")
116
+
117
+ # Handle sending query
118
+ if send_query and query:
119
+ add_to_history("user", query)
120
+ try:
121
+ result = st.session_state.pipeline.process_query(query)
122
+ answer = result["answer"]
123
+ add_to_history("assistant", answer)
124
+ add_to_qa_history(query, answer)
125
+ except Exception as e:
126
+ st.error(f"Error processing query: {str(e)}")
127
+
128
+ # Handle clearing history
129
+ if clear_history:
130
+ st.session_state.chat_history = []
131
+ st.success("ล้างประวัติสำเร็จ!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
+ # Display chat history
134
+ display_chat_history()
 
 
 
135
 
136
  if __name__ == "__main__":
137
+ main()