awacke1 commited on
Commit
ddc98f1
โ€ข
1 Parent(s): 68de287

Create backup5.sidebarrefactorapp.py

Browse files
Files changed (1) hide show
  1. backup5.sidebarrefactorapp.py +359 -0
backup5.sidebarrefactorapp.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import glob
4
+ import re
5
+ import base64
6
+ import pytz
7
+ from urllib.parse import quote
8
+ from gradio_client import Client
9
+ from datetime import datetime
10
+
11
+ # Initialize session state variables
12
+ if 'selected_file' not in st.session_state:
13
+ st.session_state.selected_file = None
14
+ if 'view_mode' not in st.session_state:
15
+ st.session_state.view_mode = 'view'
16
+ if 'files' not in st.session_state:
17
+ st.session_state.files = []
18
+
19
+ # Define the markdown variables
20
+ Boxing_and_MMA_Commentary_and_Knowledge = """
21
+ # Boxing and UFC Study of 1971 - 2024 The Greatest Fights History
22
+
23
+ 1. In Boxing, the most heart breaking fight in Boxing was the Boom Boom Mancini fight with Duku Kim.
24
+ 2. After changes to Boxing made it more safe due to the heart break.
25
+ 3. Rehydration of the brain after weight ins loss preparation for a match is life saving change.
26
+ 4. Fighting went from 15 rounds to 12.
27
+
28
+ # UFC By Contrast..
29
+ 1. 5 Rounds of 5 Minutes each.
30
+ 2. Greatest UFC Fighters:
31
+ - Jon Jones could be the greatest of all time (GOAT) since he never lost.
32
+ - George St. Pierre
33
+ - BJ Penn
34
+ - Anderson Silva
35
+ - Mighty Mouse MMA's heart at 125 pounds
36
+ - Kabib retired 29 and 0
37
+ - Fedor Milliano
38
+ - Alex Pereira
39
+ - James Tony
40
+ - Randy Couture
41
+ 3. You have to Judge them in their Championship Peak
42
+ 4. Chris Weidman
43
+ 5. Connor McGregor
44
+ 6. Leg Breaking - Shin calcification and breaking baseball bats
45
+
46
+ # References:
47
+ 1. Joe Rogan - Interview #2219
48
+ 2. Donald J Trump
49
+ """
50
+
51
+ Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds = """
52
+ # Multiplayer Simulated Worlds
53
+
54
+ 1. 7 Days To Die PC
55
+ 2. ARK: Survival Evolved PC
56
+ 3. Arma 3 PC
57
+ 4. Atlas PC
58
+ 5. Conan Exiles PC
59
+ 6. Craftopia PC
60
+ 7. DayZ PC
61
+ 8. Eco - Global Survival PC
62
+ 9. Empyrion - Galactic Survival PC
63
+ 10. Factorio PC
64
+ 11. Farming Simulator 19 PC
65
+ 12. Crossplay
66
+ 13. Farming Simulator 22
67
+ 14. Last Oasis PC
68
+ 15. Last Oasis Classic PC
69
+ 16. Minecraft (Vanilla) PC
70
+ 17. Crossplay
71
+ 18. Path of Titans
72
+ 19. Rust PC
73
+ 20. SCP: Secret Laboratory PC
74
+ 21. SCUM PC
75
+ 22. Satisfactory PC
76
+ 23. Satisfactory (Experimental) PC
77
+ 24. Crossplay
78
+ 25. Space Engineers
79
+ 26. Terraria (tShock & Vanilla) PC
80
+ 27. The Forest PC
81
+ 28. Crossplay
82
+ 29. Valheim
83
+ """
84
+
85
+ def get_display_name(filename):
86
+ """Extract text from parentheses or return filename as is."""
87
+ match = re.search(r'\((.*?)\)', filename)
88
+ if match:
89
+ return match.group(1)
90
+ return filename
91
+
92
+ def sanitize_filename(text):
93
+ """Create a safe filename from text while preserving spaces."""
94
+ # First replace unsafe characters with spaces
95
+ safe_text = re.sub(r'[^\w\s-]', ' ', text)
96
+ # Remove any multiple spaces
97
+ safe_text = re.sub(r'\s+', ' ', safe_text)
98
+ # Trim leading/trailing spaces
99
+ safe_text = safe_text.strip()
100
+ return safe_text[:50] # Limit length to 50 chars
101
+
102
+ def generate_timestamp_filename(query):
103
+ """Generate filename with format: 1103AM 11032024 (Query).md"""
104
+ # Get current time in Central timezone
105
+ central = pytz.timezone('US/Central')
106
+ current_time = datetime.now(central)
107
+
108
+ # Format the timestamp parts
109
+ time_str = current_time.strftime("%I%M%p") # 1103AM format
110
+ date_str = current_time.strftime("%m%d%Y") # 11032024 format
111
+
112
+ # Clean up the query for filename - now preserving spaces
113
+ safe_query = sanitize_filename(query)
114
+
115
+ # Construct filename: "1103AM 11032024 (Input with spaces).md"
116
+ filename = f"{time_str} {date_str} ({safe_query}).md"
117
+
118
+ return filename
119
+
120
+ def save_ai_interaction(query, ai_result):
121
+ """Save AI interaction to a markdown file with new filename format."""
122
+ filename = generate_timestamp_filename(query)
123
+
124
+ # Format the content
125
+ content = f"""# Query: {query}
126
+
127
+ ## AI Response
128
+ {ai_result}
129
+ """
130
+
131
+ # Save to file
132
+ try:
133
+ with open(filename, 'w', encoding='utf-8') as f:
134
+ f.write(content)
135
+ return filename
136
+ except Exception as e:
137
+ st.error(f"Error saving file: {e}")
138
+ return None
139
+
140
+ def get_file_download_link(file_path):
141
+ """Generate a base64 download link for a file."""
142
+ try:
143
+ with open(file_path, 'r', encoding='utf-8') as f:
144
+ content = f.read()
145
+ b64 = base64.b64encode(content.encode()).decode()
146
+ return f"data:text/markdown;base64,{b64}"
147
+ except Exception as e:
148
+ st.error(f"Error creating download link: {e}")
149
+ return None
150
+
151
+ def extract_terms(markdown_text):
152
+ """Parse markdown text and extract terms."""
153
+ lines = markdown_text.strip().split('\n')
154
+ terms = []
155
+ for line in lines:
156
+ line = re.sub(r'^[#*\->\d\.\s]+', '', line).strip()
157
+ if line:
158
+ terms.append(line)
159
+ return terms
160
+
161
+ def display_terms_with_links(terms):
162
+ """Display terms with various search links."""
163
+ search_urls = {
164
+ "๐Ÿš€๐ŸŒŒArXiv": lambda k: f"/?q={quote(k)}",
165
+ "๐Ÿ“–": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
166
+ "๐Ÿ”": lambda k: f"https://www.google.com/search?q={quote(k)}",
167
+ "โ–ถ๏ธ": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
168
+ "๐Ÿ”Ž": lambda k: f"https://www.bing.com/search?q={quote(k)}",
169
+ "๐Ÿฆ": lambda k: f"https://twitter.com/search?q={quote(k)}",
170
+ }
171
+ for term in terms:
172
+ links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
173
+ st.markdown(f"- **{term}** {links_md}", unsafe_allow_html=True)
174
+
175
+ def perform_ai_lookup(query):
176
+ """Perform AI lookup using Gradio client."""
177
+ st.write("Performing AI Lookup...")
178
+ client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
179
+ result1 = client.predict(
180
+ prompt=query,
181
+ llm_model_picked="mistralai/Mixtral-8x7B-Instruct-v0.1",
182
+ stream_outputs=True,
183
+ api_name="/ask_llm"
184
+ )
185
+ st.markdown("### Mixtral-8x7B-Instruct-v0.1 Result")
186
+ st.markdown(result1)
187
+ result2 = client.predict(
188
+ prompt=query,
189
+ llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
190
+ stream_outputs=True,
191
+ api_name="/ask_llm"
192
+ )
193
+ st.markdown("### Mistral-7B-Instruct-v0.2 Result")
194
+ st.markdown(result2)
195
+ combined_result = f"{result1}\n\n{result2}"
196
+ return combined_result
197
+
198
+ def display_file_content(file_path):
199
+ """Display file content with editing capabilities."""
200
+ try:
201
+ with open(file_path, 'r', encoding='utf-8') as f:
202
+ content = f.read()
203
+
204
+ # Display as code with line numbers
205
+ st.code(content, line_numbers=True)
206
+
207
+ # Edit functionality
208
+ edited_content = st.text_area(
209
+ "Edit content",
210
+ content,
211
+ height=400,
212
+ key=f"edit_{os.path.basename(file_path)}"
213
+ )
214
+
215
+ if st.button("Save Changes", key=f"save_{os.path.basename(file_path)}"):
216
+ try:
217
+ with open(file_path, 'w', encoding='utf-8') as f:
218
+ f.write(edited_content)
219
+ st.success(f"Successfully saved changes to {file_path}")
220
+ except Exception as e:
221
+ st.error(f"Error saving changes: {e}")
222
+ except Exception as e:
223
+ st.error(f"Error reading file: {e}")
224
+
225
+ def file_management_sidebar():
226
+ """Redesigned sidebar with improved layout and additional functionality."""
227
+ st.sidebar.title("๐Ÿ“ File Management")
228
+
229
+ # Get list of .md files excluding README.md
230
+ md_files = [file for file in glob.glob("*.md") if file.lower() != 'readme.md']
231
+ md_files.sort()
232
+ st.session_state.files = md_files
233
+
234
+ if md_files:
235
+ st.sidebar.markdown("### Saved Files")
236
+ for idx, file in enumerate(md_files):
237
+ st.sidebar.markdown("---") # Separator between files
238
+
239
+ # Display filename
240
+ st.sidebar.text(file)
241
+
242
+ # Display download link with simplified text
243
+ display_name = get_display_name(file)
244
+ download_link = get_file_download_link(file)
245
+ if download_link:
246
+ st.sidebar.markdown(f"๐Ÿ“ฅ [{display_name}]({download_link})", unsafe_allow_html=True)
247
+
248
+ # Action buttons in a row
249
+ col1, col2, col3 = st.sidebar.columns(3)
250
+
251
+ with col1:
252
+ if st.button("๐Ÿ“„ View", key=f"view_{idx}"):
253
+ st.session_state.selected_file = file
254
+ st.session_state.view_mode = 'view'
255
+
256
+ with col2:
257
+ if st.button("โœ๏ธ Edit", key=f"edit_{idx}"):
258
+ st.session_state.selected_file = file
259
+ st.session_state.view_mode = 'edit'
260
+
261
+ with col3:
262
+ if st.button("๐Ÿ”„ Rerun", key=f"rerun_{idx}"):
263
+ try:
264
+ with open(file, 'r', encoding='utf-8') as f:
265
+ content = f.read()
266
+
267
+ # Prepare the prompt with the prefix
268
+ rerun_prefix = """For the markdown below reduce the text to a humorous fun outline with emojis and markdown outline levels in outline that convey all the facts and adds wise quotes and funny statements to engage the reader:
269
+
270
+ """
271
+ full_prompt = rerun_prefix + content
272
+
273
+ # Perform AI lookup and save results
274
+ ai_result = perform_ai_lookup(full_prompt)
275
+ saved_file = save_ai_interaction(f"Rerun of {file}", ai_result)
276
+
277
+ if saved_file:
278
+ st.success(f"Created fun version in {saved_file}")
279
+ st.session_state.selected_file = saved_file
280
+ st.session_state.view_mode = 'view'
281
+
282
+ except Exception as e:
283
+ st.error(f"Error during rerun: {e}")
284
+
285
+ st.sidebar.markdown("---")
286
+ # Option to create a new markdown file
287
+ if st.sidebar.button("๐Ÿ“ Create New Note"):
288
+ filename = generate_timestamp_filename("New Note")
289
+ with open(filename, 'w', encoding='utf-8') as f:
290
+ f.write("# New Markdown File\n")
291
+ st.sidebar.success(f"Created: {filename}")
292
+ st.session_state.selected_file = filename
293
+ st.session_state.view_mode = 'edit'
294
+ else:
295
+ st.sidebar.write("No markdown files found.")
296
+ if st.sidebar.button("๐Ÿ“ Create First Note"):
297
+ filename = generate_timestamp_filename("New Note")
298
+ with open(filename, 'w', encoding='utf-8') as f:
299
+ f.write("# New Markdown File\n")
300
+ st.sidebar.success(f"Created: {filename}")
301
+ st.session_state.selected_file = filename
302
+ st.session_state.view_mode = 'edit'
303
+
304
+ def main():
305
+ st.title("Markdown Content with AI Lookup and File Management")
306
+
307
+ # Process query parameters and AI lookup first
308
+ query_params = st.query_params
309
+ query = query_params.get('q', '')
310
+ show_initial_content = True # Flag to control initial content display
311
+
312
+ # First priority: Handle active query
313
+ if query:
314
+ show_initial_content = False # Hide initial content when showing query results
315
+ st.write(f"### Search query received: {query}")
316
+ try:
317
+ ai_result = perform_ai_lookup(query)
318
+
319
+ # Save the interaction
320
+ saved_file = save_ai_interaction(query, ai_result)
321
+ if saved_file:
322
+ st.success(f"Saved interaction to {saved_file}")
323
+ st.session_state.selected_file = saved_file
324
+ st.session_state.view_mode = 'view'
325
+ except Exception as e:
326
+ st.error(f"Error during AI lookup: {e}")
327
+
328
+ # File management sidebar
329
+ file_management_sidebar()
330
+
331
+ # Second priority: Display selected file content if any
332
+ if st.session_state.selected_file:
333
+ show_initial_content = False # Hide initial content when showing file content
334
+ st.markdown(f"### Current File: {st.session_state.selected_file}")
335
+ display_file_content(st.session_state.selected_file)
336
+
337
+ # Show initial content: Either when first landing or when no interactive elements are active
338
+ if show_initial_content:
339
+ # First show the clickable terms with links
340
+ terms1 = extract_terms(Boxing_and_MMA_Commentary_and_Knowledge)
341
+ terms2 = extract_terms(Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds)
342
+ all_terms = terms1 + terms2
343
+
344
+ col1, col2 = st.columns(2)
345
+
346
+ with col1:
347
+ st.markdown("### Boxing & MMA")
348
+ st.markdown(Boxing_and_MMA_Commentary_and_Knowledge)
349
+ st.markdown("#### Related Links")
350
+ display_terms_with_links(terms1)
351
+
352
+ with col2:
353
+ st.markdown("### Multiplayer Games")
354
+ st.markdown(Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds)
355
+ st.markdown("#### Related Links")
356
+ display_terms_with_links(terms2)
357
+
358
+ if __name__ == "__main__":
359
+ main()