Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
| 13 |
-
from urllib.parse import quote
|
| 14 |
-
from gradio_client import Client
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
#
|
| 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")
|
| 24 |
|
| 25 |
-
#
|
| 26 |
LOCAL_APP_URL = "https://huggingface.co/spaces/awacke1/AzureCosmosDBUI"
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
| 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 |
-
|
| 45 |
-
|
| 46 |
-
|
| 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 |
-
|
| 69 |
-
|
| 70 |
with open(file_path, "rb") as file:
|
| 71 |
contents = file.read()
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
#
|
| 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 |
-
#
|
| 213 |
-
def
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 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 |
-
|
| 332 |
-
|
| 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 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
lines = content.splitlines()
|
| 343 |
-
for line in lines:
|
| 344 |
-
if line.startswith('#'):
|
| 345 |
-
return line.lstrip('#').strip()
|
| 346 |
-
return None
|
| 347 |
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
if not should_save:
|
| 352 |
-
return None
|
| 353 |
|
| 354 |
-
|
| 355 |
-
|
|
|
|
|
|
|
|
|
|
| 356 |
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
|
| 363 |
-
|
| 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 |
-
|
|
|
|
| 371 |
|
| 372 |
-
|
| 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 |
-
#
|
| 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 |
-
#
|
| 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 |
-
#
|
| 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
|
| 434 |
|
| 435 |
if st.session_state.logged_in:
|
| 436 |
-
#
|
| 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 |
-
#
|
| 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 |
-
#
|
| 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 |
-
#
|
| 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 |
-
#
|
| 494 |
total_docs = len(documents)
|
| 495 |
doc = documents[st.session_state.current_index]
|
| 496 |
st.markdown(f"#### Document ID: {doc.get('id', '')}")
|
| 497 |
|
| 498 |
-
#
|
| 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 |
-
#
|
| 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 |
-
|
| 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 |
-
#
|
| 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 |
-
#
|
| 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 |
-
#
|
| 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 |
-
#
|
| 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 |
-
#
|
| 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 |
-
#
|
| 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(
|
| 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 |
-
#
|
| 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 |
|
|
|
|
|
|
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