awacke1 commited on
Commit
a587e1f
Β·
verified Β·
1 Parent(s): 8d67e66

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -150
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import streamlit as st
2
- from streamlit.components.v1 import components
3
  from pathlib import Path
4
  import json
5
  import time
@@ -15,18 +15,28 @@ import glob
15
  import os
16
  import zipfile
17
 
18
- # Initialize session state for chat history if not exists
19
- if 'chat_history' not in st.session_state:
20
- st.session_state.chat_history = []
21
- if 'messages' not in st.session_state:
22
- st.session_state.messages = []
23
- if 'current_file' not in st.session_state:
24
- st.session_state.current_file = None
25
- if 'file_content' not in st.session_state:
26
- st.session_state.file_content = None
 
 
 
 
 
 
 
 
 
 
27
 
28
  def create_zip_of_files(files):
29
- """Create a zip file containing all markdown files"""
30
  zip_buffer = BytesIO()
31
  with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
32
  for file in files:
@@ -53,21 +63,51 @@ def load_file(filepath):
53
  with open(filepath, 'r', encoding='utf-8') as f:
54
  return f.read()
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  def display_file_manager():
57
  """Display file management sidebar with guaranteed unique button keys."""
58
  st.sidebar.title("πŸ“ File Management")
59
  all_files = glob.glob("*.md")
60
  all_files.sort(reverse=True)
61
 
62
- if st.sidebar.button("πŸ—‘ Delete All", key="delete_all_files_button"):
63
- for file in all_files:
64
- os.remove(file)
65
- st.rerun()
 
 
 
 
 
 
 
66
 
67
- if st.sidebar.button("⬇️ Download All", key="download_all_files_button"):
68
- zip_file = create_zip_of_files(all_files)
69
- st.sidebar.markdown(get_download_link(zip_file), unsafe_allow_html=True)
70
 
 
71
  for idx, file in enumerate(all_files):
72
  file_stat = os.stat(file)
73
  unique_id = f"{idx}_{file_stat.st_size}_{file_stat.st_mtime}"
@@ -88,151 +128,105 @@ def display_file_manager():
88
  os.remove(file)
89
  st.rerun()
90
 
91
- def process_with_gpt(user_input):
92
- """Process input with GPT-4"""
93
- # Add your GPT processing logic here
94
- response = f"GPT-4 Response to: {user_input}"
95
- st.session_state.messages.append({"role": "user", "content": user_input})
96
- st.session_state.messages.append({"role": "assistant", "content": response})
97
- return response
98
-
99
- def process_with_claude(user_input):
100
- """Process input with Claude"""
101
- # Add your Claude processing logic here
102
- response = f"Claude Response to: {user_input}"
103
- st.session_state.chat_history.append({
104
- "user": user_input,
105
- "claude": response
106
- })
107
- return response
108
-
109
- def perform_ai_lookup(query):
110
- """Perform AI lookup with ArXiv"""
111
- # Add your ArXiv lookup logic here
112
- return f"ArXiv results for: {query}"
113
-
114
- def search_arxiv(query):
115
- """Search ArXiv papers"""
116
- # Add your ArXiv search logic here
117
- return f"ArXiv search results for: {query}"
118
-
119
- def create_media_gallery():
120
- """Create media gallery interface"""
121
- st.subheader("Media Gallery")
122
- st.write("Media gallery functionality goes here")
123
-
124
- def show_chat_history():
125
- """Display chat history for both models"""
126
- st.subheader("Chat History πŸ“œ")
127
- tab1, tab2 = st.tabs(["Claude History", "GPT-4o History"])
128
 
129
  with tab1:
130
- for chat in st.session_state.chat_history:
131
- st.text_area("You:", chat["user"], height=100)
132
- st.text_area("Claude:", chat["claude"], height=200)
133
- st.markdown(chat["claude"])
 
 
 
 
 
 
134
 
135
  with tab2:
136
- for message in st.session_state.messages:
137
- with st.chat_message(message["role"]):
138
- st.markdown(message["content"])
139
-
140
- def handle_voice_input(model_choice):
141
- """Handle voice input tab logic"""
142
- st.subheader("Voice Recognition")
143
- if 'voice_transcript' not in st.session_state:
144
- st.session_state.voice_transcript = ""
145
 
146
- user_input = st.text_area("Message:", height=100)
147
- if st.button("Send πŸ“¨") and user_input:
148
- process_ai_input(user_input, model_choice)
149
-
150
- show_chat_history()
151
-
152
- def handle_file_editor():
153
- """Handle file editor tab logic"""
154
- if st.session_state.current_file:
155
- st.subheader(f"Editing: {st.session_state.current_file}")
156
- new_content = st.text_area("Content:", st.session_state.file_content, height=300)
157
- if st.button("Save Changes"):
158
- with open(st.session_state.current_file, 'w', encoding='utf-8') as file:
159
- file.write(new_content)
160
- st.success("File updated successfully!")
161
-
162
- def process_ai_input(user_input, model_choice):
163
- """Handle AI processing based on model choice"""
164
- if model_choice == "GPT-4o":
165
- gpt_response = process_with_gpt(user_input)
166
- elif model_choice == "Claude-3":
167
- claude_response = process_with_claude(user_input)
168
- else: # All Three AIs
169
- col1, col2, col3 = st.columns(3)
170
- with col2:
171
- st.subheader("Claude-3.5 Sonnet:")
172
- try:
173
- claude_response = process_with_claude(user_input)
174
- except:
175
- st.write('Claude 3.5 Sonnet out of tokens.')
176
- with col1:
177
- st.subheader("GPT-4o Omni:")
178
- try:
179
- gpt_response = process_with_gpt(user_input)
180
- except:
181
- st.write('GPT 4o out of tokens')
182
- with col3:
183
- st.subheader("Arxiv and Mistral Research:")
184
- with st.spinner("Searching ArXiv..."):
185
- try:
186
- results = perform_ai_lookup(user_input)
187
- st.markdown(results)
188
- except:
189
- st.write("Arxiv Mistral too busy - try again.")
190
 
191
- def handle_arxiv_search():
192
- """Handle ArXiv search tab logic"""
193
- query = st.text_input("Enter your research query:")
194
- if query:
195
- with st.spinner("Searching ArXiv..."):
196
- results = search_arxiv(query)
197
- st.markdown(results)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  def main():
200
- st.sidebar.markdown("### 🚲BikeAIπŸ† Claude and GPT Multi-Agent Research AI")
201
 
202
- # Display file manager in sidebar first
203
  display_file_manager()
204
 
205
- # Model Selection
206
- model_choice = st.sidebar.radio(
207
- "Choose AI Model:",
208
- ["GPT+Claude+Arxiv", "GPT-4o", "Claude-3"]
209
- )
210
 
211
- # Main navigation
212
- tab_main = st.radio("Choose Action:",
213
- ["🎀 Voice Input", "πŸ“Έ Media Gallery", "πŸ” Search ArXiv", "πŸ“ File Editor"],
214
- horizontal=True)
215
-
216
- try:
217
- # Component Magic section - wrapped in try/except in case component isn't available
218
- mycomponent = components.declare_component("mycomponent", path="mycomponent")
219
- value = mycomponent(my_input_value="hello there")
220
- st.write("Received", value)
221
 
222
- if value is not None:
223
- process_ai_input(value, model_choice)
224
- except:
225
- st.warning("Voice component not available")
226
-
227
- # Handle main tab navigation
228
- if tab_main == "🎀 Voice Input":
229
- handle_voice_input(model_choice)
230
- elif tab_main == "πŸ“Έ Media Gallery":
231
- create_media_gallery()
232
- elif tab_main == "πŸ” Search ArXiv":
233
- handle_arxiv_search()
234
- elif tab_main == "πŸ“ File Editor":
235
- handle_file_editor()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
  if __name__ == "__main__":
238
  main()
 
1
  import streamlit as st
2
+ from streamlit.components.v1 import html
3
  from pathlib import Path
4
  import json
5
  import time
 
15
  import os
16
  import zipfile
17
 
18
+ # File type definitions
19
+ FILE_TYPES = {
20
+ "md": "πŸ“ Markdown",
21
+ "txt": "πŸ“„ Text",
22
+ "json": "πŸ”§ JSON",
23
+ "csv": "πŸ“Š CSV",
24
+ "xlsx": "πŸ“— Excel",
25
+ "yaml": "βš™οΈ YAML",
26
+ "xml": "πŸ”— XML"
27
+ }
28
+
29
+ # Initialize session state
30
+ for key in ['file_data', 'file_types', 'md_outline', 'rendered_content',
31
+ 'file_history', 'md_versions', 'md_files_history', 'combined_markdown',
32
+ 'current_file', 'file_content']:
33
+ if key not in st.session_state:
34
+ st.session_state[key] = {} if key in ['file_data', 'file_types', 'md_outline',
35
+ 'rendered_content', 'md_versions'] else [] if key in ['file_history',
36
+ 'md_files_history'] else None if key in ['current_file', 'file_content'] else ""
37
 
38
  def create_zip_of_files(files):
39
+ """Create a zip file containing all files"""
40
  zip_buffer = BytesIO()
41
  with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
42
  for file in files:
 
63
  with open(filepath, 'r', encoding='utf-8') as f:
64
  return f.read()
65
 
66
+ def encode_content(content):
67
+ """Encode content to base64"""
68
+ return base64.b64encode(content.encode()).decode()
69
+
70
+ def decode_content(encoded_content):
71
+ """Decode content from base64"""
72
+ return base64.b64decode(encoded_content.encode()).decode()
73
+
74
+ def parse_markdown_outline(content):
75
+ """Generate an outline from markdown content"""
76
+ return [{'level': len(line.split()[0]), 'title': line.strip('#').strip(),
77
+ 'indent': ' ' * (len(line.split()[0]) - 1)}
78
+ for line in content.split('\n') if line.strip().startswith('#')]
79
+
80
+ def combine_markdown_files():
81
+ """Combine markdown files into a single document"""
82
+ all_files = glob.glob("*.md")
83
+ combined = []
84
+ for filepath in sorted(all_files):
85
+ with open(filepath, 'r', encoding='utf-8') as f:
86
+ content = f.read()
87
+ combined.append(f"# {filepath}\n\n{content}\n\n---\n\n")
88
+ return "".join(combined)
89
+
90
  def display_file_manager():
91
  """Display file management sidebar with guaranteed unique button keys."""
92
  st.sidebar.title("πŸ“ File Management")
93
  all_files = glob.glob("*.md")
94
  all_files.sort(reverse=True)
95
 
96
+ col1, col2 = st.sidebar.columns(2)
97
+ with col1:
98
+ if st.button("πŸ—‘ Delete All", key="delete_all_files_button"):
99
+ for file in all_files:
100
+ if file != "README.md": # Protect README.md
101
+ os.remove(file)
102
+ st.rerun()
103
+ with col2:
104
+ if st.button("⬇️ Download All", key="download_all_files_button"):
105
+ zip_file = create_zip_of_files(all_files)
106
+ st.sidebar.markdown(get_download_link(zip_file), unsafe_allow_html=True)
107
 
108
+ st.sidebar.markdown("---")
 
 
109
 
110
+ # Create unique keys using file attributes
111
  for idx, file in enumerate(all_files):
112
  file_stat = os.stat(file)
113
  unique_id = f"{idx}_{file_stat.st_size}_{file_stat.st_mtime}"
 
128
  os.remove(file)
129
  st.rerun()
130
 
131
+ def create_markdown_tabs(content, filename):
132
+ """Create tabs for markdown content viewing and editing"""
133
+ tab1, tab2 = st.tabs(["πŸ“ Editor", "πŸ‘€ Preview"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  with tab1:
136
+ edited_content = st.text_area("Edit your markdown", content, height=300,
137
+ key=f"edit_{filename}")
138
+ if edited_content != content:
139
+ st.session_state.file_data[filename] = edited_content
140
+ content = edited_content
141
+
142
+ if st.button("πŸ’Ύ Save"):
143
+ with open(filename, 'w', encoding='utf-8') as f:
144
+ f.write(edited_content)
145
+ st.success("✨ Saved successfully!")
146
 
147
  with tab2:
148
+ st.markdown(content, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
149
 
150
+ return content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
+ def read_file_content(uploaded_file):
153
+ """Smart file reader with enhanced markdown handling"""
154
+ file_type = uploaded_file.name.split('.')[-1].lower()
155
+ try:
156
+ if file_type == 'md':
157
+ content = uploaded_file.getvalue().decode()
158
+ with open(uploaded_file.name, 'w', encoding='utf-8') as f:
159
+ f.write(content)
160
+ return content, "md"
161
+ elif file_type in ['csv', 'xlsx']:
162
+ df = pd.read_csv(uploaded_file) if file_type == 'csv' else pd.read_excel(uploaded_file)
163
+ return df.to_string(), file_type
164
+ elif file_type == 'json':
165
+ return json.dumps(json.load(uploaded_file), indent=2), "json"
166
+ elif file_type == 'yaml':
167
+ return yaml.dump(yaml.safe_load(uploaded_file)), "yaml"
168
+ else:
169
+ return uploaded_file.getvalue().decode(), "txt"
170
+ except Exception as e:
171
+ st.error(f"🚨 Error reading {uploaded_file.name}: {str(e)}")
172
+ return None, None
173
 
174
  def main():
175
+ st.set_page_config(page_title="Markdown Handler", layout="wide")
176
 
177
+ # Display file manager in sidebar
178
  display_file_manager()
179
 
180
+ st.title("πŸ“šβœ¨ Super Smart File Handler with Markdown Magic! βœ¨πŸ“š")
 
 
 
 
181
 
182
+ # Add tabs for different views
183
+ upload_tab, book_tab = st.tabs(["πŸ“€ File Upload", "πŸ“– Book View"])
184
+
185
+ with upload_tab:
186
+ col1, col2 = st.columns(2)
 
 
 
 
 
187
 
188
+ with col1:
189
+ single_uploaded_file = st.file_uploader(
190
+ "πŸ“€ Upload single file",
191
+ type=list(FILE_TYPES.keys()),
192
+ help="Supports: " + ", ".join([f"{v} (.{k})" for k, v in FILE_TYPES.items()]),
193
+ key="single_uploader"
194
+ )
195
+
196
+ with col2:
197
+ multiple_uploaded_files = st.file_uploader(
198
+ "πŸ“š Upload multiple files",
199
+ type=list(FILE_TYPES.keys()),
200
+ accept_multiple_files=True,
201
+ help="Upload multiple files to view as a book",
202
+ key="multiple_uploader"
203
+ )
204
+
205
+ # Process uploads
206
+ if single_uploaded_file:
207
+ content, file_type = read_file_content(single_uploaded_file)
208
+ if content is not None:
209
+ st.success(f"πŸŽ‰ Loaded {FILE_TYPES.get(file_type, 'πŸ“„')} file: {single_uploaded_file.name}")
210
+
211
+ if multiple_uploaded_files:
212
+ for uploaded_file in multiple_uploaded_files:
213
+ content, file_type = read_file_content(uploaded_file)
214
+ if content is not None:
215
+ st.success(f"πŸŽ‰ Loaded {uploaded_file.name}")
216
+ st.rerun()
217
+
218
+ # Show current file if selected
219
+ if st.session_state.current_file and st.session_state.file_content:
220
+ st.markdown("---")
221
+ create_markdown_tabs(st.session_state.file_content, st.session_state.current_file)
222
+
223
+ with book_tab:
224
+ st.markdown("## πŸ“– Book View")
225
+ combined_content = combine_markdown_files()
226
+ if combined_content:
227
+ st.markdown(combined_content, unsafe_allow_html=True)
228
+ else:
229
+ st.info("Upload some markdown files to see them combined here!")
230
 
231
  if __name__ == "__main__":
232
  main()