awacke1 commited on
Commit
b827b8b
·
verified ·
1 Parent(s): 4b123de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -308
app.py CHANGED
@@ -7,11 +7,6 @@ import json
7
  import os
8
  import pandas as pd
9
  import pytz
10
-
11
-
12
-
13
-
14
-
15
  import random
16
  import re
17
  import shutil
@@ -25,21 +20,10 @@ from azure.cosmos import CosmosClient, exceptions
25
  from datetime import datetime
26
  from git import Repo
27
  from github import Github
28
-
29
  from gradio_client import Client
30
  from urllib.parse import quote
31
 
32
 
33
- # Add these imports at the top of your file
34
- from gradio_client import Client, handle_file
35
- import tempfile
36
- from PIL import Image
37
- import io
38
- import requests
39
- import numpy as np
40
-
41
-
42
-
43
  # 🎭 App Configuration - Because every app needs a good costume!
44
  Site_Name = '🐙GitCosmos🌌 - AI Azure Cosmos DB and Github Agent'
45
  title = "🐙GitCosmos🌌 - AI Azure Cosmos DB and Github Agent"
@@ -244,7 +228,6 @@ def save_to_cosmos_db(container, query, response1, response2):
244
 
245
 
246
  def save_to_cosmos_db_old(container, query, response1, response2):
247
-
248
  try:
249
  if container:
250
  record = {
@@ -574,9 +557,6 @@ def load_file_content(file_path):
574
  try:
575
  with open(file_path, 'r', encoding='utf-8') as file:
576
  return file.read()
577
-
578
-
579
-
580
  except Exception as e:
581
  st.error(f"Error loading file: {str(e)}")
582
  return None
@@ -763,11 +743,6 @@ def update_file_management_section():
763
 
764
  with col2:
765
  st.markdown(get_download_link(file), unsafe_allow_html=True)
766
-
767
-
768
-
769
-
770
-
771
 
772
  with col3:
773
  if st.button("📂", key=f"edit_{file}"):
@@ -797,233 +772,8 @@ def update_file_management_section():
797
  display_file_editor(st.session_state.current_file)
798
 
799
 
800
- # Function to create HTML for autoplaying and looping video (for the full cinematic effect 🎥)
801
- def get_video_html(video_path, width="100%"):
802
- video_url = f"data:video/mp4;base64,{base64.b64encode(open(video_path, 'rb').read()).decode()}"
803
- return f'''
804
- <video width="{width}" controls autoplay muted loop>
805
- <source src="{video_url}" type="video/mp4">
806
- Your browser does not support the video tag.
807
- </video>
808
- '''
809
-
810
-
811
-
812
-
813
- # *********
814
- def validate_and_preprocess_image(file_data, target_size=(576, 1024)):
815
- """Validate and preprocess image for video generation with improved BytesIO handling"""
816
- try:
817
- st.write("Starting image preprocessing...")
818
-
819
- # Handle different input types
820
- if isinstance(file_data, bytes):
821
- st.write("Processing bytes input")
822
- img = Image.open(io.BytesIO(file_data))
823
- elif hasattr(file_data, 'read'):
824
- st.write("Processing file-like object")
825
- # Reset file pointer if possible
826
- if hasattr(file_data, 'seek'):
827
- file_data.seek(0)
828
- img = Image.open(file_data)
829
- elif isinstance(file_data, Image.Image):
830
- st.write("Processing PIL Image input")
831
- img = file_data
832
- else:
833
- raise ValueError(f"Unsupported input type: {type(file_data)}")
834
-
835
- st.write(f"Successfully loaded image: {img.format}, size={img.size}, mode={img.mode}")
836
-
837
- # Convert to RGB if necessary
838
- if img.mode != 'RGB':
839
- st.write(f"Converting image from {img.mode} to RGB")
840
- img = img.convert('RGB')
841
-
842
- # Calculate aspect ratio
843
- aspect_ratio = img.size[0] / img.size[1]
844
- st.write(f"Original aspect ratio: {aspect_ratio:.2f}")
845
-
846
- # Determine target dimensions maintaining aspect ratio
847
- if aspect_ratio > target_size[0]/target_size[1]: # Wider than target
848
- new_width = target_size[0]
849
- new_height = int(new_width / aspect_ratio)
850
- else: # Taller than target
851
- new_height = target_size[1]
852
- new_width = int(new_height * aspect_ratio)
853
-
854
- # Ensure dimensions are even numbers
855
- new_width = (new_width // 2) * 2
856
- new_height = (new_height // 2) * 2
857
-
858
- st.write(f"Resizing to: {new_width}x{new_height}")
859
-
860
- # Resize image using high-quality downsampling
861
- resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
862
-
863
- # Create white background image of target size
864
- final_img = Image.new('RGB', target_size, (255, 255, 255))
865
-
866
- # Calculate position to paste resized image (center)
867
- paste_x = (target_size[0] - new_width) // 2
868
- paste_y = (target_size[1] - new_height) // 2
869
-
870
- # Paste resized image onto white background
871
- final_img.paste(resized_img, (paste_x, paste_y))
872
-
873
- st.write(f"Final image size: {final_img.size}")
874
- return final_img
875
-
876
- except Exception as e:
877
- st.error(f"Error in image preprocessing: {str(e)}\nType of input: {type(file_data)}")
878
- return None
879
-
880
- def add_video_generation_ui(container):
881
- """Enhanced video generation UI with improved file handling"""
882
- st.markdown("### 🎥 Video Generation")
883
-
884
- col1, col2 = st.columns([2, 1])
885
-
886
- with col1:
887
- uploaded_file = st.file_uploader(
888
- "Upload Image for Video Generation 🖼️",
889
- type=['png', 'jpg', 'jpeg'],
890
- help="Upload a clear, well-lit image. Recommended size: 576x1024 pixels."
891
- )
892
-
893
- with col2:
894
- st.markdown("#### Generation Parameters")
895
- motion_bucket_id = st.slider(
896
- "Motion Intensity 🌊",
897
- min_value=1,
898
- max_value=255,
899
- value=127,
900
- help="Lower values create subtle movement, higher values create more dramatic motion"
901
- )
902
- fps_id = st.slider(
903
- "Frames per Second 🎬",
904
- min_value=1,
905
- max_value=30,
906
- value=6,
907
- help="Higher values create smoother but potentially less stable videos"
908
- )
909
-
910
- with st.expander("Advanced Options"):
911
- use_custom_seed = st.checkbox("Use Custom Seed")
912
- if use_custom_seed:
913
- seed = st.number_input("Seed Value", value=int(time.time() * 1000))
914
- else:
915
- seed = None
916
 
917
- if uploaded_file is not None:
918
- try:
919
- # Read file data
920
- file_data = uploaded_file.read()
921
-
922
- # Preview original image
923
- preview_col1, preview_col2 = st.columns(2)
924
- with preview_col1:
925
- st.write("Original Image:")
926
- original_img = Image.open(io.BytesIO(file_data))
927
- st.image(original_img, caption="Original", use_column_width=True)
928
-
929
- # Preview preprocessed image
930
- with preview_col2:
931
- # Create a new BytesIO object with the file data
932
- preprocessed = validate_and_preprocess_image(io.BytesIO(file_data))
933
- if preprocessed:
934
- st.write("Preprocessed Image:")
935
- st.image(preprocessed, caption="Preprocessed", use_column_width=True)
936
- else:
937
- st.error("Failed to preprocess image")
938
- return
939
-
940
- if st.button("🎥 Generate Video", help="Start video generation process"):
941
- with st.spinner("Processing your video... This may take a few minutes 🎬"):
942
- # Save preprocessed image to temporary file
943
- with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_file:
944
- preprocessed.save(temp_file.name, format='PNG')
945
- st.write(f"Saved preprocessed image to temporary file: {temp_file.name}")
946
-
947
- try:
948
- # Initialize the Gradio client
949
- client = Client(
950
- "awacke1/stable-video-diffusion",
951
- hf_token=os.environ.get("HUGGINGFACE_TOKEN")
952
- )
953
-
954
- # Generate video
955
- result = client.predict(
956
- image=temp_file.name,
957
- seed=seed if seed is not None else int(time.time() * 1000),
958
- randomize_seed=seed is None,
959
- motion_bucket_id=motion_bucket_id,
960
- fps_id=fps_id,
961
- api_name="/video"
962
- )
963
-
964
- if result and isinstance(result, tuple) and len(result) >= 1:
965
- video_path = result[0].get('video') if isinstance(result[0], dict) else None
966
- if video_path and os.path.exists(video_path):
967
- # Save video locally
968
- video_filename = f"generated_video_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
969
- shutil.copy(video_path, video_filename)
970
-
971
- st.success(f"""
972
- Video generated successfully! 🎉
973
- - Seed: {seed if seed is not None else 'Random'}
974
- - Motion Intensity: {motion_bucket_id}
975
- - FPS: {fps_id}
976
- """)
977
-
978
- st.video(video_filename)
979
-
980
- # Save to Cosmos DB
981
- if container:
982
- video_record = {
983
- "id": generate_unique_id(),
984
- "type": "generated_video",
985
- "filename": video_filename,
986
- "seed": seed if seed is not None else "random",
987
- "motion_bucket_id": motion_bucket_id,
988
- "fps_id": fps_id,
989
- "timestamp": datetime.now().isoformat()
990
- }
991
- success, message = insert_record(container, video_record)
992
- if success:
993
- st.success("Video record saved to database!")
994
- else:
995
- st.error(f"Error saving video record: {message}")
996
- else:
997
- st.error("Failed to generate video: Invalid result format")
998
- else:
999
- st.error("Failed to generate video: No result returned")
1000
-
1001
- except Exception as e:
1002
- st.error(f"Error generating video: {str(e)}")
1003
- finally:
1004
- # Cleanup temporary file
1005
- try:
1006
- os.unlink(temp_file.name)
1007
- st.write("Cleaned up temporary file")
1008
- except Exception as e:
1009
- st.warning(f"Error cleaning up temporary file: {str(e)}")
1010
 
1011
- except Exception as e:
1012
- st.error(f"Error processing uploaded file: {str(e)}")
1013
-
1014
-
1015
- # ******************************************
1016
-
1017
- # Function to create HTML for audio player (when life needs a soundtrack 🎶)
1018
- def get_audio_html(audio_path, width="100%"):
1019
- audio_url = f"data:audio/mpeg;base64,{base64.b64encode(open(audio_path, 'rb').read()).decode()}"
1020
- return f'''
1021
- <audio controls style="width: {width};">
1022
- <source src="{audio_url}" type="audio/mpeg">
1023
- Your browser does not support the audio element.
1024
- </audio>
1025
- '''
1026
-
1027
  # 🎭 Main function - "All the world's a stage, and all the code merely players" -Shakespeare, probably
1028
  def main():
1029
  st.markdown("### 🐙Git🌌Cosmos💫 - Azure Cosmos DB and Github Agent")
@@ -1286,6 +1036,56 @@ def main():
1286
  except Exception as e:
1287
  st.error(f"Error processing deletion: {str(e)}")
1288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1289
 
1290
 
1291
 
@@ -1313,12 +1113,6 @@ def main():
1313
 
1314
  # Save and AI operations columns
1315
 
1316
-
1317
- # Video Generator call - the video generation UI for container:
1318
- add_video_generation_ui(container)
1319
-
1320
-
1321
-
1322
  if st.button("🤖 Run AI", key=f'run_with_ai_button_{idx}'):
1323
  # Your existing AI processing code here
1324
  values_with_space = []
@@ -1352,48 +1146,7 @@ def main():
1352
  except Exception as e:
1353
  st.error(f"Error saving document: {str(e)}")
1354
 
1355
-
1356
- # File Editor (When you need to tweak things ✏️)
1357
- if hasattr(st.session_state, 'current_file'):
1358
- st.subheader(f"Editing: {st.session_state.current_file} 🛠")
1359
- new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
1360
- if st.button("Save Changes 💾"):
1361
- with open(st.session_state.current_file, 'w', encoding='utf-8') as file:
1362
- file.write(new_content)
1363
- st.success("File updated successfully! 🎉")
1364
-
1365
- # Image Gallery (For your viewing pleasure 📸)
1366
- st.subheader("Image Gallery 🖼")
1367
- image_files = glob.glob("*.png") + glob.glob("*.jpg") + glob.glob("*.jpeg")
1368
- image_cols = st.slider("Gallery Columns 🖼", min_value=1, max_value=15, value=5)
1369
- cols = st.columns(image_cols)
1370
- for idx, image_file in enumerate(image_files):
1371
- with cols[idx % image_cols]:
1372
- img = Image.open(image_file)
1373
- #st.image(img, caption=image_file, use_column_width=True)
1374
- st.image(img, use_column_width=True)
1375
- display_glossary_entity(os.path.splitext(image_file)[0])
1376
-
1377
- # Video Gallery (Let’s roll the tapes 🎬)
1378
- st.subheader("Video Gallery 🎥")
1379
- video_files = glob.glob("*.mp4")
1380
- video_cols = st.slider("Gallery Columns 🎬", min_value=1, max_value=5, value=3)
1381
- cols = st.columns(video_cols)
1382
- for idx, video_file in enumerate(video_files):
1383
- with cols[idx % video_cols]:
1384
- st.markdown(get_video_html(video_file, width="100%"), unsafe_allow_html=True)
1385
- display_glossary_entity(os.path.splitext(video_file)[0])
1386
-
1387
- # Audio Gallery (Tunes for the mood 🎶)
1388
- st.subheader("Audio Gallery 🎧")
1389
- audio_files = glob.glob("*.mp3") + glob.glob("*.wav")
1390
- audio_cols = st.slider("Gallery Columns 🎶", min_value=1, max_value=15, value=5)
1391
- cols = st.columns(audio_cols)
1392
- for idx, audio_file in enumerate(audio_files):
1393
- with cols[idx % audio_cols]:
1394
- st.markdown(get_audio_html(audio_file, width="100%"), unsafe_allow_html=True)
1395
- display_glossary_entity(os.path.splitext(audio_file)[0])
1396
-
1397
 
1398
 
1399
 
@@ -1624,15 +1377,6 @@ def main():
1624
  st.text_area("Claude replied 🤖:", chat["claude"], height=200, disabled=True)
1625
  st.markdown("---")
1626
 
1627
-
1628
-
1629
-
1630
-
1631
-
1632
-
1633
-
1634
-
1635
-
1636
 
1637
  # 📝 File editor - "Edit with care, save with flair"
1638
  if hasattr(st.session_state, 'current_file'):
@@ -1669,6 +1413,5 @@ def main():
1669
  st.session_state.current_index = 0
1670
  st.rerun()
1671
 
1672
-
1673
  if __name__ == "__main__":
1674
  main()
 
7
  import os
8
  import pandas as pd
9
  import pytz
 
 
 
 
 
10
  import random
11
  import re
12
  import shutil
 
20
  from datetime import datetime
21
  from git import Repo
22
  from github import Github
 
23
  from gradio_client import Client
24
  from urllib.parse import quote
25
 
26
 
 
 
 
 
 
 
 
 
 
 
27
  # 🎭 App Configuration - Because every app needs a good costume!
28
  Site_Name = '🐙GitCosmos🌌 - AI Azure Cosmos DB and Github Agent'
29
  title = "🐙GitCosmos🌌 - AI Azure Cosmos DB and Github Agent"
 
228
 
229
 
230
  def save_to_cosmos_db_old(container, query, response1, response2):
 
231
  try:
232
  if container:
233
  record = {
 
557
  try:
558
  with open(file_path, 'r', encoding='utf-8') as file:
559
  return file.read()
 
 
 
560
  except Exception as e:
561
  st.error(f"Error loading file: {str(e)}")
562
  return None
 
743
 
744
  with col2:
745
  st.markdown(get_download_link(file), unsafe_allow_html=True)
 
 
 
 
 
746
 
747
  with col3:
748
  if st.button("📂", key=f"edit_{file}"):
 
772
  display_file_editor(st.session_state.current_file)
773
 
774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
775
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777
  # 🎭 Main function - "All the world's a stage, and all the code merely players" -Shakespeare, probably
778
  def main():
779
  st.markdown("### 🐙Git🌌Cosmos💫 - Azure Cosmos DB and Github Agent")
 
1036
  except Exception as e:
1037
  st.error(f"Error processing deletion: {str(e)}")
1038
 
1039
+ elif selected_view == 'Show as Code Editor - Old':
1040
+ Label = '#### 💻 Code editor view'
1041
+ st.markdown(Label)
1042
+ total_docs = len(documents)
1043
+ doc = documents[st.session_state.current_index]
1044
+ # st.markdown(f"#### Document ID: {doc.get('id', '')}")
1045
+ doc_str = st.text_area("Edit Document",
1046
+ value=json.dumps(doc, indent=2),
1047
+ height=300,
1048
+ key=f'code_editor_{st.session_state.current_index}')
1049
+
1050
+ col_prev, col_next = st.columns([1, 1])
1051
+ with col_prev:
1052
+ if st.button("⬅️ Previous", key='prev_code'):
1053
+ if st.session_state.current_index > 0:
1054
+ st.session_state.current_index -= 1
1055
+ st.rerun()
1056
+ with col_next:
1057
+ if st.button("➡️ Next", key='next_code'):
1058
+ if st.session_state.current_index < total_docs - 1:
1059
+ st.session_state.current_index += 1
1060
+ st.rerun()
1061
+
1062
+ col_save, col_delete = st.columns([1, 1])
1063
+ with col_save:
1064
+ if st.button("💾 Save Changes", key=f'save_button_{st.session_state.current_index}'):
1065
+ try:
1066
+ updated_doc = json.loads(doc_str)
1067
+ response = container.upsert_item(body=updated_doc)
1068
+ if response:
1069
+ st.success(f"Document {updated_doc['id']} saved successfully.")
1070
+ st.session_state.selected_document_id = updated_doc['id']
1071
+ st.rerun()
1072
+ except Exception as e:
1073
+ st.error(f"Error saving document: {str(e)}")
1074
+
1075
+ with col_delete:
1076
+ if st.button("🗑️ Delete", key=f'delete_button_{st.session_state.current_index}'):
1077
+ try:
1078
+ current_doc = json.loads(doc_str)
1079
+ # Direct deletion using container method with id and partition key
1080
+ delete = container.delete_item(current_doc["id"], current_doc["id"])
1081
+ if delete:
1082
+ st.success(f"Document {current_doc['id']} deleted successfully.")
1083
+ if st.session_state.current_index > 0:
1084
+ st.session_state.current_index -= 1
1085
+ st.rerun()
1086
+ except Exception as e:
1087
+ st.error(f"Error deleting document: {str(e)}")
1088
+
1089
 
1090
 
1091
 
 
1113
 
1114
  # Save and AI operations columns
1115
 
 
 
 
 
 
 
1116
  if st.button("🤖 Run AI", key=f'run_with_ai_button_{idx}'):
1117
  # Your existing AI processing code here
1118
  values_with_space = []
 
1146
  except Exception as e:
1147
  st.error(f"Error saving document: {str(e)}")
1148
 
1149
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1150
 
1151
 
1152
 
 
1377
  st.text_area("Claude replied 🤖:", chat["claude"], height=200, disabled=True)
1378
  st.markdown("---")
1379
 
 
 
 
 
 
 
 
 
 
1380
 
1381
  # 📝 File editor - "Edit with care, save with flair"
1382
  if hasattr(st.session_state, 'current_file'):
 
1413
  st.session_state.current_index = 0
1414
  st.rerun()
1415
 
 
1416
  if __name__ == "__main__":
1417
  main()