awacke1 commited on
Commit
75d3fb0
Β·
verified Β·
1 Parent(s): 104cda3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -1272
app.py CHANGED
@@ -9,89 +9,131 @@ from git import Repo
9
  from datetime import datetime
10
  import base64
11
  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")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- # 🌌 Cosmos DB configuration
20
  ENDPOINT = "https://acae-afd.documents.azure.com:443/"
21
  DATABASE_NAME = os.environ.get("COSMOS_DATABASE_NAME")
22
  CONTAINER_NAME = os.environ.get("COSMOS_CONTAINER_NAME")
23
- Key = os.environ.get("Key") # πŸ”‘ Don't forget your key!
24
 
25
- # 🏠 Your local app URL (Change this to your app's URL)
26
  LOCAL_APP_URL = "https://huggingface.co/spaces/awacke1/AzureCosmosDBUI"
27
 
28
- # πŸ™ GitHub configuration
29
- def download_github_repo(url, local_path):
30
- # 🚚 Let's download that GitHub repo!
31
- if os.path.exists(local_path):
32
- shutil.rmtree(local_path)
33
- Repo.clone_from(url, local_path)
34
-
35
- def create_zip_file(source_dir, output_filename):
36
- # πŸ“¦ Zipping up files like a pro!
37
- shutil.make_archive(output_filename, 'zip', source_dir)
38
-
39
- def create_repo(g, repo_name):
40
- # πŸ› οΈ Creating a new GitHub repo. Magic!
41
- user = g.get_user()
42
- return user.create_repo(repo_name)
43
 
44
- def push_to_github(local_path, repo, github_token):
45
- # πŸš€ Pushing code to GitHub. Hold on tight!
46
- repo_url = f"https://{github_token}@github.com/{repo.full_name}.git"
47
- local_repo = Repo(local_path)
48
-
49
- if 'origin' in [remote.name for remote in local_repo.remotes]:
50
- origin = local_repo.remote('origin')
51
- origin.set_url(repo_url)
52
- else:
53
- origin = local_repo.create_remote('origin', repo_url)
54
-
55
- if not local_repo.heads:
56
- local_repo.git.checkout('-b', 'main')
57
- current_branch = 'main'
58
- else:
59
- current_branch = local_repo.active_branch.name
60
-
61
- local_repo.git.add(A=True)
62
-
63
- if local_repo.is_dirty():
64
- local_repo.git.commit('-m', 'Initial commit')
65
-
66
- origin.push(refspec=f'{current_branch}:{current_branch}')
67
 
68
- def get_base64_download_link(file_path, file_name):
69
- # πŸ§™β€β™‚οΈ Generating a magical download link!
70
  with open(file_path, "rb") as file:
71
  contents = file.read()
72
- base64_encoded = base64.b64encode(contents).decode()
73
- return f'<a href="data:application/zip;base64,{base64_encoded}" download="{file_name}">⬇️ Download {file_name}</a>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
 
 
 
 
 
 
 
 
75
 
76
- # 🧭 New functions for dynamic sidebar navigation
77
  def get_databases(client):
78
- # πŸ“š Fetching list of databases. So many options!
79
  return [db['id'] for db in client.list_databases()]
80
 
81
  def get_containers(database):
82
- # πŸ“‚ Getting containers. Containers within containers!
83
  return [container['id'] for container in database.list_containers()]
84
 
85
  def get_documents(container, limit=None):
86
- # πŸ“ Retrieving documents. Shhh, don't tell anyone!
87
  query = "SELECT * FROM c ORDER BY c._ts DESC"
88
  items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
89
  return items
90
 
91
-
92
- # 🌟 Cosmos DB functions
93
  def insert_record(container, record):
94
- # πŸ“₯ Inserting a record into the Cosmosβ€”hope we don't disturb any aliens! πŸ‘½
95
  try:
96
  container.create_item(body=record)
97
  return True, "Record inserted successfully! πŸŽ‰"
@@ -101,7 +143,6 @@ def insert_record(container, record):
101
  return False, f"An unexpected error occurred: {str(e)} 😱"
102
 
103
  def update_record(container, updated_record):
104
- # πŸ”„ Updating a recordβ€”giving it a cosmic makeover! ✨
105
  try:
106
  container.upsert_item(body=updated_record)
107
  return True, f"Record with id {updated_record['id']} successfully updated. πŸ› οΈ"
@@ -111,7 +152,6 @@ def update_record(container, updated_record):
111
  return False, f"An unexpected error occurred: {traceback.format_exc()} 😱"
112
 
113
  def delete_record(container, name, id):
114
- # πŸ—‘οΈ Deleting a recordβ€”sending it into the cosmic void! 🌌
115
  try:
116
  container.delete_item(item=id, partition_key=id)
117
  return True, f"Successfully deleted record with name: {name} and id: {id} πŸ—‘οΈ"
@@ -122,72 +162,6 @@ def delete_record(container, name, id):
122
  except Exception as e:
123
  return False, f"An unexpected error occurred: {traceback.format_exc()} 😱"
124
 
125
- # 🎲 Function to generate a unique UUID
126
- def generate_unique_id():
127
- # πŸ§™β€β™‚οΈ Generating a unique UUID!
128
- return str(uuid.uuid4())
129
-
130
- # πŸ“¦ Function to archive current container
131
- def archive_current_container(database_name, container_name, client):
132
- # πŸ“¦ Archiving the entire containerβ€”time to pack up the stars! 🌠
133
- try:
134
- base_dir = "./cosmos_archive_current_container"
135
- if os.path.exists(base_dir):
136
- shutil.rmtree(base_dir)
137
- os.makedirs(base_dir)
138
-
139
- db_client = client.get_database_client(database_name)
140
- container_client = db_client.get_container_client(container_name)
141
- items = list(container_client.read_all_items())
142
-
143
- container_dir = os.path.join(base_dir, container_name)
144
- os.makedirs(container_dir)
145
-
146
- for item in items:
147
- item_id = item.get('id', f"unknown_{datetime.now().strftime('%Y%m%d%H%M%S')}")
148
- with open(os.path.join(container_dir, f"{item_id}.json"), 'w') as f:
149
- json.dump(item, f, indent=2)
150
-
151
- archive_name = f"{container_name}_archive_{datetime.now().strftime('%Y%m%d%H%M%S')}"
152
- shutil.make_archive(archive_name, 'zip', base_dir)
153
-
154
- return get_base64_download_link(f"{archive_name}.zip", f"{archive_name}.zip")
155
- except Exception as e:
156
- return f"An error occurred while archiving data: {str(e)} 😒"
157
-
158
-
159
- # πŸ”— Helper to extract hyperlinks
160
- def extract_hyperlinks(responses):
161
- # πŸ”— Extracting hyperlinksβ€”connecting the dots across the universe! πŸ•ΈοΈ
162
- hyperlinks = []
163
- for response in responses:
164
- parsed_response = json.loads(response)
165
- links = [value for key, value in parsed_response.items() if isinstance(value, str) and value.startswith("http")]
166
- hyperlinks.extend(links)
167
- return hyperlinks
168
-
169
- # πŸ“‹ Helper to format text with line numbers
170
- def format_with_line_numbers(text):
171
- # πŸ“‹ Formatting text with line numbersβ€”organizing the cosmos one line at a time! πŸ“
172
- lines = text.splitlines()
173
- formatted_text = '\n'.join(f"{i+1}: {line}" for i, line in enumerate(lines))
174
- return formatted_text
175
-
176
-
177
- def generate_unique_id():
178
- return str(uuid.uuid4())
179
-
180
- def get_databases(client):
181
- return [db['id'] for db in client.list_databases()]
182
-
183
- def get_containers(database):
184
- return [container['id'] for container in database.list_containers()]
185
-
186
- def get_documents(container, limit=None):
187
- query = "SELECT * FROM c ORDER BY c._ts DESC"
188
- items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
189
- return items
190
-
191
  def save_to_cosmos_db(container, query, response1, response2):
192
  try:
193
  if container:
@@ -195,7 +169,8 @@ def save_to_cosmos_db(container, query, response1, response2):
195
  "id": generate_unique_id(),
196
  "query": query,
197
  "response1": response1,
198
- "response2": response2
 
199
  }
200
  try:
201
  container.create_item(body=record)
@@ -209,193 +184,47 @@ def save_to_cosmos_db(container, query, response1, response2):
209
  except Exception as e:
210
  st.error(f"An unexpected error occurred: {str(e)}")
211
 
212
- # Add dropdowns for model and database choices
213
- def search_glossary(query):
214
- st.markdown(f"### πŸ” Search Glossary for: `{query}`")
215
-
216
- # Dropdown for model selection
217
- model_options = ['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None']
218
- model_choice = st.selectbox('🧠 Select LLM Model', options=model_options, index=1)
219
-
220
- # Dropdown for database selection
221
- database_options = ['Semantic Search', 'Arxiv Search - Latest - (EXPERIMENTAL)']
222
- database_choice = st.selectbox('πŸ“š Select Database', options=database_options, index=0)
223
-
224
-
225
-
226
- # Run Button with Emoji
227
- #if st.button("πŸš€ Run"):
228
-
229
- # πŸ•΅οΈβ€β™‚οΈ Searching the glossary for: query
230
- all_results = ""
231
- st.markdown(f"- {query}")
232
-
233
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM
234
- #database_choice Literal['Semantic Search', 'Arxiv Search - Latest - (EXPERIMENTAL)'] Default: "Semantic Search"
235
- #llm_model_picked Literal['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None'] Default: "mistralai/Mistral-7B-Instruct-v0.2"
236
- client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
237
-
238
-
239
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /ask_llm
240
- result = client.predict(
241
- prompt=query,
242
- llm_model_picked="mistralai/Mixtral-8x7B-Instruct-v0.1",
243
- stream_outputs=True,
244
- api_name="/ask_llm"
245
- )
246
- st.markdown(result)
247
- st.code(result, language="python", line_numbers=True)
248
-
249
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /ask_llm
250
- result2 = client.predict(
251
- prompt=query,
252
- llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
253
- stream_outputs=True,
254
- api_name="/ask_llm"
255
- )
256
- st.markdown(result2)
257
- st.code(result2, language="python", line_numbers=True)
258
-
259
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /ask_llm
260
- result3 = client.predict(
261
- prompt=query,
262
- llm_model_picked="google/gemma-7b-it",
263
- stream_outputs=True,
264
- api_name="/ask_llm"
265
- )
266
- st.markdown(result3)
267
- st.code(result3, language="python", line_numbers=True)
268
-
269
-
270
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /update_with_rag_md
271
- response2 = client.predict(
272
- message=query, # str in 'parameter_13' Textbox component
273
- llm_results_use=10,
274
- database_choice="Semantic Search",
275
- llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
276
- api_name="/update_with_rag_md"
277
- ) # update_with_rag_md Returns tuple of 2 elements [0] str The output value that appears in the "value_14" Markdown component. [1] str
278
-
279
- st.markdown(response2[0])
280
- st.code(response2[0], language="python", line_numbers=True, wrap_lines=True)
281
-
282
- st.markdown(response2[1])
283
- st.code(response2[1], language="python", line_numbers=True, wrap_lines=True)
284
-
285
- # When saving results, pass the container
286
- try:
287
- save_to_cosmos_db(st.session_state.cosmos_container, query, result, result)
288
- save_to_cosmos_db(st.session_state.cosmos_container, query, result2, result2)
289
- save_to_cosmos_db(st.session_state.cosmos_container, query, result3, result3)
290
- save_to_cosmos_db(st.session_state.cosmos_container, query, response2[0], response2[0])
291
- save_to_cosmos_db(st.session_state.cosmos_container, query, response2[1], response2[1])
292
- except exceptions.CosmosHttpResponseError as e:
293
- return False, f"HTTP error occurred: {str(e)} 🚨"
294
- except Exception as e:
295
- return False, f"An unexpected error occurred: {str(e)} 😱"
296
-
297
-
298
- try:
299
- # Aggregate hyperlinks and show with emojis
300
- hyperlinks = extract_hyperlinks([response1, response2])
301
- st.markdown("### πŸ”— Aggregated Hyperlinks")
302
- for link in hyperlinks:
303
- st.markdown(f"πŸ”— [{link}]({link})")
304
-
305
- # Show responses in a code format with line numbers
306
- st.markdown("### πŸ“œ Response Outputs with Line Numbers")
307
- st.code(f"Response 1: \n{format_with_line_numbers(response1)}\n\nResponse 2: \n{format_with_line_numbers(response2)}", language="json")
308
- except exceptions.CosmosHttpResponseError as e:
309
- return False, f"HTTP error occurred: {str(e)} 🚨"
310
- except Exception as e:
311
- return False, f"An unexpected error occurred: {str(e)} 😱"
312
-
313
-
314
-
315
-
316
- # 🎀 Function to process text input
317
- def process_text(text_input):
318
- # 🎀 Processing text inputβ€”translating human words into cosmic signals! πŸ“‘
319
- if text_input:
320
- if 'messages' not in st.session_state:
321
- st.session_state.messages = []
322
-
323
- st.session_state.messages.append({"role": "user", "content": text_input})
324
-
325
- with st.chat_message("user"):
326
- st.markdown(text_input)
327
-
328
- with st.chat_message("assistant"):
329
- search_glossary(text_input)
330
 
331
- # πŸ“ Function to generate a filename
332
- def generate_filename(text, file_type):
333
- # πŸ“ Generate a filename based on the text input
334
- safe_text = "".join(c if c.isalnum() or c in (' ', '.', '_') else '_' for c in text)
335
- safe_text = "_".join(safe_text.strip().split())
336
- filename = f"{safe_text}.{file_type}"
337
- return filename
338
 
339
- # πŸ•΅οΈβ€β™€οΈ Function to extract markdown title
340
- def extract_markdown_title(content):
341
- # πŸ•΅οΈβ€β™€οΈ Extracting markdown titleβ€”finding the headline in the cosmic news! πŸ“°
342
- lines = content.splitlines()
343
- for line in lines:
344
- if line.startswith('#'):
345
- return line.lstrip('#').strip()
346
- return None
347
 
348
- # πŸ’Ύ Function to create and save a file
349
- def create_and_save_file(content, file_type="md", prompt=None, is_image=False, should_save=True):
350
- # πŸ’Ύ Creating and saving a fileβ€”capturing cosmic wisdom! πŸ“
351
- if not should_save:
352
- return None
353
 
354
- # Step 1: Generate filename based on the prompt or content
355
- filename = generate_filename(prompt if prompt else content, file_type)
 
 
 
356
 
357
- # Step 2: If it's a markdown file, check if it has a title
358
- if file_type == "md":
359
- title_from_content = extract_markdown_title(content)
360
- if title_from_content:
361
- filename = generate_filename(title_from_content, file_type)
362
 
363
- # Step 3: Save the file
364
- with open(filename, "w", encoding="utf-8") as f:
365
- if is_image:
366
- f.write(content)
367
- else:
368
- f.write(prompt + "\n\n" + content)
369
 
370
- return filename
 
371
 
372
- # πŸ€– Function to insert an auto-generated record
373
- def insert_auto_generated_record(container):
374
- # πŸ€– Automatically generating a record and inserting it into Cosmos DB!
375
- try:
376
- # Generate a unique id
377
- new_id = generate_unique_id()
378
- # Create a sample JSON document
379
- new_doc = {
380
- 'id': new_id,
381
- 'name': f'Sample Name {new_id[:8]}',
382
- 'description': 'This is a sample auto-generated description.',
383
- 'timestamp': datetime.utcnow().isoformat()
384
- }
385
- # Insert the document
386
- container.create_item(body=new_doc)
387
- return True, f"Record inserted successfully with id: {new_id} πŸŽ‰"
388
- except exceptions.CosmosHttpResponseError as e:
389
- return False, f"HTTP error occurred: {str(e)} 🚨"
390
- except Exception as e:
391
- return False, f"An unexpected error occurred: {str(e)} 😱"
392
 
393
- # 🎈 Main function
394
  def main():
395
- # 🎈 Let's modify the main app to be more fun!
396
  st.title("πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent")
397
 
398
- # 🚦 Initialize session state
399
  if 'logged_in' not in st.session_state:
400
  st.session_state.logged_in = False
401
  if 'selected_records' not in st.session_state:
@@ -413,32 +242,21 @@ def main():
413
  if 'cloned_doc' not in st.session_state:
414
  st.session_state.cloned_doc = None
415
 
416
- # βš™οΈ q= Run ArXiv search from query parameters
417
- try:
418
- query_params = st.query_params
419
- query = query_params.get('q') or query_params.get('query') or ''
420
- if query:
421
- # πŸ•΅οΈβ€β™‚οΈ We have a query! Let's process it!
422
- process_text(query)
423
- st.stop() # Stop further execution
424
- except Exception as e:
425
- st.markdown(' ')
426
-
427
- # πŸ” Automatic Login
428
  if Key:
429
  st.session_state.primary_key = Key
430
  st.session_state.logged_in = True
431
  else:
432
  st.error("Cosmos DB Key is not set in environment variables. πŸ”‘βŒ")
433
- return # Can't proceed without a key
434
 
435
  if st.session_state.logged_in:
436
- # 🌌 Initialize Cosmos DB client
437
  try:
438
  if st.session_state.client is None:
439
  st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
440
 
441
- # πŸ—„οΈ Sidebar for database, container, and document selection
442
  st.sidebar.title("πŸ™Git🌌CosmosπŸ’«πŸ—„οΈNavigator")
443
 
444
  databases = get_databases(st.session_state.client)
@@ -465,7 +283,7 @@ def main():
465
  if st.session_state.selected_container:
466
  container = database.get_container_client(st.session_state.selected_container)
467
 
468
- # πŸ“¦ Add Export button
469
  if st.button("πŸ“¦ Export Container Data"):
470
  download_link = archive_current_container(st.session_state.selected_database, st.session_state.selected_container, st.session_state.client)
471
  if download_link.startswith('<a'):
@@ -485,17 +303,17 @@ def main():
485
  st.info(f"Showing all {len(documents_to_display)} documents.")
486
 
487
  if documents_to_display:
488
- # 🎨 Add Viewer/Editor selection
489
  view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit and Save', 'Clone Document', 'New Record']
490
  selected_view = st.selectbox("Select Viewer/Editor", view_options, index=2)
491
 
492
  if selected_view == 'Show as Markdown':
493
- # πŸ–ŒοΈ Show each record as Markdown with navigation
494
  total_docs = len(documents)
495
  doc = documents[st.session_state.current_index]
496
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
497
 
498
- # πŸ•΅οΈβ€β™‚οΈ Let's extract values from the JSON that have at least one space
499
  values_with_space = []
500
  def extract_values(obj):
501
  if isinstance(obj, dict):
@@ -510,25 +328,10 @@ def main():
510
 
511
  extract_values(doc)
512
 
513
- # πŸ”— Let's create a list of links for these values
514
- search_urls = {
515
- "πŸš€πŸŒŒArXiv": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}",
516
- "πŸƒAnalyst": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix')}",
517
- "πŸ“šPyCoder": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix2')}",
518
- "πŸ”¬JSCoder": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix3')}",
519
- "🏠": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}",
520
- "πŸ“–": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
521
- "πŸ”": lambda k: f"https://www.google.com/search?q={quote(k)}",
522
- "▢️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
523
- "πŸ”Ž": lambda k: f"https://www.bing.com/search?q={quote(k)}",
524
- "πŸŽ₯": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
525
- "🐦": lambda k: f"https://twitter.com/search?q={quote(k)}",
526
- }
527
-
528
  st.markdown("#### πŸ”— Links for Extracted Texts")
529
  for term in values_with_space:
530
- links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
531
- st.markdown(f"**{term}** <small>{links_md}</small>", unsafe_allow_html=True)
532
 
533
  # Show the document content as markdown
534
  content = json.dumps(doc, indent=2)
@@ -548,7 +351,7 @@ def main():
548
  st.rerun()
549
 
550
  elif selected_view == 'Show as Code Editor':
551
- # πŸ’» Show each record in a code editor with navigation
552
  total_docs = len(documents)
553
  doc = documents[st.session_state.current_index]
554
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
@@ -578,14 +381,13 @@ def main():
578
  st.error(f"Invalid JSON: {str(e)} 🚫")
579
 
580
  elif selected_view == 'Show as Edit and Save':
581
- # ✏️ Show as Edit and Save in columns
582
  st.markdown("#### Edit the document fields below:")
583
 
584
  # Create columns for each document
585
  num_cols = len(documents_to_display)
586
  cols = st.columns(num_cols)
587
 
588
-
589
  for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
590
  with col:
591
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
@@ -616,12 +418,8 @@ def main():
616
  # Use the entire document as input
617
  search_glossary(json.dumps(editable_doc, indent=2))
618
 
619
-
620
-
621
-
622
-
623
  elif selected_view == 'Clone Document':
624
- # 🧬 Clone Document per record
625
  st.markdown("#### Clone a document:")
626
  for idx, doc in enumerate(documents_to_display):
627
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
@@ -651,9 +449,9 @@ def main():
651
  st.error(message)
652
  except json.JSONDecodeError as e:
653
  st.error(f"Invalid JSON: {str(e)} 🚫")
654
-
655
  elif selected_view == 'New Record':
656
- # πŸ†• New Record
657
  st.markdown("#### Create a new document:")
658
  if st.button("πŸ€– Insert Auto-Generated Record"):
659
  success, message = insert_auto_generated_record(container)
@@ -679,11 +477,11 @@ def main():
679
  st.error(message)
680
  except json.JSONDecodeError as e:
681
  st.error(f"Invalid JSON: {str(e)} 🚫")
682
-
683
  else:
684
  st.sidebar.info("No documents found in this container. πŸ“­")
685
-
686
- # πŸŽ‰ Main content area
687
  st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
688
  if st.session_state.selected_container:
689
  if documents_to_display:
@@ -691,8 +489,8 @@ def main():
691
  st.dataframe(df)
692
  else:
693
  st.info("No documents to display. 🧐")
694
-
695
- # πŸ™ GitHub section
696
  st.subheader("πŸ™ GitHub Operations")
697
  github_token = os.environ.get("GITHUB") # Read GitHub token from environment variable
698
  source_repo = st.text_input("Source GitHub Repository URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
@@ -707,7 +505,7 @@ def main():
707
  download_github_repo(source_repo, local_path)
708
  zip_filename = f"{new_repo_name}.zip"
709
  create_zip_file(local_path, zip_filename[:-4])
710
- st.markdown(get_base64_download_link(zip_filename, zip_filename), unsafe_allow_html=True)
711
  st.success("Repository cloned successfully! πŸŽ‰")
712
  except Exception as e:
713
  st.error(f"An error occurred: {str(e)} 😒")
@@ -737,12 +535,84 @@ def main():
737
  else:
738
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740
  except exceptions.CosmosHttpResponseError as e:
741
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
742
  except Exception as e:
743
  st.error(f"An unexpected error occurred: {str(e)} 😱")
744
 
745
- # πŸšͺ Logout button
746
  if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
747
  st.session_state.logged_in = False
748
  st.session_state.selected_records.clear()
@@ -753,921 +623,5 @@ def main():
753
  st.session_state.current_index = 0
754
  st.rerun()
755
 
756
- # πŸ™ GitHub configuration
757
- def download_github_repo(url, local_path):
758
- # 🚚 Let's download that GitHub repo!
759
- if os.path.exists(local_path):
760
- shutil.rmtree(local_path)
761
- Repo.clone_from(url, local_path)
762
-
763
- def create_zip_file(source_dir, output_filename):
764
- # πŸ“¦ Zipping up files like a pro!
765
- shutil.make_archive(output_filename, 'zip', source_dir)
766
-
767
- def create_repo(g, repo_name):
768
- # πŸ› οΈ Creating a new GitHub repo. Magic!
769
- user = g.get_user()
770
- return user.create_repo(repo_name)
771
-
772
- def push_to_github(local_path, repo, github_token):
773
- # πŸš€ Pushing code to GitHub. Hold on tight!
774
- repo_url = f"https://{github_token}@github.com/{repo.full_name}.git"
775
- local_repo = Repo(local_path)
776
-
777
- if 'origin' in [remote.name for remote in local_repo.remotes]:
778
- origin = local_repo.remote('origin')
779
- origin.set_url(repo_url)
780
- else:
781
- origin = local_repo.create_remote('origin', repo_url)
782
-
783
- if not local_repo.heads:
784
- local_repo.git.checkout('-b', 'main')
785
- current_branch = 'main'
786
- else:
787
- current_branch = local_repo.active_branch.name
788
-
789
- local_repo.git.add(A=True)
790
-
791
- if local_repo.is_dirty():
792
- local_repo.git.commit('-m', 'Initial commit')
793
-
794
- origin.push(refspec=f'{current_branch}:{current_branch}')
795
-
796
- def get_base64_download_link(file_path, file_name):
797
- # πŸ§™β€β™‚οΈ Generating a magical download link!
798
- with open(file_path, "rb") as file:
799
- contents = file.read()
800
- base64_encoded = base64.b64encode(contents).decode()
801
- return f'<a href="data:application/zip;base64,{base64_encoded}" download="{file_name}">⬇️ Download {file_name}</a>'
802
-
803
-
804
- # 🧭 New functions for dynamic sidebar navigation
805
- def get_databases(client):
806
- # πŸ“š Fetching list of databases. So many options!
807
- return [db['id'] for db in client.list_databases()]
808
-
809
- def get_containers(database):
810
- # πŸ“‚ Getting containers. Containers within containers!
811
- return [container['id'] for container in database.list_containers()]
812
-
813
- def get_documents(container, limit=None):
814
- # πŸ“ Retrieving documents. Shhh, don't tell anyone!
815
- query = "SELECT * FROM c ORDER BY c._ts DESC"
816
- items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
817
- return items
818
-
819
-
820
- # 🌟 Cosmos DB functions
821
- def insert_record(container, record):
822
- # πŸ“₯ Inserting a record into the Cosmosβ€”hope we don't disturb any aliens! πŸ‘½
823
- try:
824
- container.create_item(body=record)
825
- return True, "Record inserted successfully! πŸŽ‰"
826
- except exceptions.CosmosHttpResponseError as e:
827
- return False, f"HTTP error occurred: {str(e)} 🚨"
828
- except Exception as e:
829
- return False, f"An unexpected error occurred: {str(e)} 😱"
830
-
831
- def update_record(container, updated_record):
832
- # πŸ”„ Updating a recordβ€”giving it a cosmic makeover! ✨
833
- try:
834
- container.upsert_item(body=updated_record)
835
- return True, f"Record with id {updated_record['id']} successfully updated. πŸ› οΈ"
836
- except exceptions.CosmosHttpResponseError as e:
837
- return False, f"HTTP error occurred: {str(e)} 🚨"
838
- except Exception as e:
839
- return False, f"An unexpected error occurred: {traceback.format_exc()} 😱"
840
-
841
- def delete_record(container, name, id):
842
- # πŸ—‘οΈ Deleting a recordβ€”sending it into the cosmic void! 🌌
843
- try:
844
- container.delete_item(item=id, partition_key=id)
845
- return True, f"Successfully deleted record with name: {name} and id: {id} πŸ—‘οΈ"
846
- except exceptions.CosmosResourceNotFoundError:
847
- return False, f"Record with id {id} not found. It may have been already deleted. πŸ•΅οΈβ€β™‚οΈ"
848
- except exceptions.CosmosHttpResponseError as e:
849
- return False, f"HTTP error occurred: {str(e)} 🚨"
850
- except Exception as e:
851
- return False, f"An unexpected error occurred: {traceback.format_exc()} 😱"
852
-
853
- # 🎲 Function to generate a unique UUID
854
- def generate_unique_id():
855
- # πŸ§™β€β™‚οΈ Generating a unique UUID!
856
- return str(uuid.uuid4())
857
-
858
- # πŸ“¦ Function to archive current container
859
- def archive_current_container(database_name, container_name, client):
860
- # πŸ“¦ Archiving the entire containerβ€”time to pack up the stars! 🌠
861
- try:
862
- base_dir = "./cosmos_archive_current_container"
863
- if os.path.exists(base_dir):
864
- shutil.rmtree(base_dir)
865
- os.makedirs(base_dir)
866
-
867
- db_client = client.get_database_client(database_name)
868
- container_client = db_client.get_container_client(container_name)
869
- items = list(container_client.read_all_items())
870
-
871
- container_dir = os.path.join(base_dir, container_name)
872
- os.makedirs(container_dir)
873
-
874
- for item in items:
875
- item_id = item.get('id', f"unknown_{datetime.now().strftime('%Y%m%d%H%M%S')}")
876
- with open(os.path.join(container_dir, f"{item_id}.json"), 'w') as f:
877
- json.dump(item, f, indent=2)
878
-
879
- archive_name = f"{container_name}_archive_{datetime.now().strftime('%Y%m%d%H%M%S')}"
880
- shutil.make_archive(archive_name, 'zip', base_dir)
881
-
882
- return get_base64_download_link(f"{archive_name}.zip", f"{archive_name}.zip")
883
- except Exception as e:
884
- return f"An error occurred while archiving data: {str(e)} 😒"
885
-
886
-
887
- # πŸ”— Helper to extract hyperlinks
888
- def extract_hyperlinks(responses):
889
- # πŸ”— Extracting hyperlinksβ€”connecting the dots across the universe! πŸ•ΈοΈ
890
- hyperlinks = []
891
- for response in responses:
892
- parsed_response = json.loads(response)
893
- links = [value for key, value in parsed_response.items() if isinstance(value, str) and value.startswith("http")]
894
- hyperlinks.extend(links)
895
- return hyperlinks
896
-
897
- # πŸ“‹ Helper to format text with line numbers
898
- def format_with_line_numbers(text):
899
- # πŸ“‹ Formatting text with line numbersβ€”organizing the cosmos one line at a time! πŸ“
900
- lines = text.splitlines()
901
- formatted_text = '\n'.join(f"{i+1}: {line}" for i, line in enumerate(lines))
902
- return formatted_text
903
-
904
-
905
- def generate_unique_id():
906
- return str(uuid.uuid4())
907
-
908
- def get_databases(client):
909
- return [db['id'] for db in client.list_databases()]
910
-
911
- def get_containers(database):
912
- return [container['id'] for container in database.list_containers()]
913
-
914
- def get_documents(container, limit=None):
915
- query = "SELECT * FROM c ORDER BY c._ts DESC"
916
- items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
917
- return items
918
-
919
- def save_to_cosmos_db(container, query, response1, response2):
920
- try:
921
- if container:
922
- record = {
923
- "id": generate_unique_id(),
924
- "query": query,
925
- "response1": response1,
926
- "response2": response2
927
- }
928
- try:
929
- container.create_item(body=record)
930
- st.success(f"Record saved successfully with ID: {record['id']}")
931
- # Refresh the documents display
932
- st.session_state.documents = get_documents(container)
933
- except exceptions.CosmosHttpResponseError as e:
934
- st.error(f"Error saving record to Cosmos DB: {e}")
935
- else:
936
- st.error("Cosmos DB container is not initialized.")
937
- except Exception as e:
938
- st.error(f"An unexpected error occurred: {str(e)}")
939
-
940
- # Add dropdowns for model and database choices
941
- def search_glossary(query):
942
- st.markdown(f"### πŸ” Search Glossary for: `{query}`")
943
-
944
- # Dropdown for model selection
945
- model_options = ['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None']
946
- model_choice = st.selectbox('🧠 Select LLM Model', options=model_options, index=1)
947
-
948
- # Dropdown for database selection
949
- database_options = ['Semantic Search', 'Arxiv Search - Latest - (EXPERIMENTAL)']
950
- database_choice = st.selectbox('πŸ“š Select Database', options=database_options, index=0)
951
-
952
-
953
-
954
- # Run Button with Emoji
955
- #if st.button("πŸš€ Run"):
956
-
957
- # πŸ•΅οΈβ€β™‚οΈ Searching the glossary for: query
958
- all_results = ""
959
- st.markdown(f"- {query}")
960
-
961
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM
962
- #database_choice Literal['Semantic Search', 'Arxiv Search - Latest - (EXPERIMENTAL)'] Default: "Semantic Search"
963
- #llm_model_picked Literal['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None'] Default: "mistralai/Mistral-7B-Instruct-v0.2"
964
- client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
965
-
966
-
967
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /ask_llm
968
- result = client.predict(
969
- prompt=query,
970
- llm_model_picked="mistralai/Mixtral-8x7B-Instruct-v0.1",
971
- stream_outputs=True,
972
- api_name="/ask_llm"
973
- )
974
- st.markdown(result)
975
- st.code(result, language="python", line_numbers=True)
976
-
977
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /ask_llm
978
- result2 = client.predict(
979
- prompt=query,
980
- llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
981
- stream_outputs=True,
982
- api_name="/ask_llm"
983
- )
984
- st.markdown(result2)
985
- st.code(result2, language="python", line_numbers=True)
986
-
987
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /ask_llm
988
- result3 = client.predict(
989
- prompt=query,
990
- llm_model_picked="google/gemma-7b-it",
991
- stream_outputs=True,
992
- api_name="/ask_llm"
993
- )
994
- st.markdown(result3)
995
- st.code(result3, language="python", line_numbers=True)
996
-
997
-
998
- # πŸ” ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /update_with_rag_md
999
- response2 = client.predict(
1000
- message=query, # str in 'parameter_13' Textbox component
1001
- llm_results_use=10,
1002
- database_choice="Semantic Search",
1003
- llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
1004
- api_name="/update_with_rag_md"
1005
- ) # update_with_rag_md Returns tuple of 2 elements [0] str The output value that appears in the "value_14" Markdown component. [1] str
1006
-
1007
- st.markdown(response2[0])
1008
- st.code(response2[0], language="python", line_numbers=True, wrap_lines=True)
1009
-
1010
- st.markdown(response2[1])
1011
- st.code(response2[1], language="python", line_numbers=True, wrap_lines=True)
1012
-
1013
- # When saving results, pass the container
1014
- try:
1015
- save_to_cosmos_db(st.session_state.cosmos_container, query, result, result)
1016
- save_to_cosmos_db(st.session_state.cosmos_container, query, result2, result2)
1017
- save_to_cosmos_db(st.session_state.cosmos_container, query, result3, result3)
1018
- save_to_cosmos_db(st.session_state.cosmos_container, query, response2[0], response2[0])
1019
- save_to_cosmos_db(st.session_state.cosmos_container, query, response2[1], response2[1])
1020
- except exceptions.CosmosHttpResponseError as e:
1021
- return False, f"HTTP error occurred: {str(e)} 🚨"
1022
- except Exception as e:
1023
- return False, f"An unexpected error occurred: {str(e)} 😱"
1024
-
1025
-
1026
- try:
1027
- # Aggregate hyperlinks and show with emojis
1028
- hyperlinks = extract_hyperlinks([response1, response2])
1029
- st.markdown("### πŸ”— Aggregated Hyperlinks")
1030
- for link in hyperlinks:
1031
- st.markdown(f"πŸ”— [{link}]({link})")
1032
-
1033
- # Show responses in a code format with line numbers
1034
- st.markdown("### πŸ“œ Response Outputs with Line Numbers")
1035
- st.code(f"Response 1: \n{format_with_line_numbers(response1)}\n\nResponse 2: \n{format_with_line_numbers(response2)}", language="json")
1036
- except exceptions.CosmosHttpResponseError as e:
1037
- return False, f"HTTP error occurred: {str(e)} 🚨"
1038
- except Exception as e:
1039
- return False, f"An unexpected error occurred: {str(e)} 😱"
1040
-
1041
-
1042
-
1043
-
1044
- # 🎀 Function to process text input
1045
- def process_text(text_input):
1046
- # 🎀 Processing text inputβ€”translating human words into cosmic signals! πŸ“‘
1047
- if text_input:
1048
- if 'messages' not in st.session_state:
1049
- st.session_state.messages = []
1050
-
1051
- st.session_state.messages.append({"role": "user", "content": text_input})
1052
-
1053
- with st.chat_message("user"):
1054
- st.markdown(text_input)
1055
-
1056
- with st.chat_message("assistant"):
1057
- search_glossary(text_input)
1058
-
1059
- # πŸ“ Function to generate a filename
1060
- def generate_filename(text, file_type):
1061
- # πŸ“ Generate a filename based on the text input
1062
- safe_text = "".join(c if c.isalnum() or c in (' ', '.', '_') else '_' for c in text)
1063
- safe_text = "_".join(safe_text.strip().split())
1064
- filename = f"{safe_text}.{file_type}"
1065
- return filename
1066
-
1067
- # πŸ•΅οΈβ€β™€οΈ Function to extract markdown title
1068
- def extract_markdown_title(content):
1069
- # πŸ•΅οΈβ€β™€οΈ Extracting markdown titleβ€”finding the headline in the cosmic news! πŸ“°
1070
- lines = content.splitlines()
1071
- for line in lines:
1072
- if line.startswith('#'):
1073
- return line.lstrip('#').strip()
1074
- return None
1075
-
1076
- # πŸ’Ύ Function to create and save a file
1077
- def create_and_save_file(content, file_type="md", prompt=None, is_image=False, should_save=True):
1078
- # πŸ’Ύ Creating and saving a fileβ€”capturing cosmic wisdom! πŸ“
1079
- if not should_save:
1080
- return None
1081
-
1082
- # Step 1: Generate filename based on the prompt or content
1083
- filename = generate_filename(prompt if prompt else content, file_type)
1084
-
1085
- # Step 2: If it's a markdown file, check if it has a title
1086
- if file_type == "md":
1087
- title_from_content = extract_markdown_title(content)
1088
- if title_from_content:
1089
- filename = generate_filename(title_from_content, file_type)
1090
-
1091
- # Step 3: Save the file
1092
- with open(filename, "w", encoding="utf-8") as f:
1093
- if is_image:
1094
- f.write(content)
1095
- else:
1096
- f.write(prompt + "\n\n" + content)
1097
-
1098
- return filename
1099
-
1100
- # πŸ€– Function to insert an auto-generated record
1101
- def insert_auto_generated_record(container):
1102
- # πŸ€– Automatically generating a record and inserting it into Cosmos DB!
1103
- try:
1104
- # Generate a unique id
1105
- new_id = generate_unique_id()
1106
- # Create a sample JSON document
1107
- new_doc = {
1108
- 'id': new_id,
1109
- 'name': f'Sample Name {new_id[:8]}',
1110
- 'description': 'This is a sample auto-generated description.',
1111
- 'timestamp': datetime.utcnow().isoformat()
1112
- }
1113
- # Insert the document
1114
- container.create_item(body=new_doc)
1115
- return True, f"Record inserted successfully with id: {new_id} πŸŽ‰"
1116
- except exceptions.CosmosHttpResponseError as e:
1117
- return False, f"HTTP error occurred: {str(e)} 🚨"
1118
- except Exception as e:
1119
- return False, f"An unexpected error occurred: {str(e)} 😱"
1120
-
1121
- # 🎈 Main function
1122
- def main2():
1123
- # 🎈 Let's modify the main app to be more fun!
1124
- st.title("πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent")
1125
-
1126
- # 🚦 Initialize session state
1127
- if 'logged_in' not in st.session_state:
1128
- st.session_state.logged_in = False
1129
- if 'selected_records' not in st.session_state:
1130
- st.session_state.selected_records = []
1131
- if 'client' not in st.session_state:
1132
- st.session_state.client = None
1133
- if 'selected_database' not in st.session_state:
1134
- st.session_state.selected_database = None
1135
- if 'selected_container' not in st.session_state:
1136
- st.session_state.selected_container = None
1137
- if 'selected_document_id' not in st.session_state:
1138
- st.session_state.selected_document_id = None
1139
- if 'current_index' not in st.session_state:
1140
- st.session_state.current_index = 0
1141
- if 'cloned_doc' not in st.session_state:
1142
- st.session_state.cloned_doc = None
1143
-
1144
- # βš™οΈ q= Run ArXiv search from query parameters
1145
- try:
1146
- query_params = st.query_params
1147
- query = query_params.get('q') or query_params.get('query') or ''
1148
- if query:
1149
- # πŸ•΅οΈβ€β™‚οΈ We have a query! Let's process it!
1150
- process_text(query)
1151
- st.stop() # Stop further execution
1152
- except Exception as e:
1153
- st.markdown(' ')
1154
-
1155
- # πŸ” Automatic Login
1156
- if Key:
1157
- st.session_state.primary_key = Key
1158
- st.session_state.logged_in = True
1159
- else:
1160
- st.error("Cosmos DB Key is not set in environment variables. πŸ”‘βŒ")
1161
- return # Can't proceed without a key
1162
-
1163
- if st.session_state.logged_in:
1164
- # 🌌 Initialize Cosmos DB client
1165
- try:
1166
- if st.session_state.client is None:
1167
- st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
1168
-
1169
- # πŸ—„οΈ Sidebar for database, container, and document selection
1170
- st.sidebar.title("πŸ™Git🌌CosmosπŸ’«πŸ—„οΈNavigator")
1171
-
1172
- databases = get_databases(st.session_state.client)
1173
- selected_db = st.sidebar.selectbox("πŸ—ƒοΈ Select Database", databases)
1174
-
1175
- if selected_db != st.session_state.selected_database:
1176
- st.session_state.selected_database = selected_db
1177
- st.session_state.selected_container = None
1178
- st.session_state.selected_document_id = None
1179
- st.session_state.current_index = 0
1180
- st.rerun()
1181
-
1182
- if st.session_state.selected_database:
1183
- database = st.session_state.client.get_database_client(st.session_state.selected_database)
1184
- containers = get_containers(database)
1185
- selected_container = st.sidebar.selectbox("πŸ“ Select Container", containers)
1186
-
1187
- if selected_container != st.session_state.selected_container:
1188
- st.session_state.selected_container = selected_container
1189
- st.session_state.selected_document_id = None
1190
- st.session_state.current_index = 0
1191
- st.rerun()
1192
-
1193
- if st.session_state.selected_container:
1194
- container = database.get_container_client(st.session_state.selected_container)
1195
-
1196
- # πŸ“¦ Add Export button
1197
- if st.button("πŸ“¦ Export Container Data"):
1198
- download_link = archive_current_container(st.session_state.selected_database, st.session_state.selected_container, st.session_state.client)
1199
- if download_link.startswith('<a'):
1200
- st.markdown(download_link, unsafe_allow_html=True)
1201
- else:
1202
- st.error(download_link)
1203
-
1204
- # Fetch documents
1205
- documents = get_documents(container)
1206
- total_docs = len(documents)
1207
-
1208
- if total_docs > 5:
1209
- documents_to_display = documents[:5]
1210
- st.info("Showing top 5 most recent documents.")
1211
- else:
1212
- documents_to_display = documents
1213
- st.info(f"Showing all {len(documents_to_display)} documents.")
1214
-
1215
- if documents_to_display:
1216
- # 🎨 Add Viewer/Editor selection
1217
- view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit and Save', 'Clone Document', 'New Record']
1218
- selected_view = st.selectbox("Select Viewer/Editor", view_options, index=2)
1219
-
1220
- if selected_view == 'Show as Markdown':
1221
- # πŸ–ŒοΈ Show each record as Markdown with navigation
1222
- total_docs = len(documents)
1223
- doc = documents[st.session_state.current_index]
1224
- st.markdown(f"#### Document ID: {doc.get('id', '')}")
1225
-
1226
- # πŸ•΅οΈβ€β™‚οΈ Let's extract values from the JSON that have at least one space
1227
- values_with_space = []
1228
- def extract_values(obj):
1229
- if isinstance(obj, dict):
1230
- for k, v in obj.items():
1231
- extract_values(v)
1232
- elif isinstance(obj, list):
1233
- for item in obj:
1234
- extract_values(item)
1235
- elif isinstance(obj, str):
1236
- if ' ' in obj:
1237
- values_with_space.append(obj)
1238
-
1239
- extract_values(doc)
1240
-
1241
- # πŸ”— Let's create a list of links for these values
1242
- search_urls = {
1243
- "πŸš€πŸŒŒArXiv": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}",
1244
- "πŸƒAnalyst": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix')}",
1245
- "πŸ“šPyCoder": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix2')}",
1246
- "πŸ”¬JSCoder": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix3')}",
1247
- "🏠": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}",
1248
- "πŸ“–": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
1249
- "πŸ”": lambda k: f"https://www.google.com/search?q={quote(k)}",
1250
- "▢️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
1251
- "πŸ”Ž": lambda k: f"https://www.bing.com/search?q={quote(k)}",
1252
- "πŸŽ₯": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
1253
- "🐦": lambda k: f"https://twitter.com/search?q={quote(k)}",
1254
- }
1255
-
1256
- st.markdown("#### πŸ”— Links for Extracted Texts")
1257
- for term in values_with_space:
1258
- links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
1259
- st.markdown(f"**{term}** <small>{links_md}</small>", unsafe_allow_html=True)
1260
-
1261
- # Show the document content as markdown
1262
- content = json.dumps(doc, indent=2)
1263
- st.markdown(f"```json\n{content}\n```")
1264
-
1265
- # Navigation buttons
1266
- col_prev, col_next = st.columns([1, 1])
1267
- with col_prev:
1268
- if st.button("⬅️ Previous", key='prev_markdown'):
1269
- if st.session_state.current_index > 0:
1270
- st.session_state.current_index -= 1
1271
- st.rerun()
1272
- with col_next:
1273
- if st.button("➑️ Next", key='next_markdown'):
1274
- if st.session_state.current_index < total_docs - 1:
1275
- st.session_state.current_index += 1
1276
- st.rerun()
1277
-
1278
- elif selected_view == 'Show as Code Editor':
1279
- # πŸ’» Show each record in a code editor with navigation
1280
- total_docs = len(documents)
1281
- doc = documents[st.session_state.current_index]
1282
- st.markdown(f"#### Document ID: {doc.get('id', '')}")
1283
- doc_str = st.text_area("Edit Document", value=json.dumps(doc, indent=2), height=300, key=f'code_editor_{st.session_state.current_index}')
1284
- col_prev, col_next = st.columns([1, 1])
1285
- with col_prev:
1286
- if st.button("⬅️ Previous", key='prev_code'):
1287
- if st.session_state.current_index > 0:
1288
- st.session_state.current_index -= 1
1289
- st.rerun()
1290
- with col_next:
1291
- if st.button("➑️ Next", key='next_code'):
1292
- if st.session_state.current_index < total_docs - 1:
1293
- st.session_state.current_index += 1
1294
- st.rerun()
1295
- if st.button("πŸ’Ύ Save Changes", key=f'save_button_{st.session_state.current_index}'):
1296
- try:
1297
- updated_doc = json.loads(doc_str)
1298
- success, message = update_record(container, updated_doc)
1299
- if success:
1300
- st.success(f"Document {updated_doc['id']} saved successfully.")
1301
- st.session_state.selected_document_id = updated_doc['id']
1302
- st.rerun()
1303
- else:
1304
- st.error(message)
1305
- except json.JSONDecodeError as e:
1306
- st.error(f"Invalid JSON: {str(e)} 🚫")
1307
-
1308
- elif selected_view == 'Show as Edit and Save':
1309
- # ✏️ Show as Edit and Save in columns
1310
- st.markdown("#### Edit the document fields below:")
1311
-
1312
- # Create columns for each document
1313
- num_cols = len(documents_to_display)
1314
- cols = st.columns(num_cols)
1315
-
1316
-
1317
- for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
1318
- with col:
1319
- st.markdown(f"##### Document ID: {doc.get('id', '')}")
1320
- editable_id = st.text_input("ID", value=doc.get('id', ''), key=f'edit_id_{idx}')
1321
- # Remove 'id' from the document for editing other fields
1322
- editable_doc = doc.copy()
1323
- editable_doc.pop('id', None)
1324
- doc_str = st.text_area("Document Content (in JSON format)", value=json.dumps(editable_doc, indent=2), height=300, key=f'doc_str_{idx}')
1325
-
1326
- # Add the "Run With AI" button next to "Save Changes"
1327
- col_save, col_ai = st.columns(2)
1328
- with col_save:
1329
- if st.button("πŸ’Ύ Save Changes", key=f'save_button_{idx}'):
1330
- try:
1331
- updated_doc = json.loads(doc_str)
1332
- updated_doc['id'] = editable_id # Include the possibly edited ID
1333
- success, message = update_record(container, updated_doc)
1334
- if success:
1335
- st.success(f"Document {updated_doc['id']} saved successfully.")
1336
- st.session_state.selected_document_id = updated_doc['id']
1337
- st.rerun()
1338
- else:
1339
- st.error(message)
1340
- except json.JSONDecodeError as e:
1341
- st.error(f"Invalid JSON: {str(e)} 🚫")
1342
- with col_ai:
1343
- if st.button("πŸ€– Run With AI", key=f'run_with_ai_button_{idx}'):
1344
- # Use the entire document as input
1345
- search_glossary(json.dumps(editable_doc, indent=2))
1346
-
1347
-
1348
-
1349
-
1350
-
1351
- elif selected_view == 'Clone Document':
1352
- # 🧬 Clone Document per record
1353
- st.markdown("#### Clone a document:")
1354
- for idx, doc in enumerate(documents_to_display):
1355
- st.markdown(f"##### Document ID: {doc.get('id', '')}")
1356
- if st.button("πŸ“„ Clone Document", key=f'clone_button_{idx}'):
1357
- cloned_doc = doc.copy()
1358
- # Generate a unique ID
1359
- cloned_doc['id'] = generate_unique_id()
1360
- st.session_state.cloned_doc = cloned_doc
1361
- st.session_state.cloned_doc_str = json.dumps(cloned_doc, indent=2)
1362
- st.session_state.clone_mode = True
1363
- st.rerun()
1364
- if st.session_state.get('clone_mode', False):
1365
- st.markdown("#### Edit Cloned Document:")
1366
- cloned_doc_str = st.text_area("Cloned Document Content (in JSON format)", value=st.session_state.cloned_doc_str, height=300)
1367
- if st.button("πŸ’Ύ Save Cloned Document"):
1368
- try:
1369
- new_doc = json.loads(cloned_doc_str)
1370
- success, message = insert_record(container, new_doc)
1371
- if success:
1372
- st.success(f"Cloned document saved with id: {new_doc['id']} πŸŽ‰")
1373
- st.session_state.selected_document_id = new_doc['id']
1374
- st.session_state.clone_mode = False
1375
- st.session_state.cloned_doc = None
1376
- st.session_state.cloned_doc_str = ''
1377
- st.rerun()
1378
- else:
1379
- st.error(message)
1380
- except json.JSONDecodeError as e:
1381
- st.error(f"Invalid JSON: {str(e)} 🚫")
1382
-
1383
- elif selected_view == 'New Record':
1384
- # πŸ†• New Record
1385
- st.markdown("#### Create a new document:")
1386
- if st.button("πŸ€– Insert Auto-Generated Record"):
1387
- success, message = insert_auto_generated_record(container)
1388
- if success:
1389
- st.success(message)
1390
- st.rerun()
1391
- else:
1392
- st.error(message)
1393
- else:
1394
- new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
1395
- new_doc_str = st.text_area("Document Content (in JSON format)", value='{}', height=300)
1396
- if st.button("βž• Create New Document"):
1397
- try:
1398
- new_doc = json.loads(new_doc_str)
1399
- new_doc['id'] = new_id # Use the provided ID
1400
- success, message = insert_record(container, new_doc)
1401
- if success:
1402
- st.success(f"New document created with id: {new_doc['id']} πŸŽ‰")
1403
- st.session_state.selected_document_id = new_doc['id']
1404
- # Switch to 'Show as Edit and Save' mode
1405
- st.rerun()
1406
- else:
1407
- st.error(message)
1408
- except json.JSONDecodeError as e:
1409
- st.error(f"Invalid JSON: {str(e)} 🚫")
1410
-
1411
- else:
1412
- st.sidebar.info("No documents found in this container. πŸ“­")
1413
-
1414
- # πŸŽ‰ Main content area
1415
- st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
1416
- if st.session_state.selected_container:
1417
- if documents_to_display:
1418
- df = pd.DataFrame(documents_to_display)
1419
- st.dataframe(df)
1420
- else:
1421
- st.info("No documents to display. 🧐")
1422
-
1423
- # πŸ™ GitHub section
1424
- st.subheader("πŸ™ GitHub Operations")
1425
- github_token = os.environ.get("GITHUB") # Read GitHub token from environment variable
1426
- source_repo = st.text_input("Source GitHub Repository URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
1427
- new_repo_name = st.text_input("New Repository Name (for cloning)", value=f"AIExample-Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
1428
-
1429
- col1, col2 = st.columns(2)
1430
- with col1:
1431
- if st.button("πŸ“₯ Clone Repository"):
1432
- if github_token and source_repo:
1433
- try:
1434
- local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
1435
- download_github_repo(source_repo, local_path)
1436
- zip_filename = f"{new_repo_name}.zip"
1437
- create_zip_file(local_path, zip_filename[:-4])
1438
- st.markdown(get_base64_download_link(zip_filename, zip_filename), unsafe_allow_html=True)
1439
- st.success("Repository cloned successfully! πŸŽ‰")
1440
- except Exception as e:
1441
- st.error(f"An error occurred: {str(e)} 😒")
1442
- finally:
1443
- if os.path.exists(local_path):
1444
- shutil.rmtree(local_path)
1445
- if os.path.exists(zip_filename):
1446
- os.remove(zip_filename)
1447
- else:
1448
- st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
1449
-
1450
- with col2:
1451
- if st.button("πŸ“€ Push to New Repository"):
1452
- if github_token and source_repo:
1453
- try:
1454
- g = Github(github_token)
1455
- new_repo = create_repo(g, new_repo_name)
1456
- local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
1457
- download_github_repo(source_repo, local_path)
1458
- push_to_github(local_path, new_repo, github_token)
1459
- st.success(f"Repository pushed successfully to {new_repo.html_url} πŸš€")
1460
- except Exception as e:
1461
- st.error(f"An error occurred: {str(e)} 😒")
1462
- finally:
1463
- if os.path.exists(local_path):
1464
- shutil.rmtree(local_path)
1465
- else:
1466
- st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
1467
-
1468
- except exceptions.CosmosHttpResponseError as e:
1469
- st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
1470
- except Exception as e:
1471
- st.error(f"An unexpected error occurred: {str(e)} 😱")
1472
-
1473
- # πŸšͺ Logout button
1474
- if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
1475
- st.session_state.logged_in = False
1476
- st.session_state.selected_records.clear()
1477
- st.session_state.client = None
1478
- st.session_state.selected_database = None
1479
- st.session_state.selected_container = None
1480
- st.session_state.selected_document_id = None
1481
- st.session_state.current_index = 0
1482
- st.rerun()
1483
-
1484
-
1485
-
1486
-
1487
-
1488
-
1489
-
1490
- # Set up the Anthropic client
1491
- client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
1492
-
1493
- # Initialize session state
1494
- if "chat_history" not in st.session_state:
1495
- st.session_state.chat_history = []
1496
-
1497
- # Helper Functions: All Your Essentials πŸš€
1498
-
1499
- # Function to get a file download link (because you deserve easy downloads 😎)
1500
- def get_download_link(file_path):
1501
- with open(file_path, "rb") as file:
1502
- contents = file.read()
1503
- b64 = base64.b64encode(contents).decode()
1504
- file_name = os.path.basename(file_path)
1505
- return f'<a href="data:file/txt;base64,{b64}" download="{file_name}">Download {file_name}πŸ“‚</a>'
1506
-
1507
- # Function to generate a filename based on prompt and time (because names matter πŸ•’)
1508
- def generate_filename(prompt, file_type):
1509
- central = pytz.timezone('US/Central')
1510
- safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
1511
- safe_prompt = re.sub(r'\W+', '_', prompt)[:90]
1512
- return f"{safe_date_time}_{safe_prompt}.{file_type}"
1513
-
1514
- # Function to create and save a file (and avoid the black hole of lost data πŸ•³)
1515
- def create_file(filename, prompt, response, should_save=True):
1516
- if not should_save:
1517
- return
1518
- with open(filename, 'w', encoding='utf-8') as file:
1519
- file.write(prompt + "\n\n" + response)
1520
-
1521
- # Function to load file content (for revisiting the past πŸ“œ)
1522
- def load_file(file_name):
1523
- with open(file_name, "r", encoding='utf-8') as file:
1524
- content = file.read()
1525
- return content
1526
-
1527
- # Function to display handy glossary entity links (search like a pro πŸ”)
1528
- def display_glossary_entity(k):
1529
- search_urls = {
1530
- "πŸš€πŸŒŒArXiv": lambda k: f"/?q={quote(k)}",
1531
- "πŸ“–": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
1532
- "πŸ”": lambda k: f"https://www.google.com/search?q={quote(k)}",
1533
- "πŸŽ₯": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
1534
- }
1535
- links_md = ' '.join([f"[{emoji}]({url(k)})" for emoji, url in search_urls.items()])
1536
- st.markdown(f"**{k}** <small>{links_md}</small>", unsafe_allow_html=True)
1537
-
1538
- # Function to create zip of files (because more is more 🧳)
1539
- def create_zip_of_files(files):
1540
- import zipfile
1541
- zip_name = "all_files.zip"
1542
- with zipfile.ZipFile(zip_name, 'w') as zipf:
1543
- for file in files:
1544
- zipf.write(file)
1545
- return zip_name
1546
-
1547
- # Function to create HTML for autoplaying and looping video (for the full cinematic effect πŸŽ₯)
1548
- def get_video_html(video_path, width="100%"):
1549
- video_url = f"data:video/mp4;base64,{base64.b64encode(open(video_path, 'rb').read()).decode()}"
1550
- return f'''
1551
- <video width="{width}" controls autoplay muted loop>
1552
- <source src="{video_url}" type="video/mp4">
1553
- Your browser does not support the video tag.
1554
- </video>
1555
- '''
1556
-
1557
- # Function to create HTML for audio player (when life needs a soundtrack 🎢)
1558
- def get_audio_html(audio_path, width="100%"):
1559
- audio_url = f"data:audio/mpeg;base64,{base64.b64encode(open(audio_path, 'rb').read()).decode()}"
1560
- return f'''
1561
- <audio controls style="width: {width};">
1562
- <source src="{audio_url}" type="audio/mpeg">
1563
- Your browser does not support the audio element.
1564
- </audio>
1565
- '''
1566
-
1567
-
1568
- # Streamlit App Layout (like a house with better flow 🏑)
1569
- def main():
1570
-
1571
- # Sidebar with Useful Controls (All the VIP actions πŸŽ›)
1572
- st.sidebar.title("🧠ClaudeπŸ“")
1573
-
1574
- all_files = glob.glob("*.md")
1575
- all_files.sort(reverse=True)
1576
-
1577
- if st.sidebar.button("πŸ—‘ Delete All"):
1578
- for file in all_files:
1579
- os.remove(file)
1580
- st.rerun()
1581
-
1582
- if st.sidebar.button("⬇️ Download All"):
1583
- zip_file = create_zip_of_files(all_files)
1584
- st.sidebar.markdown(get_download_link(zip_file), unsafe_allow_html=True)
1585
-
1586
- for file in all_files:
1587
- col1, col2, col3, col4 = st.sidebar.columns([1,3,1,1])
1588
- with col1:
1589
- if st.button("🌐", key="view_"+file):
1590
- st.session_state.current_file = file
1591
- st.session_state.file_content = load_file(file)
1592
- with col2:
1593
- st.markdown(get_download_link(file), unsafe_allow_html=True)
1594
- with col3:
1595
- if st.button("πŸ“‚", key="edit_"+file):
1596
- st.session_state.current_file = file
1597
- st.session_state.file_content = load_file(file)
1598
- with col4:
1599
- if st.button("πŸ—‘", key="delete_"+file):
1600
- os.remove(file)
1601
- st.rerun()
1602
-
1603
- # Main Area: Chat with Claude (He’s a good listener πŸ’¬)
1604
- user_input = st.text_area("Message πŸ“¨:", height=100)
1605
-
1606
- if st.button("Send πŸ“¨"):
1607
- if user_input:
1608
- response = client.messages.create(
1609
- model="claude-3-sonnet-20240229",
1610
- max_tokens=1000,
1611
- messages=[
1612
- {"role": "user", "content": user_input}
1613
- ]
1614
- )
1615
- st.write("Claude's reply 🧠:")
1616
- st.write(response.content[0].text)
1617
-
1618
- filename = generate_filename(user_input, "md")
1619
- create_file(filename, user_input, response.content[0].text)
1620
-
1621
- st.session_state.chat_history.append({"user": user_input, "claude": response.content[0].text})
1622
-
1623
- # Display Chat History (Never forget a good chat πŸ’­)
1624
- st.subheader("Past Conversations πŸ“œ")
1625
- for chat in st.session_state.chat_history:
1626
- st.text_area("You said πŸ’¬:", chat["user"], height=100, disabled=True)
1627
- st.text_area("Claude replied πŸ€–:", chat["claude"], height=200, disabled=True)
1628
- st.markdown("---")
1629
-
1630
- # File Editor (When you need to tweak things ✏️)
1631
- if hasattr(st.session_state, 'current_file'):
1632
- st.subheader(f"Editing: {st.session_state.current_file} πŸ› ")
1633
- new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
1634
- if st.button("Save Changes πŸ’Ύ"):
1635
- with open(st.session_state.current_file, 'w', encoding='utf-8') as file:
1636
- file.write(new_content)
1637
- st.success("File updated successfully! πŸŽ‰")
1638
-
1639
- # Image Gallery (For your viewing pleasure πŸ“Έ)
1640
- st.subheader("Image Gallery πŸ–Ό")
1641
- image_files = glob.glob("*.png") + glob.glob("*.jpg") + glob.glob("*.jpeg")
1642
- image_cols = st.slider("Gallery Columns πŸ–Ό", min_value=1, max_value=15, value=5)
1643
- cols = st.columns(image_cols)
1644
- for idx, image_file in enumerate(image_files):
1645
- with cols[idx % image_cols]:
1646
- img = Image.open(image_file)
1647
- #st.image(img, caption=image_file, use_column_width=True)
1648
- st.image(img, use_column_width=True)
1649
- display_glossary_entity(os.path.splitext(image_file)[0])
1650
-
1651
- # Video Gallery (Let’s roll the tapes 🎬)
1652
- st.subheader("Video Gallery πŸŽ₯")
1653
- video_files = glob.glob("*.mp4")
1654
- video_cols = st.slider("Gallery Columns 🎬", min_value=1, max_value=5, value=3)
1655
- cols = st.columns(video_cols)
1656
- for idx, video_file in enumerate(video_files):
1657
- with cols[idx % video_cols]:
1658
- st.markdown(get_video_html(video_file, width="100%"), unsafe_allow_html=True)
1659
- display_glossary_entity(os.path.splitext(video_file)[0])
1660
-
1661
- # Audio Gallery (Tunes for the mood 🎢)
1662
- st.subheader("Audio Gallery 🎧")
1663
- audio_files = glob.glob("*.mp3") + glob.glob("*.wav")
1664
- audio_cols = st.slider("Gallery Columns 🎢", min_value=1, max_value=15, value=5)
1665
- cols = st.columns(audio_cols)
1666
- for idx, audio_file in enumerate(audio_files):
1667
- with cols[idx % audio_cols]:
1668
- st.markdown(get_audio_html(audio_file, width="100%"), unsafe_allow_html=True)
1669
- display_glossary_entity(os.path.splitext(audio_file)[0])
1670
-
1671
  if __name__ == "__main__":
1672
- main()
1673
-
 
9
  from datetime import datetime
10
  import base64
11
  import json
12
+ import uuid
13
+ from urllib.parse import quote
14
+ from gradio_client import Client
15
+ import anthropic
16
+ import glob
17
+ import pytz
18
+ import re
19
+ from PIL import Image
20
+ import zipfile
21
+
22
+ # App Configuration
23
+ Site_Name = 'πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent'
24
+ title = "πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent"
25
+ helpURL = 'https://huggingface.co/awacke1'
26
+ bugURL = 'https://huggingface.co/spaces/awacke1'
27
+ icons = 'πŸ™πŸŒŒπŸ’«'
28
+
29
+ st.set_page_config(
30
+ page_title=title,
31
+ page_icon=icons,
32
+ layout="wide",
33
+ initial_sidebar_state="auto",
34
+ menu_items={
35
+ 'Get Help': helpURL,
36
+ 'Report a bug': bugURL,
37
+ 'About': title
38
+ }
39
+ )
40
 
41
+ # Cosmos DB configuration
42
  ENDPOINT = "https://acae-afd.documents.azure.com:443/"
43
  DATABASE_NAME = os.environ.get("COSMOS_DATABASE_NAME")
44
  CONTAINER_NAME = os.environ.get("COSMOS_CONTAINER_NAME")
45
+ Key = os.environ.get("Key")
46
 
47
+ # Your local app URL (Change this to your app's URL)
48
  LOCAL_APP_URL = "https://huggingface.co/spaces/awacke1/AzureCosmosDBUI"
49
 
50
+ # Anthropic configuration
51
+ client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ # Initialize session state
54
+ if "chat_history" not in st.session_state:
55
+ st.session_state.chat_history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # Helper Functions
58
+ def get_download_link(file_path):
59
  with open(file_path, "rb") as file:
60
  contents = file.read()
61
+ b64 = base64.b64encode(contents).decode()
62
+ file_name = os.path.basename(file_path)
63
+ return f'<a href="data:file/txt;base64,{b64}" download="{file_name}">Download {file_name}πŸ“‚</a>'
64
+
65
+ def generate_unique_id():
66
+ now = datetime.now()
67
+ date_time = now.strftime("%d%m%Y%H%M%S")
68
+ ms = now.microsecond // 1000
69
+ unique_id = f"{date_time}{ms:03d}"
70
+ return unique_id
71
+
72
+ def generate_filename(prompt, file_type):
73
+ central = pytz.timezone('US/Central')
74
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
75
+ safe_prompt = re.sub(r'\W+', '', prompt)[:90]
76
+ return f"{safe_date_time}{safe_prompt}.{file_type}"
77
+
78
+ def create_file(filename, prompt, response, should_save=True):
79
+ if not should_save:
80
+ return
81
+ with open(filename, 'w', encoding='utf-8') as file:
82
+ file.write(prompt + "\n\n" + response)
83
+
84
+ def load_file(file_name):
85
+ with open(file_name, "r", encoding='utf-8') as file:
86
+ content = file.read()
87
+ return content
88
+
89
+ def display_glossary_entity(k):
90
+ search_urls = {
91
+ "πŸš€πŸŒŒArXiv": lambda k: f"/?q={quote(k)}",
92
+ "πŸ“–": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
93
+ "πŸ”": lambda k: f"https://www.google.com/search?q={quote(k)}",
94
+ "πŸŽ₯": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
95
+ }
96
+ links_md = ' '.join([f"<a href='{url(k)}' target='_blank'>{emoji}</a>" for emoji, url in search_urls.items()])
97
+ st.markdown(f"{k} {links_md}", unsafe_allow_html=True)
98
+
99
+ def create_zip_of_files(files):
100
+ zip_name = "all_files.zip"
101
+ with zipfile.ZipFile(zip_name, 'w') as zipf:
102
+ for file in files:
103
+ zipf.write(file)
104
+ return zip_name
105
+
106
+ def get_video_html(video_path, width="100%"):
107
+ video_url = f"data:video/mp4;base64,{base64.b64encode(open(video_path, 'rb').read()).decode()}"
108
+ return f'''
109
+ <video width="{width}" controls autoplay loop>
110
+ <source src="{video_url}" type="video/mp4">
111
+ Your browser does not support the video tag.
112
+ </video>
113
+ '''
114
 
115
+ def get_audio_html(audio_path, width="100%"):
116
+ audio_url = f"data:audio/mpeg;base64,{base64.b64encode(open(audio_path, 'rb').read()).decode()}"
117
+ return f'''
118
+ <audio controls style="width:{width}">
119
+ <source src="{audio_url}" type="audio/mpeg">
120
+ Your browser does not support the audio element.
121
+ </audio>
122
+ '''
123
 
124
+ # Cosmos DB functions
125
  def get_databases(client):
 
126
  return [db['id'] for db in client.list_databases()]
127
 
128
  def get_containers(database):
 
129
  return [container['id'] for container in database.list_containers()]
130
 
131
  def get_documents(container, limit=None):
 
132
  query = "SELECT * FROM c ORDER BY c._ts DESC"
133
  items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
134
  return items
135
 
 
 
136
  def insert_record(container, record):
 
137
  try:
138
  container.create_item(body=record)
139
  return True, "Record inserted successfully! πŸŽ‰"
 
143
  return False, f"An unexpected error occurred: {str(e)} 😱"
144
 
145
  def update_record(container, updated_record):
 
146
  try:
147
  container.upsert_item(body=updated_record)
148
  return True, f"Record with id {updated_record['id']} successfully updated. πŸ› οΈ"
 
152
  return False, f"An unexpected error occurred: {traceback.format_exc()} 😱"
153
 
154
  def delete_record(container, name, id):
 
155
  try:
156
  container.delete_item(item=id, partition_key=id)
157
  return True, f"Successfully deleted record with name: {name} and id: {id} πŸ—‘οΈ"
 
162
  except Exception as e:
163
  return False, f"An unexpected error occurred: {traceback.format_exc()} 😱"
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  def save_to_cosmos_db(container, query, response1, response2):
166
  try:
167
  if container:
 
169
  "id": generate_unique_id(),
170
  "query": query,
171
  "response1": response1,
172
+ "response2": response2,
173
+ "timestamp": datetime.utcnow().isoformat()
174
  }
175
  try:
176
  container.create_item(body=record)
 
184
  except Exception as e:
185
  st.error(f"An unexpected error occurred: {str(e)}")
186
 
187
+ # GitHub functions
188
+ def download_github_repo(url, local_path):
189
+ if os.path.exists(local_path):
190
+ shutil.rmtree(local_path)
191
+ Repo.clone_from(url, local_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
+ def create_zip_file(source_dir, output_filename):
194
+ shutil.make_archive(output_filename, 'zip', source_dir)
 
 
 
 
 
195
 
196
+ def create_repo(g, repo_name):
197
+ user = g.get_user()
198
+ return user.create_repo(repo_name)
 
 
 
 
 
199
 
200
+ def push_to_github(local_path, repo, github_token):
201
+ repo_url = f"https://{github_token}@github.com/{repo.full_name}.git"
202
+ local_repo = Repo(local_path)
 
 
203
 
204
+ if 'origin' in [remote.name for remote in local_repo.remotes]:
205
+ origin = local_repo.remote('origin')
206
+ origin.set_url(repo_url)
207
+ else:
208
+ origin = local_repo.create_remote('origin', repo_url)
209
 
210
+ if not local_repo.heads:
211
+ local_repo.git.checkout('-b', 'main')
212
+ current_branch = 'main'
213
+ else:
214
+ current_branch = local_repo.active_branch.name
215
 
216
+ local_repo.git.add(A=True)
 
 
 
 
 
217
 
218
+ if local_repo.is_dirty():
219
+ local_repo.git.commit('-m', 'Initial commit')
220
 
221
+ origin.push(refspec=f'{current_branch}:{current_branch}')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
+ # Main function
224
  def main():
 
225
  st.title("πŸ™Git🌌CosmosπŸ’« - Azure Cosmos DB and Github Agent")
226
 
227
+ # Initialize session state
228
  if 'logged_in' not in st.session_state:
229
  st.session_state.logged_in = False
230
  if 'selected_records' not in st.session_state:
 
242
  if 'cloned_doc' not in st.session_state:
243
  st.session_state.cloned_doc = None
244
 
245
+ # Automatic Login
 
 
 
 
 
 
 
 
 
 
 
246
  if Key:
247
  st.session_state.primary_key = Key
248
  st.session_state.logged_in = True
249
  else:
250
  st.error("Cosmos DB Key is not set in environment variables. πŸ”‘βŒ")
251
+ return
252
 
253
  if st.session_state.logged_in:
254
+ # Initialize Cosmos DB client
255
  try:
256
  if st.session_state.client is None:
257
  st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
258
 
259
+ # Sidebar for database, container, and document selection
260
  st.sidebar.title("πŸ™Git🌌CosmosπŸ’«πŸ—„οΈNavigator")
261
 
262
  databases = get_databases(st.session_state.client)
 
283
  if st.session_state.selected_container:
284
  container = database.get_container_client(st.session_state.selected_container)
285
 
286
+ # Add Export button
287
  if st.button("πŸ“¦ Export Container Data"):
288
  download_link = archive_current_container(st.session_state.selected_database, st.session_state.selected_container, st.session_state.client)
289
  if download_link.startswith('<a'):
 
303
  st.info(f"Showing all {len(documents_to_display)} documents.")
304
 
305
  if documents_to_display:
306
+ # Add Viewer/Editor selection
307
  view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit and Save', 'Clone Document', 'New Record']
308
  selected_view = st.selectbox("Select Viewer/Editor", view_options, index=2)
309
 
310
  if selected_view == 'Show as Markdown':
311
+ # Show each record as Markdown with navigation
312
  total_docs = len(documents)
313
  doc = documents[st.session_state.current_index]
314
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
315
 
316
+ # Extract values from the JSON that have at least one space
317
  values_with_space = []
318
  def extract_values(obj):
319
  if isinstance(obj, dict):
 
328
 
329
  extract_values(doc)
330
 
331
+ # Create a list of links for these values
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  st.markdown("#### πŸ”— Links for Extracted Texts")
333
  for term in values_with_space:
334
+ display_glossary_entity(term)
 
335
 
336
  # Show the document content as markdown
337
  content = json.dumps(doc, indent=2)
 
351
  st.rerun()
352
 
353
  elif selected_view == 'Show as Code Editor':
354
+ # Show each record in a code editor with navigation
355
  total_docs = len(documents)
356
  doc = documents[st.session_state.current_index]
357
  st.markdown(f"#### Document ID: {doc.get('id', '')}")
 
381
  st.error(f"Invalid JSON: {str(e)} 🚫")
382
 
383
  elif selected_view == 'Show as Edit and Save':
384
+ # Show as Edit and Save in columns
385
  st.markdown("#### Edit the document fields below:")
386
 
387
  # Create columns for each document
388
  num_cols = len(documents_to_display)
389
  cols = st.columns(num_cols)
390
 
 
391
  for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
392
  with col:
393
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
 
418
  # Use the entire document as input
419
  search_glossary(json.dumps(editable_doc, indent=2))
420
 
 
 
 
 
421
  elif selected_view == 'Clone Document':
422
+ # Clone Document per record
423
  st.markdown("#### Clone a document:")
424
  for idx, doc in enumerate(documents_to_display):
425
  st.markdown(f"##### Document ID: {doc.get('id', '')}")
 
449
  st.error(message)
450
  except json.JSONDecodeError as e:
451
  st.error(f"Invalid JSON: {str(e)} 🚫")
452
+
453
  elif selected_view == 'New Record':
454
+ # New Record
455
  st.markdown("#### Create a new document:")
456
  if st.button("πŸ€– Insert Auto-Generated Record"):
457
  success, message = insert_auto_generated_record(container)
 
477
  st.error(message)
478
  except json.JSONDecodeError as e:
479
  st.error(f"Invalid JSON: {str(e)} 🚫")
480
+
481
  else:
482
  st.sidebar.info("No documents found in this container. πŸ“­")
483
+
484
+ # Main content area
485
  st.subheader(f"πŸ“Š Container: {st.session_state.selected_container}")
486
  if st.session_state.selected_container:
487
  if documents_to_display:
 
489
  st.dataframe(df)
490
  else:
491
  st.info("No documents to display. 🧐")
492
+
493
+ # GitHub section
494
  st.subheader("πŸ™ GitHub Operations")
495
  github_token = os.environ.get("GITHUB") # Read GitHub token from environment variable
496
  source_repo = st.text_input("Source GitHub Repository URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
 
505
  download_github_repo(source_repo, local_path)
506
  zip_filename = f"{new_repo_name}.zip"
507
  create_zip_file(local_path, zip_filename[:-4])
508
+ st.markdown(get_download_link(zip_filename), unsafe_allow_html=True)
509
  st.success("Repository cloned successfully! πŸŽ‰")
510
  except Exception as e:
511
  st.error(f"An error occurred: {str(e)} 😒")
 
535
  else:
536
  st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πŸ”‘β“")
537
 
538
+ # Chat with Claude
539
+ st.subheader("πŸ’¬ Chat with Claude")
540
+ user_input = st.text_area("Message πŸ“¨:", height=100)
541
+
542
+ if st.button("Send πŸ“¨"):
543
+ if user_input:
544
+ response = client.messages.create(
545
+ model="claude-3-sonnet-20240229",
546
+ max_tokens=1000,
547
+ messages=[
548
+ {"role": "user", "content": user_input}
549
+ ]
550
+ )
551
+ st.write("Claude's reply 🧠:")
552
+ st.write(response.content[0].text)
553
+
554
+ filename = generate_filename(user_input, "md")
555
+ create_file(filename, user_input, response.content[0].text)
556
+
557
+ st.session_state.chat_history.append({"user": user_input, "claude": response.content[0].text})
558
+
559
+ # Save to Cosmos DB
560
+ save_to_cosmos_db(container, user_input, response.content[0].text, "")
561
+
562
+ # Display Chat History
563
+ st.subheader("Past Conversations πŸ“œ")
564
+ for chat in st.session_state.chat_history:
565
+ st.text_area("You said πŸ’¬:", chat["user"], height=100, disabled=True)
566
+ st.text_area("Claude replied πŸ€–:", chat["claude"], height=200, disabled=True)
567
+ st.markdown("---")
568
+
569
+ # File Editor
570
+ if hasattr(st.session_state, 'current_file'):
571
+ st.subheader(f"Editing: {st.session_state.current_file} πŸ› ")
572
+ new_content = st.text_area("File Content ✏️:", st.session_state.file_content, height=300)
573
+ if st.button("Save Changes πŸ’Ύ"):
574
+ with open(st.session_state.current_file, 'w', encoding='utf-8') as file:
575
+ file.write(new_content)
576
+ st.success("File updated successfully! πŸŽ‰")
577
+
578
+ # File Management
579
+ st.sidebar.title("πŸ“ File Management")
580
+
581
+ all_files = glob.glob("*.md")
582
+ all_files.sort(reverse=True)
583
+
584
+ if st.sidebar.button("πŸ—‘ Delete All Files"):
585
+ for file in all_files:
586
+ os.remove(file)
587
+ st.rerun()
588
+
589
+ if st.sidebar.button("⬇️ Download All Files"):
590
+ zip_file = create_zip_of_files(all_files)
591
+ st.sidebar.markdown(get_download_link(zip_file), unsafe_allow_html=True)
592
+
593
+ for file in all_files:
594
+ col1, col2, col3, col4 = st.sidebar.columns([1,3,1,1])
595
+ with col1:
596
+ if st.button("🌐", key="view_"+file):
597
+ st.session_state.current_file = file
598
+ st.session_state.file_content = load_file(file)
599
+ with col2:
600
+ st.markdown(get_download_link(file), unsafe_allow_html=True)
601
+ with col3:
602
+ if st.button("πŸ“‚", key="edit_"+file):
603
+ st.session_state.current_file = file
604
+ st.session_state.file_content = load_file(file)
605
+ with col4:
606
+ if st.button("πŸ—‘", key="delete_"+file):
607
+ os.remove(file)
608
+ st.rerun()
609
+
610
  except exceptions.CosmosHttpResponseError as e:
611
  st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} 🚨")
612
  except Exception as e:
613
  st.error(f"An unexpected error occurred: {str(e)} 😱")
614
 
615
+ # Logout button
616
  if st.session_state.logged_in and st.sidebar.button("πŸšͺ Logout"):
617
  st.session_state.logged_in = False
618
  st.session_state.selected_records.clear()
 
623
  st.session_state.current_index = 0
624
  st.rerun()
625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
626
  if __name__ == "__main__":
627
+ main()