JirasakJo commited on
Commit
cb2ef4d
·
verified ·
1 Parent(s): a1563ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -29
app.py CHANGED
@@ -12,9 +12,12 @@ from calendar_rag import (
12
  PipelineConfig
13
  )
14
 
15
- all_history = []
 
16
 
17
- export GITHUB_REPO_PATH = r"D:\Last SWU\swu-chat-bot-project"
 
 
18
 
19
  # Custom CSS for enhanced styling
20
  def load_custom_css():
@@ -136,17 +139,19 @@ def save_qa_history(history_entry):
136
  history_file = Path("qa_history.json")
137
 
138
  # Initialize or load existing history
 
139
  if history_file.exists():
140
- with open(history_file, "r", encoding="utf-8") as f:
141
- try:
142
  history_data = json.load(f)
143
- except json.JSONDecodeError:
144
- history_data = []
145
- else:
146
- history_data = []
147
 
148
- # Append new entry
149
- history_data.append(history_entry)
 
 
 
150
 
151
  # Save updated history locally
152
  with open(history_file, "w", encoding="utf-8") as f:
@@ -154,12 +159,11 @@ def save_qa_history(history_entry):
154
 
155
  # Try to push to GitHub if configured
156
  try:
157
- # Get repository path from environment variable or streamlit secrets
158
  repo_path = os.getenv('GITHUB_REPO_PATH') or st.secrets.get('GITHUB_REPO_PATH')
159
 
160
  if repo_path and Path(repo_path).exists():
161
  repo = Repo(repo_path)
162
- repo.git.add("qa_history.json")
163
  if repo.is_dirty():
164
  repo.index.commit("Update QA history")
165
  origin = repo.remote(name="origin")
@@ -171,7 +175,6 @@ def save_qa_history(history_entry):
171
 
172
  except Exception as git_error:
173
  print(f"GitHub sync failed (continuing without GitHub push): {str(git_error)}")
174
- # Continue execution - GitHub sync is optional
175
 
176
  return True
177
 
@@ -180,34 +183,44 @@ def save_qa_history(history_entry):
180
  return False
181
 
182
  def add_to_qa_history(query: str, answer: str):
183
- """Add new QA pair to history and store it in all_history"""
184
  history_entry = {
185
  "timestamp": (datetime.now() + timedelta(hours=7)).isoformat(),
186
  "query": query,
187
  "answer": answer
188
  }
189
 
190
- # Append the new history entry to the all_history list
191
- all_history.append(history_entry)
192
-
193
  return history_entry
194
 
195
  def clear_qa_history():
196
- """Clear QA history file"""
197
  try:
198
- # Write empty list to history file
 
 
 
199
  with open("qa_history.json", "w", encoding="utf-8") as f:
200
  json.dump([], f, ensure_ascii=False, indent=2)
201
 
 
 
 
 
202
  # Push to Hugging Face
203
- hf_token = os.getenv('HF_TOKEN') or st.secrets['HF_TOKEN']
204
- api = HfApi(token=hf_token)
205
- api.upload_file(
206
- path_or_fileobj="qa_history.json",
207
- path_in_repo="qa_history.json",
208
- repo_id="JirasakJo/Questions_Graduate_Studies_Calendar_2024",
209
- repo_type="space"
210
- )
 
 
 
 
211
  except Exception as e:
212
  st.error(f"Error clearing QA history: {str(e)}")
213
 
@@ -217,9 +230,12 @@ def add_to_history(role: str, message: str):
217
 
218
  # If this is an assistant response, save the QA pair
219
  if role == "assistant" and len(st.session_state.chat_history) >= 2:
220
- # Get the corresponding user query (previous message)
221
  user_query = st.session_state.chat_history[-2][1]
222
- add_to_qa_history(user_query, message)
 
 
 
 
223
 
224
  def display_chat_history():
225
  """Display chat history with enhanced styling"""
 
12
  PipelineConfig
13
  )
14
 
15
+ # Define repository path
16
+ os.environ["GITHUB_REPO_PATH"] = r"D:\Last SWU\swu-chat-bot-project"
17
 
18
+ # Initialize global state
19
+ if 'all_history' not in st.session_state:
20
+ st.session_state.all_history = []
21
 
22
  # Custom CSS for enhanced styling
23
  def load_custom_css():
 
139
  history_file = Path("qa_history.json")
140
 
141
  # Initialize or load existing history
142
+ history_data = []
143
  if history_file.exists():
144
+ try:
145
+ with open(history_file, "r", encoding="utf-8") as f:
146
  history_data = json.load(f)
147
+ except json.JSONDecodeError:
148
+ pass
 
 
149
 
150
+ # Append new entry if it's a list of entries
151
+ if isinstance(history_entry, list):
152
+ history_data.extend(history_entry)
153
+ else:
154
+ history_data.append(history_entry)
155
 
156
  # Save updated history locally
157
  with open(history_file, "w", encoding="utf-8") as f:
 
159
 
160
  # Try to push to GitHub if configured
161
  try:
 
162
  repo_path = os.getenv('GITHUB_REPO_PATH') or st.secrets.get('GITHUB_REPO_PATH')
163
 
164
  if repo_path and Path(repo_path).exists():
165
  repo = Repo(repo_path)
166
+ repo.git.add(str(history_file.absolute()))
167
  if repo.is_dirty():
168
  repo.index.commit("Update QA history")
169
  origin = repo.remote(name="origin")
 
175
 
176
  except Exception as git_error:
177
  print(f"GitHub sync failed (continuing without GitHub push): {str(git_error)}")
 
178
 
179
  return True
180
 
 
183
  return False
184
 
185
  def add_to_qa_history(query: str, answer: str):
186
+ """Add new QA pair to history and store it in session state"""
187
  history_entry = {
188
  "timestamp": (datetime.now() + timedelta(hours=7)).isoformat(),
189
  "query": query,
190
  "answer": answer
191
  }
192
 
193
+ # Append to session state history
194
+ st.session_state.all_history.append(history_entry)
 
195
  return history_entry
196
 
197
  def clear_qa_history():
198
+ """Clear QA history and sync with all storages"""
199
  try:
200
+ # Clear session state
201
+ st.session_state.all_history = []
202
+
203
+ # Clear local file
204
  with open("qa_history.json", "w", encoding="utf-8") as f:
205
  json.dump([], f, ensure_ascii=False, indent=2)
206
 
207
+ # Push to GitHub
208
+ if st.session_state.github_sync_enabled:
209
+ save_qa_history([])
210
+
211
  # Push to Hugging Face
212
+ try:
213
+ hf_token = os.getenv('HF_TOKEN') or st.secrets['HF_TOKEN']
214
+ api = HfApi(token=hf_token)
215
+ api.upload_file(
216
+ path_or_fileobj="qa_history.json",
217
+ path_in_repo="qa_history.json",
218
+ repo_id="JirasakJo/Questions_Graduate_Studies_Calendar_2024",
219
+ repo_type="space"
220
+ )
221
+ except Exception as hf_error:
222
+ print(f"Hugging Face sync failed: {str(hf_error)}")
223
+
224
  except Exception as e:
225
  st.error(f"Error clearing QA history: {str(e)}")
226
 
 
230
 
231
  # If this is an assistant response, save the QA pair
232
  if role == "assistant" and len(st.session_state.chat_history) >= 2:
 
233
  user_query = st.session_state.chat_history[-2][1]
234
+ history_entry = add_to_qa_history(user_query, message)
235
+
236
+ # Save to storage if GitHub sync is enabled
237
+ if st.session_state.github_sync_enabled:
238
+ save_qa_history(history_entry)
239
 
240
  def display_chat_history():
241
  """Display chat history with enhanced styling"""