awacke1 commited on
Commit
14d2c55
β€’
1 Parent(s): bdabcd9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -1
app.py CHANGED
@@ -306,4 +306,176 @@ def main():
306
  with col_prev:
307
  if st.button("⬅️ Previous", key='prev_code'):
308
  if st.session_state.current_index > 0:
309
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  with col_prev:
307
  if st.button("⬅️ Previous", key='prev_code'):
308
  if st.session_state.current_index > 0:
309
+ st.session_state.current_index -= 1
310
+ st.rerun()
311
+ with col_next:
312
+ if st.button("➑️ Next", key='next_code'):
313
+ if st.session_state.current_index < total_docs - 1:
314
+ st.session_state.current_index += 1
315
+ st.rerun()
316
+ if st.button("πŸ’Ύ Save Changes", key=f'save_button_{st.session_state.current_index}'):
317
+ try:
318
+ updated_doc = json.loads(doc_str)
319
+ success, message = update_record(container, updated_doc)
320
+ if success:
321
+ st.success(f"Document {updated_doc['id']} saved successfully.")
322
+ st.session_state.selected_document_id = updated_doc['id']
323
+ st.rerun()
324
+ else:
325
+ st.error(message)
326
+ except json.JSONDecodeError as e:
327
+ st.error(f"Invalid JSON: {str(e)} 🚫")
328
+ elif selected_view == 'Show as Edit and Save':
329
+ # ✏️ Show as Edit and Save in columns
330
+ st.markdown("#### Edit the document fields below:")
331
+
332
+ # Create columns for each document
333
+ num_cols = len(documents_to_display)
334
+ cols = st.columns(num_cols)
335
+
336
+ for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
337
+ with col:
338
+ st.markdown(f"##### Document ID: {doc.get('id', '')}")
339
+ editable_id = st.text_input("ID", value=doc.get('id', ''), key=f'edit_id_{idx}')
340
+ # Remove 'id' from the document for editing other fields
341
+ editable_doc = doc.copy()
342
+ editable_doc.pop('id', None)
343
+ doc_str = st.text_area("Document Content (in JSON format)", value=json.dumps(editable_doc, indent=2), height=300, key=f'doc_str_{idx}')
344
+ if st.button("πŸ’Ύ Save Changes", key=f'save_button_{idx}'):
345
+ try:
346
+ updated_doc = json.loads(doc_str)
347
+ updated_doc['id'] = editable_id # Include the possibly edited ID
348
+ success, message = update_record(container, updated_doc)
349
+ if success:
350
+ st.success(f"Document {updated_doc['id']} saved successfully.")
351
+ st.session_state.selected_document_id = updated_doc['id']
352
+ st.rerun()
353
+ else:
354
+ st.error(message)
355
+ except json.JSONDecodeError as e:
356
+ st.error(f"Invalid JSON: {str(e)} 🚫")
357
+ elif selected_view == 'Clone Document':
358
+ # 🧬 Clone Document per record
359
+ st.markdown("#### Clone a document:")
360
+ for idx, doc in enumerate(documents_to_display):
361
+ st.markdown(f"##### Document ID: {doc.get('id', '')}")
362
+ if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
363
+ cloned_doc = doc.copy()
364
+ # Generate a unique ID
365
+ cloned_doc['id'] = generate_unique_id()
366
+ st.session_state.cloned_doc = cloned_doc
367
+ st.session_state.cloned_doc_str = json.dumps(cloned_doc, indent=2)
368
+ st.session_state.clone_mode = True
369
+ st.rerun()
370
+ if st.session_state.get('clone_mode', False):
371
+ st.markdown("#### Edit Cloned Document:")
372
+ cloned_doc_str = st.text_area("Cloned Document Content (in JSON format)", value=st.session_state.cloned_doc_str, height=300)
373
+ if st.button("πŸ’Ύ Save Cloned Document"):
374
+ try:
375
+ new_doc = json.loads(cloned_doc_str)
376
+ success, message = insert_record(container, new_doc)
377
+ if success:
378
+ st.success(f"Cloned document saved with id: {new_doc['id']} πŸŽ‰")
379
+ st.session_state.selected_document_id = new_doc['id']
380
+ st.session_state.clone_mode = False
381
+ st.session_state.cloned_doc = None
382
+ st.session_state.cloned_doc_str = ''
383
+ st.rerun()
384
+ else:
385
+ st.error(message)
386
+ except json.JSONDecodeError as e:
387
+ st.error(f"Invalid JSON: {str(e)} 🚫")
388
+ elif selected_view == 'New Record':
389
+ # πŸ†• New Record
390
+ st.markdown("#### Create a new document:")
391
+ new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
392
+ new_doc_str = st.text_area("Document Content (in JSON format)", value='{}', height=300)
393
+ if st.button("βž• Create New Document"):
394
+ try:
395
+ new_doc = json.loads(new_doc_str)
396
+ new_doc['id'] = new_id # Use the provided ID
397
+ success, message = insert_record(container, new_doc)
398
+ if success:
399
+ st.success(f"New document created with id: {new_doc['id']} πŸŽ‰")
400
+ st.session_state.selected_document_id = new_doc['id']
401
+ # Switch to 'Show as Edit and Save' mode
402
+ st.rerun()
403
+ else:
404
+ st.error(message)
405
+ except json.JSONDecodeError as e:
406
+ st.error(f"Invalid JSON: {str(e)} 🚫")
407
+ else:
408
+ st.sidebar.info("No documents found in this container. πŸ“­")
409
+
410
+ # πŸŽ‰ Main content area
411
+ st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
412
+ if st.session_state.selected_container:
413
+ if documents_to_display:
414
+ df = pd.DataFrame(documents_to_display)
415
+ st.dataframe(df)
416
+ else:
417
+ st.info("No documents to display. 🧐")
418
+
419
+ # πŸ™ GitHub section
420
+ st.subheader("πŸ™ GitHub Operations")
421
+ github_token = os.environ.get("GITHUB") # Read GitHub token from environment variable
422
+ source_repo = st.text_input("Source GitHub Repository URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
423
+ new_repo_name = st.text_input("New Repository Name (for cloning)", value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
424
+
425
+ col1, col2 = st.columns(2)
426
+ with col1:
427
+ if st.button("πŸ“₯ Clone Repository"):
428
+ if github_token and source_repo:
429
+ try:
430
+ local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
431
+ download_github_repo(source_repo, local_path)
432
+ zip_filename = f"{new_repo_name}.zip"
433
+ create_zip_file(local_path, zip_filename[:-4])
434
+ st.markdown(get_base64_download_link(zip_filename, zip_filename), unsafe_allow_html=True)
435
+ st.success("Repository cloned successfully! πŸŽ‰")
436
+ except Exception as e:
437
+ st.error(f"An error occurred: {str(e)} 😒")
438
+ finally:
439
+ if os.path.exists(local_path):
440
+ shutil.rmtree(local_path)
441
+ if os.path.exists(zip_filename):
442
+ os.remove(zip_filename)
443
+ else:
444
+ st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
445
+
446
+ with col2:
447
+ if st.button("πŸ“€ Push to New Repository"):
448
+ if github_token and source_repo:
449
+ try:
450
+ g = Github(github_token)
451
+ new_repo = create_repo(g, new_repo_name)
452
+ local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
453
+ download_github_repo(source_repo, local_path)
454
+ push_to_github(local_path, new_repo, github_token)
455
+ st.success(f"Repository pushed successfully to {new_repo.html_url} πŸš€")
456
+ except Exception as e:
457
+ st.error(f"An error occurred: {str(e)} 😒")
458
+ finally:
459
+ if os.path.exists(local_path):
460
+ shutil.rmtree(local_path)
461
+ else:
462
+ st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
463
+
464
+ except exceptions.CosmosHttpResponseError as e:
465
+ st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
466
+ except Exception as e:
467
+ st.error(f"An unexpected error occurred: {str(e)} 😱")
468
+
469
+ # πŸšͺ Logout button
470
+ if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
471
+ st.session_state.logged_in = False
472
+ st.session_state.selected_records.clear()
473
+ st.session_state.client = None
474
+ st.session_state.selected_database = None
475
+ st.session_state.selected_container = None
476
+ st.session_state.selected_document_id = None
477
+ st.session_state.current_index = 0
478
+ st.rerun()
479
+
480
+ if __name__ == "__main__":
481
+ main()