awacke1 commited on
Commit
5cc2332
Β·
verified Β·
1 Parent(s): e8fe3a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -57
app.py CHANGED
@@ -11,17 +11,17 @@ from PIL import Image
11
  import re
12
  from urllib.parse import quote
13
 
14
- # 1. Configuration
15
- Site_Name = 'πŸ€–πŸ§ AntπŸ”¬ClaudeπŸ“'
16
- title="πŸ€–πŸ§ AntπŸ”¬ClaudeπŸ“"
17
  helpURL='https://huggingface.co/awacke1'
18
  bugURL='https://huggingface.co/spaces/awacke1'
19
  icons='πŸ€–πŸ§ πŸ”¬πŸ“'
 
20
  st.set_page_config(
21
  page_title=title,
22
  page_icon=icons,
23
  layout="wide",
24
- #initial_sidebar_state="expanded",
25
  initial_sidebar_state="auto",
26
  menu_items={
27
  'Get Help': helpURL,
@@ -37,36 +37,37 @@ client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
37
  if "chat_history" not in st.session_state:
38
  st.session_state.chat_history = []
39
 
40
- # Function to get file download link
 
 
41
  def get_download_link(file_path):
42
  with open(file_path, "rb") as file:
43
  contents = file.read()
44
  b64 = base64.b64encode(contents).decode()
45
  file_name = os.path.basename(file_path)
46
- return f'<a href="data:file/txt;base64,{b64}" download="{file_name}">Download {file_name}</a>'
47
 
48
- # Function to generate filename
49
  def generate_filename(prompt, file_type):
50
  central = pytz.timezone('US/Central')
51
  safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
52
- replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
53
- safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:90]
54
  return f"{safe_date_time}_{safe_prompt}.{file_type}"
55
 
56
- # Function to create file
57
  def create_file(filename, prompt, response, should_save=True):
58
  if not should_save:
59
  return
60
  with open(filename, 'w', encoding='utf-8') as file:
61
  file.write(prompt + "\n\n" + response)
62
 
63
- # Function to load file content
64
  def load_file(file_name):
65
  with open(file_name, "r", encoding='utf-8') as file:
66
  content = file.read()
67
  return content
68
 
69
- # Function to display glossary entity
70
  def display_glossary_entity(k):
71
  search_urls = {
72
  "πŸš€πŸŒŒArXiv": lambda k: f"/?q={quote(k)}",
@@ -77,7 +78,7 @@ def display_glossary_entity(k):
77
  links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
78
  st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
79
 
80
- # Function to create zip of files
81
  def create_zip_of_files(files):
82
  import zipfile
83
  zip_name = "all_files.zip"
@@ -86,15 +87,7 @@ def create_zip_of_files(files):
86
  zipf.write(file)
87
  return zip_name
88
 
89
- # Function to get zip download link
90
- def get_zip_download_link(zip_file):
91
- with open(zip_file, 'rb') as f:
92
- data = f.read()
93
- b64 = base64.b64encode(data).decode()
94
- href = f'<a href="data:application/zip;base64,{b64}" download="{zip_file}">Download All</a>'
95
- return href
96
-
97
- # Function to create HTML for autoplaying and looping video
98
  def get_video_html(video_path, width="100%"):
99
  video_url = f"data:video/mp4;base64,{base64.b64encode(open(video_path, 'rb').read()).decode()}"
100
  return f'''
@@ -104,7 +97,7 @@ def get_video_html(video_path, width="100%"):
104
  </video>
105
  '''
106
 
107
- # Function to create HTML for audio player
108
  def get_audio_html(audio_path, width="100%"):
109
  audio_url = f"data:audio/mpeg;base64,{base64.b64encode(open(audio_path, 'rb').read()).decode()}"
110
  return f'''
@@ -115,17 +108,14 @@ def get_audio_html(audio_path, width="100%"):
115
  '''
116
 
117
 
118
-
119
- # Streamlit app
120
  def main():
121
 
122
- # Sidebar
123
- st.sidebar.title("πŸ€–πŸ§ AntπŸ”¬ClaudeπŸ“πŸ”Š - Anthropic Claude 3.5 Sonnet")
124
 
125
- # File management
126
  all_files = glob.glob("*.md")
127
- all_files = [file for file in all_files if len(os.path.splitext(file)[0]) >= 10]
128
- all_files.sort(key=lambda x: (os.path.splitext(x)[1], x), reverse=True)
129
 
130
  if st.sidebar.button("πŸ—‘ Delete All"):
131
  for file in all_files:
@@ -134,7 +124,7 @@ def main():
134
 
135
  if st.sidebar.button("⬇️ Download All"):
136
  zip_file = create_zip_of_files(all_files)
137
- st.sidebar.markdown(get_zip_download_link(zip_file), unsafe_allow_html=True)
138
 
139
  for file in all_files:
140
  col1, col2, col3, col4 = st.sidebar.columns([1,3,1,1])
@@ -153,10 +143,10 @@ def main():
153
  os.remove(file)
154
  st.rerun()
155
 
156
- # Main content area
157
- user_input = st.text_area("Enter your message:", height=100)
158
 
159
- if st.button("Send"):
160
  if user_input:
161
  response = client.messages.create(
162
  model="claude-3-sonnet-20240229",
@@ -165,58 +155,56 @@ def main():
165
  {"role": "user", "content": user_input}
166
  ]
167
  )
168
-
169
- st.write("Claude's response:")
170
  st.write(response.content[0].text)
171
 
172
- # Save response to file
173
  filename = generate_filename(user_input, "md")
174
  create_file(filename, user_input, response.content[0].text)
175
 
176
- # Add to chat history
177
  st.session_state.chat_history.append({"user": user_input, "claude": response.content[0].text})
178
 
179
- # Display chat history
180
- st.subheader("Chat History")
181
  for chat in st.session_state.chat_history:
182
- st.text_area("You:", chat["user"], height=100, disabled=True)
183
- st.text_area("Claude:", chat["claude"], height=200, disabled=True)
184
  st.markdown("---")
185
 
186
- # File content viewer/editor
187
  if hasattr(st.session_state, 'current_file'):
188
- st.subheader(f"Editing: {st.session_state.current_file}")
189
- new_content = st.text_area("File Content:", st.session_state.file_content, height=300)
190
- if st.button("Save Changes"):
191
  with open(st.session_state.current_file, 'w', encoding='utf-8') as file:
192
  file.write(new_content)
193
- st.success("File updated successfully!")
194
 
195
- # Image Gallery
196
- st.subheader("Image Gallery")
197
  image_files = glob.glob("*.png") + glob.glob("*.jpg") + glob.glob("*.jpeg")
198
- image_cols = st.slider("Image Gallery Columns", min_value=1, max_value=5, value=3)
199
  cols = st.columns(image_cols)
200
  for idx, image_file in enumerate(image_files):
201
  with cols[idx % image_cols]:
202
  img = Image.open(image_file)
203
- st.image(img, caption=image_file, use_column_width=True)
 
204
  display_glossary_entity(os.path.splitext(image_file)[0])
205
 
206
- # Video Gallery
207
- st.subheader("Video Gallery")
208
  video_files = glob.glob("*.mp4")
209
- video_cols = st.slider("Video Gallery Columns", min_value=1, max_value=5, value=3)
210
  cols = st.columns(video_cols)
211
  for idx, video_file in enumerate(video_files):
212
  with cols[idx % video_cols]:
213
  st.markdown(get_video_html(video_file, width="100%"), unsafe_allow_html=True)
214
  display_glossary_entity(os.path.splitext(video_file)[0])
215
 
216
- # Audio Gallery
217
- st.subheader("Audio Gallery")
218
  audio_files = glob.glob("*.mp3") + glob.glob("*.wav")
219
- audio_cols = st.slider("Audio Gallery Columns", min_value=1, max_value=5, value=3)
220
  cols = st.columns(audio_cols)
221
  for idx, audio_file in enumerate(audio_files):
222
  with cols[idx % audio_cols]:
 
11
  import re
12
  from urllib.parse import quote
13
 
14
+ # 1. App Configuration
15
+ Site_Name = 'πŸ€–πŸ§ Claude35πŸ“πŸ”¬'
16
+ title="πŸ€–πŸ§ Claude35πŸ“πŸ”¬"
17
  helpURL='https://huggingface.co/awacke1'
18
  bugURL='https://huggingface.co/spaces/awacke1'
19
  icons='πŸ€–πŸ§ πŸ”¬πŸ“'
20
+
21
  st.set_page_config(
22
  page_title=title,
23
  page_icon=icons,
24
  layout="wide",
 
25
  initial_sidebar_state="auto",
26
  menu_items={
27
  'Get Help': helpURL,
 
37
  if "chat_history" not in st.session_state:
38
  st.session_state.chat_history = []
39
 
40
+ # Helper Functions: All Your Essentials πŸš€
41
+
42
+ # Function to get a file download link (because you deserve easy downloads 😎)
43
  def get_download_link(file_path):
44
  with open(file_path, "rb") as file:
45
  contents = file.read()
46
  b64 = base64.b64encode(contents).decode()
47
  file_name = os.path.basename(file_path)
48
+ return f'<a href="data:file/txt;base64,{b64}" download="{file_name}">Download {file_name}πŸ“‚</a>'
49
 
50
+ # Function to generate a filename based on prompt and time (because names matter πŸ•’)
51
  def generate_filename(prompt, file_type):
52
  central = pytz.timezone('US/Central')
53
  safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
54
+ safe_prompt = re.sub(r'\W+', '_', prompt)[:90]
 
55
  return f"{safe_date_time}_{safe_prompt}.{file_type}"
56
 
57
+ # Function to create and save a file (and avoid the black hole of lost data πŸ•³)
58
  def create_file(filename, prompt, response, should_save=True):
59
  if not should_save:
60
  return
61
  with open(filename, 'w', encoding='utf-8') as file:
62
  file.write(prompt + "\n\n" + response)
63
 
64
+ # Function to load file content (for revisiting the past πŸ“œ)
65
  def load_file(file_name):
66
  with open(file_name, "r", encoding='utf-8') as file:
67
  content = file.read()
68
  return content
69
 
70
+ # Function to display handy glossary entity links (search like a pro πŸ”)
71
  def display_glossary_entity(k):
72
  search_urls = {
73
  "πŸš€πŸŒŒArXiv": lambda k: f"/?q={quote(k)}",
 
78
  links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
79
  st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
80
 
81
+ # Function to create zip of files (because more is more 🧳)
82
  def create_zip_of_files(files):
83
  import zipfile
84
  zip_name = "all_files.zip"
 
87
  zipf.write(file)
88
  return zip_name
89
 
90
+ # Function to create HTML for autoplaying and looping video (for the full cinematic effect πŸŽ₯)
 
 
 
 
 
 
 
 
91
  def get_video_html(video_path, width="100%"):
92
  video_url = f"data:video/mp4;base64,{base64.b64encode(open(video_path, 'rb').read()).decode()}"
93
  return f'''
 
97
  </video>
98
  '''
99
 
100
+ # Function to create HTML for audio player (when life needs a soundtrack 🎢)
101
  def get_audio_html(audio_path, width="100%"):
102
  audio_url = f"data:audio/mpeg;base64,{base64.b64encode(open(audio_path, 'rb').read()).decode()}"
103
  return f'''
 
108
  '''
109
 
110
 
111
+ # Streamlit App Layout (like a house with better flow 🏑)
 
112
  def main():
113
 
114
+ # Sidebar with Useful Controls (All the VIP actions πŸŽ›)
115
+ st.sidebar.title("🧠ClaudeπŸ“")
116
 
 
117
  all_files = glob.glob("*.md")
118
+ all_files.sort(reverse=True)
 
119
 
120
  if st.sidebar.button("πŸ—‘ Delete All"):
121
  for file in all_files:
 
124
 
125
  if st.sidebar.button("⬇️ Download All"):
126
  zip_file = create_zip_of_files(all_files)
127
+ st.sidebar.markdown(get_download_link(zip_file), unsafe_allow_html=True)
128
 
129
  for file in all_files:
130
  col1, col2, col3, col4 = st.sidebar.columns([1,3,1,1])
 
143
  os.remove(file)
144
  st.rerun()
145
 
146
+ # Main Area: Chat with Claude (He’s a good listener πŸ’¬)
147
+ user_input = st.text_area("Message πŸ“¨:", height=100)
148
 
149
+ if st.button("Send πŸ“¨"):
150
  if user_input:
151
  response = client.messages.create(
152
  model="claude-3-sonnet-20240229",
 
155
  {"role": "user", "content": user_input}
156
  ]
157
  )
158
+ st.write("Claude's reply 🧠:")
 
159
  st.write(response.content[0].text)
160
 
 
161
  filename = generate_filename(user_input, "md")
162
  create_file(filename, user_input, response.content[0].text)
163
 
 
164
  st.session_state.chat_history.append({"user": user_input, "claude": response.content[0].text})
165
 
166
+ # Display Chat History (Never forget a good chat πŸ’­)
167
+ st.subheader("Past Conversations πŸ“œ")
168
  for chat in st.session_state.chat_history:
169
+ st.text_area("You said πŸ’¬:", chat["user"], height=100, disabled=True)
170
+ st.text_area("Claude replied πŸ€–:", chat["claude"], height=200, disabled=True)
171
  st.markdown("---")
172
 
173
+ # File Editor (When you need to tweak things ✏️)
174
  if hasattr(st.session_state, 'current_file'):
175
+ st.subheader(f"Editing: {st.session_state.current_file} πŸ› ")
176
+ new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
177
+ if st.button("Save Changes πŸ’Ύ"):
178
  with open(st.session_state.current_file, 'w', encoding='utf-8') as file:
179
  file.write(new_content)
180
+ st.success("File updated successfully! πŸŽ‰")
181
 
182
+ # Image Gallery (For your viewing pleasure πŸ“Έ)
183
+ st.subheader("Image Gallery πŸ–Ό")
184
  image_files = glob.glob("*.png") + glob.glob("*.jpg") + glob.glob("*.jpeg")
185
+ image_cols = st.slider("Gallery Columns πŸ–Ό", min_value=1, max_value=15, value=5)
186
  cols = st.columns(image_cols)
187
  for idx, image_file in enumerate(image_files):
188
  with cols[idx % image_cols]:
189
  img = Image.open(image_file)
190
+ #st.image(img, caption=image_file, use_column_width=True)
191
+ st.image(img, use_column_width=True)
192
  display_glossary_entity(os.path.splitext(image_file)[0])
193
 
194
+ # Video Gallery (Let’s roll the tapes 🎬)
195
+ st.subheader("Video Gallery πŸŽ₯")
196
  video_files = glob.glob("*.mp4")
197
+ video_cols = st.slider("Gallery Columns 🎬", min_value=1, max_value=5, value=3)
198
  cols = st.columns(video_cols)
199
  for idx, video_file in enumerate(video_files):
200
  with cols[idx % video_cols]:
201
  st.markdown(get_video_html(video_file, width="100%"), unsafe_allow_html=True)
202
  display_glossary_entity(os.path.splitext(video_file)[0])
203
 
204
+ # Audio Gallery (Tunes for the mood 🎢)
205
+ st.subheader("Audio Gallery 🎧")
206
  audio_files = glob.glob("*.mp3") + glob.glob("*.wav")
207
+ audio_cols = st.slider("Gallery Columns 🎢", min_value=1, max_value=15, value=5)
208
  cols = st.columns(audio_cols)
209
  for idx, audio_file in enumerate(audio_files):
210
  with cols[idx % audio_cols]: