awacke1 commited on
Commit
d153553
1 Parent(s): 93f54d2

Update backup4.QuerryParamsFixed..app.py

Browse files
Files changed (1) hide show
  1. backup4.QuerryParamsFixed..app.py +109 -114
backup4.QuerryParamsFixed..app.py CHANGED
@@ -2,9 +2,9 @@ import streamlit as st
2
  import os
3
  import glob
4
  import re
 
5
  from urllib.parse import quote
6
  from gradio_client import Client
7
- import json
8
  from datetime import datetime
9
 
10
  # Initialize session state variables
@@ -81,6 +81,50 @@ Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds = """
81
  29. Valheim
82
  """
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  # Function to parse markdown text and extract terms
85
  def extract_terms(markdown_text):
86
  lines = markdown_text.strip().split('\n')
@@ -108,9 +152,7 @@ def display_terms_with_links(terms):
108
  # Function to perform AI lookup using Gradio client
109
  def perform_ai_lookup(query):
110
  st.write("Performing AI Lookup...")
111
- # Initialize the Gradio client
112
  client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
113
- # Perform the AI lookup using the Mixtral and Mistral models
114
  result1 = client.predict(
115
  prompt=query,
116
  llm_model_picked="mistralai/Mixtral-8x7B-Instruct-v0.1",
@@ -130,70 +172,67 @@ def perform_ai_lookup(query):
130
  combined_result = f"{result1}\n\n{result2}"
131
  return combined_result
132
 
133
- # Function to extract URLs from AI result
134
- def extract_urls(text):
135
  try:
136
- date_pattern = re.compile(r'### (\d{2} \w{3} \d{4})')
137
- abs_link_pattern = re.compile(r'\[(.*?)\]\((https://arxiv\.org/abs/\d+\.\d+)\)')
138
- pdf_link_pattern = re.compile(r'\[⬇️\]\((https://arxiv\.org/pdf/\d+\.\d+)\)')
139
- title_pattern = re.compile(r'### \d{2} \w{3} \d{4} \| \[(.*?)\]')
140
- date_matches = date_pattern.findall(text)
141
- abs_link_matches = abs_link_pattern.findall(text)
142
- pdf_link_matches = pdf_link_pattern.findall(text)
143
- title_matches = title_pattern.findall(text)
144
-
145
- markdown_text = ""
146
- for i in range(len(date_matches)):
147
- date = date_matches[i]
148
- title = title_matches[i]
149
- abs_link = abs_link_matches[i][1]
150
- pdf_link = pdf_link_matches[i]
151
- markdown_text += f"**Date:** {date}\n\n"
152
- markdown_text += f"**Title:** {title}\n\n"
153
- markdown_text += f"**Abstract Link:** [{abs_link}]({abs_link})\n\n"
154
- markdown_text += f"**PDF Link:** [{pdf_link}]({pdf_link})\n\n"
155
- markdown_text += "---\n\n"
156
- return markdown_text
157
-
158
  except Exception as e:
159
- st.write(f"An error occurred in extract_urls: {e}")
160
- return ''
161
-
162
- # Function to generate filename based on date and content
163
- def generate_filename(prefix, content):
164
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
165
- safe_content = re.sub(r'\W+', '_', content[:50])
166
- filename = f"{prefix}_{timestamp}_{safe_content}.md"
167
- return filename
168
 
169
- # Sidebar for file management
170
  def file_management_sidebar():
 
171
  st.sidebar.title("📁 File Management")
172
 
173
- # Get list of .md files excluding README.md
174
- md_files = [file for file in glob.glob("*.md") if os.path.basename(file).lower() != 'readme.md']
175
- md_files.sort()
176
- st.session_state.files = md_files # Update session state
177
-
178
  if md_files:
179
  st.sidebar.markdown("### Markdown Files")
180
  for idx, file in enumerate(md_files):
181
- # Create a unique key for each file
182
- key_base = f"file_{idx}_{file}"
183
- col1, col2, col3 = st.sidebar.columns([6, 1, 1])
184
  with col1:
185
  st.write(file)
 
186
  with col2:
187
- if st.sidebar.button("📄", key=f"view_{key_base}"):
 
 
 
 
 
188
  st.session_state.selected_file = file
189
  st.session_state.view_mode = 'view'
190
- with col3:
191
- if st.sidebar.button("✏️", key=f"edit_{key_base}"):
 
 
192
  st.session_state.selected_file = file
193
  st.session_state.view_mode = 'edit'
 
194
  # Option to create a new markdown file
195
  if st.sidebar.button("Create New Markdown File"):
196
- # Generate automatic filename
197
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
198
  new_filename = f"note_{timestamp}.md"
199
  with open(new_filename, 'w', encoding='utf-8') as f:
@@ -204,7 +243,6 @@ def file_management_sidebar():
204
  else:
205
  st.sidebar.write("No markdown files found.")
206
  if st.sidebar.button("Create New Markdown File"):
207
- # Generate automatic filename
208
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
209
  new_filename = f"note_{timestamp}.md"
210
  with open(new_filename, 'w', encoding='utf-8') as f:
@@ -213,8 +251,6 @@ def file_management_sidebar():
213
  st.session_state.selected_file = new_filename
214
  st.session_state.view_mode = 'edit'
215
 
216
-
217
- # Main application logic
218
  def main():
219
  st.title("Markdown Content with AI Lookup and File Management")
220
 
@@ -230,72 +266,31 @@ def main():
230
  all_terms = terms1 + terms2
231
  display_terms_with_links(all_terms)
232
 
233
- # Process 'q' query parameter from the URL
234
- try:
235
- query_params = st.query_params
236
- query = (query_params.get('q') or query_params.get('query') or [''])
237
- if len(query) > 1:
238
- st.write(f"### Search query received: {query}")
 
239
  ai_result = perform_ai_lookup(query)
240
- markdown_text = extract_urls(ai_result)
241
- st.markdown("## Extracted URLs")
242
- st.markdown(markdown_text)
243
- filename = generate_filename(ai_result, query)
244
- with open(filename, 'w', encoding='utf-8') as f:
245
- f.write(markdown_text)
246
- st.write(f"Generated file **{filename}** with AI results for {query}")
247
- st.query_params.clear()
248
- st.session_state.selected_file = filename
249
- st.session_state.view_mode = 'view'
250
-
251
- except Exception as e:
252
- st.write(f"An error occurred while processing query parameters: {e}")
253
-
254
- # Handle 'action' and 'query' parameters
255
- params = st.query_params
256
- if 'action' in params:
257
- action = st.query_params()['action'][0]
258
- if action == 'show_message':
259
- st.success("Showing a message because 'action=show_message' was found in the URL.")
260
- elif action == 'clear':
261
- # Clear query parameters
262
- st.query_params.clear()
263
-
264
- if 'query' in st.query_params:
265
- query = st.query_params['query'][0] # Get the query parameter
266
- # Display content or image based on the query
267
- #display_content_or_image(query)
268
- st.markdown("To Implement:")
269
- st.markdown(query)
270
 
271
  # File management sidebar
272
  file_management_sidebar()
273
 
274
- # Display the selected file
275
- selected_file = st.session_state.get('selected_file')
276
- if selected_file:
277
- view_mode = st.session_state.get('view_mode', 'view')
278
- if os.path.exists(selected_file):
279
- if view_mode == 'view':
280
- st.markdown(f"### Viewing {selected_file}")
281
- with open(selected_file, 'r', encoding='utf-8') as f:
282
- file_content = f.read()
283
- st.markdown(file_content)
284
- elif view_mode == 'edit':
285
- st.markdown(f"### Editing {selected_file}")
286
- with open(selected_file, 'r', encoding='utf-8') as f:
287
- file_content = f.read()
288
- edited_content = st.text_area("Edit the markdown content", file_content, height=400)
289
- if st.button("Save Changes"):
290
- with open(selected_file, 'w', encoding='utf-8') as f:
291
- f.write(edited_content)
292
- st.success(f"Changes saved to {selected_file}")
293
- # Update the file list in session state
294
- st.session_state.files = [file for file in glob.glob("*.md") if os.path.basename(file).lower() != 'readme.md']
295
- else:
296
- st.error("Selected file does not exist.")
297
- else:
298
- st.info("No file selected.")
299
 
300
  if __name__ == "__main__":
301
- main()
 
2
  import os
3
  import glob
4
  import re
5
+ import base64
6
  from urllib.parse import quote
7
  from gradio_client import Client
 
8
  from datetime import datetime
9
 
10
  # Initialize session state variables
 
81
  29. Valheim
82
  """
83
 
84
+ def sanitize_filename(text):
85
+ """Create a safe filename from text."""
86
+ # Remove or replace unsafe characters
87
+ safe_text = re.sub(r'[^\w\s-]', '_', text)
88
+ safe_text = re.sub(r'\s+', '_', safe_text)
89
+ return safe_text[:50] # Limit length to 50 chars
90
+
91
+ def save_ai_interaction(query, ai_result):
92
+ """Save AI interaction to a markdown file."""
93
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
94
+ safe_query = sanitize_filename(query)
95
+ filename = f"ai_interaction_{timestamp}_{safe_query}.md"
96
+
97
+ # Format the content
98
+ content = f"""# AI Interaction - {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
99
+
100
+ ## Query
101
+ {query}
102
+
103
+ ## AI Response
104
+ {ai_result}
105
+ """
106
+
107
+ # Save to file
108
+ try:
109
+ with open(filename, 'w', encoding='utf-8') as f:
110
+ f.write(content)
111
+ return filename
112
+ except Exception as e:
113
+ st.error(f"Error saving file: {e}")
114
+ return None
115
+
116
+ def get_file_download_link(file_path):
117
+ """Generate a base64 download link for a file."""
118
+ try:
119
+ with open(file_path, 'r', encoding='utf-8') as f:
120
+ content = f.read()
121
+ b64 = base64.b64encode(content.encode()).decode()
122
+ filename = os.path.basename(file_path)
123
+ return f'<a href="data:text/markdown;base64,{b64}" download="{filename}">{filename}</a>'
124
+ except Exception as e:
125
+ st.error(f"Error creating download link: {e}")
126
+ return None
127
+
128
  # Function to parse markdown text and extract terms
129
  def extract_terms(markdown_text):
130
  lines = markdown_text.strip().split('\n')
 
152
  # Function to perform AI lookup using Gradio client
153
  def perform_ai_lookup(query):
154
  st.write("Performing AI Lookup...")
 
155
  client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
 
156
  result1 = client.predict(
157
  prompt=query,
158
  llm_model_picked="mistralai/Mixtral-8x7B-Instruct-v0.1",
 
172
  combined_result = f"{result1}\n\n{result2}"
173
  return combined_result
174
 
175
+ def display_file_content(file_path):
176
+ """Display file content with editing capabilities."""
177
  try:
178
+ with open(file_path, 'r', encoding='utf-8') as f:
179
+ content = f.read()
180
+
181
+ # Display as code with line numbers
182
+ st.code(content, line_numbers=True)
183
+
184
+ # Edit functionality
185
+ edited_content = st.text_area(
186
+ "Edit content",
187
+ content,
188
+ height=400,
189
+ key=f"edit_{os.path.basename(file_path)}"
190
+ )
191
+
192
+ if st.button("Save Changes", key=f"save_{os.path.basename(file_path)}"):
193
+ try:
194
+ with open(file_path, 'w', encoding='utf-8') as f:
195
+ f.write(edited_content)
196
+ st.success(f"Successfully saved changes to {file_path}")
197
+ except Exception as e:
198
+ st.error(f"Error saving changes: {e}")
 
199
  except Exception as e:
200
+ st.error(f"Error reading file: {e}")
 
 
 
 
 
 
 
 
201
 
 
202
  def file_management_sidebar():
203
+ """Enhanced sidebar with file management capabilities."""
204
  st.sidebar.title("📁 File Management")
205
 
206
+ # Get list of .md files
207
+ md_files = sorted(glob.glob("*.md"))
208
+ st.session_state.files = md_files
209
+
 
210
  if md_files:
211
  st.sidebar.markdown("### Markdown Files")
212
  for idx, file in enumerate(md_files):
213
+ col1, col2, col3, col4 = st.sidebar.columns([4, 2, 1, 1])
214
+
 
215
  with col1:
216
  st.write(file)
217
+
218
  with col2:
219
+ # Base64 download link
220
+ st.markdown(get_file_download_link(file), unsafe_allow_html=True)
221
+
222
+ with col3:
223
+ # View button
224
+ if st.button("📄", key=f"view_{idx}"):
225
  st.session_state.selected_file = file
226
  st.session_state.view_mode = 'view'
227
+
228
+ with col4:
229
+ # Edit button
230
+ if st.button("✏️", key=f"edit_{idx}"):
231
  st.session_state.selected_file = file
232
  st.session_state.view_mode = 'edit'
233
+
234
  # Option to create a new markdown file
235
  if st.sidebar.button("Create New Markdown File"):
 
236
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
237
  new_filename = f"note_{timestamp}.md"
238
  with open(new_filename, 'w', encoding='utf-8') as f:
 
243
  else:
244
  st.sidebar.write("No markdown files found.")
245
  if st.sidebar.button("Create New Markdown File"):
 
246
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
247
  new_filename = f"note_{timestamp}.md"
248
  with open(new_filename, 'w', encoding='utf-8') as f:
 
251
  st.session_state.selected_file = new_filename
252
  st.session_state.view_mode = 'edit'
253
 
 
 
254
  def main():
255
  st.title("Markdown Content with AI Lookup and File Management")
256
 
 
266
  all_terms = terms1 + terms2
267
  display_terms_with_links(all_terms)
268
 
269
+ # Process query parameters and AI lookup
270
+ query_params = st.query_params
271
+ query = query_params.get('q', '')
272
+
273
+ if query:
274
+ st.write(f"### Search query received: {query}")
275
+ try:
276
  ai_result = perform_ai_lookup(query)
277
+
278
+ # Save the interaction
279
+ saved_file = save_ai_interaction(query, ai_result)
280
+ if saved_file:
281
+ st.success(f"Saved interaction to {saved_file}")
282
+ st.session_state.selected_file = saved_file
283
+ st.session_state.view_mode = 'view'
284
+ except Exception as e:
285
+ st.error(f"Error during AI lookup: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
 
287
  # File management sidebar
288
  file_management_sidebar()
289
 
290
+ # Display selected file
291
+ if st.session_state.selected_file:
292
+ st.markdown(f"### Current File: {st.session_state.selected_file}")
293
+ display_file_content(st.session_state.selected_file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
  if __name__ == "__main__":
296
+ main()