JirasakJo commited on
Commit
174bdd3
·
verified ·
1 Parent(s): 81958e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -68
app.py CHANGED
@@ -1,9 +1,7 @@
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 (
@@ -122,9 +120,11 @@ def load_qa_history():
122
  st.error(f"Error loading QA history: {str(e)}")
123
  return []
124
 
 
125
  def save_qa_history(history_entry):
126
  """Save QA history entry to local JSON file and push to Hugging Face"""
127
  try:
 
128
  history_file = Path("qa_history.json")
129
 
130
  # Initialize or load existing history
@@ -144,22 +144,29 @@ def save_qa_history(history_entry):
144
  with open("qa_history.json", "w", encoding="utf-8") as f:
145
  json.dump(history_data, f, ensure_ascii=False, indent=2)
146
 
147
- # Push to Hugging Face without triggering a reload
148
- try:
149
- hf_token = os.getenv('HF_TOKEN') or st.secrets['HF_TOKEN']
150
- api = HfApi(token=hf_token)
151
- api.upload_file(
152
- path_or_fileobj="qa_history.json",
153
- path_in_repo="qa_history.json",
154
- repo_id="JirasakJo/Questions_Graduate_Studies_Calendar_2024",
155
- repo_type="space"
156
- )
157
- except Exception as e:
158
- st.warning(f"Warning: Could not sync history to Hugging Face: {str(e)}", icon="⚠️")
159
-
160
  except Exception as e:
161
  st.error(f"Error saving QA history: {str(e)}")
162
 
 
 
 
 
 
 
 
 
 
 
 
163
  def clear_qa_history():
164
  """Clear QA history file"""
165
  try:
@@ -178,7 +185,17 @@ def clear_qa_history():
178
  )
179
  except Exception as e:
180
  st.error(f"Error clearing QA history: {str(e)}")
181
-
 
 
 
 
 
 
 
 
 
 
182
  def display_chat_history():
183
  """Display chat history with enhanced styling"""
184
  for i, (role, message) in enumerate(st.session_state.chat_history):
@@ -197,29 +214,6 @@ def display_chat_history():
197
  </div>
198
  """, unsafe_allow_html=True)
199
 
200
- def process_query(query: str, pipeline):
201
- """Process a query and update the chat history"""
202
- try:
203
- result = pipeline.process_query(query)
204
-
205
- # Add to session state history
206
- st.session_state.chat_history.append(("user", query))
207
- st.session_state.chat_history.append(("assistant", result["answer"]))
208
-
209
- # Save to QA history without reloading
210
- history_entry = {
211
- "timestamp": (datetime.now() + timedelta(hours=7)).isoformat(),
212
- "query": query,
213
- "answer": result["answer"]
214
- }
215
- save_qa_history(history_entry)
216
-
217
- return result
218
-
219
- except Exception as e:
220
- st.error(f"Error processing query: {str(e)}")
221
- return None
222
-
223
  def main():
224
  # Page config
225
  st.set_page_config(
@@ -238,9 +232,6 @@ def main():
238
 
239
  if 'chat_history' not in st.session_state:
240
  st.session_state.chat_history = []
241
-
242
- if 'current_result' not in st.session_state:
243
- st.session_state.current_result = None
244
 
245
  # Load QA history at startup
246
  if 'qa_history_loaded' not in st.session_state:
@@ -273,7 +264,6 @@ def main():
273
  </label>
274
  """, unsafe_allow_html=True)
275
 
276
- # Query input with key
277
  query = st.text_input(
278
  "",
279
  placeholder="เช่น: วันสุดท้ายของการสอบปากเปล่าในภาคเรียนที่ 1/2567 คือวันที่เท่าไร?",
@@ -292,43 +282,49 @@ def main():
292
  )
293
 
294
  with col2:
295
- if st.button(
296
  "🗑️ ล้างประวัติ",
297
  type="secondary",
298
  use_container_width=True,
299
  key="clear_history_button"
300
- ):
301
- st.session_state.chat_history = []
302
- st.session_state.current_result = None
303
- clear_qa_history()
304
- st.rerun()
305
 
306
  # Process query
307
  if send_query and query:
308
  if st.session_state.pipeline is None:
309
  st.error("❌ ไม่สามารถเชื่อมต่อกับระบบได้ กรุณาลองใหม่อีกครั้ง")
310
- else:
 
 
 
 
311
  with st.spinner("🔍 กำลังค้นหาคำตอบ..."):
312
- result = process_query(query, st.session_state.pipeline)
313
- if result:
314
- st.session_state.current_result = result
315
-
316
- # Display reference documents
317
- with st.expander("📚 แสดงข้อมูลอ้างอิง", expanded=False):
318
- for i, doc in enumerate(result["documents"], 1):
319
- st.markdown(f"""
320
- <div style="padding: 1rem; background-color: #F9FAFB; border-radius: 8px; margin: 0.5rem 0;">
321
- <strong>เอกสารที่ {i}:</strong><br>
322
- {doc.content}
323
- </div>
324
- """, unsafe_allow_html=True)
325
-
326
- # Display query analysis
327
- with st.expander("🔍 รายละเอียดการวิเคราะห์คำถาม", expanded=False):
328
- st.json(result["query_info"])
329
 
330
  elif send_query and not query:
331
  st.warning("⚠️ กรุณาระบุคำถาม")
 
 
 
 
 
 
332
 
333
  with info_col:
334
  # System information
@@ -364,11 +360,17 @@ def main():
364
  </div>
365
  </div>
366
  """.format(
367
- (datetime.now() + timedelta(hours=7)).strftime('%Y-%m-%d %H:%M:%S'),
368
  "status-online" if st.session_state.pipeline else "status-offline",
369
  "🟢" if st.session_state.pipeline else "🔴",
370
  "พร้อมใช้งาน" if st.session_state.pipeline else "ไม่พร้อมใช้งาน"
371
  ), unsafe_allow_html=True)
372
 
 
 
 
 
 
 
373
  if __name__ == "__main__":
374
  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 (
 
120
  st.error(f"Error loading QA history: {str(e)}")
121
  return []
122
 
123
+
124
  def save_qa_history(history_entry):
125
  """Save QA history entry to local JSON file and push to Hugging Face"""
126
  try:
127
+
128
  history_file = Path("qa_history.json")
129
 
130
  # Initialize or load existing history
 
144
  with open("qa_history.json", "w", encoding="utf-8") as f:
145
  json.dump(history_data, f, ensure_ascii=False, indent=2)
146
 
147
+ # Push to Hugging Face
148
+ hf_token = os.getenv('HF_TOKEN') or st.secrets['HF_TOKEN']
149
+ api = HfApi(token=hf_token)
150
+ api.upload_file(
151
+ path_or_fileobj="qa_history.json",
152
+ path_in_repo="qa_history.json",
153
+ repo_id="JirasakJo/Questions_Graduate_Studies_Calendar_2024",
154
+ repo_type="space"
155
+ )
 
 
 
 
156
  except Exception as e:
157
  st.error(f"Error saving QA history: {str(e)}")
158
 
159
+ def add_to_qa_history(query: str, answer: str):
160
+ """Add new QA pair to history"""
161
+ history_entry = {
162
+ "timestamp": (datetime.now() + timedelta(hours=7)).isoformat(),
163
+ "query": query,
164
+ "answer": answer
165
+ }
166
+
167
+ save_qa_history(history_entry)
168
+ return history_entry
169
+
170
  def clear_qa_history():
171
  """Clear QA history file"""
172
  try:
 
185
  )
186
  except Exception as e:
187
  st.error(f"Error clearing QA history: {str(e)}")
188
+
189
+ def add_to_history(role: str, message: str):
190
+ """Add message to chat history and save if it's a complete QA pair"""
191
+ st.session_state.chat_history.append((role, message))
192
+
193
+ # If this is an assistant response, save the QA pair
194
+ if role == "assistant" and len(st.session_state.chat_history) >= 2:
195
+ # Get the corresponding user query (previous message)
196
+ user_query = st.session_state.chat_history[-2][1]
197
+ add_to_qa_history(user_query, message)
198
+
199
  def display_chat_history():
200
  """Display chat history with enhanced styling"""
201
  for i, (role, message) in enumerate(st.session_state.chat_history):
 
214
  </div>
215
  """, unsafe_allow_html=True)
216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  def main():
218
  # Page config
219
  st.set_page_config(
 
232
 
233
  if 'chat_history' not in st.session_state:
234
  st.session_state.chat_history = []
 
 
 
235
 
236
  # Load QA history at startup
237
  if 'qa_history_loaded' not in st.session_state:
 
264
  </label>
265
  """, unsafe_allow_html=True)
266
 
 
267
  query = st.text_input(
268
  "",
269
  placeholder="เช่น: วันสุดท้ายของการสอบปากเปล่าในภาคเรียนที่ 1/2567 คือวันที่เท่าไร?",
 
282
  )
283
 
284
  with col2:
285
+ clear_history = st.button(
286
  "🗑️ ล้างประวัติ",
287
  type="secondary",
288
  use_container_width=True,
289
  key="clear_history_button"
290
+ )
 
 
 
 
291
 
292
  # Process query
293
  if send_query and query:
294
  if st.session_state.pipeline is None:
295
  st.error("❌ ไม่สามารถเชื่อมต่อกับระบบได้ กรุณาลองใหม่อีกครั้ง")
296
+ return
297
+
298
+ add_to_history("user", query)
299
+
300
+ try:
301
  with st.spinner("🔍 กำลังค้นหาคำตอบ..."):
302
+ result = st.session_state.pipeline.process_query(query)
303
+ add_to_history("assistant", result["answer"])
304
+
305
+ with st.expander("📚 แสดงข้อมูลอ้างอิง", expanded=False):
306
+ for i, doc in enumerate(result["documents"], 1):
307
+ st.markdown(f"""
308
+ <div style="padding: 1rem; background-color: #F9FAFB; border-radius: 8px; margin: 0.5rem 0;">
309
+ <strong>เอกสารที่ {i}:</strong><br>
310
+ {doc.content}
311
+ </div>
312
+ """, unsafe_allow_html=True)
313
+
314
+ with st.expander("🔍 รายละเอียดการวิเคราะห์คำถาม", expanded=False):
315
+ st.json(result["query_info"])
316
+
317
+ except Exception as e:
318
+ st.error(f"❌ เกิดข้อผิดพลาด: {str(e)}")
319
 
320
  elif send_query and not query:
321
  st.warning("⚠️ กรุณาระบุคำถาม")
322
+
323
+ # Clear history
324
+ if clear_history:
325
+ st.session_state.chat_history = []
326
+ save_qa_history([]) # Clear saved history
327
+ st.rerun()
328
 
329
  with info_col:
330
  # System information
 
360
  </div>
361
  </div>
362
  """.format(
363
+ (datetime.now() + timedelta(hours=6)).strftime('%Y-%m-%d %H:%M:%S'),
364
  "status-online" if st.session_state.pipeline else "status-offline",
365
  "🟢" if st.session_state.pipeline else "🔴",
366
  "พร้อมใช้งาน" if st.session_state.pipeline else "ไม่พร้อมใช้งาน"
367
  ), unsafe_allow_html=True)
368
 
369
+ # Handle clear history action
370
+ if clear_history:
371
+ st.session_state.chat_history = []
372
+ clear_qa_history()
373
+ st.rerun()
374
+
375
  if __name__ == "__main__":
376
  main()