awacke1 commited on
Commit
b7d7c4e
Β·
verified Β·
1 Parent(s): 3cf4bd9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -13
app.py CHANGED
@@ -12,6 +12,7 @@ import json
12
  import uuid # 🎲 For generating unique IDs
13
  from urllib.parse import quote # πŸ”— For encoding URLs
14
  from gradio_client import Client # 🌐 For connecting to Gradio apps
 
15
 
16
  # πŸŽ‰ Welcome to our fun-filled Cosmos DB and GitHub Integration app!
17
  st.set_page_config(layout="wide")
@@ -25,6 +26,10 @@ Key = os.environ.get("Key") # πŸ”‘ Don't forget your key!
25
  # 🏠 Your local app URL (Change this to your app's URL)
26
  LOCAL_APP_URL = "http://localhost:8501"
27
 
 
 
 
 
28
  # πŸ™ GitHub configuration
29
  def download_github_repo(url, local_path):
30
  # 🚚 Let's download that GitHub repo!
@@ -182,6 +187,77 @@ def search_glossary(query):
182
  st.markdown(responseall)
183
  return responseall
184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  # 🎈 Let's modify the main app to be more fun!
186
  def main():
187
  st.title("πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent")
@@ -204,13 +280,16 @@ def main():
204
  if 'cloned_doc' not in st.session_state:
205
  st.session_state.cloned_doc = None
206
 
207
- # πŸ” Check for query parameters
208
- query_params = st.get_query_params()
209
- if 'q' in query_params:
210
- query = query_params['q'][0] # Get the first value of 'q'
211
- # πŸ•΅οΈβ€β™‚οΈ We have a query! Let's search the glossary!
212
- search_glossary(query)
213
- st.stop() # Stop further execution
 
 
 
214
 
215
  # πŸ” Automatic Login
216
  if Key:
@@ -300,10 +379,10 @@ def main():
300
 
301
  # πŸ”— Let's create a list of links for these values
302
  search_urls = {
303
- "πŸš€πŸŒŒArXiv": lambda k: f"/?q={quote(k)}",
304
- "πŸƒAnalyst": lambda k: f"/?q={quote(k)}-{quote('PromptPrefix')}",
305
- "πŸ“šPyCoder": lambda k: f"/?q={quote(k)}-{quote('PromptPrefix2')}",
306
- "πŸ”¬JSCoder": lambda k: f"/?q={quote(k)}-{quote('PromptPrefix3')}",
307
  "🏠": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}",
308
  "πŸ“–": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
309
  "πŸ”": lambda k: f"https://www.google.com/search?q={quote(k)}",
@@ -497,8 +576,8 @@ def main():
497
  finally:
498
  if os.path.exists(local_path):
499
  shutil.rmtree(local_path)
500
- #else:
501
- #st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
502
 
503
  except exceptions.CosmosHttpResponseError as e:
504
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
 
12
  import uuid # 🎲 For generating unique IDs
13
  from urllib.parse import quote # πŸ”— For encoding URLs
14
  from gradio_client import Client # 🌐 For connecting to Gradio apps
15
+ import openai # πŸ€– For OpenAI API interactions
16
 
17
  # πŸŽ‰ Welcome to our fun-filled Cosmos DB and GitHub Integration app!
18
  st.set_page_config(layout="wide")
 
26
  # 🏠 Your local app URL (Change this to your app's URL)
27
  LOCAL_APP_URL = "http://localhost:8501"
28
 
29
+ # πŸ€– OpenAI configuration
30
+ openai.api_key = os.environ.get("OPENAI_API_KEY")
31
+ MODEL = "gpt-3.5-turbo" # Replace with your desired model
32
+
33
  # πŸ™ GitHub configuration
34
  def download_github_repo(url, local_path):
35
  # 🚚 Let's download that GitHub repo!
 
187
  st.markdown(responseall)
188
  return responseall
189
 
190
+ # πŸ“ Function to process text input
191
+ def process_text(text_input):
192
+ if text_input:
193
+ if 'messages' not in st.session_state:
194
+ st.session_state.messages = []
195
+
196
+ st.session_state.messages.append({"role": "user", "content": text_input})
197
+
198
+ with st.chat_message("user"):
199
+ st.markdown(text_input)
200
+
201
+ with st.chat_message("assistant"):
202
+ completion = openai.ChatCompletion.create(
203
+ model=MODEL,
204
+ messages=[
205
+ {"role": m["role"], "content": m["content"]}
206
+ for m in st.session_state.messages
207
+ ],
208
+ stream=False
209
+ )
210
+ return_text = completion.choices[0].message.content
211
+ st.write("Assistant: " + return_text)
212
+ filename = generate_filename(text_input, "md")
213
+
214
+ create_and_save_file(return_text, file_type="md", prompt=text_input, is_image=False, should_save=True)
215
+ st.session_state.messages.append({"role": "assistant", "content": return_text})
216
+
217
+ # πŸ“„ Function to generate a filename
218
+ def generate_filename(text, file_type):
219
+ # πŸ“ Generate a filename based on the text input
220
+ safe_text = "".join(c if c.isalnum() or c in (' ', '.', '_') else '_' for c in text)
221
+ safe_text = "_".join(safe_text.strip().split())
222
+ filename = f"{safe_text}.{file_type}"
223
+ return filename
224
+
225
+ # 🏷️ Function to extract markdown title
226
+ def extract_markdown_title(content):
227
+ # πŸ” Extract the first markdown heading as the title
228
+ lines = content.splitlines()
229
+ for line in lines:
230
+ if line.startswith('#'):
231
+ return line.lstrip('#').strip()
232
+ return None
233
+
234
+ # πŸ’Ύ Function to create and save a file
235
+ def create_and_save_file(content, file_type="md", prompt=None, is_image=False, should_save=True):
236
+ """
237
+ Combines file name generation and file creation into one function.
238
+ If the file is a markdown file, extracts the title from the content (if available) and uses it for the filename.
239
+ """
240
+ if not should_save:
241
+ return None
242
+
243
+ # Step 1: Generate filename based on the prompt or content
244
+ filename = generate_filename(prompt if prompt else content, file_type)
245
+
246
+ # Step 2: If it's a markdown file, check if it has a title (e.g., # Heading in markdown)
247
+ if file_type == "md":
248
+ title_from_content = extract_markdown_title(content)
249
+ if title_from_content:
250
+ filename = generate_filename(title_from_content, file_type)
251
+
252
+ # Step 3: Save the file
253
+ with open(filename, "w", encoding="utf-8") as f:
254
+ if is_image:
255
+ f.write(content)
256
+ else:
257
+ f.write(prompt + "\n\n" + content)
258
+
259
+ return filename
260
+
261
  # 🎈 Let's modify the main app to be more fun!
262
  def main():
263
  st.title("πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent")
 
280
  if 'cloned_doc' not in st.session_state:
281
  st.session_state.cloned_doc = None
282
 
283
+ # βš™οΈ q= Run ArXiv search from query parameters
284
+ try:
285
+ query_params = st.query_params
286
+ query = (query_params.get('q') or query_params.get('query') or [''])[0]
287
+ if query:
288
+ # πŸ•΅οΈβ€β™‚οΈ We have a query! Let's process it!
289
+ process_text(query)
290
+ st.stop() # Stop further execution
291
+ except Exception as e:
292
+ st.markdown(' ')
293
 
294
  # πŸ” Automatic Login
295
  if Key:
 
379
 
380
  # πŸ”— Let's create a list of links for these values
381
  search_urls = {
382
+ "πŸš€πŸŒŒArXiv": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}",
383
+ "πŸƒAnalyst": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix')}",
384
+ "πŸ“šPyCoder": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix2')}",
385
+ "πŸ”¬JSCoder": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix3')}",
386
  "🏠": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}",
387
  "πŸ“–": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
388
  "πŸ”": lambda k: f"https://www.google.com/search?q={quote(k)}",
 
576
  finally:
577
  if os.path.exists(local_path):
578
  shutil.rmtree(local_path)
579
+ else:
580
+ st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
581
 
582
  except exceptions.CosmosHttpResponseError as e:
583
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")