Spaces:
Running
Running
Update app15.py
Browse files
app15.py
CHANGED
@@ -15,7 +15,7 @@ import traceback
|
|
15 |
import uuid
|
16 |
import zipfile
|
17 |
from PIL import Image
|
18 |
-
from azure.cosmos import CosmosClient, exceptions
|
19 |
from datetime import datetime
|
20 |
from git import Repo
|
21 |
from github import Github
|
@@ -26,6 +26,20 @@ import requests
|
|
26 |
import numpy as np
|
27 |
from urllib.parse import quote
|
28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
# %% βββββββββββββ APP CONFIGURATION βββββββββββββ
|
30 |
Site_Name = 'π GitCosmos'
|
31 |
title = "π GitCosmos"
|
@@ -33,15 +47,15 @@ helpURL = 'https://huggingface.co/awacke1'
|
|
33 |
bugURL = 'https://huggingface.co/spaces/awacke1/AzureCosmosDBUI/'
|
34 |
icons = 'πππ«'
|
35 |
st.set_page_config(
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
)
|
46 |
|
47 |
# Cosmos DB & App URLs
|
@@ -53,743 +67,796 @@ LOCAL_APP_URL = "https://huggingface.co/spaces/awacke1/AzureCosmosDBUI"
|
|
53 |
CosmosDBUrl = 'https://portal.azure.com/#@AaronCWackergmail.onmicrosoft.com/resource/subscriptions/003fba60-5b3f-48f4-ab36-3ed11bc40816/resourceGroups/datasets/providers/Microsoft.DocumentDB/databaseAccounts/acae-afd/dataExplorer'
|
54 |
|
55 |
# %% βββββββββββββ HELPER FUNCTIONS βββββββββββββ
|
56 |
-
# π Get download link from file
|
57 |
def get_download_link(file_path):
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
|
64 |
-
# π Generate a unique ID
|
65 |
def generate_unique_id():
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
|
72 |
-
# π Generate a filename from a prompt
|
73 |
def generate_filename(prompt, file_type):
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
|
79 |
-
# πΎ Create and save a file with prompt & response
|
80 |
def create_file(filename, prompt, response, should_save=True):
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
|
86 |
-
# π Load file content from disk
|
87 |
def load_file(file_name):
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
|
92 |
-
# π Display glossary entity with quick links
|
93 |
def display_glossary_entity(k):
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
# ποΈ Create zip of multiple files
|
104 |
def create_zip_of_files(files):
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
|
111 |
-
# π¬ Get HTML for video playback
|
112 |
def get_video_html(video_path, width="100%"):
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
# π΅ Get HTML for audio playback
|
122 |
def get_audio_html(audio_path, width="100%"):
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
# π Preprocess text for JSON safety
|
132 |
def preprocess_text(text):
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
|
139 |
# %% βββββββββββββ COSMOS DB FUNCTIONS βββββββββββββ
|
140 |
-
# π List all databases in Cosmos
|
141 |
def get_databases(client):
|
142 |
-
|
143 |
|
144 |
-
# π¦ List all containers in a database
|
145 |
def get_containers(database):
|
146 |
-
|
147 |
|
148 |
-
# π Query documents from a container (most recent first)
|
149 |
def get_documents(container, limit=None):
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
|
154 |
-
# π₯ Insert a new record into Cosmos
|
155 |
def insert_record(container, record):
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
# π Update an existing Cosmos record
|
165 |
def update_record(container, updated_record):
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
# ποΈ Delete a record from Cosmos DB using /id as partition key
|
175 |
def delete_record(container, record):
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
# Perform the deletion
|
203 |
-
container.delete_item(item=doc_id, partition_key=partition_key_value)
|
204 |
-
success_msg = f"Record {doc_id} successfully deleted from Cosmos DB. ποΈ"
|
205 |
-
st.session_state.delete_log.append(success_msg)
|
206 |
-
return True, success_msg
|
207 |
-
|
208 |
-
except exceptions.CosmosResourceNotFoundError:
|
209 |
-
success_msg = f"Record {doc_id} not found in Cosmos DB (already deleted or never existed). ποΈ"
|
210 |
-
st.session_state.delete_log.append(success_msg)
|
211 |
-
return True, success_msg # Treat as success since the goal is removal
|
212 |
-
except exceptions.CosmosHttpResponseError as e:
|
213 |
-
error_msg = f"HTTP error deleting {doc_id}: {str(e)}. π¨"
|
214 |
-
st.session_state.delete_log.append(error_msg)
|
215 |
-
return False, error_msg
|
216 |
-
except Exception as e:
|
217 |
-
error_msg = f"Unexpected error deleting {doc_id}: {str(traceback.format_exc())}. π±"
|
218 |
-
st.session_state.delete_log.append(error_msg)
|
219 |
-
return False, error_msg
|
220 |
-
|
221 |
-
# πΎ Save a new document to Cosmos DB with extra fields
|
222 |
def save_to_cosmos_db(container, query, response1, response2):
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
# ποΈ Archive all documents in a container and provide a download link
|
247 |
def archive_current_container(database_name, container_name, client):
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
267 |
|
268 |
# %% βββββββββββββ GITHUB FUNCTIONS βββββββββββββ
|
269 |
-
# π₯ Clone a GitHub repository locally
|
270 |
def download_github_repo(url, local_path):
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
|
275 |
-
# ποΈ Zip a directory
|
276 |
def create_zip_file(source_dir, output_filename):
|
277 |
-
|
278 |
|
279 |
-
# ποΈ Create a new GitHub repo via API
|
280 |
def create_repo(g, repo_name):
|
281 |
-
|
282 |
-
|
283 |
|
284 |
-
# π Push local repo changes to GitHub
|
285 |
def push_to_github(local_path, repo, github_token):
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
|
303 |
# %% βββββββββββββ FILE & MEDIA MANAGEMENT FUNCTIONS βββββββββββββ
|
304 |
-
# π List saved Markdown files in sidebar with actions
|
305 |
def display_saved_files_in_sidebar():
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
# π Display file viewer in main area
|
324 |
def display_file_viewer(file_path):
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
# βοΈ Display file editor (Markdown & Code)
|
336 |
def display_file_editor(file_path):
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
# πΎ Save content to a file (with error handling)
|
364 |
def save_file_content(file_path, content):
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
# ποΈ Update file management UI section (view, edit, delete)
|
374 |
def update_file_management_section():
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
429 |
|
430 |
# %% βββββββββββββ VIDEO & AUDIO UI FUNCTIONS βββββββββββββ
|
431 |
-
# πΌοΈ Validate and preprocess an image for video generation
|
432 |
def validate_and_preprocess_image(file_data, target_size=(576, 1024)):
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
# βΆοΈ Add video generation UI with Gradio client
|
467 |
def add_video_generation_ui(container):
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
|
545 |
# %% βββββββββββββ MAIN FUNCTION βββββββββββββ
|
546 |
-
# π Main app entry point
|
547 |
def main():
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
-
|
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 |
-
|
731 |
-
|
732 |
-
|
733 |
-
|
734 |
-
|
735 |
-
|
736 |
-
|
737 |
-
|
738 |
-
|
739 |
-
|
740 |
-
|
741 |
-
|
742 |
-
|
743 |
-
|
744 |
-
|
745 |
-
|
746 |
-
|
747 |
-
|
748 |
-
|
749 |
-
|
750 |
-
|
751 |
-
|
752 |
-
|
753 |
-
|
754 |
-
|
755 |
-
|
756 |
-
|
757 |
-
|
758 |
-
|
759 |
-
|
760 |
-
|
761 |
-
|
762 |
-
|
763 |
-
|
764 |
-
|
765 |
-
|
766 |
-
|
767 |
-
|
768 |
-
|
769 |
-
|
770 |
-
|
771 |
-
|
772 |
-
|
773 |
-
|
774 |
-
|
775 |
-
|
776 |
-
|
777 |
-
|
778 |
-
|
779 |
-
|
780 |
-
|
781 |
-
|
782 |
-
|
783 |
-
|
784 |
-
|
785 |
-
|
786 |
-
|
787 |
-
|
788 |
-
|
789 |
-
|
790 |
-
|
791 |
-
|
792 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
793 |
|
794 |
if __name__ == "__main__":
|
795 |
-
|
|
|
15 |
import uuid
|
16 |
import zipfile
|
17 |
from PIL import Image
|
18 |
+
from azure.cosmos import CosmosClient, PartitionKey, exceptions
|
19 |
from datetime import datetime
|
20 |
from git import Repo
|
21 |
from github import Github
|
|
|
26 |
import numpy as np
|
27 |
from urllib.parse import quote
|
28 |
|
29 |
+
# External help links for AI tools
|
30 |
+
external_links = [
|
31 |
+
{"title": "MergeKit Official GitHub", "url": "https://github.com/arcee-ai/MergeKit", "emoji": "π»"},
|
32 |
+
{"title": "MergeKit arXiv Paper", "url": "https://arxiv.org/abs/xxxx.xxxxx", "emoji": "π"},
|
33 |
+
{"title": "MergeKit Tutorial", "url": "https://huggingface.co/blog/mergekit-tutorial", "emoji": "βοΈ"},
|
34 |
+
{"title": "MergeKit Sample Usage", "url": "https://github.com/arcee-ai/MergeKit#examples", "emoji": "π"},
|
35 |
+
{"title": "DistillKit Official GitHub", "url": "https://github.com/arcee-ai/DistillKit", "emoji": "π»"},
|
36 |
+
{"title": "DistillKit Announcing Blog Post", "url": "https://arcee.ai/blog/distillkit-announcement", "emoji": "βοΈ"},
|
37 |
+
{"title": "DistillKit Sample Usage", "url": "https://github.com/arcee-ai/DistillKit#usage", "emoji": "π"},
|
38 |
+
{"title": "Spectrum Hugging Face Blog Post", "url": "https://huggingface.co/blog/spectrum", "emoji": "βοΈ"},
|
39 |
+
{"title": "Hugging Face Model Merging Docs", "url": "https://huggingface.co/docs/peft/model_merging", "emoji": "π"},
|
40 |
+
{"title": "arcee.ai Official Website", "url": "https://arcee.ai", "emoji": "π"},
|
41 |
+
]
|
42 |
+
|
43 |
# %% βββββββββββββ APP CONFIGURATION βββββββββββββ
|
44 |
Site_Name = 'π GitCosmos'
|
45 |
title = "π GitCosmos"
|
|
|
47 |
bugURL = 'https://huggingface.co/spaces/awacke1/AzureCosmosDBUI/'
|
48 |
icons = 'πππ«'
|
49 |
st.set_page_config(
|
50 |
+
page_title=title,
|
51 |
+
page_icon=icons,
|
52 |
+
layout="wide",
|
53 |
+
initial_sidebar_state="auto",
|
54 |
+
menu_items={
|
55 |
+
'Get Help': helpURL,
|
56 |
+
'Report a bug': bugURL,
|
57 |
+
'About': title
|
58 |
+
}
|
59 |
)
|
60 |
|
61 |
# Cosmos DB & App URLs
|
|
|
67 |
CosmosDBUrl = 'https://portal.azure.com/#@AaronCWackergmail.onmicrosoft.com/resource/subscriptions/003fba60-5b3f-48f4-ab36-3ed11bc40816/resourceGroups/datasets/providers/Microsoft.DocumentDB/databaseAccounts/acae-afd/dataExplorer'
|
68 |
|
69 |
# %% βββββββββββββ HELPER FUNCTIONS βββββββββββββ
|
|
|
70 |
def get_download_link(file_path):
|
71 |
+
with open(file_path, "rb") as file:
|
72 |
+
contents = file.read()
|
73 |
+
b64 = base64.b64encode(contents).decode()
|
74 |
+
file_name = os.path.basename(file_path)
|
75 |
+
return f'<a href="data:file/txt;base64,{b64}" download="{file_name}">Download {file_name} π</a>'
|
76 |
|
|
|
77 |
def generate_unique_id():
|
78 |
+
timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
|
79 |
+
unique_uuid = str(uuid.uuid4())
|
80 |
+
return_value = f"{timestamp}-{unique_uuid}"
|
81 |
+
st.write('New ID: ' + return_value)
|
82 |
+
return return_value
|
83 |
|
|
|
84 |
def generate_filename(prompt, file_type):
|
85 |
+
central = pytz.timezone('US/Central')
|
86 |
+
safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
|
87 |
+
safe_prompt = re.sub(r'\W+', '', prompt)[:90]
|
88 |
+
return f"{safe_date_time}{safe_prompt}.{file_type}"
|
89 |
|
|
|
90 |
def create_file(filename, prompt, response, should_save=True):
|
91 |
+
if not should_save:
|
92 |
+
return
|
93 |
+
with open(filename, 'w', encoding='utf-8') as file:
|
94 |
+
file.write(prompt + "\n\n" + response)
|
95 |
|
|
|
96 |
def load_file(file_name):
|
97 |
+
with open(file_name, "r", encoding='utf-8') as file:
|
98 |
+
content = file.read()
|
99 |
+
return content
|
100 |
|
|
|
101 |
def display_glossary_entity(k):
|
102 |
+
search_urls = {
|
103 |
+
"π": lambda k: f"/?q={k}",
|
104 |
+
"π": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
|
105 |
+
"π": lambda k: f"https://www.google.com/search?q={quote(k)}",
|
106 |
+
"π₯": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
|
107 |
+
}
|
108 |
+
links_md = ' '.join([f"<a href='{url(k)}' target='_blank'>{emoji}</a>" for emoji, url in search_urls.items()])
|
109 |
+
st.markdown(f"{k} {links_md}", unsafe_allow_html=True)
|
110 |
+
|
|
|
111 |
def create_zip_of_files(files):
|
112 |
+
zip_name = "all_files.zip"
|
113 |
+
with zipfile.ZipFile(zip_name, 'w') as zipf:
|
114 |
+
for file in files:
|
115 |
+
zipf.write(file)
|
116 |
+
return zip_name
|
117 |
|
|
|
118 |
def get_video_html(video_path, width="100%"):
|
119 |
+
video_url = f"data:video/mp4;base64,{base64.b64encode(open(video_path, 'rb').read()).decode()}"
|
120 |
+
return f'''
|
121 |
+
<video width="{width}" controls autoplay loop>
|
122 |
+
<source src="{video_url}" type="video/mp4">
|
123 |
+
Your browser does not support video.
|
124 |
+
</video>
|
125 |
+
'''
|
126 |
+
|
|
|
127 |
def get_audio_html(audio_path, width="100%"):
|
128 |
+
audio_url = f"data:audio/mpeg;base64,{base64.b64encode(open(audio_path, 'rb').read()).decode()}"
|
129 |
+
return f'''
|
130 |
+
<audio controls style="width:{width}">
|
131 |
+
<source src="{audio_url}" type="audio/mpeg">
|
132 |
+
Your browser does not support audio.
|
133 |
+
</audio>
|
134 |
+
'''
|
135 |
+
|
|
|
136 |
def preprocess_text(text):
|
137 |
+
text = text.replace('\r\n', '\\n').replace('\r', '\\n').replace('\n', '\\n')
|
138 |
+
text = text.replace('"', '\\"')
|
139 |
+
text = re.sub(r'[\t]', ' ', text)
|
140 |
+
text = re.sub(r'[^\x00-\x7F]+', '', text)
|
141 |
+
return text.strip()
|
142 |
|
143 |
# %% βββββββββββββ COSMOS DB FUNCTIONS βββββββββββββ
|
|
|
144 |
def get_databases(client):
|
145 |
+
return [db['id'] for db in client.list_databases()]
|
146 |
|
|
|
147 |
def get_containers(database):
|
148 |
+
return [container['id'] for container in database.list_containers()]
|
149 |
|
|
|
150 |
def get_documents(container, limit=None):
|
151 |
+
query = "SELECT * FROM c ORDER BY c._ts DESC"
|
152 |
+
items = list(container.query_items(query=query, enable_cross_partition_query=True, max_item_count=limit))
|
153 |
+
return items
|
154 |
|
|
|
155 |
def insert_record(container, record):
|
156 |
+
try:
|
157 |
+
container.create_item(body=record)
|
158 |
+
return True, "Inserted! π"
|
159 |
+
except exceptions.CosmosHttpResponseError as e:
|
160 |
+
return False, f"HTTP error: {str(e)} π¨"
|
161 |
+
except Exception as e:
|
162 |
+
return False, f"Error: {str(e)} π±"
|
163 |
+
|
|
|
164 |
def update_record(container, updated_record):
|
165 |
+
try:
|
166 |
+
container.upsert_item(body=updated_record)
|
167 |
+
return True, f"Updated {updated_record['id']} π οΈ"
|
168 |
+
except exceptions.CosmosHttpResponseError as e:
|
169 |
+
return False, f"HTTP error: {str(e)} π¨"
|
170 |
+
except Exception as e:
|
171 |
+
return False, f"Error: {traceback.format_exc()} π±"
|
172 |
+
|
|
|
173 |
def delete_record(container, record):
|
174 |
+
try:
|
175 |
+
if "id" not in record:
|
176 |
+
return False, "Record must contain an 'id' field. π"
|
177 |
+
doc_id = record["id"]
|
178 |
+
if "delete_log" not in st.session_state:
|
179 |
+
st.session_state.delete_log = []
|
180 |
+
st.session_state.delete_log.append(f"Attempting to delete document: {json.dumps(record, indent=2)}")
|
181 |
+
partition_key_value = doc_id
|
182 |
+
st.session_state.delete_log.append(f"Using ID and Partition Key: {partition_key_value}")
|
183 |
+
container.delete_item(item=doc_id, partition_key=partition_key_value)
|
184 |
+
success_msg = f"Record {doc_id} successfully deleted from Cosmos DB. ποΈ"
|
185 |
+
st.session_state.delete_log.append(success_msg)
|
186 |
+
return True, success_msg
|
187 |
+
except exceptions.CosmosResourceNotFoundError:
|
188 |
+
success_msg = f"Record {doc_id} not found in Cosmos DB (already deleted or never existed). ποΈ"
|
189 |
+
st.session_state.delete_log.append(success_msg)
|
190 |
+
return True, success_msg
|
191 |
+
except exceptions.CosmosHttpResponseError as e:
|
192 |
+
error_msg = f"HTTP error deleting {doc_id}: {str(e)}. π¨"
|
193 |
+
st.session_state.delete_log.append(error_msg)
|
194 |
+
return False, error_msg
|
195 |
+
except Exception as e:
|
196 |
+
error_msg = f"Unexpected error deleting {doc_id}: {str(traceback.format_exc())}. π±"
|
197 |
+
st.session_state.delete_log.append(error_msg)
|
198 |
+
return False, error_msg
|
199 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
def save_to_cosmos_db(container, query, response1, response2):
|
201 |
+
try:
|
202 |
+
if container:
|
203 |
+
timestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
|
204 |
+
unique_uuid = str(uuid.uuid4())
|
205 |
+
new_id = f"{timestamp}-{unique_uuid}"
|
206 |
+
record = {
|
207 |
+
"id": new_id,
|
208 |
+
"name": new_id,
|
209 |
+
"query": query,
|
210 |
+
"response1": response1,
|
211 |
+
"response2": response2,
|
212 |
+
"timestamp": datetime.utcnow().isoformat(),
|
213 |
+
"type": "ai_response",
|
214 |
+
"version": "1.0"
|
215 |
+
}
|
216 |
+
container.create_item(body=record)
|
217 |
+
st.success(f"Saved: {record['id']}")
|
218 |
+
st.session_state.documents = get_documents(container)
|
219 |
+
else:
|
220 |
+
st.error("Cosmos container not initialized.")
|
221 |
+
except Exception as e:
|
222 |
+
st.error(f"Save error: {str(e)}")
|
223 |
+
|
|
|
224 |
def archive_current_container(database_name, container_name, client):
|
225 |
+
try:
|
226 |
+
base_dir = "./cosmos_archive_current_container"
|
227 |
+
if os.path.exists(base_dir):
|
228 |
+
shutil.rmtree(base_dir)
|
229 |
+
os.makedirs(base_dir)
|
230 |
+
db_client = client.get_database_client(database_name)
|
231 |
+
container_client = db_client.get_container_client(container_name)
|
232 |
+
items = list(container_client.read_all_items())
|
233 |
+
container_dir = os.path.join(base_dir, container_name)
|
234 |
+
os.makedirs(container_dir)
|
235 |
+
for item in items:
|
236 |
+
item_id = item.get('id', f"unknown_{datetime.now().strftime('%Y%m%d%H%M%S')}")
|
237 |
+
with open(os.path.join(container_dir, f"{item_id}.json"), 'w') as f:
|
238 |
+
json.dump(item, f, indent=2)
|
239 |
+
archive_name = f"{container_name}_archive_{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
240 |
+
shutil.make_archive(archive_name, 'zip', base_dir)
|
241 |
+
return get_download_link(f"{archive_name}.zip")
|
242 |
+
except Exception as e:
|
243 |
+
return f"Archive error: {str(e)} π’"
|
244 |
+
|
245 |
+
# %% βββββββββββββ ADVANCED COSMOS FUNCTIONS βββββββββββββ
|
246 |
+
def create_new_container(database, container_id, partition_key_path,
|
247 |
+
analytical_storage_ttl=None, indexing_policy=None, vector_embedding_policy=None):
|
248 |
+
try:
|
249 |
+
# Try creating with analytical_storage_ttl if provided.
|
250 |
+
if analytical_storage_ttl is not None:
|
251 |
+
container = database.create_container(
|
252 |
+
id=container_id,
|
253 |
+
partition_key=PartitionKey(path=partition_key_path),
|
254 |
+
analytical_storage_ttl=analytical_storage_ttl,
|
255 |
+
indexing_policy=indexing_policy,
|
256 |
+
vector_embedding_policy=vector_embedding_policy
|
257 |
+
)
|
258 |
+
else:
|
259 |
+
container = database.create_container(
|
260 |
+
id=container_id,
|
261 |
+
partition_key=PartitionKey(path=partition_key_path),
|
262 |
+
indexing_policy=indexing_policy,
|
263 |
+
vector_embedding_policy=vector_embedding_policy
|
264 |
+
)
|
265 |
+
except exceptions.CosmosHttpResponseError as e:
|
266 |
+
# If the error is due to the analytical_storage_ttl property not being valid, try again without it.
|
267 |
+
if analytical_storage_ttl is not None and "analyticalStorageTtl" in str(e):
|
268 |
+
try:
|
269 |
+
container = database.create_container(
|
270 |
+
id=container_id,
|
271 |
+
partition_key=PartitionKey(path=partition_key_path),
|
272 |
+
indexing_policy=indexing_policy,
|
273 |
+
vector_embedding_policy=vector_embedding_policy
|
274 |
+
)
|
275 |
+
except Exception as e2:
|
276 |
+
st.error(f"Error creating container without analytical_storage_ttl: {str(e2)}")
|
277 |
+
return None
|
278 |
+
elif isinstance(e, exceptions.CosmosResourceExistsError):
|
279 |
+
container = database.get_container_client(container_id)
|
280 |
+
else:
|
281 |
+
st.error(f"Error creating container: {str(e)}")
|
282 |
+
return None
|
283 |
+
return container
|
284 |
+
|
285 |
+
def advanced_insert_item(container, item):
|
286 |
+
try:
|
287 |
+
container.upsert_item(item)
|
288 |
+
return True, f"Item {item.get('id', '')} inserted. β"
|
289 |
+
except Exception as e:
|
290 |
+
return False, str(e)
|
291 |
+
|
292 |
+
def advanced_update_item(container, item):
|
293 |
+
try:
|
294 |
+
container.upsert_item(item)
|
295 |
+
return True, f"Item {item.get('id', '')} updated. βοΈ"
|
296 |
+
except Exception as e:
|
297 |
+
return False, str(e)
|
298 |
+
|
299 |
+
def advanced_delete_item(container, item_id, partition_key_value):
|
300 |
+
try:
|
301 |
+
container.delete_item(item=item_id, partition_key=partition_key_value)
|
302 |
+
return True, f"Item {item_id} deleted. ποΈ"
|
303 |
+
except Exception as e:
|
304 |
+
return False, str(e)
|
305 |
+
|
306 |
+
def vector_search(container, query_vector, vector_field, top=10, exact_search=False):
|
307 |
+
query_vector_str = json.dumps(query_vector)
|
308 |
+
query = f"""SELECT TOP {top} c.id, VectorDistance(c.{vector_field}, {query_vector_str}, {str(exact_search).lower()},
|
309 |
+
{{'dataType':'float32','distanceFunction':'cosine'}}) AS SimilarityScore
|
310 |
+
FROM c ORDER BY SimilarityScore"""
|
311 |
+
results = list(container.query_items(query=query, enable_cross_partition_query=True))
|
312 |
+
return results
|
313 |
|
314 |
# %% βββββββββββββ GITHUB FUNCTIONS βββββββββββββ
|
|
|
315 |
def download_github_repo(url, local_path):
|
316 |
+
if os.path.exists(local_path):
|
317 |
+
shutil.rmtree(local_path)
|
318 |
+
Repo.clone_from(url, local_path)
|
319 |
|
|
|
320 |
def create_zip_file(source_dir, output_filename):
|
321 |
+
shutil.make_archive(output_filename, 'zip', source_dir)
|
322 |
|
|
|
323 |
def create_repo(g, repo_name):
|
324 |
+
user = g.get_user()
|
325 |
+
return user.create_repo(repo_name)
|
326 |
|
|
|
327 |
def push_to_github(local_path, repo, github_token):
|
328 |
+
repo_url = f"https://{github_token}@github.com/{repo.full_name}.git"
|
329 |
+
local_repo = Repo(local_path)
|
330 |
+
if 'origin' in [remote.name for remote in local_repo.remotes]:
|
331 |
+
origin = local_repo.remote('origin')
|
332 |
+
origin.set_url(repo_url)
|
333 |
+
else:
|
334 |
+
origin = local_repo.create_remote('origin', repo_url)
|
335 |
+
if not local_repo.heads:
|
336 |
+
local_repo.git.checkout('-b', 'main')
|
337 |
+
current_branch = 'main'
|
338 |
+
else:
|
339 |
+
current_branch = local_repo.active_branch.name
|
340 |
+
local_repo.git.add(A=True)
|
341 |
+
if local_repo.is_dirty():
|
342 |
+
local_repo.git.commit('-m', 'Initial commit')
|
343 |
+
origin.push(refspec=f'{current_branch}:{current_branch}')
|
344 |
|
345 |
# %% βββββββββββββ FILE & MEDIA MANAGEMENT FUNCTIONS βββββββββββββ
|
|
|
346 |
def display_saved_files_in_sidebar():
|
347 |
+
all_files = sorted([f for f in glob.glob("*.md") if not f.lower().startswith('readme')], reverse=True)
|
348 |
+
st.sidebar.markdown("## π Files")
|
349 |
+
for file in all_files:
|
350 |
+
col1, col2, col3 = st.sidebar.columns([6, 2, 1])
|
351 |
+
with col1:
|
352 |
+
st.markdown(f"π {file}")
|
353 |
+
with col2:
|
354 |
+
st.sidebar.download_button(
|
355 |
+
label="β¬οΈ",
|
356 |
+
data=open(file, 'rb').read(),
|
357 |
+
file_name=file
|
358 |
+
)
|
359 |
+
with col3:
|
360 |
+
if st.sidebar.button("π", key=f"delete_{file}"):
|
361 |
+
os.remove(file)
|
362 |
+
st.rerun()
|
363 |
+
|
|
|
364 |
def display_file_viewer(file_path):
|
365 |
+
content = load_file(file_path)
|
366 |
+
if content:
|
367 |
+
st.markdown("### π File Viewer")
|
368 |
+
st.markdown(f"**{file_path}**")
|
369 |
+
file_stats = os.stat(file_path)
|
370 |
+
st.markdown(f"**Mod:** {datetime.fromtimestamp(file_stats.st_mtime).strftime('%Y-%m-%d %H:%M:%S')} | **Size:** {file_stats.st_size} bytes")
|
371 |
+
st.markdown("---")
|
372 |
+
st.markdown(content)
|
373 |
+
st.download_button("β¬οΈ", data=content, file_name=os.path.basename(file_path), mime="text/markdown")
|
374 |
+
|
|
|
375 |
def display_file_editor(file_path):
|
376 |
+
if 'file_content' not in st.session_state:
|
377 |
+
st.session_state.file_content = {}
|
378 |
+
if file_path not in st.session_state.file_content:
|
379 |
+
content = load_file(file_path)
|
380 |
+
if content is not None:
|
381 |
+
st.session_state.file_content[file_path] = content
|
382 |
+
else:
|
383 |
+
return
|
384 |
+
st.markdown("### βοΈ Edit File")
|
385 |
+
st.markdown(f"**Editing:** {file_path}")
|
386 |
+
md_tab, code_tab = st.tabs(["Markdown", "Code"])
|
387 |
+
with md_tab:
|
388 |
+
st.markdown(st.session_state.file_content[file_path])
|
389 |
+
with code_tab:
|
390 |
+
new_content = st.text_area("Edit:", value=st.session_state.file_content[file_path], height=400, key=f"editor_{hash(file_path)}")
|
391 |
+
col1, col2 = st.columns([1, 5])
|
392 |
+
with col1:
|
393 |
+
if st.button("πΎ Save"):
|
394 |
+
if save_file_content(file_path, new_content):
|
395 |
+
st.session_state.file_content[file_path] = new_content
|
396 |
+
st.success("Saved! π")
|
397 |
+
time.sleep(1)
|
398 |
+
st.rerun()
|
399 |
+
with col2:
|
400 |
+
st.download_button("β¬οΈ", data=new_content, file_name=os.path.basename(file_path), mime="text/markdown")
|
401 |
+
|
|
|
402 |
def save_file_content(file_path, content):
|
403 |
+
try:
|
404 |
+
with open(file_path, 'w', encoding='utf-8') as file:
|
405 |
+
file.write(content)
|
406 |
+
return True
|
407 |
+
except Exception as e:
|
408 |
+
st.error(f"Save error: {str(e)}")
|
409 |
+
return False
|
410 |
+
|
|
|
411 |
def update_file_management_section():
|
412 |
+
if 'file_view_mode' not in st.session_state:
|
413 |
+
st.session_state.file_view_mode = None
|
414 |
+
if 'current_file' not in st.session_state:
|
415 |
+
st.session_state.current_file = None
|
416 |
+
if 'file_content' not in st.session_state:
|
417 |
+
st.session_state.file_content = {}
|
418 |
+
all_files = sorted(glob.glob("*.md"), reverse=True)
|
419 |
+
st.sidebar.title("π Files")
|
420 |
+
if st.sidebar.button("π Delete All"):
|
421 |
+
for file in all_files:
|
422 |
+
os.remove(file)
|
423 |
+
st.session_state.file_content = {}
|
424 |
+
st.session_state.current_file = None
|
425 |
+
st.session_state.file_view_mode = None
|
426 |
+
st.rerun()
|
427 |
+
if st.sidebar.button("β¬οΈ Download All"):
|
428 |
+
zip_file = create_zip_of_files(all_files)
|
429 |
+
st.sidebar.markdown(get_download_link(zip_file), unsafe_allow_html=True)
|
430 |
+
for file in all_files:
|
431 |
+
col1, col2, col3, col4 = st.sidebar.columns([1, 3, 1, 1])
|
432 |
+
with col1:
|
433 |
+
if st.button("π", key=f"view_{file}"):
|
434 |
+
st.session_state.current_file = file
|
435 |
+
st.session_state.file_view_mode = 'view'
|
436 |
+
if file not in st.session_state.file_content:
|
437 |
+
content = load_file(file)
|
438 |
+
if content is not None:
|
439 |
+
st.session_state.file_content[file] = content
|
440 |
+
st.rerun()
|
441 |
+
with col2:
|
442 |
+
st.markdown(get_download_link(file), unsafe_allow_html=True)
|
443 |
+
with col3:
|
444 |
+
if st.button("π", key=f"edit_{file}"):
|
445 |
+
st.session_state.current_file = file
|
446 |
+
st.session_state.file_view_mode = 'edit'
|
447 |
+
if file not in st.session_state.file_content:
|
448 |
+
content = load_file(file)
|
449 |
+
if content is not None:
|
450 |
+
st.session_state.file_content[file] = content
|
451 |
+
st.rerun()
|
452 |
+
with col4:
|
453 |
+
if st.button("π", key=f"delete_{file}"):
|
454 |
+
os.remove(file)
|
455 |
+
if file in st.session_state.file_content:
|
456 |
+
del st.session_state.file_content[file]
|
457 |
+
if st.session_state.current_file == file:
|
458 |
+
st.session_state.current_file = None
|
459 |
+
st.session_state.file_view_mode = None
|
460 |
+
st.rerun()
|
461 |
+
|
462 |
+
st.sidebar.markdown("---")
|
463 |
+
st.sidebar.title("External Help Links")
|
464 |
+
for link in external_links:
|
465 |
+
st.sidebar.markdown(f"{link['emoji']} [{link['title']}]({link['url']})", unsafe_allow_html=True)
|
466 |
+
|
467 |
+
if st.session_state.current_file:
|
468 |
+
if st.session_state.file_view_mode == 'view':
|
469 |
+
display_file_viewer(st.session_state.current_file)
|
470 |
+
elif st.session_state.file_view_mode == 'edit':
|
471 |
+
display_file_editor(st.session_state.current_file)
|
472 |
|
473 |
# %% βββββββββββββ VIDEO & AUDIO UI FUNCTIONS βββββββββββββ
|
|
|
474 |
def validate_and_preprocess_image(file_data, target_size=(576, 1024)):
|
475 |
+
try:
|
476 |
+
st.write("Preprocessing image...")
|
477 |
+
if isinstance(file_data, bytes):
|
478 |
+
img = Image.open(io.BytesIO(file_data))
|
479 |
+
elif hasattr(file_data, 'read'):
|
480 |
+
if hasattr(file_data, 'seek'):
|
481 |
+
file_data.seek(0)
|
482 |
+
img = Image.open(file_data)
|
483 |
+
elif isinstance(file_data, Image.Image):
|
484 |
+
img = file_data
|
485 |
+
else:
|
486 |
+
raise ValueError(f"Unsupported input: {type(file_data)}")
|
487 |
+
if img.mode != 'RGB':
|
488 |
+
img = img.convert('RGB')
|
489 |
+
aspect_ratio = img.size[0] / img.size[1]
|
490 |
+
if aspect_ratio > target_size[0] / target_size[1]:
|
491 |
+
new_width = target_size[0]
|
492 |
+
new_height = int(new_width / aspect_ratio)
|
493 |
+
else:
|
494 |
+
new_height = target_size[1]
|
495 |
+
new_width = int(new_height * aspect_ratio)
|
496 |
+
new_width = (new_width // 2) * 2
|
497 |
+
new_height = (new_height // 2) * 2
|
498 |
+
resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
499 |
+
final_img = Image.new('RGB', target_size, (255, 255, 255))
|
500 |
+
paste_x = (target_size[0] - new_width) // 2
|
501 |
+
paste_y = (target_size[1] - new_height) // 2
|
502 |
+
final_img.paste(resized_img, (paste_x, paste_y))
|
503 |
+
return final_img
|
504 |
+
except Exception as e:
|
505 |
+
st.error(f"Image error: {str(e)}")
|
506 |
+
return None
|
507 |
+
|
|
|
508 |
def add_video_generation_ui(container):
|
509 |
+
st.markdown("### π₯ Video Gen")
|
510 |
+
col1, col2 = st.columns([2, 1])
|
511 |
+
with col1:
|
512 |
+
uploaded_file = st.file_uploader("Upload Image πΌοΈ", type=['png', 'jpg', 'jpeg'])
|
513 |
+
with col2:
|
514 |
+
st.markdown("#### Params")
|
515 |
+
motion = st.slider("π Motion", 1, 255, 127)
|
516 |
+
fps = st.slider("π¬ FPS", 1, 30, 6)
|
517 |
+
with st.expander("Advanced"):
|
518 |
+
use_custom = st.checkbox("Custom Seed")
|
519 |
+
seed = st.number_input("Seed", value=int(time.time() * 1000)) if use_custom else None
|
520 |
+
if uploaded_file is not None:
|
521 |
+
try:
|
522 |
+
file_data = uploaded_file.read()
|
523 |
+
preview1, preview2 = st.columns(2)
|
524 |
+
with preview1:
|
525 |
+
st.write("Original")
|
526 |
+
st.image(Image.open(io.BytesIO(file_data)), use_column_width=True)
|
527 |
+
with preview2:
|
528 |
+
proc_img = validate_and_preprocess_image(io.BytesIO(file_data))
|
529 |
+
if proc_img:
|
530 |
+
st.write("Processed")
|
531 |
+
st.image(proc_img, use_column_width=True)
|
532 |
+
else:
|
533 |
+
st.error("Preprocess failed")
|
534 |
+
return
|
535 |
+
if st.button("π₯ Generate"):
|
536 |
+
with st.spinner("Generating video..."):
|
537 |
+
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_file:
|
538 |
+
proc_img.save(temp_file.name, format='PNG')
|
539 |
+
try:
|
540 |
+
client = Client("awacke1/stable-video-diffusion", hf_token=os.environ.get("HUGGINGFACE_TOKEN"))
|
541 |
+
result = client.predict(
|
542 |
+
image=temp_file.name,
|
543 |
+
seed=seed if seed is not None else int(time.time() * 1000),
|
544 |
+
randomize_seed=seed is None,
|
545 |
+
motion_bucket_id=motion,
|
546 |
+
fps_id=fps,
|
547 |
+
api_name="/video"
|
548 |
+
)
|
549 |
+
if result and isinstance(result, tuple) and len(result) >= 1:
|
550 |
+
video_path = result[0].get('video') if isinstance(result[0], dict) else None
|
551 |
+
if video_path and os.path.exists(video_path):
|
552 |
+
video_filename = f"generated_video_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
|
553 |
+
shutil.copy(video_path, video_filename)
|
554 |
+
st.success(f"Video generated! π")
|
555 |
+
st.video(video_filename)
|
556 |
+
if container:
|
557 |
+
video_record = {
|
558 |
+
"id": generate_unique_id(),
|
559 |
+
"type": "generated_video",
|
560 |
+
"filename": video_filename,
|
561 |
+
"seed": seed if seed is not None else "random",
|
562 |
+
"motion": motion,
|
563 |
+
"fps": fps,
|
564 |
+
"timestamp": datetime.now().isoformat()
|
565 |
+
}
|
566 |
+
success, message = insert_record(container, video_record)
|
567 |
+
if success:
|
568 |
+
st.success("DB record saved!")
|
569 |
+
else:
|
570 |
+
st.error(f"DB error: {message}")
|
571 |
+
else:
|
572 |
+
st.error("Invalid result format")
|
573 |
+
else:
|
574 |
+
st.error("No result returned")
|
575 |
+
except Exception as e:
|
576 |
+
st.error(f"Video gen error: {str(e)}")
|
577 |
+
finally:
|
578 |
+
try:
|
579 |
+
os.unlink(temp_file.name)
|
580 |
+
st.write("Temp file removed")
|
581 |
+
except Exception as e:
|
582 |
+
st.warning(f"Cleanup error: {str(e)}")
|
583 |
+
except Exception as e:
|
584 |
+
st.error(f"Upload error: {str(e)}")
|
585 |
|
586 |
# %% βββββββββββββ MAIN FUNCTION βββββββββββββ
|
|
|
587 |
def main():
|
588 |
+
st.markdown("### π GitCosmos - Cosmos & Git Hub")
|
589 |
+
if "chat_history" not in st.session_state:
|
590 |
+
st.session_state.chat_history = []
|
591 |
+
# Auth & Cosmos client initialization
|
592 |
+
if Key:
|
593 |
+
st.session_state.primary_key = Key
|
594 |
+
st.session_state.logged_in = True
|
595 |
+
else:
|
596 |
+
st.error("Missing Cosmos Key πβ")
|
597 |
+
return
|
598 |
+
if st.session_state.logged_in:
|
599 |
+
try:
|
600 |
+
if st.session_state.get("client") is None:
|
601 |
+
st.session_state.client = CosmosClient(ENDPOINT, credential=st.session_state.primary_key)
|
602 |
+
st.sidebar.title("π Navigator")
|
603 |
+
databases = get_databases(st.session_state.client)
|
604 |
+
selected_db = st.sidebar.selectbox("ποΈ DB", databases)
|
605 |
+
st.markdown(CosmosDBUrl)
|
606 |
+
if selected_db != st.session_state.get("selected_database"):
|
607 |
+
st.session_state.selected_database = selected_db
|
608 |
+
st.session_state.selected_container = None
|
609 |
+
st.session_state.selected_document_id = None
|
610 |
+
st.session_state.current_index = 0
|
611 |
+
st.rerun()
|
612 |
+
if st.session_state.selected_database:
|
613 |
+
database = st.session_state.client.get_database_client(st.session_state.selected_database)
|
614 |
+
|
615 |
+
# New Container button under DB menu
|
616 |
+
if "show_new_container_form" not in st.session_state:
|
617 |
+
st.session_state.show_new_container_form = False
|
618 |
+
if st.sidebar.button("π New Container"):
|
619 |
+
st.session_state.show_new_container_form = True
|
620 |
+
if st.session_state.show_new_container_form:
|
621 |
+
with st.sidebar.form("new_container_form"):
|
622 |
+
new_container_id = st.text_input("Container ID", value="newContainer")
|
623 |
+
new_partition_key = st.text_input("Partition Key", value="/id")
|
624 |
+
new_analytical = st.checkbox("Enable Analytical Store", value=False)
|
625 |
+
submitted = st.form_submit_button("Create Container")
|
626 |
+
if submitted:
|
627 |
+
analytical_ttl = -1 if new_analytical else None
|
628 |
+
new_container = create_new_container(
|
629 |
+
database,
|
630 |
+
new_container_id,
|
631 |
+
new_partition_key,
|
632 |
+
analytical_storage_ttl=analytical_ttl
|
633 |
+
)
|
634 |
+
if new_container:
|
635 |
+
st.success(f"Container '{new_container_id}' created.")
|
636 |
+
st.session_state.show_new_container_form = False
|
637 |
+
st.session_state.new_container_created = new_container_id
|
638 |
+
st.rerun()
|
639 |
+
|
640 |
+
# Update container list
|
641 |
+
containers = get_containers(database)
|
642 |
+
if "new_container_created" in st.session_state and st.session_state.new_container_created not in containers:
|
643 |
+
containers.append(st.session_state.new_container_created)
|
644 |
+
selected_container = st.sidebar.selectbox("π Container", containers)
|
645 |
+
if selected_container != st.session_state.get("selected_container"):
|
646 |
+
st.session_state.selected_container = selected_container
|
647 |
+
st.session_state.selected_document_id = None
|
648 |
+
st.session_state.current_index = 0
|
649 |
+
st.rerun()
|
650 |
+
if st.session_state.selected_container:
|
651 |
+
container = database.get_container_client(st.session_state.selected_container)
|
652 |
+
if st.sidebar.button("π¦ Export"):
|
653 |
+
download_link = archive_current_container(st.session_state.selected_database, st.session_state.selected_container, st.session_state.client)
|
654 |
+
if download_link.startswith('<a'):
|
655 |
+
st.markdown(download_link, unsafe_allow_html=True)
|
656 |
+
else:
|
657 |
+
st.error(download_link)
|
658 |
+
documents = get_documents(container)
|
659 |
+
total_docs = len(documents)
|
660 |
+
num_docs = st.slider("Docs", 1, 20, 1)
|
661 |
+
documents_to_display = documents[:num_docs] if total_docs > num_docs else documents
|
662 |
+
st.sidebar.info(f"Showing {len(documents_to_display)} docs")
|
663 |
+
# Document Viewer / Editor
|
664 |
+
view_options = ['Markdown', 'Code', 'Run AI', 'Clone', 'New']
|
665 |
+
selected_view = st.sidebar.selectbox("View", view_options, index=1)
|
666 |
+
if selected_view == 'Markdown':
|
667 |
+
st.markdown("#### π Markdown")
|
668 |
+
if documents:
|
669 |
+
doc = documents[st.session_state.current_index]
|
670 |
+
content = json.dumps(doc, indent=2)
|
671 |
+
st.markdown(f"```json\n{content}\n```")
|
672 |
+
col_prev, col_next = st.columns(2)
|
673 |
+
with col_prev:
|
674 |
+
if st.button("β¬
οΈ") and st.session_state.current_index > 0:
|
675 |
+
st.session_state.current_index -= 1
|
676 |
+
st.rerun()
|
677 |
+
with col_next:
|
678 |
+
if st.button("β‘οΈ") and st.session_state.current_index < total_docs - 1:
|
679 |
+
st.session_state.current_index += 1
|
680 |
+
st.rerun()
|
681 |
+
elif selected_view == 'Code':
|
682 |
+
st.markdown("#### π» Code Editor")
|
683 |
+
if documents:
|
684 |
+
doc = documents[st.session_state.current_index]
|
685 |
+
doc_str = st.text_area("Edit JSON", value=json.dumps(doc, indent=2), height=300, key=f'code_{st.session_state.current_index}')
|
686 |
+
col_prev, col_next = st.columns(2)
|
687 |
+
with col_prev:
|
688 |
+
if st.button("β¬
οΈ") and st.session_state.current_index > 0:
|
689 |
+
st.session_state.current_index -= 1
|
690 |
+
st.rerun()
|
691 |
+
with col_next:
|
692 |
+
if st.button("β‘οΈ") and st.session_state.current_index < total_docs - 1:
|
693 |
+
st.session_state.current_index += 1
|
694 |
+
st.rerun()
|
695 |
+
col_save, col_delete = st.columns(2)
|
696 |
+
with col_save:
|
697 |
+
if st.button("πΎ Save", key=f'save_{st.session_state.current_index}'):
|
698 |
+
try:
|
699 |
+
updated_doc = json.loads(doc_str)
|
700 |
+
container.upsert_item(body=updated_doc)
|
701 |
+
st.success(f"Saved {updated_doc['id']}")
|
702 |
+
st.rerun()
|
703 |
+
except Exception as e:
|
704 |
+
st.error(f"Save err: {str(e)}")
|
705 |
+
with col_delete:
|
706 |
+
if st.button("ποΈ Delete", key=f'delete_{st.session_state.current_index}'):
|
707 |
+
try:
|
708 |
+
current_doc = json.loads(doc_str)
|
709 |
+
success, message = delete_record(container, current_doc)
|
710 |
+
if success:
|
711 |
+
st.success(message)
|
712 |
+
st.rerun()
|
713 |
+
else:
|
714 |
+
st.error(message)
|
715 |
+
except Exception as e:
|
716 |
+
st.error(f"Delete err: {str(e)}")
|
717 |
+
if "delete_log" in st.session_state and st.session_state.delete_log:
|
718 |
+
st.subheader("Delete Log")
|
719 |
+
for log_entry in st.session_state.delete_log[-5:]:
|
720 |
+
st.write(log_entry)
|
721 |
+
elif selected_view == 'Run AI':
|
722 |
+
st.markdown("#### π€ Run AI (stub)")
|
723 |
+
st.info("AI functionality not implemented.")
|
724 |
+
elif selected_view == 'Clone':
|
725 |
+
st.markdown("#### π Clone")
|
726 |
+
if documents:
|
727 |
+
doc = documents[st.session_state.current_index]
|
728 |
+
st.markdown(f"Original ID: {doc.get('id', '')}")
|
729 |
+
new_id = st.text_input("New ID", value=generate_unique_id(), key='new_clone_id')
|
730 |
+
new_name = st.text_input("New Name", value=f"Clone_{new_id[:8]}", key='new_clone_name')
|
731 |
+
new_doc = {'id': new_id, 'name': new_name, **{k: v for k, v in doc.items() if k not in ['id', 'name', '_rid', '_self', '_etag', '_attachments', '_ts']}}
|
732 |
+
doc_str = st.text_area("Edit JSON", value=json.dumps(new_doc, indent=2), height=300, key='clone_preview')
|
733 |
+
col1, col2 = st.columns(2)
|
734 |
+
with col1:
|
735 |
+
if st.button("οΏ½οΏ½οΏ½ Regenerate"):
|
736 |
+
new_id = generate_unique_id()
|
737 |
+
st.session_state.new_clone_id = new_id
|
738 |
+
st.rerun()
|
739 |
+
with col2:
|
740 |
+
if st.button("πΎ Save Clone"):
|
741 |
+
try:
|
742 |
+
final_doc = json.loads(doc_str)
|
743 |
+
for field in ['_rid', '_self', '_etag', '_attachments', '_ts']:
|
744 |
+
final_doc.pop(field, None)
|
745 |
+
container.create_item(body=final_doc)
|
746 |
+
st.success(f"Cloned {final_doc['id']}")
|
747 |
+
st.rerun()
|
748 |
+
except Exception as e:
|
749 |
+
st.error(f"Clone err: {str(e)}")
|
750 |
+
col_prev, col_next = st.columns(2)
|
751 |
+
with col_prev:
|
752 |
+
if st.button("β¬
οΈ") and st.session_state.current_index > 0:
|
753 |
+
st.session_state.current_index -= 1
|
754 |
+
st.rerun()
|
755 |
+
with col_next:
|
756 |
+
if st.button("β‘οΈ") and st.session_state.current_index < total_docs - 1:
|
757 |
+
st.session_state.current_index += 1
|
758 |
+
st.rerun()
|
759 |
+
elif selected_view == 'New':
|
760 |
+
st.markdown("#### β New Doc")
|
761 |
+
if st.button("π€ Auto-Gen"):
|
762 |
+
auto_doc = {
|
763 |
+
"id": generate_unique_id(),
|
764 |
+
"name": f"Auto {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
|
765 |
+
"content": "Auto-generated record.",
|
766 |
+
"timestamp": datetime.now().isoformat()
|
767 |
+
}
|
768 |
+
success, message = insert_record(container, auto_doc)
|
769 |
+
if success:
|
770 |
+
st.success(message)
|
771 |
+
st.rerun()
|
772 |
+
else:
|
773 |
+
st.error(message)
|
774 |
+
else:
|
775 |
+
new_id = st.text_input("ID", value=generate_unique_id(), key='new_id')
|
776 |
+
default_doc = {
|
777 |
+
"id": new_id,
|
778 |
+
"name": "New Doc",
|
779 |
+
"content": "",
|
780 |
+
"timestamp": datetime.now().isoformat()
|
781 |
+
}
|
782 |
+
new_doc_str = st.text_area("JSON", value=json.dumps(default_doc, indent=2), height=300)
|
783 |
+
if st.button("β Create"):
|
784 |
+
try:
|
785 |
+
cleaned = preprocess_text(new_doc_str)
|
786 |
+
new_doc = json.loads(cleaned)
|
787 |
+
new_doc['id'] = new_id
|
788 |
+
success, message = insert_record(container, new_doc)
|
789 |
+
if success:
|
790 |
+
st.success(f"Created {new_doc['id']}")
|
791 |
+
st.rerun()
|
792 |
+
else:
|
793 |
+
st.error(message)
|
794 |
+
except Exception as e:
|
795 |
+
st.error(f"Create err: {str(e)}")
|
796 |
+
st.subheader(f"π {st.session_state.selected_container}")
|
797 |
+
if documents_to_display:
|
798 |
+
df = pd.DataFrame(documents_to_display)
|
799 |
+
st.dataframe(df)
|
800 |
+
else:
|
801 |
+
st.info("No docs.")
|
802 |
+
|
803 |
+
# GitHub Ops section
|
804 |
+
st.subheader("π GitHub Ops")
|
805 |
+
github_token = os.environ.get("GITHUB")
|
806 |
+
source_repo = st.text_input("Source Repo URL", value="https://github.com/AaronCWacker/AIExamples-8-24-Streamlit")
|
807 |
+
new_repo_name = st.text_input("New Repo Name", value=f"Clone-{datetime.now().strftime('%Y%m%d_%H%M%S')}")
|
808 |
+
col_g1, col_g2 = st.columns(2)
|
809 |
+
with col_g1:
|
810 |
+
if st.button("π₯ Clone Repo"):
|
811 |
+
if github_token and source_repo:
|
812 |
+
try:
|
813 |
+
local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
|
814 |
+
download_github_repo(source_repo, local_path)
|
815 |
+
zip_filename = f"{new_repo_name}.zip"
|
816 |
+
create_zip_file(local_path, zip_filename[:-4])
|
817 |
+
st.markdown(get_download_link(zip_filename), unsafe_allow_html=True)
|
818 |
+
st.success("Cloned! π")
|
819 |
+
except Exception as e:
|
820 |
+
st.error(f"Clone err: {str(e)}")
|
821 |
+
finally:
|
822 |
+
if os.path.exists(local_path):
|
823 |
+
shutil.rmtree(local_path)
|
824 |
+
if os.path.exists(zip_filename):
|
825 |
+
os.remove(zip_filename)
|
826 |
+
else:
|
827 |
+
st.error("Missing token or URL πβ")
|
828 |
+
with col_g2:
|
829 |
+
if st.button("π€ Push Repo"):
|
830 |
+
if github_token and source_repo:
|
831 |
+
try:
|
832 |
+
g = Github(github_token)
|
833 |
+
new_repo = create_repo(g, new_repo_name)
|
834 |
+
local_path = f"./temp_repo_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
|
835 |
+
download_github_repo(source_repo, local_path)
|
836 |
+
push_to_github(local_path, new_repo, github_token)
|
837 |
+
st.success(f"Pushed to {new_repo.html_url} π")
|
838 |
+
except Exception as e:
|
839 |
+
st.error(f"Push err: {str(e)}")
|
840 |
+
finally:
|
841 |
+
if os.path.exists(local_path):
|
842 |
+
shutil.rmtree(local_path)
|
843 |
+
else:
|
844 |
+
st.error("Missing token or URL πβ")
|
845 |
+
update_file_management_section()
|
846 |
+
except exceptions.CosmosHttpResponseError as e:
|
847 |
+
st.error(f"Cosmos error: {str(e)} π¨")
|
848 |
+
except Exception as e:
|
849 |
+
st.error(f"Error: {str(e)} π±")
|
850 |
+
if st.session_state.logged_in and st.sidebar.button("πͺ Logout"):
|
851 |
+
st.markdown("#### πͺ Logout")
|
852 |
+
st.session_state.logged_in = False
|
853 |
+
st.session_state.selected_records = []
|
854 |
+
st.session_state.client = None
|
855 |
+
st.session_state.selected_database = None
|
856 |
+
st.session_state.selected_container = None
|
857 |
+
st.session_state.selected_document_id = None
|
858 |
+
st.session_state.current_index = 0
|
859 |
+
st.rerun()
|
860 |
|
861 |
if __name__ == "__main__":
|
862 |
+
main()
|