jonels1988 commited on
Commit
0186fe5
Β·
verified Β·
1 Parent(s): 739634d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -51
app.py CHANGED
@@ -1,28 +1,64 @@
1
  import streamlit as st
2
  import json
3
- import os
4
  import base64
5
  from PIL import Image
6
  import io
 
 
7
 
8
- # Initialize session state
9
- if 'knowledge_base' not in st.session_state:
10
- # For Hugging Face Spaces, we'll use a different approach for persistence
11
- if os.path.exists('knowledge_base.json'):
12
- with open('knowledge_base.json', 'r') as f:
13
- st.session_state.knowledge_base = json.load(f)
14
- else:
15
- st.session_state.knowledge_base = {
16
- "categories": []
17
- }
18
 
19
- def save_data():
20
- """Save data to JSON file"""
 
 
 
 
 
21
  try:
22
- with open('knowledge_base.json', 'w') as f:
23
- json.dump(st.session_state.knowledge_base, f, indent=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  except Exception as e:
25
  st.error(f"Error saving data: {e}")
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  def image_to_base64(image):
28
  """Convert PIL Image to base64 string"""
@@ -44,17 +80,17 @@ def display_base64_image(base64_string):
44
 
45
  # Main App
46
  st.set_page_config(
47
- page_title="Business Knowledge Base",
48
  page_icon="πŸ“š",
49
  layout="wide",
50
  initial_sidebar_state="expanded"
51
  )
52
 
53
- st.title("πŸ“š Business Solutions Knowledge Base")
54
 
55
  # Sidebar for navigation
56
  st.sidebar.title("Navigation")
57
- menu = st.sidebar.radio("Go to", ["View Knowledge", "Add Content", "Manage Categories"])
58
 
59
  if menu == "View Knowledge":
60
  st.header("Browse Knowledge Base")
@@ -130,9 +166,9 @@ elif menu == "Add Content":
130
  'name': new_subtopic,
131
  'articles': []
132
  })
133
- save_data()
134
- st.success(f"Subtopic '{new_subtopic}' added!")
135
- st.rerun()
136
  else:
137
  st.error("Subtopic with this name already exists!")
138
  else:
@@ -148,9 +184,9 @@ elif menu == "Add Content":
148
  'name': new_category,
149
  'subtopics': []
150
  })
151
- save_data()
152
- st.success(f"Category '{new_category}' created!")
153
- st.rerun()
154
  else:
155
  st.error("Category with this name already exists!")
156
 
@@ -201,9 +237,9 @@ elif menu == "Add Content":
201
  'description': article_description,
202
  'steps': steps
203
  })
204
- save_data()
205
- st.success("Article added successfully!")
206
- st.rerun()
207
  else:
208
  st.error("Article with this title already exists!")
209
  else:
@@ -229,18 +265,18 @@ elif menu == "Manage Categories":
229
  if st.button("Update Name", key=f"update_cat_{i}") and new_name != category['name']:
230
  if new_name not in [cat['name'] for cat in categories if cat['name'] != category['name']]:
231
  category['name'] = new_name
232
- save_data()
233
- st.success("Category name updated!")
234
- st.rerun()
235
  else:
236
  st.error("Category name already exists!")
237
 
238
  with col2:
239
  if st.button("❌ Delete Category", key=f"del_cat_{i}"):
240
  categories.pop(i)
241
- save_data()
242
- st.success("Category deleted!")
243
- st.rerun()
244
 
245
  # Manage subtopics
246
  if category.get('subtopics'):
@@ -254,23 +290,73 @@ elif menu == "Manage Categories":
254
  with sub_col3:
255
  if st.button("Delete", key=f"del_sub_{i}_{j}"):
256
  category['subtopics'].pop(j)
257
- save_data()
258
- st.success("Subtopic deleted!")
259
- st.rerun()
260
 
261
  if new_sub_name != subtopic['name']:
262
  if st.button("Update Subtopic", key=f"update_sub_{i}_{j}"):
263
  if new_sub_name not in [st['name'] for st in category['subtopics'] if st['name'] != subtopic['name']]:
264
  subtopic['name'] = new_sub_name
265
- save_data()
266
- st.success("Subtopic name updated!")
267
- st.rerun()
268
  else:
269
  st.error("Subtopic name already exists!")
270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  # Initialize with default business categories
272
  st.sidebar.markdown("---")
273
- if st.sidebar.button("Initialize with Business Categories"):
274
  st.session_state.knowledge_base = {
275
  "categories": [
276
  {
@@ -316,15 +402,11 @@ if st.sidebar.button("Initialize with Business Categories"):
316
  }
317
  ]
318
  }
319
- save_data()
320
- st.sidebar.success("Business categories initialized!")
321
- st.rerun()
322
 
323
- # Data export/import (optional)
324
- st.sidebar.markdown("---")
325
- st.sidebar.download_button(
326
- label="Export Knowledge Base",
327
- data=json.dumps(st.session_state.knowledge_base, indent=2),
328
- file_name="knowledge_base_backup.json",
329
- mime="application/json"
330
- )
 
1
  import streamlit as st
2
  import json
 
3
  import base64
4
  from PIL import Image
5
  import io
6
+ from huggingface_hub import HfApi, hf_hub_download
7
+ import os
8
 
9
+ # Initialize Hugging Face API
10
+ api = HfApi()
 
 
 
 
 
 
 
 
11
 
12
+ # Your Hugging Face username - CHANGE THIS TO YOUR USERNAME
13
+ USERNAME = "your-username" # πŸ‘ˆ CHANGE THIS to your actual Hugging Face username
14
+ REPO_ID = f"{USERNAME}/mdbg-business-knowledge-base-data"
15
+ DATA_FILE = "knowledge_base.json"
16
+
17
+ def load_data():
18
+ """Load data from Hugging Face Dataset"""
19
  try:
20
+ # Try to download the data file from Hugging Face
21
+ file_path = hf_hub_download(
22
+ repo_id=REPO_ID,
23
+ filename=DATA_FILE,
24
+ token=os.environ.get('HF_TOKEN') or st.secrets.get('HF_TOKEN')
25
+ )
26
+ with open(file_path, 'r') as f:
27
+ return json.load(f)
28
+ except Exception as e:
29
+ st.sidebar.warning(f"Could not load existing data: {e}")
30
+ # Return default structure if no data exists
31
+ return {"categories": []}
32
+
33
+ def save_data(data):
34
+ """Save data to Hugging Face Dataset"""
35
+ try:
36
+ # Create temporary file
37
+ with open(DATA_FILE, 'w') as f:
38
+ json.dump(data, f, indent=2)
39
+
40
+ # Upload to Hugging Face Hub
41
+ api.upload_file(
42
+ path_or_fileobj=DATA_FILE,
43
+ path_in_repo=DATA_FILE,
44
+ repo_id=REPO_ID,
45
+ repo_type="dataset",
46
+ token=os.environ.get('HF_TOKEN') or st.secrets.get('HF_TOKEN')
47
+ )
48
+ return True
49
  except Exception as e:
50
  st.error(f"Error saving data: {e}")
51
+ st.info("Please make sure:")
52
+ st.info("1. You've created a dataset repository")
53
+ st.info("2. Your HF_TOKEN has write permissions")
54
+ return False
55
+
56
+ # Initialize session state
57
+ if 'knowledge_base' not in st.session_state:
58
+ st.session_state.knowledge_base = load_data()
59
+
60
+ if 'initialized' not in st.session_state:
61
+ st.session_state.initialized = False
62
 
63
  def image_to_base64(image):
64
  """Convert PIL Image to base64 string"""
 
80
 
81
  # Main App
82
  st.set_page_config(
83
+ page_title="MDBG Business Solutions Knowledge Base",
84
  page_icon="πŸ“š",
85
  layout="wide",
86
  initial_sidebar_state="expanded"
87
  )
88
 
89
+ st.title("πŸ“š MDBG Business Solutions Knowledge Base")
90
 
91
  # Sidebar for navigation
92
  st.sidebar.title("Navigation")
93
+ menu = st.sidebar.radio("Go to", ["View Knowledge", "Add Content", "Manage Categories", "Data Management"])
94
 
95
  if menu == "View Knowledge":
96
  st.header("Browse Knowledge Base")
 
166
  'name': new_subtopic,
167
  'articles': []
168
  })
169
+ if save_data(st.session_state.knowledge_base):
170
+ st.success(f"Subtopic '{new_subtopic}' added!")
171
+ st.rerun()
172
  else:
173
  st.error("Subtopic with this name already exists!")
174
  else:
 
184
  'name': new_category,
185
  'subtopics': []
186
  })
187
+ if save_data(st.session_state.knowledge_base):
188
+ st.success(f"Category '{new_category}' created!")
189
+ st.rerun()
190
  else:
191
  st.error("Category with this name already exists!")
192
 
 
237
  'description': article_description,
238
  'steps': steps
239
  })
240
+ if save_data(st.session_state.knowledge_base):
241
+ st.success("Article added successfully!")
242
+ st.rerun()
243
  else:
244
  st.error("Article with this title already exists!")
245
  else:
 
265
  if st.button("Update Name", key=f"update_cat_{i}") and new_name != category['name']:
266
  if new_name not in [cat['name'] for cat in categories if cat['name'] != category['name']]:
267
  category['name'] = new_name
268
+ if save_data(st.session_state.knowledge_base):
269
+ st.success("Category name updated!")
270
+ st.rerun()
271
  else:
272
  st.error("Category name already exists!")
273
 
274
  with col2:
275
  if st.button("❌ Delete Category", key=f"del_cat_{i}"):
276
  categories.pop(i)
277
+ if save_data(st.session_state.knowledge_base):
278
+ st.success("Category deleted!")
279
+ st.rerun()
280
 
281
  # Manage subtopics
282
  if category.get('subtopics'):
 
290
  with sub_col3:
291
  if st.button("Delete", key=f"del_sub_{i}_{j}"):
292
  category['subtopics'].pop(j)
293
+ if save_data(st.session_state.knowledge_base):
294
+ st.success("Subtopic deleted!")
295
+ st.rerun()
296
 
297
  if new_sub_name != subtopic['name']:
298
  if st.button("Update Subtopic", key=f"update_sub_{i}_{j}"):
299
  if new_sub_name not in [st['name'] for st in category['subtopics'] if st['name'] != subtopic['name']]:
300
  subtopic['name'] = new_sub_name
301
+ if save_data(st.session_state.knowledge_base):
302
+ st.success("Subtopic name updated!")
303
+ st.rerun()
304
  else:
305
  st.error("Subtopic name already exists!")
306
 
307
+ elif menu == "Data Management":
308
+ st.header("Data Management")
309
+
310
+ st.info("""
311
+ **Important:** To prevent data loss when updating the Space, we're now using Hugging Face Datasets for storage.
312
+ Follow these steps to set up persistent storage:
313
+ """)
314
+
315
+ st.subheader("Setup Instructions:")
316
+ st.write("1. **Create a Dataset Repository**")
317
+ st.code("""
318
+ - Go to huggingface.co/datasets
319
+ - Click 'Create new dataset'
320
+ - Name it: 'mdbg-business-knowledge-base-data'
321
+ - Set to Private (recommended)
322
+ """)
323
+
324
+ st.write("2. **Update Your Username**")
325
+ st.write("In the app code, change 'your-username' to your actual Hugging Face username")
326
+
327
+ st.write("3. **Add HF Token (Optional)**")
328
+ st.write("For private datasets, add your HF token to Space secrets")
329
+
330
+ st.subheader("Current Data Status:")
331
+ st.json(st.session_state.knowledge_base)
332
+
333
+ # Export/Import
334
+ col1, col2 = st.columns(2)
335
+
336
+ with col1:
337
+ st.download_button(
338
+ label="πŸ“₯ Export Knowledge Base",
339
+ data=json.dumps(st.session_state.knowledge_base, indent=2),
340
+ file_name="mdbg_knowledge_base_backup.json",
341
+ mime="application/json"
342
+ )
343
+
344
+ with col2:
345
+ uploaded_file = st.file_uploader("πŸ“€ Import Knowledge Base", type=['json'])
346
+ if uploaded_file is not None:
347
+ try:
348
+ imported_data = json.load(uploaded_file)
349
+ if st.button("Confirm Import"):
350
+ st.session_state.knowledge_base = imported_data
351
+ if save_data(st.session_state.knowledge_base):
352
+ st.success("Data imported successfully!")
353
+ st.rerun()
354
+ except Exception as e:
355
+ st.error(f"Error importing file: {e}")
356
+
357
  # Initialize with default business categories
358
  st.sidebar.markdown("---")
359
+ if st.sidebar.button("πŸš€ Initialize with Business Categories"):
360
  st.session_state.knowledge_base = {
361
  "categories": [
362
  {
 
402
  }
403
  ]
404
  }
405
+ if save_data(st.session_state.knowledge_base):
406
+ st.sidebar.success("Business categories initialized!")
407
+ st.rerun()
408
 
409
+ # Manual save button
410
+ if st.sidebar.button("πŸ’Ύ Manual Save"):
411
+ if save_data(st.session_state.knowledge_base):
412
+ st.sidebar.success("Data saved successfully!")