Rulga commited on
Commit
3022177
·
1 Parent(s): 13e02f0

feat: initialize chat history folder and improve error messages for saving/loading

Browse files
Files changed (1) hide show
  1. app.py +12 -26
app.py CHANGED
@@ -24,14 +24,18 @@ if 'kb_info' not in st.session_state:
24
  'size': None
25
  }
26
 
27
- # Добавить инициализацию chat_history
28
  if 'chat_history' not in st.session_state:
29
  st.session_state.chat_history = []
30
 
31
- # Добавить инициализацию messages, если её ещё нет
32
  if 'messages' not in st.session_state:
33
  st.session_state.messages = []
34
 
 
 
 
 
35
  # Display title and knowledge base info
36
  # st.title("www.Status.Law Legal Assistant")
37
 
@@ -55,10 +59,6 @@ if st.session_state.kb_info['build_time'] and st.session_state.kb_info['size']:
55
  # Path to store vector database
56
  VECTOR_STORE_PATH = "vector_store"
57
 
58
- # Создание папки истории, если она не существует
59
- if not os.path.exists("chat_history"):
60
- os.makedirs("chat_history")
61
-
62
  # Website URLs
63
  urls = [
64
  "https://status.law",
@@ -144,7 +144,7 @@ def build_knowledge_base(embeddings):
144
 
145
  return vector_store
146
 
147
- # Функция для сохранения истории чата
148
  def save_chat_to_file(chat_history):
149
  current_date = datetime.now().strftime("%Y-%m-%d")
150
  filename = f"chat_history/chat_history_{current_date}.json"
@@ -153,9 +153,9 @@ def save_chat_to_file(chat_history):
153
  with open(filename, 'w', encoding='utf-8') as f:
154
  json.dump(chat_history, f, ensure_ascii=False, indent=2)
155
  except Exception as e:
156
- st.error(f"Ошибка при сохранении истории чата: {e}")
157
 
158
- # Функция для загрузки истории чата
159
  def load_chat_history():
160
  current_date = datetime.now().strftime("%Y-%m-%d")
161
  filename = f"chat_history/chat_history_{current_date}.json"
@@ -165,7 +165,7 @@ def load_chat_history():
165
  with open(filename, 'r', encoding='utf-8') as f:
166
  return json.load(f)
167
  except Exception as e:
168
- st.error(f"Ошибка при загрузке истории чата: {e}")
169
  return []
170
  return []
171
 
@@ -194,7 +194,7 @@ def main():
194
  if 'messages' not in st.session_state:
195
  st.session_state.messages = []
196
 
197
- # Загрузка истории чата при запуске
198
  if not st.session_state.chat_history:
199
  st.session_state.chat_history = load_chat_history()
200
 
@@ -239,7 +239,7 @@ def main():
239
 
240
  st.write(response)
241
 
242
- # Сохранение в историю чата
243
  chat_entry = {
244
  "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
245
  "question": question,
@@ -256,18 +256,4 @@ def main():
256
  })
257
 
258
  if __name__ == "__main__":
259
- main()
260
-
261
- # Добавить кнопку для выгрузки истории чата (опционально)
262
- if st.sidebar.button("Скачать историю чата"):
263
- current_date = datetime.now().strftime("%Y-%m-%d")
264
- filename = f"chat_history_{current_date}.json"
265
-
266
- if st.session_state.chat_history:
267
- json_str = json.dumps(st.session_state.chat_history, ensure_ascii=False, indent=2)
268
- st.download_button(
269
- label="Скачать JSON",
270
- data=json_str.encode('utf-8'),
271
- file_name=filename,
272
- mime="application/json"
273
  )
 
24
  'size': None
25
  }
26
 
27
+ # Initialize chat_history in session_state
28
  if 'chat_history' not in st.session_state:
29
  st.session_state.chat_history = []
30
 
31
+ # Initialize messages if not exists
32
  if 'messages' not in st.session_state:
33
  st.session_state.messages = []
34
 
35
+ # Create history folder if not exists
36
+ if not os.path.exists("chat_history"):
37
+ os.makedirs("chat_history")
38
+
39
  # Display title and knowledge base info
40
  # st.title("www.Status.Law Legal Assistant")
41
 
 
59
  # Path to store vector database
60
  VECTOR_STORE_PATH = "vector_store"
61
 
 
 
 
 
62
  # Website URLs
63
  urls = [
64
  "https://status.law",
 
144
 
145
  return vector_store
146
 
147
+ # Function to save chat history
148
  def save_chat_to_file(chat_history):
149
  current_date = datetime.now().strftime("%Y-%m-%d")
150
  filename = f"chat_history/chat_history_{current_date}.json"
 
153
  with open(filename, 'w', encoding='utf-8') as f:
154
  json.dump(chat_history, f, ensure_ascii=False, indent=2)
155
  except Exception as e:
156
+ st.error(f"Error saving chat history: {e}")
157
 
158
+ # Function to load chat history
159
  def load_chat_history():
160
  current_date = datetime.now().strftime("%Y-%m-%d")
161
  filename = f"chat_history/chat_history_{current_date}.json"
 
165
  with open(filename, 'r', encoding='utf-8') as f:
166
  return json.load(f)
167
  except Exception as e:
168
+ st.error(f"Error loading chat history: {e}")
169
  return []
170
  return []
171
 
 
194
  if 'messages' not in st.session_state:
195
  st.session_state.messages = []
196
 
197
+ # Load chat history on startup
198
  if not st.session_state.chat_history:
199
  st.session_state.chat_history = load_chat_history()
200
 
 
239
 
240
  st.write(response)
241
 
242
+ # Save to chat history
243
  chat_entry = {
244
  "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
245
  "question": question,
 
256
  })
257
 
258
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  )