File size: 56,029 Bytes
7236ce8 3d01981 bdd313e b0e4549 3d01981 3a5391d 3d01981 7236ce8 3a5391d 7236ce8 3a5391d 7236ce8 3d01981 7236ce8 3a5391d 7236ce8 3d01981 7236ce8 3a5391d bdd313e 7236ce8 562ef4f 7236ce8 3a5391d 3d01981 7236ce8 3a5391d 7236ce8 3d01981 7236ce8 3d01981 7236ce8 3d01981 7236ce8 3d01981 6c9f5a9 3d01981 7236ce8 3a5391d 3d01981 b0e4549 bdd313e 3d01981 3a5391d 3d01981 562ef4f 3d01981 3a5391d 3d01981 7236ce8 3a5391d 7236ce8 3d01981 7236ce8 3d01981 7236ce8 3a5391d 3d01981 3a5391d 3d01981 6c9f5a9 3d01981 3a5391d 562ef4f 3a5391d 562ef4f 3a5391d 562ef4f 3a5391d 562ef4f 3a5391d 562ef4f 3a5391d b0e4549 562ef4f b0e4549 562ef4f 3a5391d 562ef4f b0e4549 562ef4f b0e4549 562ef4f b0e4549 3a5391d b0e4549 3a5391d 6c9f5a9 562ef4f 6c9f5a9 b0e4549 3a5391d b0e4549 562ef4f b0e4549 3a5391d ae88433 562ef4f 3a5391d 562ef4f 3d01981 bdd313e 562ef4f 60430b4 3a5391d 3d01981 bdd313e 3d01981 bdd313e 3a5391d 60430b4 bdd313e 3a5391d bdd313e 3a5391d ae88433 562ef4f ae88433 562ef4f 3a5391d 60430b4 9d1d48c 562ef4f 9d1d48c 562ef4f ae88433 562ef4f ae88433 562ef4f ae88433 9d1d48c 60430b4 bdd313e 3a5391d 562ef4f 3d01981 3a5391d 3d01981 3a5391d 3d01981 562ef4f 3a5391d 562ef4f 3d01981 bdd313e 3d01981 bdd313e b0e4549 bdd313e 3d01981 3a5391d 562ef4f 3d01981 562ef4f 3a5391d 562ef4f 3d01981 7236ce8 3d01981 3a5391d 3d01981 562ef4f 3a5391d 562ef4f 3d01981 7236ce8 3a5391d 3d01981 562ef4f 3a5391d 562ef4f 3d01981 3a5391d 3d01981 562ef4f 3a5391d 562ef4f 3d01981 7236ce8 3d01981 3a5391d 562ef4f 3d01981 562ef4f 3a5391d 562ef4f 3d01981 7236ce8 3d01981 3a5391d 3d01981 3a5391d 562ef4f 3d01981 562ef4f 3a5391d 562ef4f 3d01981 7236ce8 3d01981 7236ce8 3d01981 3a5391d 3d01981 562ef4f 3a5391d 562ef4f 3d01981 7236ce8 3d01981 3a5391d 3d01981 562ef4f 3a5391d 562ef4f 3d01981 562ef4f 3d01981 b198154 562ef4f 3d01981 b198154 3a5391d 0a38743 562ef4f 3a5391d 562ef4f 3d01981 562ef4f 60430b4 562ef4f 3a5391d 3d01981 562ef4f 3a5391d 562ef4f 3d01981 ae88433 562ef4f 9d1d48c ae88433 3a5391d ae88433 562ef4f 3a5391d 562ef4f ae88433 562ef4f ae88433 3d01981 3a5391d b0e4549 562ef4f 3a5391d 562ef4f b0e4549 ae88433 562ef4f b0e4549 562ef4f b0e4549 ae88433 562ef4f b0e4549 3a5391d 9d1d48c 562ef4f 3a5391d 562ef4f b198154 3a5391d 9d1d48c 562ef4f 3a5391d 562ef4f 3d01981 562ef4f 26b513b b198154 3a5391d 7236ce8 562ef4f 3a5391d 562ef4f 3d01981 7236ce8 3d01981 7236ce8 3d01981 7236ce8 3d01981 7236ce8 3d01981 7236ce8 3d01981 7236ce8 3a5391d 7236ce8 562ef4f 3a5391d 562ef4f 3d01981 7236ce8 3d01981 7236ce8 3d01981 7236ce8 3a5391d 7236ce8 562ef4f 3a5391d 562ef4f 3d01981 7236ce8 3d01981 7236ce8 3a5391d 3d01981 562ef4f 3a5391d 562ef4f 3d01981 bdd313e 3d01981 bdd313e 3d01981 bdd313e 562ef4f 9d1d48c 3d01981 3a5391d 3d01981 3a5391d bdd313e 562ef4f 3a5391d 562ef4f bdd313e b0e4549 9d1d48c b0e4549 9d1d48c 3d01981 3a5391d 0a38743 562ef4f 3a5391d 562ef4f 0a38743 9d1d48c 0a38743 9d1d48c 0a38743 562ef4f 9d1d48c 0a38743 9d1d48c 0a38743 3a5391d 3d01981 562ef4f 3a5391d 562ef4f 3d01981 3a5391d 3d01981 3a5391d 9d1d48c 3a5391d b0e4549 3a5391d 9d1d48c 3a5391d 9d1d48c 7236ce8 3a5391d 9d1d48c 7236ce8 3a5391d 562ef4f 3a5391d 562ef4f 3a5391d 564fd41 7236ce8 562ef4f 3a5391d 562ef4f 3d01981 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 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 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 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 364 365 366 367 368 369 370 371 372 373 374 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 431 432 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 467 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 546 547 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 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 |
import streamlit as st
import asyncio
import websockets
import uuid
import argparse
from datetime import datetime
import os
import random
import time
import hashlib
from PIL import Image
import glob
import base64
import io
import streamlit.components.v1 as components
import edge_tts
import nest_asyncio
import re
from streamlit_paste_button import paste_image_button
import pytz
import shutil
from urllib.parse import urlencode
from PyPDF2 import PdfReader
import json
# Patch for nested async - sneaky fix, a loopโs heroic mix! ๐โจ
nest_asyncio.apply()
# Static config - constants rule, a cosmic tool, our sagaโs jewel! ๐๐
icons = '๐ค๐ง ๐ฌ๐'
START_ROOM = "Sector ๐"
# Page setup - dressing up with flair, a UI so rare, in Streamlitโs glare! ๐ผ๏ธ๐
st.set_page_config(
page_title="๐ค๐ง MMO Chat Brain๐๐ฌ",
page_icon=icons,
layout="wide",
initial_sidebar_state="auto"
)
# Funky usernames with voices - a cosmic cast, shared memoryโs blast! ๐๐ญ
FUN_USERNAMES = {
"CosmicJester ๐": "en-US-AriaNeural",
"PixelPanda ๐ผ": "en-US-JennyNeural",
"QuantumQuack ๐ฆ": "en-GB-SoniaNeural",
"StellarSquirrel ๐ฟ๏ธ": "en-AU-NatashaNeural",
"GizmoGuru โ๏ธ": "en-CA-ClaraNeural",
"NebulaNinja ๐ ": "en-US-GuyNeural",
"ByteBuster ๐พ": "en-GB-RyanNeural",
"GalacticGopher ๐": "en-AU-WilliamNeural",
"RocketRaccoon ๐": "en-CA-LiamNeural",
"EchoElf ๐ง": "en-US-AnaNeural",
"PhantomFox ๐ฆ": "en-US-BrandonNeural",
"WittyWizard ๐ง": "en-GB-ThomasNeural",
"LunarLlama ๐": "en-AU-FreyaNeural",
"SolarSloth โ๏ธ": "en-CA-LindaNeural",
"AstroAlpaca ๐ฆ": "en-US-ChristopherNeural",
"CyberCoyote ๐บ": "en-GB-ElliotNeural",
"MysticMoose ๐ฆ": "en-AU-JamesNeural",
"GlitchGnome ๐ง": "en-CA-EthanNeural",
"VortexViper ๐": "en-US-AmberNeural",
"ChronoChimp ๐": "en-GB-LibbyNeural"
}
# Top-level files and directories - the treasure trove, shared memoryโs grove! ๐บ๏ธ๐
CHAT_FILE = "global_chat.md"
QUOTE_VOTES_FILE = "quote_votes.md"
MEDIA_VOTES_FILE = "media_votes.md"
HISTORY_FILE = "chat_history.md"
STATE_FILE = "user_state.txt"
AUDIO_DIR = "audio_logs"
MEDIA_DIR = "media_files"
os.makedirs(AUDIO_DIR, exist_ok=True)
os.makedirs(MEDIA_DIR, exist_ok=True)
# Fancy digits - numbers dance, in shared cache, a numeric trance! ๐ข๐
UNICODE_DIGITS = {i: f"{i}\uFE0Fโฃ" for i in range(10)}
# Massive font collection - typographyโs spree, in shared cache, a scribeโs decree! ๐๏ธ๐จ
UNICODE_FONTS = [
("Normal", lambda x: x),
("Bold", lambda x: "".join(chr(ord(c) + 0x1D400 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D41A - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Italic", lambda x: "".join(chr(ord(c) + 0x1D434 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D44E - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Bold Italic", lambda x: "".join(chr(ord(c) + 0x1D468 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D482 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Script", lambda x: "".join(chr(ord(c) + 0x1D49C - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D4B6 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Bold Script", lambda x: "".join(chr(ord(c) + 0x1D4D0 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D4EA - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Fraktur", lambda x: "".join(chr(ord(c) + 0x1D504 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D51E - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Bold Fraktur", lambda x: "".join(chr(ord(c) + 0x1D56C - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D586 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Double Struck", lambda x: "".join(chr(ord(c) + 0x1D538 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D552 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Sans Serif", lambda x: "".join(chr(ord(c) + 0x1D5A0 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D5BA - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Sans Serif Bold", lambda x: "".join(chr(ord(c) + 0x1D5D4 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D5EE - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Sans Serif Italic", lambda x: "".join(chr(ord(c) + 0x1D608 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D622 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Sans Serif Bold Italic", lambda x: "".join(chr(ord(c) + 0x1D63C - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D656 - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Monospace", lambda x: "".join(chr(ord(c) + 0x1D670 - 0x41) if 'A' <= c <= 'Z' else chr(ord(c) + 0x1D68A - 0x61) if 'a' <= c <= 'z' else c for c in x)),
("Circled", lambda x: "".join(chr(ord(c) - 0x41 + 0x24B6) if 'A' <= c <= 'Z' else chr(ord(c) - 0x61 + 0x24D0) if 'a' <= c <= 'z' else c for c in x)),
("Squared", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F130) if 'A' <= c <= 'Z' else c for c in x)),
("Negative Circled", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F150) if 'A' <= c <= 'Z' else c for c in x)),
("Negative Squared", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F170) if 'A' <= c <= 'Z' else c for c in x)),
("Regional Indicator", lambda x: "".join(chr(ord(c) - 0x41 + 0x1F1E6) if 'A' <= c <= 'Z' else c for c in x)),
]
# Global state - keeping tabs, a shared sagaโs grab! ๐๐ โ epic memoryโs lab!
if 'server_running' not in st.session_state:
st.session_state.server_running = False
if 'server_task' not in st.session_state:
st.session_state.server_task = None
if 'active_connections' not in st.session_state:
st.session_state.active_connections = {}
if 'media_notifications' not in st.session_state:
st.session_state.media_notifications = []
if 'last_chat_update' not in st.session_state:
st.session_state.last_chat_update = 0
if 'displayed_chat_lines' not in st.session_state:
st.session_state.displayed_chat_lines = []
if 'message_text' not in st.session_state:
st.session_state.message_text = ""
if 'audio_cache' not in st.session_state:
st.session_state.audio_cache = {}
if 'pasted_image_data' not in st.session_state:
st.session_state.pasted_image_data = None
if 'quote_line' not in st.session_state:
st.session_state.quote_line = None
if 'refresh_rate' not in st.session_state:
st.session_state.refresh_rate = 5
if 'base64_cache' not in st.session_state:
st.session_state.base64_cache = {}
if 'image_hashes' not in st.session_state:
st.session_state.image_hashes = set()
if 'gallery_columns' not in st.session_state:
st.session_state.gallery_columns = 1
if 'user_id' not in st.session_state:
st.session_state.user_id = None
if 'user_hash' not in st.session_state:
st.session_state.user_hash = None
# Timestamp wizardry - clock ticks with flair, a temporal affair, in shared air! โฐ๐ฉ
def format_timestamp_prefix(username):
central = pytz.timezone('US/Central')
now = datetime.now(central)
return f"{username}-{now.strftime('%I-%M-%p-%m-%d-%Y')}-{st.session_state.user_id}"
# Compute image hash - a cryptographic clash, securing our flash, in shared dash! ๐ก๏ธ๐
def compute_image_hash(image_data):
if isinstance(image_data, Image.Image):
img_byte_arr = io.BytesIO()
image_data.save(img_byte_arr, format='PNG')
img_bytes = img_byte_arr.getvalue()
else:
img_bytes = image_data
return hashlib.md5(img_bytes).hexdigest()[:8]
# Node naming - christening the beast, a heroic feast, in shared yeast! ๐๐ผ
def get_node_name():
parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
parser.add_argument('--node-name', type=str, default=None)
parser.add_argument('--port', type=int, default=8501)
args = parser.parse_args()
username = st.session_state.get('username', 'System ๐')
log_action(username, "๐๐ผ - Node naming - christening the beast!")
return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port
# Action logger - spying on deeds, a stealthy steed, in shared need! ๐ต๏ธ๐
def log_action(username, action):
if 'action_log' not in st.session_state:
st.session_state.action_log = {}
user_log = st.session_state.action_log.setdefault(username, {})
current_time = time.time()
user_log = {k: v for k, v in user_log.items() if current_time - v < 10}
st.session_state.action_log[username] = user_log
if action not in user_log:
central = pytz.timezone('US/Central')
with open(HISTORY_FILE, 'a') as f:
f.write(f"[{datetime.now(central).strftime('%Y-%m-%d %H:%M:%S')}] {username}: {action}\n")
user_log[action] = current_time
# Clean text - strip the fancy fluff, a scribeโs tough bluff, in shared puff! ๐งน๐
def clean_text_for_tts(text):
cleaned = re.sub(r'[#*!\[\]]+', '', text)
cleaned = ' '.join(cleaned.split())
return cleaned if cleaned else "No text to speak" # Default if empty
# Shared Memory Cache - the epic vault, a shared memory assault, in Streamlitโs fault! ๐ณ๏ธ๐พ
@st.cache_resource
def get_shared_memory():
"""
Oh, the cache, a grand, shared hall, where data dances, never to fall!
Thread-safe and global, it holds our lore, across users and sessions, forevermore! ๐๐ง
"""
class SharedMemory:
def __init__(self):
self.chat_history = [] # Condensed dialogs, epic tales condensed!
self.media_files = [] # Media treasures, shared with flair and bends!
self.cache_time = datetime.now() # Timestamp of glory, a heroโs blend!
def update_chat(self, entry):
"""Add a chat entry, a rhyme in the stream, keeping our saga supreme, in shared dream! ๐ฌ๐ถ"""
self.chat_history.append(entry)
if len(self.chat_history) > 100: # Limit to keep it tight, a knightโs fight!
self.chat_history.pop(0)
def update_media(self, media_path):
"""Store media files, a visual dream, in our shared cache, a radiant beam, in shared gleam! ๐ผ๏ธ๐"""
self.media_files.append(media_path)
if len(self.media_files) > 50: # Cap the hoard, lest it grow too wide!
self.media_files.pop(0)
def get_condensed_dialogs(self):
"""Condense the chatter, a poetic pact, short and sweet, our story intact, in shared act! ๐ฃ๏ธโจ"""
return "\n".join(f"- {entry.split(': ')[1][:50]}" for entry in self.chat_history[-10:])
def clear(self):
"""Clear the cache, a dramatic purge, resetting our tale, a new surge, in shared urge! ๐๐ฅ"""
self.chat_history.clear()
self.media_files.clear()
self.cache_time = datetime.now()
return SharedMemory()
# Audio Processor Class - voices echo, a sonic hero, in shared zero! ๐ถ๐
class AudioProcessor:
def __init__(self):
self.cache_dir = AUDIO_DIR
os.makedirs(self.cache_dir, exist_ok=True)
self.metadata = self._load_metadata()
def _load_metadata(self):
metadata_file = os.path.join(self.cache_dir, "metadata.json")
return json.load(open(metadata_file)) if os.path.exists(metadata_file) else {}
def _save_metadata(self):
metadata_file = os.path.join(self.cache_dir, "metadata.json")
with open(metadata_file, 'w') as f:
json.dump(self.metadata, f)
async def create_audio(self, text, voice='en-US-AriaNeural', filename=None):
"""
Create audio, a voice that roars, in our shared cache, through cosmic doors, in shared shores! ๐ค๐
"""
cache_key = hashlib.md5(f"{text}:{voice}".encode()).hexdigest()
timestamp = format_timestamp_prefix(st.session_state.username)
filename = filename or os.path.join(self.cache_dir, f"audio_{timestamp}_{random.randint(1000, 9999)}.mp3")
if cache_key in self.metadata and os.path.exists(filename):
return filename
# Clean text for speech, a bardโs clean sweep, in shared deep!
text = text.replace("\n", " ").replace("</s>", " ").strip()
if not text:
return None
# Generate audio, a sonic leap, with edge_tts, our voices deep, in shared keep!
try:
communicate = edge_tts.Communicate(text, voice)
await communicate.save(filename)
if not os.path.exists(filename):
raise edge_tts.exceptions.NoAudioReceived("No audio file created")
except edge_tts.exceptions.NoAudioReceived as e:
log_action("System ๐", f"TTS failed for text '{text}' with voice '{voice}': {str(e)}")
return None
# Update metadata, our epic creed, in shared memory, a heroic deed, in shared need!
self.metadata[cache_key] = {
'timestamp': datetime.now().isoformat(),
'text_length': len(text),
'voice': voice
}
self._save_metadata()
return filename
# Chat saver - words locked tight, in shared memoryโs light, a shared fight! ๐ฌ๐
async def save_chat_entry(username, message, is_markdown=False, quote_line=None, media_file=None, skip_audio=False):
"""
Save chats with flair, in shared cache we dare, a rhyming affair, in shared air! โจ๐
"""
central = pytz.timezone('US/Central')
timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
user_history_file = f"{username}_history.md"
voice = st.session_state.voice if username == st.session_state.username else FUN_USERNAMES.get(username, "en-US-AriaNeural")
indent = " " if quote_line else "" # Nesting for replies, a poetic spree!
# Prepare entry, a verse so bright, in shared memoryโs sight, a shared delight!
if is_markdown:
entry = f"{indent}[{timestamp}] {username}:\n{indent}```markdown\n{indent}{message}\n{indent}```"
else:
entry = f"{indent}[{timestamp}] {username}: {message}"
if quote_line:
entry = f"{indent}> {quote_line}\n{entry}"
# Save to global chat file, a shared epic tale, never frail, in shared gale!
with open(CHAT_FILE, 'a') as f:
f.write(f"{entry}\n")
# Save to user-specific history, a personal rhyme, in shared time, a shared chime!
if not os.path.exists(user_history_file):
with open(user_history_file, 'w') as f:
f.write(f"# Chat History for {username} (Voice: {voice})\n\n")
with open(user_history_file, 'a') as f:
f.write(f"{entry}\n")
# Generate audio, unless we skip, in shared cache, a sonic grip, in shared rip!
audio_filename = None # Initialize, lest our tale derail, in shared veil!
if not skip_audio and message.strip():
cleaned_message = clean_text_for_tts(message)
audio_processor = AudioProcessor()
audio_filename = await audio_processor.create_audio(cleaned_message, voice)
if audio_filename:
with open(HISTORY_FILE, 'a') as f:
f.write(f"[{timestamp}] {username} ({voice}): Audio generated - {audio_filename}\n")
with open(user_history_file, 'a') as f:
f.write(f"{indent}[{timestamp}] Audio: {audio_filename}\n")
with open(CHAT_FILE, 'a') as f:
f.write(f"{indent}[{timestamp}] Audio: {audio_filename}\n")
# Handle media files, a visual quest, in shared memory, our treasure chest, in shared zest!
if media_file:
if isinstance(media_file, Image.Image):
timestamp_prefix = format_timestamp_prefix(username)
media_filename = f"{username}-{timestamp_prefix.split('-')[-1]}.{media_file.format.lower()}"
media_path = os.path.join(MEDIA_DIR, media_filename)
img_byte_arr = io.BytesIO()
media_file.save(img_byte_arr, format=media_file.format)
await asyncio.to_thread(lambda: open(media_path, 'wb').write(img_byte_arr.getvalue()))
media_file = media_filename
elif media_file.name in ['png', 'jpg', 'mp4', 'mp3', 'wav']:
timestamp_prefix = format_timestamp_prefix(username)
media_filename = f"{username}-{timestamp_prefix.split('-')[-1]}.{media_file.name.split('.')[-1]}"
media_path = os.path.join(MEDIA_DIR, media_filename)
await asyncio.to_thread(lambda: open(media_path, 'wb').write(media_file.getbuffer()))
media_file = media_filename
elif media_file.name == 'pdf':
timestamp_prefix = format_timestamp_prefix(username)
file_hash = hashlib.md5(media_file.getbuffer()).hexdigest()[:8]
media_filename = f"{username}-{timestamp_prefix.split('-')[-1]}-{file_hash}.pdf"
media_path = os.path.join(MEDIA_DIR, media_filename)
await asyncio.to_thread(lambda: open(media_path, 'wb').write(media_file.getbuffer()))
media_file = media_filename
with open(CHAT_FILE, 'a') as f:
f.write(f"{indent}[{timestamp}] Media: \n")
with open(user_history_file, 'a') as f:
f.write(f"{indent}[{timestamp}] Media: \n")
# Update shared memory, our epic lore, in cache forevermore, in shared core!
shared_memory = get_shared_memory()
shared_memory.update_chat(entry)
if media_file:
shared_memory.update_media(os.path.join(MEDIA_DIR, media_file))
await broadcast_message(f"{username}|{message}", "chat")
st.session_state.last_chat_update = time.time()
return audio_filename # Return, even if silent, our taleโs delight, in shared flight!
# Save chat history with image or PDF - a scribeโs historic flight, in shared night! ๐๐
async def save_chat_history_with_image(username, image_path):
"""
Save history, a scribeโs grand sight, in shared memory, pure and bright, in shared light! โจ๐
"""
central = pytz.timezone('US/Central')
timestamp = datetime.now(central).strftime("%Y-%m-%d_%H-%M-%S")
user_history_file = f"{username}_history.md"
chat_content = await load_chat()
voice = st.session_state.voice if username == st.session_state.username else FUN_USERNAMES.get(username, "en-US-AriaNeural")
if not os.path.exists(user_history_file):
with open(user_history_file, 'w') as f:
f.write(f"# Chat History for {username} (Voice: {voice})\n\n")
with open(user_history_file, 'a') as f:
f.write(f"[{timestamp}] {username} (Voice: {voice}) Shared Media: {os.path.basename(image_path)}\n")
f.write(f"```markdown\n{chat_content}\n```\n")
# Chat loader - history unleashed, a shared epic feast, in shared beast! ๐๐
@st.cache_resource
async def load_chat():
"""
Load chats, a shared memory spree, from cache with glee, our history free, in shared sea! ๐๐ฌ
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐๐ - Chat loader - history unleashed!")
if not os.path.exists(CHAT_FILE):
await asyncio.to_thread(lambda: open(CHAT_FILE, 'a').write(f"# {START_ROOM} Chat\n\nWelcome to the cosmic hub - start chatting! ๐ค\n"))
with open(CHAT_FILE, 'r') as f:
content = await asyncio.to_thread(f.read)
return content
# User lister - whoโs in the gang, a shared memory bang, in shared rang! ๐ฅ๐
async def get_user_list(chat_content):
"""
List users, a shared rosterโs rhyme, in cache divine, through space and time, in shared chime! ๐๐ญ
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐ฅ๐ - User lister - whoโs in the gang!")
users = set()
for line in chat_content.split('\n'):
if line.strip() and ': ' in line:
user = line.split(': ')[1].split(' ')[0]
users.add(user)
return sorted(list(users))
# Join checker - been here before, in shared cache, a lore galore, in shared shore! ๐ช๐
async def has_joined_before(client_id, chat_content):
"""
Check joins, a shared memory chore, in cache secure, forevermore, in shared lore! ๐๐
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐ช๐ - Join checker - been here before?")
return any(f"Client-{client_id}" in line for line in chat_content.split('\n'))
# Suggestion maker - old quips resurface, in shared cache, a verse so fierce, in shared pierce! ๐ก๐
async def get_message_suggestions(chat_content, prefix):
"""
Suggest quips, a shared memory jest, in cache we nest, our humor blessed, in shared zest! ๐๐
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐ก๐ - Suggestion maker - old quips resurface!")
lines = chat_content.split('\n')
messages = [line.split(': ', 1)[1] for line in lines if ': ' in line and line.strip()]
return [msg for msg in messages if msg.lower().startswith(prefix.lower())][:5]
# Vote saver - cheers recorded, in shared cache, our cheers restored, in shared chord! ๐๐
@st.cache_resource
async def save_vote(file, item, user_hash, username, comment=""):
"""
Save votes, a shared tallyโs cheer, in cache so clear, our triumph near, in shared spear! ๐๐
"""
await asyncio.to_thread(log_action, username, "๐๐ - Vote saver - cheers recorded!")
central = pytz.timezone('US/Central')
timestamp = datetime.now(central).strftime("%Y-%m-%d %H:%M:%S")
entry = f"[{timestamp}] {user_hash} voted for {item}"
await asyncio.to_thread(lambda: open(file, 'a').write(f"{entry}\n"))
await asyncio.to_thread(lambda: open(HISTORY_FILE, "a").write(f"- {timestamp} - User {user_hash} voted for {item}\n"))
chat_message = f"{username} upvoted: \"{item}\""
if comment:
chat_message += f" - {comment}"
await save_chat_entry(username, chat_message)
return entry # Return for caching, our epic fling, in shared ring!
# Vote counter - tallying the love, in shared cache, a tale above, in shared glove! ๐๐
@st.cache_resource
async def load_votes(file):
"""
Count votes, a shared tallyโs might, in cache so bright, our victoryโs light, in shared fight! ๐๐
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐๐ - Vote counter - tallying the love!")
if not os.path.exists(file):
await asyncio.to_thread(lambda: open(file, 'w').write("# Vote Tally\n\nNo votes yet - get clicking! ๐ฑ๏ธ\n"))
with open(file, 'r') as f:
content = await asyncio.to_thread(f.read)
lines = content.strip().split('\n')[2:]
votes = {}
user_votes = set()
for line in lines:
if line.strip() and 'voted for' in line:
user_hash = line.split('] ')[1].split(' voted for ')[0]
item = line.split('voted for ')[1]
vote_key = f"{user_hash}-{item}"
if vote_key not in user_votes:
votes[item] = votes.get(item, 0) + 1
user_votes.add(vote_key)
return votes
# Hash generator - secret codes ahoy, in shared cache, a cryptic joy, in shared toy! ๐๐ต๏ธ
async def generate_user_hash():
"""
Generate hashes, a shared codeโs chime, in cache sublime, through space and time, in shared rhyme! ๐๐
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐๐ต๏ธ - Hash generator - secret codes ahoy!")
if 'user_hash' not in st.session_state:
st.session_state.user_hash = hashlib.md5(str(random.getrandbits(128)).encode()).hexdigest()[:8]
return st.session_state.user_hash
# Audio maker - voices come alive, in shared cache, a sonic dive, in shared hive! ๐ถ๐
async def async_edge_tts_generate(text, voice, rate=0, pitch=0, file_format="mp3"):
"""
Make audio, a shared voiceโs thrill, in cache we fill, with sonic will, in shared hill! ๐ค๐
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐ถ๐ - Audio maker - voices come alive!")
timestamp = format_timestamp_prefix(username)
filename = os.path.join(AUDIO_DIR, f"audio_{timestamp}_{random.randint(1000, 9999)}.mp3")
communicate = edge_tts.Communicate(text, voice, rate=f"{rate:+d}%", pitch=f"{pitch:+d}Hz")
try:
await communicate.save(filename)
return filename if os.path.exists(filename) else None
except edge_tts.exceptions.NoAudioReceived:
with open(HISTORY_FILE, 'a') as f:
central = pytz.timezone('US/Central')
f.write(f"[{datetime.now(central).strftime('%Y-%m-%d %H:%M:%S')}] {username}: Audio failed - No audio received for '{text}'\n")
return None
# Audio player - tunes blast off, in shared cache, a musical scoff, in shared toff! ๐๐
def play_and_download_audio(file_path):
"""
Play tunes, a shared melodyโs jest, in cache expressed, our audio quest, in shared zest! ๐ต๐
"""
if file_path and os.path.exists(file_path):
st.audio(file_path)
with open(file_path, "rb") as f:
b64 = base64.b64encode(f.read()).decode()
dl_link = f'<a href="data:audio/mpeg;base64,{b64}" download="{os.path.basename(file_path)}">๐ต Download {os.path.basename(file_path)}</a>'
st.markdown(dl_link, unsafe_allow_html=True)
# Image saver - pics preserved, in shared cache, a visual burst, in shared thirst! ๐ธ๐พ
async def save_pasted_image(image, username):
"""
Save images, a shared sightโs cheer, in cache so clear, our vision near, in shared spear! ๐ผ๏ธ๐
"""
await asyncio.to_thread(log_action, username, "๐ธ๐พ - Image saver - pics preserved!")
timestamp = format_timestamp_prefix(username)
media_filename = f"{username}-{timestamp.split('-')[-1]}.png"
media_path = os.path.join(MEDIA_DIR, media_filename)
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format='PNG')
await asyncio.to_thread(lambda: open(media_path, 'wb').write(img_byte_arr.getvalue()))
return media_filename
# Video and Audio savers - media magic, in shared cache, a heroic tragic, in shared magic! ๐ฅ๐ถ
async def save_media(file, username, ext):
"""
Save media, a shared epicโs might, in cache so bright, our treasures ignite, in shared kite! ๐ง๐ฅ
"""
await asyncio.to_thread(log_action, username, f"๐ธ๐พ - Media saver - {ext} preserved!")
timestamp = format_timestamp_prefix(username)
media_filename = f"{username}-{timestamp.split('-')[-1]}.{ext}"
media_path = os.path.join(MEDIA_DIR, media_filename)
await asyncio.to_thread(lambda: open(media_path, 'wb').write(file.getbuffer()))
return media_filename
# PDF saver and audio generator - documents dance, in shared cache, a chance, in shared trance! ๐๐ถ
async def save_pdf_and_generate_audio(pdf_file, username, max_pages=10):
"""
Save PDFs, a shared documentโs glee, in cache we see, our historyโs key, in shared sea! ๐๐
"""
await asyncio.to_thread(log_action, username, "๐๐ถ - PDF saver and audio generator!")
timestamp = format_timestamp_prefix(username)
file_hash = hashlib.md5(pdf_file.getbuffer()).hexdigest()[:8]
pdf_filename = f"{username}-{timestamp.split('-')[-1]}-{file_hash}.pdf"
media_path = os.path.join(MEDIA_DIR, pdf_filename)
with open(media_path, 'wb') as f:
f.write(pdf_file.getbuffer())
reader = PdfReader(media_path)
total_pages = min(len(reader.pages), max_pages)
texts = []
audio_files = []
audio_processor = AudioProcessor()
voice = st.session_state.voice if username == st.session_state.username else FUN_USERNAMES.get(username, "en-US-AriaNeural")
for i in range(total_pages):
text = reader.pages[i].extract_text()
texts.append(text)
audio_filename = f"{username}-{timestamp.split('-')[-1]}-page{i+1}-{file_hash}-voice-{voice}.mp3"
audio_path = os.path.join(AUDIO_DIR, audio_filename)
audio_data = await audio_processor.create_audio(text, voice, audio_path)
if audio_data:
audio_files.append(audio_filename)
return pdf_filename, texts, audio_files
# Video renderer - movies roll, in shared cache, a visual toll, in shared roll! ๐ฅ๐ฌ
def get_video_html(video_path, width="100px"):
"""
Render videos, a shared screenโs thrill, in cache we fill, with cinematic will, in shared hill! ๐บ๐
"""
video_url = f"data:video/mp4;base64,{base64.b64encode(open(os.path.join(MEDIA_DIR, video_path), 'rb').read()).decode()}"
return f'''
<video width="{width}" controls autoplay muted loop>
<source src="{video_url}" type="video/mp4">
Your browser does not support the video tag.
</video>
'''
# Audio renderer - sounds soar, in shared cache, a sonic roar, in shared roar! ๐ถโ๏ธ
async def get_audio_html(audio_path, width="100px"):
"""
Render audio, a shared soundโs cheer, in cache so clear, our music near, in shared spear! ๐ต๐
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐ถโ๏ธ - Audio renderer - sounds soar!")
audio_url = f"data:audio/mpeg;base64,{base64.b64encode(await asyncio.to_thread(open, os.path.join(AUDIO_DIR, audio_path), 'rb').read()).decode()}"
return f'''
<audio controls style="width: {width};">
<source src="{audio_url}" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
'''
# Websocket handler - chat links up, in shared cache, a connectionโs cup, in shared cup! ๐๐
async def websocket_handler(websocket, path):
"""
Handle chats, a shared linkโs might, in cache so bright, our networkโs light, in shared night! ๐๐
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐๐ - Websocket handler - chat links up!")
try:
client_id = str(uuid.uuid4())
room_id = "chat"
st.session_state.active_connections.setdefault(room_id, {})[client_id] = websocket
chat_content = await load_chat()
username = st.session_state.get('username', random.choice(list(FUN_USERNAMES.keys())))
if not await has_joined_before(client_id, chat_content):
await save_chat_entry(f"Client-{client_id}", f"{username} has joined {START_ROOM}!")
async for message in websocket:
parts = message.split('|', 1)
if len(parts) == 2:
username, content = parts
await save_chat_entry(username, content)
except websockets.ConnectionClosed:
pass
finally:
if room_id in st.session_state.active_connections and client_id in st.session_state.active_connections[room_id]:
del st.session_state.active_connections[room_id][client_id]
# Message broadcaster - words fly far, in shared cache, a starry czar, in shared star! ๐ขโ๏ธ
async def broadcast_message(message, room_id):
"""
Broadcast words, a shared echoโs cheer, in cache so clear, our message near, in shared spear! ๐ ๐ก
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐ขโ๏ธ - Message broadcaster - words fly far!")
if room_id in st.session_state.active_connections:
disconnected = []
for client_id, ws in st.session_state.active_connections[room_id].items():
try:
await ws.send(message)
except websockets.ConnectionClosed:
disconnected.append(client_id)
for client_id in disconnected:
del st.session_state.active_connections[room_id][client_id]
# Server starter - web spins up, in shared cache, a digital pup, in shared pup! ๐ฅ๏ธ๐
async def run_websocket_server():
"""
Start server, a shared spinโs delight, in cache so right, our web takes flight, in shared night! ๐๐
"""
username = st.session_state.get('username', 'System ๐')
await asyncio.to_thread(log_action, username, "๐ฅ๏ธ๐ - Server starter - web spins up!")
if not st.session_state.server_running:
server = await websockets.serve(websocket_handler, '0.0.0.0', 8765)
st.session_state.server_running = True
await server.wait_closed()
# Delete all user files - a purge so grand, in shared cache, a clearing band, in shared land! ๐๏ธ๐ฅ
def delete_user_files():
"""
Delete files, a shared purgeโs might, in cache so light, our slate wiped tight, in shared night! ๐งน๐
"""
protected_files = {'app.py', 'requirements.txt', 'README.md', CHAT_FILE, QUOTE_VOTES_FILE, MEDIA_VOTES_FILE, HISTORY_FILE, STATE_FILE, AUDIO_DIR, MEDIA_DIR}
deleted_files = []
for file in os.listdir('.'):
if file not in protected_files and not file.endswith('_history.md'):
try:
os.remove(file)
deleted_files.append(file)
except Exception as e:
st.error(f"Failed to delete {file}: {e}")
for root, dirs, files in os.walk(AUDIO_DIR):
for file in files:
file_path = os.path.join(root, file)
try:
os.remove(file_path)
deleted_files.append(file_path)
except Exception as e:
st.error(f"Failed to delete {file_path}: {e}")
for root, dirs, files in os.walk(MEDIA_DIR):
for file in files:
file_path = os.path.join(root, file)
try:
os.remove(file_path)
deleted_files.append(file_path)
except Exception as e:
st.error(f"Failed to delete {file_path}: {e}")
st.session_state.image_hashes.clear()
st.session_state.audio_cache.clear()
st.session_state.base64_cache.clear()
st.session_state.displayed_chat_lines.clear()
shared_memory = get_shared_memory()
shared_memory.clear() # Clear shared cache on purge, in shared surge!
return deleted_files
# Query parameter checker - parse q with flair, in shared cache, a naming affair, in shared air! ๐ช๐
def check_query_params():
"""
Check queries, a shared nameโs quest, in cache so blessed, our path expressed, in shared zest! ๐๐
"""
query_params = st.query_params if hasattr(st, 'query_params') else st.experimental_get_query_params()
q_value = query_params.get("q", [None])[0]
if q_value and q_value in FUN_USERNAMES:
st.session_state.username = q_value
st.session_state.voice = FUN_USERNAMES[q_value]
return q_value
elif q_value:
st.session_state.user_id = q_value # Use as user_id if not a valid username
return None
# Mermaid graph generator - visualize our tale, in shared cache, a graphic gale, in shared vale! ๐ณ๐
def generate_mermaid_graph(chat_lines):
"""
Generate graphs, a shared visionโs rhyme, in cache sublime, our storyโs chime, in shared time! ๐งฉ๐
"""
mermaid_code = "graph TD\n"
nodes = {}
edges = []
for i, line in enumerate(chat_lines):
if line.strip() and not line.startswith(' '):
timestamp = line.split('] ')[0][1:] if '] ' in line else "Unknown"
content = line.split(': ', 1)[1] if ': ' in line else line
user = content.split(' ')[0]
message = content.split(' ', 1)[1] if ' ' in content else ''
node_id = f"{user}_{i}"
nodes[node_id] = f"{user}: {message[:20]}..." if len(message) > 20 else f"{user}: {message}"
if i + 1 < len(chat_lines) and "Audio:" in chat_lines[i + 1]:
audio_node = f"audio_{i}"
nodes[audio_node] = "๐ต"
edges.append(f"{node_id} --> {audio_node}")
if i + 2 < len(chat_lines) and "Media:" in chat_lines[i + 2]:
media_node = f"media_{i}"
nodes[media_node] = "๐ผ"
edges.append(f"{node_id} --> {media_node}")
if i > 0 and "> " in line:
parent_user = chat_lines[i-1].split(': ')[1].split(' ')[0]
parent_id = f"{parent_user}_{i-1}"
edges.append(f"{parent_id} --> {node_id}")
for node_id, label in nodes.items():
mermaid_code += f" {node_id}[\"{label}\"]\n"
mermaid_code += "\n".join(f" {edge}" for edge in edges)
return mermaid_code
# Main execution - letโs roll, in shared cache, a heroic toll, in shared soul! ๐ฒ๐
def main():
"""
Launch our saga, a shared memoryโs cheer, in Streamlitโs cache, our epic year, in shared spear! ๐โจ
"""
NODE_NAME, port = get_node_name()
# Use asyncio.run to manage the event loop cleanly, avoiding nested awaits! ๐๐
asyncio.run(async_interface())
# Async interface - our epic quest, in shared cache, a tale expressed, in shared zest! ๐ญ๐
async def async_interface():
# Generate user ID and hash, a shared identityโs clash, in shared flash! ๐๐ฎ
if not st.session_state.user_id:
st.session_state.user_id = str(uuid.uuid4())
st.session_state.user_hash = await generate_user_hash()
# Check query params, a shared nameโs quest, in cache expressed, our path impressed, in shared zest! ๐ช๐
q_value = check_query_params()
if not q_value and 'username' not in st.session_state:
chat_content = await load_chat()
available_names = [name for name in FUN_USERNAMES if not any(f"{name} has joined" in line for line in chat_content.split('\n'))]
st.session_state.username = random.choice(available_names) if available_names else random.choice(list(FUN_USERNAMES.keys()))
st.session_state.voice = FUN_USERNAMES[st.session_state.username]
st.markdown(f"**๐๏ธ Voice Selected**: {st.session_state.voice} ๐ฃ๏ธ for {st.session_state.username}")
# Check existing history, a shared memoryโs cheer, in cache so clear, our lore near, in shared spear! ๐๐
user_history_file = f"{st.session_state.username}_history.md"
if os.path.exists(user_history_file):
with open(user_history_file, 'r') as f:
st.session_state.displayed_chat_lines = f.read().split('\n')
user_url = f"/q={st.session_state.username}"
with st.container():
st.markdown(f"<small>Your unique URL path: [{user_url}]({user_url})</small>", unsafe_allow_html=True)
with st.container():
st.markdown(f"#### ๐ค๐ง MMO {st.session_state.username}๐๐ฌ")
st.markdown(f"<small>Welcome to {START_ROOM} - chat, vote, upload, paste images, and enjoy quoting! ๐ User ID: {st.session_state.user_id}</small>", unsafe_allow_html=True)
if not st.session_state.server_task:
st.session_state.server_task = asyncio.create_task(run_websocket_server())
# Unified Chat History at Top - a shared epicโs roar, condensed and stored, in shared cord! ๐ฌ๐
with st.container():
st.markdown(f"##### {START_ROOM} Chat History ๐ฌ")
shared_memory = get_shared_memory()
chat_content = await load_chat()
chat_lines = [line for line in chat_content.split('\n') if line.strip() and not line.startswith('#')]
if chat_lines:
chat_by_minute = {}
for line in reversed(chat_lines):
timestamp = line.split('] ')[0][1:] if '] ' in line else "Unknown"
minute_key = timestamp[:16] # Up to minute
if minute_key not in chat_by_minute:
chat_by_minute[minute_key] = []
chat_by_minute[minute_key].append(line)
markdown_output = ""
for minute, lines in chat_by_minute.items():
minute_output = f"###### {minute[-5:]}\n" # Show only HH:MM
for line in lines:
if ': ' in line and not line.startswith(' '):
user_message = line.split(': ', 1)[1]
user = user_message.split(' ')[0]
msg = user_message.split(' ', 1)[1] if ' ' in user_message else ''
audio_html = ""
media_content = ""
next_lines = chat_lines[chat_lines.index(line)+1:chat_lines.index(line)+3]
for nl in next_lines:
if "Audio:" in nl:
audio_file = nl.split("Audio: ")[-1].strip()
audio_html = play_and_download_audio(audio_file)
elif "Media:" in nl:
media_file = nl.split("Media: ")[-1].strip('![]()')
media_path = os.path.join(MEDIA_DIR, media_file)
if os.path.exists(media_path):
if media_file.endswith(('.png', '.jpg')):
media_content = f"<img src='file://{media_path}' width='100'>"
elif media_file.endswith('.mp4'):
media_content = get_video_html(media_file)
elif media_file.endswith('.mp3'):
media_content = await get_audio_html(media_file)
elif media_file.endswith('.pdf'):
media_content = f"๐ {os.path.basename(media_file)}"
minute_output += f"- ๐ฌ **{user}**: {msg[:50]}... {audio_html} {media_content}\n" # Condensed dialog
markdown_output += minute_output
st.markdown(markdown_output, unsafe_allow_html=True)
shared_memory.update_chat(markdown_output) # Cache condensed dialogs
# Condensed Dialogs Display - a shared tale, concise and hale, in shared vale! ๐ฃ๏ธโจ
st.markdown("###### Condensed Dialogs ๐ฃ๏ธ")
condensed_dialogs = shared_memory.get_condensed_dialogs()
st.markdown(condensed_dialogs)
# Mermaid Graph Visualization - a shared map, our chatโs trap, in shared cap! ๐ณ๐
st.markdown("###### Chat Relationship Tree ๐ณ")
mermaid_code = generate_mermaid_graph(chat_lines)
mermaid_html = f"""
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<div class="mermaid" style="height: 200px; overflow: auto;">{mermaid_code}</div>
<script>mermaid.initialize({{startOnLoad:true}});</script>
"""
components.html(mermaid_html, height=250)
with st.container():
if st.session_state.quote_line:
st.markdown(f"###### Quoting: {st.session_state.quote_line}")
quote_response = st.text_area("Add your response", key="quote_response", value=st.session_state.message_text)
paste_result_quote = paste_image_button("๐ Paste Image or Text with Quote", key="paste_button_quote")
if paste_result_quote.image_data is not None:
if isinstance(paste_result_quote.image_data, str):
st.session_state.message_text = paste_result_quote.image_data
st.text_area("Add your response", key="quote_response", value=st.session_state.message_text)
else:
st.image(paste_result_quote.image_data, caption="Received Image for Quote")
filename = await save_pasted_image(paste_result_quote.image_data, st.session_state.username)
if filename:
st.session_state.pasted_image_data = filename
await save_chat_entry(st.session_state.username, f"Pasted image: {filename}", quote_line=st.session_state.quote_line, media_file=paste_result_quote.image_data)
if st.button("Send Quote ๐", key="send_quote"):
markdown_response = f"### Quote Response\n- **Original**: {st.session_state.quote_line}\n- **{st.session_state.username} Replies**: {quote_response}"
if st.session_state.pasted_image_data:
markdown_response += f"\n- **Image**: "
await save_chat_entry(st.session_state.username, f"Pasted image: {st.session_state.pasted_image_data}", quote_line=st.session_state.quote_line, media_file=st.session_state.pasted_image_data)
st.session_state.pasted_image_data = None
await save_chat_entry(st.session_state.username, markdown_response, is_markdown=True, quote_line=st.session_state.quote_line)
st.session_state.quote_line = None
st.session_state.message_text = ''
st.rerun()
current_selection = st.session_state.username if st.session_state.username in FUN_USERNAMES else ""
new_username = st.selectbox("Change Name and Voice", [""] + list(FUN_USERNAMES.keys()), index=(list(FUN_USERNAMES.keys()).index(current_selection) + 1 if current_selection else 0), format_func=lambda x: f"{x} ({FUN_USERNAMES.get(x, 'No Voice')})" if x else "Select a name")
if new_username and new_username != st.session_state.username:
await save_chat_entry("System ๐", f"{st.session_state.username} changed name to {new_username}")
st.session_state.username = new_username
st.session_state.voice = FUN_USERNAMES[new_username]
st.markdown(f"**๐๏ธ Voice Changed**: {st.session_state.voice} ๐ฃ๏ธ for {st.session_state.username}")
st.rerun()
# Message input with Send button - a shared chatโs might, in shared night! ๐ฌ๐
col_input, col_send = st.columns([5, 1])
with col_input:
message = st.text_input(f"Message as {st.session_state.username} (Voice: {st.session_state.voice})", key="message_input", value=st.session_state.message_text)
with col_send:
if st.button("Send ๐", key="send_button"):
if message.strip() or st.session_state.pasted_image_data:
await save_chat_entry(st.session_state.username, message if message.strip() else "Image shared", is_markdown=True, media_file=st.session_state.pasted_image_data if st.session_state.pasted_image_data else None, skip_audio=not message.strip())
if st.session_state.pasted_image_data:
st.session_state.pasted_image_data = None
st.session_state.message_text = ''
st.rerun()
paste_result_msg = paste_image_button("๐ Paste Image or Text with Message", key="paste_button_msg")
if paste_result_msg.image_data is not None:
if isinstance(paste_result_msg.image_data, str):
st.session_state.message_text = paste_result_msg.image_data
st.text_input(f"Message as {st.session_state.username} (Voice: {st.session_state.voice})", key="message_input_paste", value=st.session_state.message_text)
else:
st.image(paste_result_msg.image_data, caption="Received Image for Quote")
filename = await save_pasted_image(paste_result_msg.image_data, st.session_state.username)
if filename:
await save_chat_entry(st.session_state.username, "Image shared", is_markdown=True, media_file=paste_result_msg.image_data, skip_audio=True)
st.session_state.pasted_image_data = None
st.rerun()
with st.container():
st.markdown("###### Upload Media ๐จ๐ถ๐๐ฅ")
uploaded_file = st.file_uploader("Upload Media", type=['png', 'jpg', 'mp4', 'mp3', 'wav', 'pdf', 'txt', 'md', 'py'])
if uploaded_file:
timestamp = format_timestamp_prefix(st.session_state.username)
username = st.session_state.username
ext = uploaded_file.name.split('.')[-1].lower()
if ext in ['png', 'jpg']:
filename = await save_pasted_image(uploaded_file, username)
elif ext in ['mp4', 'mp3', 'wav']:
filename = await save_media(uploaded_file, username, ext)
elif ext == 'pdf':
pdf_filename, _, _ = await save_pdf_and_generate_audio(uploaded_file, username)
filename = pdf_filename
else:
filename = f"{username}-{timestamp.split('-')[-1]}.{ext}"
media_path = os.path.join(MEDIA_DIR, filename)
await asyncio.to_thread(lambda: open(media_path, 'wb').write(uploaded_file.getbuffer()))
await save_chat_entry(username, f"Uploaded {ext.upper()}: {os.path.basename(filename)}", media_file=uploaded_file, skip_audio=True)
shared_memory = get_shared_memory()
shared_memory.update_media(os.path.join(MEDIA_DIR, filename)) # Cache media
st.success(f"Uploaded {filename}")
# Big Red Delete Button - a purge so grand, clearing our shared land, in shared sand! ๐๏ธ๐ฅ
st.markdown("###### ๐ Danger Zone")
if st.button("Try Not To Delete It All On Your First Day", key="delete_all", help="Deletes all user-added files!", type="primary", use_container_width=True):
deleted_files = delete_user_files()
if deleted_files:
st.markdown("### ๐๏ธ Deleted Files:\n" + "\n".join([f"- `{file}`" for file in deleted_files]))
shared_memory = get_shared_memory()
shared_memory.clear() # Clear shared cache on purge, in shared surge!
else:
st.markdown("### ๐๏ธ Nothing to Delete!")
st.rerun()
st.markdown("###### Refresh โณ")
refresh_rate = st.slider("Refresh Rate", 1, 300, st.session_state.refresh_rate)
st.session_state.refresh_rate = refresh_rate
timer_placeholder = st.empty()
for i in range(st.session_state.refresh_rate, -1, -1):
font_name, font_func = random.choice(UNICODE_FONTS)
countdown_str = "".join(UNICODE_DIGITS[int(d)] for d in str(i)) if i < 10 else font_func(str(i))
timer_placeholder.markdown(f"<small>โณ {font_func('Refresh in:')} {countdown_str}</small>", unsafe_allow_html=True)
await asyncio.sleep(1) # Use asyncio.sleep for async context, in shared nest!
st.rerun()
# Separate Galleries for Own and Shared Files - a shared galleryโs glare, in shared air! ๐ผ๏ธ๐ฅ
with st.container():
all_files = glob.glob(os.path.join(MEDIA_DIR, "*.md")) + glob.glob(os.path.join(MEDIA_DIR, "*.pdf")) + glob.glob(os.path.join(MEDIA_DIR, "*.txt")) + glob.glob(os.path.join(MEDIA_DIR, "*.py")) + glob.glob(os.path.join(MEDIA_DIR, "*.png")) + glob.glob(os.path.join(MEDIA_DIR, "*.jpg")) + glob.glob(os.path.join(MEDIA_DIR, "*.mp3")) + glob.glob(os.path.join(MEDIA_DIR, "*.mp4")) + glob.glob(os.path.join(AUDIO_DIR, "*.mp3"))
shared_memory = get_shared_memory()
own_files = [f for f in all_files if st.session_state.user_id in os.path.basename(f) or st.session_state.username in os.path.basename(f)]
shared_files = [f for f in all_files if f not in own_files and not f in [CHAT_FILE, QUOTE_VOTES_FILE, MEDIA_VOTES_FILE, HISTORY_FILE, STATE_FILE, os.path.join(AUDIO_DIR, "*"), os.path.join(MEDIA_DIR, "*")]]
st.markdown("###### Your Files ๐")
st.markdown("###### Image Gallery ๐ผ")
own_image_files = [f for f in own_files if f.endswith(('.png', '.jpg'))]
image_cols = st.slider("Image Gallery Columns ๐ผ (Own)", min_value=1, max_value=15, value=5)
cols = st.columns(image_cols)
for idx, image_file in enumerate(own_image_files):
with cols[idx % image_cols]:
st.image(image_file, use_container_width=True)
shared_memory.update_media(image_file) # Cache media, in shared sea!
st.markdown("###### Video Gallery ๐ฅ")
own_video_files = [f for f in own_files if f.endswith('.mp4')]
video_cols = st.slider("Video Gallery Columns ๐ฌ (Own)", min_value=1, max_value=5, value=3)
cols = st.columns(video_cols)
for idx, video_file in enumerate(own_video_files):
with cols[idx % video_cols]:
st.markdown(get_video_html(video_file), unsafe_allow_html=True)
shared_memory.update_media(video_file) # Cache media, in shared lea!
st.markdown("###### Audio Gallery ๐ง")
own_audio_files = [f for f in own_files if f.endswith(('.mp3', '.wav')) or f.startswith(os.path.join(AUDIO_DIR, "audio_"))]
audio_cols = st.slider("Audio Gallery Columns ๐ถ (Own)", min_value=1, max_value=15, value=5)
cols = st.columns(audio_cols)
for idx, audio_file in enumerate(own_audio_files):
with cols[idx % audio_cols]:
st.markdown(await get_audio_html(audio_file), unsafe_allow_html=True)
shared_memory.update_media(audio_file) # Cache media, in shared tea!
st.markdown("###### Shared Files ๐ค")
st.markdown("###### Image Gallery ๐ผ")
shared_image_files = [f for f in shared_files if f.endswith(('.png', '.jpg'))]
image_cols = st.slider("Image Gallery Columns ๐ผ (Shared)", min_value=1, max_value=15, value=5)
cols = st.columns(image_cols)
for idx, image_file in enumerate(shared_image_files):
with cols[idx % image_cols]:
st.image(image_file, use_container_width=True)
shared_memory.update_media(image_file) # Cache media, in shared bee!
st.markdown("###### Video Gallery ๐ฅ")
shared_video_files = [f for f in shared_files if f.endswith('.mp4')]
video_cols = st.slider("Video Gallery Columns ๐ฌ (Shared)", min_value=1, max_value=5, value=3)
cols = st.columns(video_cols)
for idx, video_file in enumerate(shared_video_files):
with cols[idx % video_cols]:
st.markdown(get_video_html(video_file), unsafe_allow_html=True)
shared_memory.update_media(video_file) # Cache media, in shared tree!
st.markdown("###### Audio Gallery ๐ง")
shared_audio_files = [f for f in shared_files if f.endswith(('.mp3', '.wav')) or f.startswith(os.path.join(AUDIO_DIR, "audio_"))]
audio_cols = st.slider("Audio Gallery Columns ๐ถ (Shared)", min_value=1, max_value=15, value=5)
cols = st.columns(audio_cols)
for idx, audio_file in enumerate(shared_audio_files):
with cols[idx % audio_cols]:
st.markdown(await get_audio_html(audio_file), unsafe_allow_html=True)
shared_memory.update_media(audio_file) # Cache media, in shared glee!
# Full Log at End with Download - a shared epicโs end, our tale to mend, in shared bend! ๐๐ฅ
with st.container():
st.markdown("###### Full Chat Log ๐")
with open(CHAT_FILE, 'r') as f:
history_content = f.read()
st.markdown(history_content)
st.download_button("Download Chat Log as .md", history_content, file_name=f"chat_{st.session_state.user_id}.md", mime="text/markdown")
# Clear Cache Button - purge the cache, a shared epicโs crash, in shared flash! ๐๏ธ๐
if st.button("Clear Shared Memory Cache", key="clear_cache"):
shared_memory = get_shared_memory()
shared_memory.clear()
st.success("Shared memory cache cleared, a fresh start with a bardโs heart, in shared art! ๐๐ถ")
if __name__ == "__main__":
"""
Launch our saga, a shared memoryโs cheer, in Streamlitโs cache, our epic year, in shared spear! ๐โจ
"""
main() |