Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -12,9 +12,25 @@ 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 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
# π Cosmos DB configuration
|
20 |
ENDPOINT = "https://acae-afd.documents.azure.com:443/"
|
@@ -22,12 +38,11 @@ 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 |
-
#
|
26 |
-
|
27 |
|
28 |
-
#
|
29 |
-
|
30 |
-
# MODEL = "gpt-3.5-turbo" # Replace with your desired model
|
31 |
|
32 |
# π GitHub configuration
|
33 |
def download_github_repo(url, local_path):
|
@@ -41,16 +56,16 @@ def create_zip_file(source_dir, output_filename):
|
|
41 |
shutil.make_archive(output_filename, 'zip', source_dir)
|
42 |
|
43 |
def create_repo(g, repo_name):
|
44 |
-
# π οΈ Creating a new GitHub repo.
|
45 |
user = g.get_user()
|
46 |
return user.create_repo(repo_name)
|
47 |
|
48 |
def push_to_github(local_path, repo, github_token):
|
49 |
-
# π Pushing code to GitHub.
|
50 |
repo_url = f"https://{github_token}@github.com/{repo.full_name}.git"
|
51 |
local_repo = Repo(local_path)
|
52 |
|
53 |
-
if 'origin' in [remote.name for remote
|
54 |
origin = local_repo.remote('origin')
|
55 |
origin.set_url(repo_url)
|
56 |
else:
|
@@ -76,26 +91,8 @@ def get_base64_download_link(file_path, file_name):
|
|
76 |
base64_encoded = base64.b64encode(contents).decode()
|
77 |
return f'<a href="data:application/zip;base64,{base64_encoded}" download="{file_name}">β¬οΈ Download {file_name}</a>'
|
78 |
|
79 |
-
|
80 |
-
# π§ New functions for dynamic sidebar navigation
|
81 |
-
def get_databases(client):
|
82 |
-
# π Fetching list of databases. So many options!
|
83 |
-
return [db['id'] for db in client.list_databases()]
|
84 |
-
|
85 |
-
def get_containers(database):
|
86 |
-
# π Getting containers. Containers within containers!
|
87 |
-
return [container['id'] for container in database.list_containers()]
|
88 |
-
|
89 |
-
def get_documents(container, limit=None):
|
90 |
-
# π Retrieving documents. Shhh, don't tell anyone!
|
91 |
-
query = "SELECT * FROM c ORDER BY c._ts DESC"
|
92 |
-
items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
|
93 |
-
return items
|
94 |
-
|
95 |
-
|
96 |
# π Cosmos DB functions
|
97 |
def insert_record(container, record):
|
98 |
-
# π₯ Inserting a record into the Cosmosβhope we don't disturb any aliens! π½
|
99 |
try:
|
100 |
container.create_item(body=record)
|
101 |
return True, "Record inserted successfully! π"
|
@@ -104,658 +101,134 @@ def insert_record(container, record):
|
|
104 |
except Exception as e:
|
105 |
return False, f"An unexpected error occurred: {str(e)} π±"
|
106 |
|
107 |
-
def update_record(container, updated_record):
|
108 |
-
# π Updating a recordβgiving it a cosmic makeover! β¨
|
109 |
-
try:
|
110 |
-
container.upsert_item(body=updated_record)
|
111 |
-
return True, f"Record with id {updated_record['id']} successfully updated. π οΈ"
|
112 |
-
except exceptions.CosmosHttpResponseError as e:
|
113 |
-
return False, f"HTTP error occurred: {str(e)} π¨"
|
114 |
-
except Exception as e:
|
115 |
-
return False, f"An unexpected error occurred: {traceback.format_exc()} π±"
|
116 |
-
|
117 |
-
def delete_record(container, name, id):
|
118 |
-
# ποΈ Deleting a recordβsending it into the cosmic void! π
|
119 |
-
try:
|
120 |
-
container.delete_item(item=id, partition_key=id)
|
121 |
-
return True, f"Successfully deleted record with name: {name} and id: {id} ποΈ"
|
122 |
-
except exceptions.CosmosResourceNotFoundError:
|
123 |
-
return False, f"Record with id {id} not found. It may have been already deleted. π΅οΈββοΈ"
|
124 |
-
except exceptions.CosmosHttpResponseError as e:
|
125 |
-
return False, f"HTTP error occurred: {str(e)} π¨"
|
126 |
-
except Exception as e:
|
127 |
-
return False, f"An unexpected error occurred: {traceback.format_exc()} π±"
|
128 |
-
|
129 |
# π² Function to generate a unique UUID
|
130 |
def generate_unique_id():
|
131 |
-
# π§ββοΈ Generating a unique UUID!
|
132 |
return str(uuid.uuid4())
|
133 |
|
134 |
-
#
|
135 |
-
def
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
db_client = client.get_database_client(database_name)
|
144 |
-
container_client = db_client.get_container_client(container_name)
|
145 |
-
items = list(container_client.read_all_items())
|
146 |
-
|
147 |
-
container_dir = os.path.join(base_dir, container_name)
|
148 |
-
os.makedirs(container_dir)
|
149 |
-
|
150 |
-
for item in items:
|
151 |
-
item_id = item.get('id', f"unknown_{datetime.now().strftime('%Y%m%d%H%M%S')}")
|
152 |
-
with open(os.path.join(container_dir, f"{item_id}.json"), 'w') as f:
|
153 |
-
json.dump(item, f, indent=2)
|
154 |
-
|
155 |
-
archive_name = f"{container_name}_archive_{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
156 |
-
shutil.make_archive(archive_name, 'zip', base_dir)
|
157 |
-
|
158 |
-
return get_base64_download_link(f"{archive_name}.zip", f"{archive_name}.zip")
|
159 |
-
except Exception as e:
|
160 |
-
return f"An error occurred while archiving data: {str(e)} π’"
|
161 |
-
|
162 |
-
|
163 |
-
# π Helper to extract hyperlinks
|
164 |
-
def extract_hyperlinks(responses):
|
165 |
-
# π Extracting hyperlinksβconnecting the dots across the universe! πΈοΈ
|
166 |
-
hyperlinks = []
|
167 |
-
for response in responses:
|
168 |
-
parsed_response = json.loads(response)
|
169 |
-
links = [value for key, value in parsed_response.items() if isinstance(value, str) and value.startswith("http")]
|
170 |
-
hyperlinks.extend(links)
|
171 |
-
return hyperlinks
|
172 |
-
|
173 |
-
# π Helper to format text with line numbers
|
174 |
-
def format_with_line_numbers(text):
|
175 |
-
# π Formatting text with line numbersβorganizing the cosmos one line at a time! π
|
176 |
-
lines = text.splitlines()
|
177 |
-
formatted_text = '\n'.join(f"{i+1}: {line}" for i, line in enumerate(lines))
|
178 |
-
return formatted_text
|
179 |
-
|
180 |
-
|
181 |
-
def generate_unique_id():
|
182 |
-
return str(uuid.uuid4())
|
183 |
-
|
184 |
-
def get_databases(client):
|
185 |
-
return [db['id'] for db in client.list_databases()]
|
186 |
-
|
187 |
-
def get_containers(database):
|
188 |
-
return [container['id'] for container in database.list_containers()]
|
189 |
-
|
190 |
-
def get_documents(container, limit=None):
|
191 |
-
query = "SELECT * FROM c ORDER BY c._ts DESC"
|
192 |
-
items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
|
193 |
-
return items
|
194 |
-
|
195 |
-
def save_to_cosmos_db(container, query, response1, response2):
|
196 |
-
try:
|
197 |
-
if container:
|
198 |
-
record = {
|
199 |
-
"id": generate_unique_id(),
|
200 |
-
"query": query,
|
201 |
-
"response1": response1,
|
202 |
-
"response2": response2
|
203 |
-
}
|
204 |
-
try:
|
205 |
-
container.create_item(body=record)
|
206 |
-
st.success(f"Record saved successfully with ID: {record['id']}")
|
207 |
-
# Refresh the documents display
|
208 |
-
st.session_state.documents = get_documents(container)
|
209 |
-
except exceptions.CosmosHttpResponseError as e:
|
210 |
-
st.error(f"Error saving record to Cosmos DB: {e}")
|
211 |
-
else:
|
212 |
-
st.error("Cosmos DB container is not initialized.")
|
213 |
-
except Exception as e:
|
214 |
-
st.error(f"An unexpected error occurred: {str(e)}")
|
215 |
-
|
216 |
-
# Add dropdowns for model and database choices
|
217 |
-
def search_glossary(query):
|
218 |
-
st.markdown(f"### π Search Glossary for: `{query}`")
|
219 |
-
|
220 |
-
# Dropdown for model selection
|
221 |
-
model_options = ['mistralai/Mixtral-8x7B-Instruct-v0.1', 'mistralai/Mistral-7B-Instruct-v0.2', 'google/gemma-7b-it', 'None']
|
222 |
-
model_choice = st.selectbox('π§ Select LLM Model', options=model_options, index=1)
|
223 |
-
|
224 |
-
# Dropdown for database selection
|
225 |
-
database_options = ['Semantic Search', 'Arxiv Search - Latest - (EXPERIMENTAL)']
|
226 |
-
database_choice = st.selectbox('π Select Database', options=database_options, index=0)
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
# Run Button with Emoji
|
231 |
-
#if st.button("π Run"):
|
232 |
-
|
233 |
-
# π΅οΈββοΈ Searching the glossary for: query
|
234 |
-
all_results = ""
|
235 |
-
st.markdown(f"- {query}")
|
236 |
-
|
237 |
-
# π ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM
|
238 |
-
#database_choice Literal['Semantic Search', 'Arxiv Search - Latest - (EXPERIMENTAL)'] Default: "Semantic Search"
|
239 |
-
#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"
|
240 |
-
client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
241 |
-
|
242 |
-
|
243 |
-
# π ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /ask_llm
|
244 |
-
result = client.predict(
|
245 |
-
prompt=query,
|
246 |
-
llm_model_picked="mistralai/Mixtral-8x7B-Instruct-v0.1",
|
247 |
-
stream_outputs=True,
|
248 |
-
api_name="/ask_llm"
|
249 |
-
)
|
250 |
-
st.markdown(result)
|
251 |
-
st.code(result, language="python", line_numbers=True)
|
252 |
-
|
253 |
-
# π ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /ask_llm
|
254 |
-
result2 = client.predict(
|
255 |
-
prompt=query,
|
256 |
-
llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
|
257 |
-
stream_outputs=True,
|
258 |
-
api_name="/ask_llm"
|
259 |
)
|
260 |
-
|
261 |
-
st.code(result2, language="python", line_numbers=True)
|
262 |
-
|
263 |
-
# π ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /ask_llm
|
264 |
-
result3 = client.predict(
|
265 |
-
prompt=query,
|
266 |
-
llm_model_picked="google/gemma-7b-it",
|
267 |
-
stream_outputs=True,
|
268 |
-
api_name="/ask_llm"
|
269 |
-
)
|
270 |
-
st.markdown(result3)
|
271 |
-
st.code(result3, language="python", line_numbers=True)
|
272 |
-
|
273 |
-
|
274 |
-
# π ArXiv RAG researcher expert ~-<>-~ Paper Summary & Ask LLM - api_name: /update_with_rag_md
|
275 |
-
response2 = client.predict(
|
276 |
-
message=query, # str in 'parameter_13' Textbox component
|
277 |
-
llm_results_use=10,
|
278 |
-
database_choice="Semantic Search",
|
279 |
-
llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
|
280 |
-
api_name="/update_with_rag_md"
|
281 |
-
) # update_with_rag_md Returns tuple of 2 elements [0] str The output value that appears in the "value_14" Markdown component. [1] str
|
282 |
-
|
283 |
-
st.markdown(response2[0])
|
284 |
-
st.code(response2[0], language="python", line_numbers=True, wrap_lines=True)
|
285 |
-
|
286 |
-
st.markdown(response2[1])
|
287 |
-
st.code(response2[1], language="python", line_numbers=True, wrap_lines=True)
|
288 |
-
|
289 |
-
# When saving results, pass the container
|
290 |
-
try:
|
291 |
-
save_to_cosmos_db(st.session_state.cosmos_container, query, result, result)
|
292 |
-
save_to_cosmos_db(st.session_state.cosmos_container, query, result2, result2)
|
293 |
-
save_to_cosmos_db(st.session_state.cosmos_container, query, result3, result3)
|
294 |
-
save_to_cosmos_db(st.session_state.cosmos_container, query, response2[0], response2[0])
|
295 |
-
save_to_cosmos_db(st.session_state.cosmos_container, query, response2[1], response2[1])
|
296 |
-
except exceptions.CosmosHttpResponseError as e:
|
297 |
-
return False, f"HTTP error occurred: {str(e)} π¨"
|
298 |
-
except Exception as e:
|
299 |
-
return False, f"An unexpected error occurred: {str(e)} π±"
|
300 |
-
|
301 |
-
|
302 |
-
try:
|
303 |
-
# Aggregate hyperlinks and show with emojis
|
304 |
-
hyperlinks = extract_hyperlinks([response1, response2])
|
305 |
-
st.markdown("### π Aggregated Hyperlinks")
|
306 |
-
for link in hyperlinks:
|
307 |
-
st.markdown(f"π [{link}]({link})")
|
308 |
-
|
309 |
-
# Show responses in a code format with line numbers
|
310 |
-
st.markdown("### π Response Outputs with Line Numbers")
|
311 |
-
st.code(f"Response 1: \n{format_with_line_numbers(response1)}\n\nResponse 2: \n{format_with_line_numbers(response2)}", language="json")
|
312 |
-
except exceptions.CosmosHttpResponseError as e:
|
313 |
-
return False, f"HTTP error occurred: {str(e)} π¨"
|
314 |
-
except Exception as e:
|
315 |
-
return False, f"An unexpected error occurred: {str(e)} π±"
|
316 |
-
|
317 |
-
|
318 |
|
|
|
|
|
|
|
|
|
|
|
|
|
319 |
|
320 |
-
|
321 |
-
def process_text(text_input):
|
322 |
-
# π€ Processing text inputβtranslating human words into cosmic signals! π‘
|
323 |
-
if text_input:
|
324 |
-
if 'messages' not in st.session_state:
|
325 |
-
st.session_state.messages = []
|
326 |
-
|
327 |
-
st.session_state.messages.append({"role": "user", "content": text_input})
|
328 |
-
|
329 |
-
with st.chat_message("user"):
|
330 |
-
st.markdown(text_input)
|
331 |
-
|
332 |
-
with st.chat_message("assistant"):
|
333 |
-
search_glossary(text_input)
|
334 |
-
|
335 |
-
# π Function to generate a filename
|
336 |
-
def generate_filename(text, file_type):
|
337 |
-
# π Generate a filename based on the text input
|
338 |
-
safe_text = "".join(c if c.isalnum() or c in (' ', '.', '_') else '_' for c in text)
|
339 |
-
safe_text = "_".join(safe_text.strip().split())
|
340 |
-
filename = f"{safe_text}.{file_type}"
|
341 |
-
return filename
|
342 |
-
|
343 |
-
# π΅οΈββοΈ Function to extract markdown title
|
344 |
-
def extract_markdown_title(content):
|
345 |
-
# π΅οΈββοΈ Extracting markdown titleβfinding the headline in the cosmic news! π°
|
346 |
-
lines = content.splitlines()
|
347 |
-
for line in lines:
|
348 |
-
if line.startswith('#'):
|
349 |
-
return line.lstrip('#').strip()
|
350 |
-
return None
|
351 |
-
|
352 |
-
# πΎ Function to create and save a file
|
353 |
-
def create_and_save_file(content, file_type="md", prompt=None, is_image=False, should_save=True):
|
354 |
-
# πΎ Creating and saving a fileβcapturing cosmic wisdom! π
|
355 |
if not should_save:
|
356 |
-
return
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
'name': f'Sample Name {new_id[:8]}',
|
386 |
-
'description': 'This is a sample auto-generated description.',
|
387 |
-
'timestamp': datetime.utcnow().isoformat()
|
388 |
-
}
|
389 |
-
# Insert the document
|
390 |
-
container.create_item(body=new_doc)
|
391 |
-
return True, f"Record inserted successfully with id: {new_id} π"
|
392 |
-
except exceptions.CosmosHttpResponseError as e:
|
393 |
-
return False, f"HTTP error occurred: {str(e)} π¨"
|
394 |
-
except Exception as e:
|
395 |
-
return False, f"An unexpected error occurred: {str(e)} π±"
|
396 |
-
|
397 |
-
# π Main function
|
398 |
def main():
|
399 |
-
|
400 |
-
st.title("πGitπCosmosπ« - Azure Cosmos DB and Github Agent")
|
401 |
|
402 |
-
#
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
if 'client' not in st.session_state:
|
408 |
-
st.session_state.client = None
|
409 |
-
if 'selected_database' not in st.session_state:
|
410 |
-
st.session_state.selected_database = None
|
411 |
-
if 'selected_container' not in st.session_state:
|
412 |
-
st.session_state.selected_container = None
|
413 |
-
if 'selected_document_id' not in st.session_state:
|
414 |
-
st.session_state.selected_document_id = None
|
415 |
-
if 'current_index' not in st.session_state:
|
416 |
-
st.session_state.current_index = 0
|
417 |
-
if 'cloned_doc' not in st.session_state:
|
418 |
-
st.session_state.cloned_doc = None
|
419 |
-
|
420 |
-
# βοΈ q= Run ArXiv search from query parameters
|
421 |
-
try:
|
422 |
-
query_params = st.query_params
|
423 |
-
query = query_params.get('q') or query_params.get('query') or ''
|
424 |
-
if query:
|
425 |
-
# π΅οΈββοΈ We have a query! Let's process it!
|
426 |
-
process_text(query)
|
427 |
-
st.stop() # Stop further execution
|
428 |
-
except Exception as e:
|
429 |
-
st.markdown(' ')
|
430 |
-
|
431 |
-
# π Automatic Login
|
432 |
if Key:
|
433 |
st.session_state.primary_key = Key
|
434 |
st.session_state.logged_in = True
|
435 |
-
else:
|
436 |
-
st.error("Cosmos DB Key is not set in environment variables. πβ")
|
437 |
-
return # Can't proceed without a key
|
438 |
|
439 |
-
|
440 |
-
|
441 |
-
try:
|
442 |
-
if st.session_state.client is None:
|
443 |
-
st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
|
444 |
-
|
445 |
-
# ποΈ Sidebar for database, container, and document selection
|
446 |
-
st.sidebar.title("πGitπCosmosπ«ποΈNavigator")
|
447 |
|
448 |
-
|
449 |
-
|
|
|
|
|
450 |
|
451 |
-
if selected_db
|
452 |
-
|
453 |
-
|
454 |
-
st.
|
455 |
-
st.session_state.current_index = 0
|
456 |
-
st.rerun()
|
457 |
-
|
458 |
-
if st.session_state.selected_database:
|
459 |
-
database = st.session_state.client.get_database_client(st.session_state.selected_database)
|
460 |
-
containers = get_containers(database)
|
461 |
-
selected_container = st.sidebar.selectbox("π Select Container", containers)
|
462 |
-
|
463 |
-
if selected_container != st.session_state.selected_container:
|
464 |
-
st.session_state.selected_container = selected_container
|
465 |
-
st.session_state.selected_document_id = None
|
466 |
-
st.session_state.current_index = 0
|
467 |
-
st.rerun()
|
468 |
|
469 |
-
if
|
470 |
-
container =
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
st.markdown(download_link, unsafe_allow_html=True)
|
477 |
-
else:
|
478 |
-
st.error(download_link)
|
479 |
-
|
480 |
-
# Fetch documents
|
481 |
-
documents = get_documents(container)
|
482 |
-
total_docs = len(documents)
|
483 |
-
|
484 |
-
if total_docs > 5:
|
485 |
-
documents_to_display = documents[:5]
|
486 |
-
st.info("Showing top 5 most recent documents.")
|
487 |
-
else:
|
488 |
-
documents_to_display = documents
|
489 |
-
st.info(f"Showing all {len(documents_to_display)} documents.")
|
490 |
-
|
491 |
-
if documents_to_display:
|
492 |
-
# π¨ Add Viewer/Editor selection
|
493 |
-
view_options = ['Show as Markdown', 'Show as Code Editor', 'Show as Edit and Save', 'Clone Document', 'New Record']
|
494 |
-
selected_view = st.selectbox("Select Viewer/Editor", view_options, index=2)
|
495 |
-
|
496 |
-
if selected_view == 'Show as Markdown':
|
497 |
-
# ποΈ Show each record as Markdown with navigation
|
498 |
-
total_docs = len(documents)
|
499 |
-
doc = documents[st.session_state.current_index]
|
500 |
-
st.markdown(f"#### Document ID: {doc.get('id', '')}")
|
501 |
-
|
502 |
-
# π΅οΈββοΈ Let's extract values from the JSON that have at least one space
|
503 |
-
values_with_space = []
|
504 |
-
def extract_values(obj):
|
505 |
-
if isinstance(obj, dict):
|
506 |
-
for k, v in obj.items():
|
507 |
-
extract_values(v)
|
508 |
-
elif isinstance(obj, list):
|
509 |
-
for item in obj:
|
510 |
-
extract_values(item)
|
511 |
-
elif isinstance(obj, str):
|
512 |
-
if ' ' in obj:
|
513 |
-
values_with_space.append(obj)
|
514 |
-
|
515 |
-
extract_values(doc)
|
516 |
-
|
517 |
-
# π Let's create a list of links for these values
|
518 |
-
search_urls = {
|
519 |
-
"ππArXiv": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}",
|
520 |
-
"πAnalyst": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix')}",
|
521 |
-
"πPyCoder": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix2')}",
|
522 |
-
"π¬JSCoder": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}-{quote('PromptPrefix3')}",
|
523 |
-
"π ": lambda k: f"{LOCAL_APP_URL}/?q={quote(k)}",
|
524 |
-
"π": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
|
525 |
-
"π": lambda k: f"https://www.google.com/search?q={quote(k)}",
|
526 |
-
"βΆοΈ": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
|
527 |
-
"π": lambda k: f"https://www.bing.com/search?q={quote(k)}",
|
528 |
-
"π₯": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
|
529 |
-
"π¦": lambda k: f"https://twitter.com/search?q={quote(k)}",
|
530 |
-
}
|
531 |
-
|
532 |
-
st.markdown("#### π Links for Extracted Texts")
|
533 |
-
for term in values_with_space:
|
534 |
-
links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
|
535 |
-
st.markdown(f"**{term}** <small>{links_md}</small>", unsafe_allow_html=True)
|
536 |
-
|
537 |
-
# Show the document content as markdown
|
538 |
-
content = json.dumps(doc, indent=2)
|
539 |
-
st.markdown(f"```json\n{content}\n```")
|
540 |
-
|
541 |
-
# Navigation buttons
|
542 |
-
col_prev, col_next = st.columns([1, 1])
|
543 |
-
with col_prev:
|
544 |
-
if st.button("β¬
οΈ Previous", key='prev_markdown'):
|
545 |
-
if st.session_state.current_index > 0:
|
546 |
-
st.session_state.current_index -= 1
|
547 |
-
st.rerun()
|
548 |
-
with col_next:
|
549 |
-
if st.button("β‘οΈ Next", key='next_markdown'):
|
550 |
-
if st.session_state.current_index < total_docs - 1:
|
551 |
-
st.session_state.current_index += 1
|
552 |
-
st.rerun()
|
553 |
-
|
554 |
-
elif selected_view == 'Show as Code Editor':
|
555 |
-
# π» Show each record in a code editor with navigation
|
556 |
-
total_docs = len(documents)
|
557 |
-
doc = documents[st.session_state.current_index]
|
558 |
-
st.markdown(f"#### Document ID: {doc.get('id', '')}")
|
559 |
-
doc_str = st.text_area("Edit Document", value=json.dumps(doc, indent=2), height=300, key=f'code_editor_{st.session_state.current_index}')
|
560 |
-
col_prev, col_next = st.columns([1, 1])
|
561 |
-
with col_prev:
|
562 |
-
if st.button("β¬
οΈ Previous", key='prev_code'):
|
563 |
-
if st.session_state.current_index > 0:
|
564 |
-
st.session_state.current_index -= 1
|
565 |
-
st.rerun()
|
566 |
-
with col_next:
|
567 |
-
if st.button("β‘οΈ Next", key='next_code'):
|
568 |
-
if st.session_state.current_index < total_docs - 1:
|
569 |
-
st.session_state.current_index += 1
|
570 |
-
st.rerun()
|
571 |
-
if st.button("πΎ Save Changes", key=f'save_button_{st.session_state.current_index}'):
|
572 |
-
try:
|
573 |
-
updated_doc = json.loads(doc_str)
|
574 |
-
success, message = update_record(container, updated_doc)
|
575 |
-
if success:
|
576 |
-
st.success(f"Document {updated_doc['id']} saved successfully.")
|
577 |
-
st.session_state.selected_document_id = updated_doc['id']
|
578 |
-
st.rerun()
|
579 |
-
else:
|
580 |
-
st.error(message)
|
581 |
-
except json.JSONDecodeError as e:
|
582 |
-
st.error(f"Invalid JSON: {str(e)} π«")
|
583 |
-
|
584 |
-
elif selected_view == 'Show as Edit and Save':
|
585 |
-
# βοΈ Show as Edit and Save in columns
|
586 |
-
st.markdown("#### Edit the document fields below:")
|
587 |
-
|
588 |
-
# Create columns for each document
|
589 |
-
num_cols = len(documents_to_display)
|
590 |
-
cols = st.columns(num_cols)
|
591 |
-
|
592 |
-
|
593 |
-
for idx, (col, doc) in enumerate(zip(cols, documents_to_display)):
|
594 |
-
with col:
|
595 |
-
st.markdown(f"##### Document ID: {doc.get('id', '')}")
|
596 |
-
editable_id = st.text_input("ID", value=doc.get('id', ''), key=f'edit_id_{idx}')
|
597 |
-
# Remove 'id' from the document for editing other fields
|
598 |
-
editable_doc = doc.copy()
|
599 |
-
editable_doc.pop('id', None)
|
600 |
-
doc_str = st.text_area("Document Content (in JSON format)", value=json.dumps(editable_doc, indent=2), height=300, key=f'doc_str_{idx}')
|
601 |
-
|
602 |
-
# Add the "Run With AI" button next to "Save Changes"
|
603 |
-
col_save, col_ai = st.columns(2)
|
604 |
-
with col_save:
|
605 |
-
if st.button("πΎ Save Changes", key=f'save_button_{idx}'):
|
606 |
-
try:
|
607 |
-
updated_doc = json.loads(doc_str)
|
608 |
-
updated_doc['id'] = editable_id # Include the possibly edited ID
|
609 |
-
success, message = update_record(container, updated_doc)
|
610 |
-
if success:
|
611 |
-
st.success(f"Document {updated_doc['id']} saved successfully.")
|
612 |
-
st.session_state.selected_document_id = updated_doc['id']
|
613 |
-
st.rerun()
|
614 |
-
else:
|
615 |
-
st.error(message)
|
616 |
-
except json.JSONDecodeError as e:
|
617 |
-
st.error(f"Invalid JSON: {str(e)} π«")
|
618 |
-
with col_ai:
|
619 |
-
if st.button("π€ Run With AI", key=f'run_with_ai_button_{idx}'):
|
620 |
-
# Use the entire document as input
|
621 |
-
search_glossary(json.dumps(editable_doc, indent=2))
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
elif selected_view == 'Clone Document':
|
628 |
-
# 𧬠Clone Document per record
|
629 |
-
st.markdown("#### Clone a document:")
|
630 |
-
for idx, doc in enumerate(documents_to_display):
|
631 |
-
st.markdown(f"##### Document ID: {doc.get('id', '')}")
|
632 |
-
if st.button("π Clone Document", key=f'clone_button_{idx}'):
|
633 |
-
cloned_doc = doc.copy()
|
634 |
-
# Generate a unique ID
|
635 |
-
cloned_doc['id'] = generate_unique_id()
|
636 |
-
st.session_state.cloned_doc = cloned_doc
|
637 |
-
st.session_state.cloned_doc_str = json.dumps(cloned_doc, indent=2)
|
638 |
-
st.session_state.clone_mode = True
|
639 |
-
st.rerun()
|
640 |
-
if st.session_state.get('clone_mode', False):
|
641 |
-
st.markdown("#### Edit Cloned Document:")
|
642 |
-
cloned_doc_str = st.text_area("Cloned Document Content (in JSON format)", value=st.session_state.cloned_doc_str, height=300)
|
643 |
-
if st.button("πΎ Save Cloned Document"):
|
644 |
-
try:
|
645 |
-
new_doc = json.loads(cloned_doc_str)
|
646 |
-
success, message = insert_record(container, new_doc)
|
647 |
-
if success:
|
648 |
-
st.success(f"Cloned document saved with id: {new_doc['id']} π")
|
649 |
-
st.session_state.selected_document_id = new_doc['id']
|
650 |
-
st.session_state.clone_mode = False
|
651 |
-
st.session_state.cloned_doc = None
|
652 |
-
st.session_state.cloned_doc_str = ''
|
653 |
-
st.rerun()
|
654 |
-
else:
|
655 |
-
st.error(message)
|
656 |
-
except json.JSONDecodeError as e:
|
657 |
-
st.error(f"Invalid JSON: {str(e)} π«")
|
658 |
-
|
659 |
-
elif selected_view == 'New Record':
|
660 |
-
# π New Record
|
661 |
-
st.markdown("#### Create a new document:")
|
662 |
-
if st.button("π€ Insert Auto-Generated Record"):
|
663 |
-
success, message = insert_auto_generated_record(container)
|
664 |
-
if success:
|
665 |
-
st.success(message)
|
666 |
-
st.rerun()
|
667 |
-
else:
|
668 |
-
st.error(message)
|
669 |
-
else:
|
670 |
-
new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
|
671 |
-
new_doc_str = st.text_area("Document Content (in JSON format)", value='{}', height=300)
|
672 |
-
if st.button("β Create New Document"):
|
673 |
-
try:
|
674 |
-
new_doc = json.loads(new_doc_str)
|
675 |
-
new_doc['id'] = new_id # Use the provided ID
|
676 |
-
success, message = insert_record(container, new_doc)
|
677 |
-
if success:
|
678 |
-
st.success(f"New document created with id: {new_doc['id']} π")
|
679 |
-
st.session_state.selected_document_id = new_doc['id']
|
680 |
-
# Switch to 'Show as Edit and Save' mode
|
681 |
-
st.rerun()
|
682 |
-
else:
|
683 |
-
st.error(message)
|
684 |
-
except json.JSONDecodeError as e:
|
685 |
-
st.error(f"Invalid JSON: {str(e)} π«")
|
686 |
-
|
687 |
else:
|
688 |
-
st.
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
|
705 |
-
|
706 |
-
|
707 |
-
|
708 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
|
715 |
-
|
716 |
-
|
717 |
-
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
|
722 |
-
|
723 |
-
|
724 |
-
|
725 |
-
|
726 |
-
|
727 |
-
|
728 |
-
|
729 |
-
|
730 |
-
g = Github(github_token)
|
731 |
-
new_repo = create_repo(g, new_repo_name)
|
732 |
-
local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
733 |
-
download_github_repo(source_repo, local_path)
|
734 |
-
push_to_github(local_path, new_repo, github_token)
|
735 |
-
st.success(f"Repository pushed successfully to {new_repo.html_url} π")
|
736 |
-
except Exception as e:
|
737 |
-
st.error(f"An error occurred: {str(e)} π’")
|
738 |
-
finally:
|
739 |
-
if os.path.exists(local_path):
|
740 |
-
shutil.rmtree(local_path)
|
741 |
-
else:
|
742 |
-
st.error("Please ensure GitHub token is set in environment variables and source repository URL is provided. πβ")
|
743 |
-
|
744 |
-
except exceptions.CosmosHttpResponseError as e:
|
745 |
-
st.error(f"Failed to connect to Cosmos DB. HTTP error: {str(e)} π¨")
|
746 |
-
except Exception as e:
|
747 |
-
st.error(f"An unexpected error occurred: {str(e)} π±")
|
748 |
-
|
749 |
-
# πͺ Logout button
|
750 |
-
if st.session_state.logged_in and st.sidebar.button("πͺ Logout"):
|
751 |
-
st.session_state.logged_in = False
|
752 |
-
st.session_state.selected_records.clear()
|
753 |
-
st.session_state.client = None
|
754 |
-
st.session_state.selected_database = None
|
755 |
-
st.session_state.selected_container = None
|
756 |
-
st.session_state.selected_document_id = None
|
757 |
-
st.session_state.current_index = 0
|
758 |
-
st.rerun()
|
759 |
|
760 |
if __name__ == "__main__":
|
761 |
main()
|
|
|
12 |
import uuid # π² For generating unique IDs
|
13 |
from urllib.parse import quote # π For encoding URLs
|
14 |
from gradio_client import Client # π For connecting to Gradio apps
|
15 |
+
import anthropic
|
16 |
+
import pytz
|
17 |
+
import re
|
18 |
+
from PIL import Image
|
19 |
+
import glob
|
20 |
+
from streamlit.components.v1 import html
|
21 |
+
|
22 |
+
# π Welcome to our epic Cosmos DB, GitHub, and Claude App! The universe is at your command π
|
23 |
+
st.set_page_config(
|
24 |
+
page_title="π€GitπCosmosπ« & Claudeπ§ ",
|
25 |
+
page_icon="π€ππ«π",
|
26 |
+
layout="wide",
|
27 |
+
initial_sidebar_state="auto",
|
28 |
+
menu_items={
|
29 |
+
'Get Help': 'https://huggingface.co/awacke1',
|
30 |
+
'Report a bug': 'https://huggingface.co/spaces/awacke1',
|
31 |
+
'About': 'πGitπCosmosπ« - Azure Cosmos DB and GitHub Agent, Now with Claude!'
|
32 |
+
}
|
33 |
+
)
|
34 |
|
35 |
# π Cosmos DB configuration
|
36 |
ENDPOINT = "https://acae-afd.documents.azure.com:443/"
|
|
|
38 |
CONTAINER_NAME = os.environ.get("COSMOS_CONTAINER_NAME")
|
39 |
Key = os.environ.get("Key") # π Don't forget your key!
|
40 |
|
41 |
+
# Set up the Anthropic client (Claude time π€π§ )
|
42 |
+
client_anthropic = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
|
43 |
|
44 |
+
# Set up Gradio client for ArXiv queries (ArXiv, the scholar's playground π)
|
45 |
+
client_gradio = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
|
|
|
46 |
|
47 |
# π GitHub configuration
|
48 |
def download_github_repo(url, local_path):
|
|
|
56 |
shutil.make_archive(output_filename, 'zip', source_dir)
|
57 |
|
58 |
def create_repo(g, repo_name):
|
59 |
+
# π οΈ Creating a new GitHub repo. It's alive!
|
60 |
user = g.get_user()
|
61 |
return user.create_repo(repo_name)
|
62 |
|
63 |
def push_to_github(local_path, repo, github_token):
|
64 |
+
# π Pushing code to GitHub. Blast off!
|
65 |
repo_url = f"https://{github_token}@github.com/{repo.full_name}.git"
|
66 |
local_repo = Repo(local_path)
|
67 |
|
68 |
+
if 'origin' in [remote.name for remote.local_repo.remotes]:
|
69 |
origin = local_repo.remote('origin')
|
70 |
origin.set_url(repo_url)
|
71 |
else:
|
|
|
91 |
base64_encoded = base64.b64encode(contents).decode()
|
92 |
return f'<a href="data:application/zip;base64,{base64_encoded}" download="{file_name}">β¬οΈ Download {file_name}</a>'
|
93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
# π Cosmos DB functions
|
95 |
def insert_record(container, record):
|
|
|
96 |
try:
|
97 |
container.create_item(body=record)
|
98 |
return True, "Record inserted successfully! π"
|
|
|
101 |
except Exception as e:
|
102 |
return False, f"An unexpected error occurred: {str(e)} π±"
|
103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
# π² Function to generate a unique UUID
|
105 |
def generate_unique_id():
|
|
|
106 |
return str(uuid.uuid4())
|
107 |
|
108 |
+
# Claude π§ Chat handling (Wise responses guaranteed! π€)
|
109 |
+
def chat_with_claude(user_input):
|
110 |
+
response = client_anthropic.messages.create(
|
111 |
+
model="claude-3-sonnet-20240229",
|
112 |
+
max_tokens=1000,
|
113 |
+
messages=[
|
114 |
+
{"role": "user", "content": user_input}
|
115 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
)
|
117 |
+
return response.content[0].text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
+
# File handling (Save that wisdom in files! πΎ)
|
120 |
+
def generate_filename(prompt, file_type):
|
121 |
+
central = pytz.timezone('US/Central')
|
122 |
+
safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
|
123 |
+
safe_prompt = re.sub(r'\W+', '_', prompt)[:90]
|
124 |
+
return f"{safe_date_time}_{safe_prompt}.{file_type}"
|
125 |
|
126 |
+
def create_file(filename, prompt, response, should_save=True):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
if not should_save:
|
128 |
+
return
|
129 |
+
with open(filename, 'w', encoding='utf-8') as file:
|
130 |
+
file.write(prompt + "\n\n" + response)
|
131 |
+
|
132 |
+
def load_file(file_name):
|
133 |
+
with open(file_name, "r", encoding='utf-8') as file:
|
134 |
+
content = file.read()
|
135 |
+
return content
|
136 |
+
|
137 |
+
# π¨ Image and media handling (Let's look at some visuals! πΈπ¬πΆ)
|
138 |
+
def get_video_html(video_path, width="100%"):
|
139 |
+
video_url = f"data:video/mp4;base64,{base64.b64encode(open(video_path, 'rb').read()).decode()}"
|
140 |
+
return f'''
|
141 |
+
<video width="{width}" controls autoplay muted loop>
|
142 |
+
<source src="{video_url}" type="video/mp4">
|
143 |
+
Your browser does not support the video tag.
|
144 |
+
</video>
|
145 |
+
'''
|
146 |
+
|
147 |
+
def get_audio_html(audio_path, width="100%"):
|
148 |
+
audio_url = f"data:audio/mpeg;base64,{base64.b64encode(open(audio_path, 'rb').read()).decode()}"
|
149 |
+
return f'''
|
150 |
+
<audio controls style="width: {width};">
|
151 |
+
<source src="{audio_url}" type="audio/mpeg">
|
152 |
+
Your browser does not support the audio element.
|
153 |
+
</audio>
|
154 |
+
'''
|
155 |
+
|
156 |
+
# Streamlit layout (because a clean UI is key! π )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
def main():
|
158 |
+
st.title("πGitπCosmosπ« & Claudeπ§ - The Ultimate App")
|
|
|
159 |
|
160 |
+
# Sidebar navigation (The command center π§)
|
161 |
+
st.sidebar.title("π§ Claudeπ & Cosmos Explorer")
|
162 |
+
|
163 |
+
# Cosmos DB Section
|
164 |
+
st.sidebar.header("Cosmos DB Controls")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
if Key:
|
166 |
st.session_state.primary_key = Key
|
167 |
st.session_state.logged_in = True
|
|
|
|
|
|
|
168 |
|
169 |
+
if st.session_state.logged_in:
|
170 |
+
st.sidebar.write("π Connected to Cosmos DB!")
|
|
|
|
|
|
|
|
|
|
|
|
|
171 |
|
172 |
+
# Fetch documents
|
173 |
+
cosmos_client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
|
174 |
+
databases = [db['id'] for db in cosmos_client.list_databases()]
|
175 |
+
selected_db = st.sidebar.selectbox("Select Database", databases)
|
176 |
|
177 |
+
if selected_db:
|
178 |
+
db_client = cosmos_client.get_database_client(selected_db)
|
179 |
+
containers = [container['id'] for container in db_client.list_containers()]
|
180 |
+
selected_container = st.sidebar.selectbox("Select Container", containers)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
181 |
|
182 |
+
if selected_container:
|
183 |
+
container = db_client.get_container_client(selected_container)
|
184 |
+
documents = list(container.read_all_items())
|
185 |
+
if documents:
|
186 |
+
st.write("π Document List:")
|
187 |
+
df = pd.DataFrame(documents)
|
188 |
+
st.dataframe(df)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
189 |
else:
|
190 |
+
st.write("π No documents in this container.")
|
191 |
+
|
192 |
+
# Claude Chat Section
|
193 |
+
st.header("Chat with Claude π€π§ ")
|
194 |
+
user_input = st.text_area("Ask Claude anything:")
|
195 |
+
if st.button("Send"):
|
196 |
+
if user_input:
|
197 |
+
response = chat_with_claude(user_input)
|
198 |
+
st.write(f"Claude says: {response}")
|
199 |
+
|
200 |
+
filename = generate_filename(user_input, "md")
|
201 |
+
create_file(filename, user_input, response)
|
202 |
+
|
203 |
+
if 'chat_history' not in st.session_state:
|
204 |
+
st.session_state.chat_history = []
|
205 |
+
st.session_state.chat_history.append({"user": user_input, "claude": response})
|
206 |
+
|
207 |
+
if "chat_history" in st.session_state:
|
208 |
+
st.subheader("Past Conversations π")
|
209 |
+
for chat in st.session_state.chat_history:
|
210 |
+
st.text_area("You said π¬:", chat["user"], height=100, disabled=True)
|
211 |
+
st.text_area("Claude replied π€:", chat["claude"], height=200, disabled=True)
|
212 |
+
st.markdown("---")
|
213 |
+
|
214 |
+
# Media Galleries (For those who prefer images and videos πΌπ₯πΆ)
|
215 |
+
st.subheader("Image Gallery πΌ")
|
216 |
+
image_files = glob.glob("*.png") + glob.glob("*.jpg")
|
217 |
+
cols = st.columns(3)
|
218 |
+
for idx, image_file in enumerate(image_files):
|
219 |
+
with cols[idx % 3]:
|
220 |
+
img = Image.open(image_file)
|
221 |
+
st.image(img)
|
222 |
+
|
223 |
+
st.subheader("Video Gallery π₯")
|
224 |
+
video_files = glob.glob("*.mp4")
|
225 |
+
for video_file in video_files:
|
226 |
+
st.markdown(get_video_html(video_file), unsafe_allow_html=True)
|
227 |
+
|
228 |
+
st.subheader("Audio Gallery πΆ")
|
229 |
+
audio_files = glob.glob("*.mp3") + glob.glob("*.wav")
|
230 |
+
for audio_file in audio_files:
|
231 |
+
st.markdown(get_audio_html(audio_file), unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
|
233 |
if __name__ == "__main__":
|
234 |
main()
|