jonels1988 commited on
Commit
6aba55b
·
verified ·
1 Parent(s): ef8f62d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -385
app.py CHANGED
@@ -1,412 +1,146 @@
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 = "jonels1988" # 👈 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"""
65
- try:
66
- buffered = io.BytesIO()
67
- image.save(buffered, format="PNG")
68
- return base64.b64encode(buffered.getvalue()).decode()
69
- except Exception as e:
70
- st.error(f"Error processing image: {e}")
71
- return None
72
-
73
- def display_base64_image(base64_string):
74
- """Display base64 image in Streamlit"""
75
- try:
76
- if base64_string:
77
- st.image(base64.b64decode(base64_string), use_column_width=True)
78
- except Exception as e:
79
- st.error(f"Error displaying image: {e}")
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")
 
 
97
 
98
- categories = st.session_state.knowledge_base.get('categories', [])
99
- if not categories:
100
- st.info("No categories yet. Go to 'Add Content' to create your first category!")
101
- else:
102
- # Category selection
103
- category_names = [cat['name'] for cat in categories]
104
- selected_category = st.selectbox("Select Category", category_names)
 
 
105
 
106
- if selected_category:
107
- category = next((cat for cat in categories if cat['name'] == selected_category), None)
108
- if category and category.get('subtopics'):
109
- # Subtopic selection
110
- subtopic_names = [st['name'] for st in category['subtopics']]
111
- if subtopic_names:
112
- selected_subtopic = st.selectbox("Select Subtopic", subtopic_names)
113
-
114
- if selected_subtopic:
115
- subtopic = next((st for st in category['subtopics'] if st['name'] == selected_subtopic), None)
116
- if subtopic and subtopic.get('articles'):
117
- # Article selection
118
- article_names = [art['title'] for art in subtopic['articles']]
119
- if article_names:
120
- selected_article = st.selectbox("Select Article", article_names)
121
-
122
- if selected_article:
123
- article = next((art for art in subtopic['articles'] if art['title'] == selected_article), None)
124
- if article:
125
- # Display article
126
- st.subheader(article['title'])
127
- st.write(article.get('description', 'No description available.'))
128
-
129
- # Display steps
130
- if article.get('steps'):
131
- st.subheader("Steps:")
132
- for i, step in enumerate(article['steps'], 1):
133
- st.write(f"**Step {i}:** {step.get('description', 'No description')}")
134
- if step.get('screenshot'):
135
- st.write(f"*Screenshot for Step {i}:*")
136
- display_base64_image(step['screenshot'])
137
- else:
138
- st.info("No steps added for this article.")
139
- else:
140
- st.info("No articles in this subtopic yet.")
141
- else:
142
- st.info("No subtopics in this category yet.")
143
 
144
- elif menu == "Add Content":
145
- st.header("Add New Content")
 
 
 
146
 
147
- categories = st.session_state.knowledge_base.get('categories', [])
148
- category_names = [cat['name'] for cat in categories]
149
 
 
 
 
 
150
  col1, col2 = st.columns(2)
151
 
152
  with col1:
153
- st.subheader("Add to Existing Category")
154
- if category_names:
155
- selected_category = st.selectbox("Select Category", category_names, key="existing_cat")
156
- if selected_category:
157
- category = next((cat for cat in categories if cat['name'] == selected_category), None)
158
- if category:
159
- new_subtopic = st.text_input("New Subtopic Name")
160
- if st.button("Add Subtopic") and new_subtopic:
161
- if 'subtopics' not in category:
162
- category['subtopics'] = []
163
- # Check if subtopic already exists
164
- if new_subtopic not in [st['name'] for st in category['subtopics']]:
165
- category['subtopics'].append({
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:
175
- st.info("No categories yet. Create one first!")
176
 
177
  with col2:
178
- st.subheader("Create New Category")
179
- new_category = st.text_input("New Category Name")
180
- if st.button("Create Category") and new_category:
181
- # Check if category already exists
182
- if new_category not in category_names:
183
- st.session_state.knowledge_base['categories'].append({
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
-
193
- # Add Articles
194
- st.subheader("Add Article")
195
- if category_names:
196
- selected_category_for_article = st.selectbox("Select Category for Article", category_names, key="article_cat")
197
- if selected_category_for_article:
198
- category = next((cat for cat in categories if cat['name'] == selected_category_for_article), None)
199
- if category and category.get('subtopics'):
200
- subtopic_names = [st['name'] for st in category['subtopics']]
201
- if subtopic_names:
202
- selected_subtopic_for_article = st.selectbox("Select Subtopic", subtopic_names)
203
-
204
- article_title = st.text_input("Article Title")
205
- article_description = st.text_area("Article Description")
206
-
207
- # Steps with screenshots
208
- st.subheader("Add Steps")
209
- steps = []
210
-
211
- num_steps = st.number_input("Number of Steps", min_value=1, max_value=20, value=1, key="num_steps")
212
-
213
- for i in range(num_steps):
214
- st.write(f"**Step {i+1}**")
215
- step_desc = st.text_input(f"Step {i+1} Description", key=f"step_{i}")
216
- step_screenshot = st.file_uploader(f"Step {i+1} Screenshot", type=['png', 'jpg', 'jpeg'], key=f"screenshot_{i}")
217
-
218
- step_data = {"description": step_desc}
219
- if step_screenshot:
220
- image = Image.open(step_screenshot)
221
- base64_image = image_to_base64(image)
222
- if base64_image:
223
- step_data["screenshot"] = base64_image
224
-
225
- steps.append(step_data)
226
-
227
- if st.button("Add Article") and article_title and selected_subtopic_for_article:
228
- subtopic = next((st for st in category['subtopics'] if st['name'] == selected_subtopic_for_article), None)
229
- if subtopic:
230
- if 'articles' not in subtopic:
231
- subtopic['articles'] = []
232
-
233
- # Check if article title already exists
234
- if article_title not in [art['title'] for art in subtopic['articles']]:
235
- subtopic['articles'].append({
236
- 'title': article_title,
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:
246
- st.info("No subtopics in this category. Create a subtopic first.")
247
- else:
248
- st.info("No subtopics in this category. Create a subtopic first.")
249
- else:
250
- st.info("No categories available. Create a category first.")
251
-
252
- elif menu == "Manage Categories":
253
- st.header("Manage Categories")
254
-
255
- categories = st.session_state.knowledge_base.get('categories', [])
256
 
257
- if not categories:
258
- st.info("No categories to manage.")
259
- else:
260
- for i, category in enumerate(categories):
261
- with st.expander(f"📁 {category['name']}", expanded=False):
262
- col1, col2 = st.columns([3,1])
263
- with col1:
264
- new_name = st.text_input(f"Rename Category", value=category['name'], key=f"cat_name_{i}")
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'):
283
- st.write("**Subtopics:**")
284
- for j, subtopic in enumerate(category['subtopics']):
285
- sub_col1, sub_col2, sub_col3 = st.columns([2,2,1])
286
- with sub_col1:
287
- st.write(f"• {subtopic['name']}")
288
- with sub_col2:
289
- new_sub_name = st.text_input(f"Rename subtopic", value=subtopic['name'], key=f"sub_name_{i}_{j}")
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
- {
363
- "name": "QuickBooks",
364
- "subtopics": [
365
- {"name": "Setup & Configuration", "articles": []},
366
- {"name": "Daily Operations", "articles": []},
367
- {"name": "Reporting", "articles": []},
368
- {"name": "Troubleshooting", "articles": []}
369
- ]
370
- },
371
- {
372
- "name": "PayTrace",
373
- "subtopics": [
374
- {"name": "Payment Processing", "articles": []},
375
- {"name": "Integration", "articles": []},
376
- {"name": "Reconciliation", "articles": []}
377
- ]
378
- },
379
- {
380
- "name": "Fishbowl Inventory",
381
- "subtopics": [
382
- {"name": "Inventory Management", "articles": []},
383
- {"name": "Integration with QuickBooks", "articles": []},
384
- {"name": "Reporting", "articles": []}
385
- ]
386
- },
387
- {
388
- "name": "Tax Preparation",
389
- "subtopics": [
390
- {"name": "Business Taxes", "articles": []},
391
- {"name": "Sales Tax", "articles": []},
392
- {"name": "Quarterly Estimates", "articles": []}
393
- ]
394
- },
395
- {
396
- "name": "Budgeting & Planning",
397
- "subtopics": [
398
- {"name": "Annual Budget", "articles": []},
399
- {"name": "Cash Flow Management", "articles": []},
400
- {"name": "Financial Analysis", "articles": []}
401
- ]
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!")
 
1
  import streamlit as st
 
 
 
 
 
 
2
 
3
+ # Set page config MUST be first Streamlit command
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  st.set_page_config(
5
+ page_title="Business Knowledge Base",
6
  page_icon="📚",
7
  layout="wide",
8
  initial_sidebar_state="expanded"
9
  )
10
 
11
+ # Initialize session state for knowledge base
12
+ if 'knowledge_base' not in st.session_state:
13
+ st.session_state.knowledge_base = {
14
+ 'bookkeeping': [
15
+ {
16
+ 'subTopic': 'Accounts Receivable',
17
+ 'title': 'GTM Medical Trading - Payments Tender',
18
+ 'description': 'Streamlined 3-step process for GTM Medical Trading invoice payments using AgileSuite QuickBooks system to significantly reduce processing fees while maintaining accuracy.',
19
+ 'steps': [
20
+ 'Step 1: Open AgileSuite Payment Form and input transaction date, total amount, and invoice count',
21
+ 'Step 2: Update multi-use link amount in QuickBooks and scan QR code with separate device',
22
+ 'Step 3: Process payment through customer checkout page and use action buttons to complete'
23
+ ],
24
+ 'benefits': [
25
+ 'Cost Reduction: Saves $600-$1,000+ monthly in processing fees',
26
+ 'Time Efficiency: Process 5-10 invoices simultaneously',
27
+ 'Accuracy: Automated system matching prevents duplicates',
28
+ 'Simplicity: Three straightforward steps replace complex manual processes'
29
+ ]
30
+ }
31
+ ],
32
+ 'quickbooks': [],
33
+ 'paytrace': [],
34
+ 'fishbowl': [],
35
+ 'tax': [],
36
+ 'business': [],
37
+ 'budgeting': []
38
+ }
39
 
40
+ # Main app
41
+ def main():
42
+ st.title("📚 Business Knowledge Base")
43
+ st.markdown("QuickBooks • PayTrace • Fishbowl • Tax Preparation • Business Solutions")
44
 
45
+ # Sidebar for navigation
46
+ with st.sidebar:
47
+ st.header("Categories")
48
+ selected_category = st.radio(
49
+ "Select Category:",
50
+ ["Bookkeeping - Operations", "QuickBooks", "PayTrace", "Fishbowl Inventory",
51
+ "Tax Preparation", "Business Solutions", "Budgeting"],
52
+ index=0
53
+ )
54
 
55
+ st.divider()
56
+ if st.button("➕ Add New Content"):
57
+ st.session_state.show_add_form = True
58
+
59
+ # Main content area
60
+ if selected_category == "Bookkeeping - Operations":
61
+ display_bookkeeping_content()
62
+ else:
63
+ st.info(f"Content for {selected_category} coming soon...")
64
+ st.button("Add first article to this category")
65
+
66
+ # Add content form
67
+ if st.session_state.get('show_add_form', False):
68
+ display_add_content_form()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ def display_bookkeeping_content():
71
+ st.header("Bookkeeping - Operations")
72
+
73
+ # Breadcrumb
74
+ st.caption("Home > Bookkeeping - Operations > Accounts Receivable")
75
 
76
+ # Article content
77
+ article = st.session_state.knowledge_base['bookkeeping'][0]
78
 
79
+ st.subheader(article['title'])
80
+ st.write(article['description'])
81
+
82
+ # Key points in columns
83
  col1, col2 = st.columns(2)
84
 
85
  with col1:
86
+ st.info("**💰 Cost Savings:** $600-$1,000+ monthly")
87
+ st.info("**⏱️ Time Savings:** Process 5-10 invoices together")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
  with col2:
90
+ st.info("**✅ Accuracy:** Automated matching")
91
+ st.info("**📱 Simple:** 3-step process")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
+ # 3-Step Process
94
+ st.subheader("3-Step Payment Process")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
+ steps = article['steps']
97
+ for step in steps:
98
+ st.write(f"**{step}**")
 
99
 
100
+ # Important Notes
101
+ st.warning("""
102
+ **Important Notes:**
103
+ - Always use separate device/QR code for payment entry
104
+ - Never manually match payments after processing
105
+ - Include shipping costs in total amount
106
+ - Contact support for issues rather than manual adjustments
107
  """)
108
 
109
+ # Action buttons
110
+ col1, col2, col3, col4 = st.columns(4)
 
 
 
 
 
 
 
 
 
 
111
  with col1:
112
+ if st.button("📧 Send Copy", use_container_width=True):
113
+ st.success("Copy sent to QuickBooks!")
 
 
 
 
 
114
  with col2:
115
+ if st.button("🖨️ Print", use_container_width=True):
116
+ st.success("Ready for printing...")
117
+ with col3:
118
+ if st.button("💾 Save", use_container_width=True):
119
+ st.success("Transaction saved!")
120
+ with col4:
121
+ if st.button("🗑️ Clear Form", use_container_width=True):
122
+ st.session_state.knowledge_base['bookkeeping'][0] = st.session_state.knowledge_base['bookkeeping'][0].copy()
123
+ st.rerun()
124
+
125
+ def display_add_content_form():
126
+ st.sidebar.divider()
127
+ st.sidebar.subheader("Add New Content")
128
+
129
+ with st.sidebar.form("add_content_form"):
130
+ category = st.selectbox("Category", list(st.session_state.knowledge_base.keys()))
131
+ sub_topic = st.text_input("Subtopic")
132
+ title = st.text_input("Article Title")
133
+ description = st.text_area("Description")
134
+
135
+ submitted = st.form_submit_button("Add Article")
136
+ if submitted:
137
+ if sub_topic and title:
138
+ # Add validation and saving logic here
139
+ st.sidebar.success("Article added successfully!")
140
+ st.session_state.show_add_form = False
141
+ st.rerun()
142
+ else:
143
+ st.sidebar.error("Please fill in required fields")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
+ if __name__ == "__main__":
146
+ main()