awacke1 commited on
Commit
a309cc5
ยท
verified ยท
1 Parent(s): c550791

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1172 -0
app.py ADDED
@@ -0,0 +1,1172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import asyncio
3
+ import websockets
4
+ import uuid
5
+ from datetime import datetime
6
+ import os
7
+ import random
8
+ import time
9
+ import hashlib
10
+ import glob
11
+ import base64
12
+ import io
13
+ import streamlit.components.v1 as components
14
+ import edge_tts
15
+ import nest_asyncio
16
+ import re
17
+ import pytz
18
+ import shutil
19
+ from PyPDF2 import PdfReader
20
+ import threading
21
+ import json
22
+ import zipfile
23
+ from dotenv import load_dotenv
24
+ from streamlit_marquee import streamlit_marquee
25
+ from collections import defaultdict, Counter
26
+ import pandas as pd
27
+ from streamlit_js_eval import streamlit_js_eval
28
+ from PIL import Image
29
+
30
+ # ==============================================================================
31
+ # Configuration & Constants
32
+ # ==============================================================================
33
+
34
+ # Patch asyncio for nesting
35
+ nest_asyncio.apply()
36
+
37
+ # Page Config
38
+ st.set_page_config(
39
+ page_title="๐Ÿค–๐Ÿ—๏ธ Shared World Builder ๐Ÿ†",
40
+ page_icon="๐Ÿ—๏ธ",
41
+ layout="wide",
42
+ initial_sidebar_state="expanded"
43
+ )
44
+
45
+ # General Constants
46
+ icons = '๐Ÿค–๐Ÿ—๏ธ๐Ÿ—ฃ๏ธ๐Ÿ’พ'
47
+ Site_Name = '๐Ÿค–๐Ÿ—๏ธ Shared World Builder ๐Ÿ—ฃ๏ธ'
48
+ START_ROOM = "World Lobby ๐ŸŒ"
49
+ MEDIA_DIR = "."
50
+ STATE_FILE = "user_state.txt"
51
+
52
+ # User/Chat Constants
53
+ FUN_USERNAMES = {
54
+ "BuilderBot ๐Ÿค–": "en-US-AriaNeural", "WorldWeaver ๐Ÿ•ธ๏ธ": "en-US-JennyNeural",
55
+ "Terraformer ๐ŸŒฑ": "en-GB-SoniaNeural", "SkyArchitect โ˜๏ธ": "en-AU-NatashaNeural",
56
+ "PixelPainter ๐ŸŽจ": "en-CA-ClaraNeural", "VoxelVortex ๐ŸŒช๏ธ": "en-US-GuyNeural",
57
+ "CosmicCrafter โœจ": "en-GB-RyanNeural", "GeoGuru ๐Ÿ—บ๏ธ": "en-AU-WilliamNeural",
58
+ "BlockBard ๐Ÿงฑ": "en-CA-LiamNeural", "SoundSculptor ๐Ÿ”Š": "en-US-AnaNeural",
59
+ }
60
+ EDGE_TTS_VOICES = list(set(FUN_USERNAMES.values()))
61
+ CHAT_DIR = "chat_logs"
62
+
63
+ # Audio Constants
64
+ AUDIO_CACHE_DIR = "audio_cache"
65
+ AUDIO_DIR = "audio_logs"
66
+
67
+ # World Builder Constants
68
+ SAVED_WORLDS0 = "saved_worlds"
69
+ HISTORY_LOG_DIR = "history_logs"
70
+ PLOT_WIDTH = 50.0
71
+ PLOT_DEPTH = 50.0
72
+ WORLD_STATE_FILE_MD_PREFIX = "๐ŸŒ_"
73
+
74
+ # File Emojis
75
+ FILE_EMOJIS = {"md": "๐Ÿ“", "mp3": "๐ŸŽต", "png": "๐Ÿ–ผ๏ธ", "mp4": "๐ŸŽฅ", "zip": "๐Ÿ“ฆ", "json": "๐Ÿ“„"}
76
+
77
+ # Mapping Emojis to Primitive Types
78
+ PRIMITIVE_MAP = {
79
+ "๐ŸŒณ": "Tree", "๐Ÿ—ฟ": "Rock", "๐Ÿ›๏ธ": "Simple House", "๐ŸŒฒ": "Pine Tree", "๐Ÿงฑ": "Brick Wall",
80
+ "๐Ÿ”ต": "Sphere", "๐Ÿ“ฆ": "Cube", "๐Ÿงด": "Cylinder", "๐Ÿฆ": "Cone", "๐Ÿฉ": "Torus",
81
+ "๐Ÿ„": "Mushroom", "๐ŸŒต": "Cactus", "๐Ÿ”ฅ": "Campfire", "โญ": "Star", "๐Ÿ’Ž": "Gem",
82
+ "๐Ÿ—ผ": "Tower", "๐Ÿšง": "Barrier", "โ›ฒ": "Fountain", "๐Ÿฎ": "Lantern", "๐Ÿชง": "Sign Post"
83
+ }
84
+
85
+ # Directories
86
+ for d in [CHAT_DIR, AUDIO_DIR, AUDIO_CACHE_DIR, SAVED_WORLDS_DIR, HISTORY_LOG_DIR]:
87
+ os.makedirs(d, exist_ok=True)
88
+
89
+ # Global State & Locks
90
+ world_objects_lock = threading.Lock()
91
+ world_objects = defaultdict(dict)
92
+ connected_clients = set()
93
+
94
+ # ==============================================================================
95
+ # Utility Functions
96
+ # ==============================================================================
97
+
98
+ def get_current_time_str(tz='UTC'):
99
+ try:
100
+ timezone = pytz.timezone(tz)
101
+ now_aware = datetime.now(timezone)
102
+ except pytz.UnknownTimeZoneError:
103
+ now_aware = datetime.now(pytz.utc)
104
+ return now_aware.strftime('%Y%m%d_%H%M%S')
105
+
106
+ def clean_filename_part(text, max_len=30):
107
+ if not isinstance(text, str): text = "invalid_name"
108
+ text = re.sub(r'\s+', '_', text)
109
+ text = re.sub(r'[^\w\-.]', '', text)
110
+ return text[:max_len]
111
+
112
+ def run_async(async_func, *args, **kwargs):
113
+ try:
114
+ loop = asyncio.get_running_loop()
115
+ return loop.create_task(async_func(*args, **kwargs))
116
+ except RuntimeError:
117
+ print(f"Warning: Running async func {async_func.__name__} in new event loop.")
118
+ try:
119
+ return asyncio.run(async_func(*args, **kwargs))
120
+ except Exception as e:
121
+ print(f"Error running async func {async_func.__name__} in new loop: {e}")
122
+ return None
123
+ except Exception as e:
124
+ print(f"Error scheduling async task {async_func.__name__}: {e}")
125
+ return None
126
+
127
+ def ensure_dir(dir_path):
128
+ os.makedirs(dir_path, exist_ok=True)
129
+
130
+ # ==============================================================================
131
+ # World State File Handling (Markdown + JSON)
132
+ # ==============================================================================
133
+
134
+ def generate_world_save_filename(name="World"):
135
+ timestamp = get_current_time_str()
136
+ clean_name = clean_filename_part(name)
137
+ rand_hash = hashlib.md5(str(time.time()).encode() + name.encode()).hexdigest()[:6]
138
+ return f"{WORLD_STATE_FILE_MD_PREFIX}{clean_name}_{timestamp}_{rand_hash}.md"
139
+
140
+ def parse_world_filename(filename):
141
+ basename = os.path.basename(filename)
142
+ if basename.startswith(WORLD_STATE_FILE_MD_PREFIX) and basename.endswith(".md"):
143
+ core_name = basename[len(WORLD_STATE_FILE_MD_PREFIX):-3]
144
+ parts = core_name.split('_')
145
+ if len(parts) >= 3:
146
+ timestamp_str = parts[-2]
147
+ name_parts = parts[:-2]
148
+ name = "_".join(name_parts) if name_parts else "Untitled"
149
+ dt_obj = None
150
+ try:
151
+ dt_obj = datetime.strptime(timestamp_str, '%Y%m%d_%H%M%S')
152
+ dt_obj = pytz.utc.localize(dt_obj)
153
+ except (ValueError, pytz.exceptions.AmbiguousTimeError, pytz.exceptions.NonExistentTimeError):
154
+ dt_obj = None
155
+ return {"name": name.replace('_', ' '), "timestamp": timestamp_str, "dt": dt_obj, "filename": filename}
156
+ dt_fallback = None
157
+ try:
158
+ mtime = os.path.getmtime(filename)
159
+ dt_fallback = datetime.fromtimestamp(mtime, tz=pytz.utc)
160
+ except Exception:
161
+ pass
162
+ return {"name": basename.replace('.md',''), "timestamp": "Unknown", "dt": dt_fallback, "filename": filename}
163
+
164
+ def save_world_state_to_md(target_filename_base):
165
+ global world_objects
166
+ save_path = os.path.join(SAVED_WORLDS_DIR, target_filename_base)
167
+ print(f"Acquiring lock to save world state to: {save_path}...")
168
+ success = False
169
+ with world_objects_lock:
170
+ world_data_dict = dict(world_objects)
171
+ print(f"Saving {len(world_data_dict)} objects...")
172
+ parsed_info = parse_world_filename(save_path)
173
+ timestamp_save = get_current_time_str()
174
+ md_content = f"""# World State: {parsed_info['name']}
175
+ * **File Saved:** {timestamp_save} (UTC)
176
+ * **Source Timestamp:** {parsed_info['timestamp']}
177
+ * **Objects:** {len(world_data_dict)}
178
+
179
+ ```json
180
+ {json.dumps(world_data_dict, indent=2)}
181
+ ```"""
182
+ try:
183
+ ensure_dir(SAVED_WORLDS_DIR)
184
+ with open(save_path, 'w', encoding='utf-8') as f:
185
+ f.write(md_content)
186
+ print(f"World state saved successfully to {target_filename_base}")
187
+ success = True
188
+ username = st.session_state.get('username', 'Anonymous')
189
+ clean_username = clean_filename_part(username)
190
+ player_filename_base = f"{clean_username}_{target_filename_base}"
191
+ player_save_path = os.path.join(SAVED_WORLDS_DIR, player_filename_base)
192
+ with open(player_save_path, 'w', encoding='utf-8') as f:
193
+ f.write(md_content)
194
+ print(f"Player-specific world state saved to {player_filename_base}")
195
+ except Exception as e:
196
+ print(f"Error saving world state to {save_path}: {e}")
197
+ return success
198
+
199
+ def load_world_state_from_md(filename_base):
200
+ global world_objects
201
+ load_path = os.path.join(SAVED_WORLDS_DIR, filename_base)
202
+ print(f"Loading world state from MD file: {load_path}...")
203
+ if not os.path.exists(load_path):
204
+ st.error(f"World file not found: {filename_base}")
205
+ return False
206
+ try:
207
+ with open(load_path, 'r', encoding='utf-8') as f:
208
+ content = f.read()
209
+ json_match = re.search(r"```json\s*(\{[\s\S]*?\})\s*```", content, re.IGNORECASE)
210
+ if not json_match:
211
+ st.error(f"Could not find valid JSON block in {filename_base}")
212
+ return False
213
+ world_data_dict = json.loads(json_match.group(1))
214
+ print(f"Acquiring lock to update world state from {filename_base}...")
215
+ with world_objects_lock:
216
+ world_objects.clear()
217
+ for k, v in world_data_dict.items():
218
+ world_objects[str(k)] = v
219
+ loaded_count = len(world_objects)
220
+ print(f"Loaded {loaded_count} objects from {filename_base}. Lock released.")
221
+ st.session_state.current_world_file = filename_base
222
+ return True
223
+ except json.JSONDecodeError as e:
224
+ st.error(f"Invalid JSON found in {filename_base}: {e}")
225
+ return False
226
+ except Exception as e:
227
+ st.error(f"Error loading world state from {filename_base}: {e}")
228
+ st.exception(e)
229
+ return False
230
+
231
+ def get_saved_worlds():
232
+ try:
233
+ ensure_dir(SAVED_WORLDS_DIR)
234
+ world_files = glob.glob(os.path.join(SAVED_WORLDS_DIR, "*.md"))
235
+ parsed_worlds = [parse_world_filename(f) for f in world_files]
236
+ parsed_worlds.sort(key=lambda x: x['dt'] if x['dt'] else datetime.min.replace(tzinfo=pytz.utc), reverse=True)
237
+ return parsed_worlds
238
+ except Exception as e:
239
+ print(f"Error scanning saved worlds: {e}")
240
+ st.error(f"Could not scan saved worlds: {e}")
241
+ return []
242
+
243
+ def log_action(username, action_type, data):
244
+ timestamp = get_current_time_str()
245
+ log_entry = {
246
+ "timestamp": timestamp,
247
+ "username": username,
248
+ "action": action_type,
249
+ "data": data
250
+ }
251
+ shared_log_file = os.path.join(HISTORY_LOG_DIR, "shared_history.jsonl")
252
+ try:
253
+ with open(shared_log_file, 'a', encoding='utf-8') as f:
254
+ f.write(json.dumps(log_entry) + '\n')
255
+ except Exception as e:
256
+ print(f"Error writing to shared history log: {e}")
257
+ clean_username = clean_filename_part(username)
258
+ player_log_file = os.path.join(HISTORY_LOG_DIR, f"{clean_username}_history.jsonl")
259
+ try:
260
+ with open(player_log_file, 'a', encoding='utf-8') as f:
261
+ f.write(json.dumps(log_entry) + '\n')
262
+ except Exception as e:
263
+ print(f"Error writing to player history log {player_log_file}: {e}")
264
+
265
+ # ==============================================================================
266
+ # User State & Session Init
267
+ # ==============================================================================
268
+
269
+ def save_username(username):
270
+ try:
271
+ with open(STATE_FILE, 'w') as f:
272
+ f.write(username)
273
+ except Exception as e:
274
+ print(f"Failed save username: {e}")
275
+
276
+ def load_username():
277
+ if os.path.exists(STATE_FILE):
278
+ try:
279
+ with open(STATE_FILE, 'r') as f:
280
+ return f.read().strip()
281
+ except Exception as e:
282
+ print(f"Failed load username: {e}")
283
+ return None
284
+
285
+ def init_session_state():
286
+ defaults = {
287
+ 'server_running_flag': False, 'server_instance': None, 'server_task': None,
288
+ 'active_connections': defaultdict(dict), 'last_chat_update': 0, 'message_input': "",
289
+ 'audio_cache': {}, 'tts_voice': "en-US-AriaNeural", 'chat_history': [],
290
+ 'marquee_settings': {"background": "#1E1E1E", "color": "#FFFFFF", "font-size": "14px", "animationDuration": "20s", "width": "100%", "lineHeight": "35px"},
291
+ 'enable_audio': True, 'download_link_cache': {}, 'username': None, 'autosend': False,
292
+ 'last_message': "", 'timer_start': time.time(), 'last_sent_transcript': "",
293
+ 'last_refresh': time.time(), 'auto_refresh': False, 'refresh_rate': 30,
294
+ 'selected_object': 'None', 'initial_world_state_loaded': False,
295
+ 'current_world_file': None, 'operation_timings': {}, 'performance_metrics': defaultdict(list),
296
+ 'paste_image_base64': "", 'new_world_name': "MyWorld"
297
+ }
298
+ for k, v in defaults.items():
299
+ if k not in st.session_state:
300
+ st.session_state[k] = v
301
+ if not isinstance(st.session_state.active_connections, defaultdict):
302
+ st.session_state.active_connections = defaultdict(dict)
303
+ if not isinstance(st.session_state.chat_history, list):
304
+ st.session_state.chat_history = []
305
+ if not isinstance(st.session_state.marquee_settings, dict):
306
+ st.session_state.marquee_settings = defaults['marquee_settings']
307
+ if not isinstance(st.session_state.audio_cache, dict):
308
+ st.session_state.audio_cache = {}
309
+ if not isinstance(st.session_state.download_link_cache, dict):
310
+ st.session_state.download_link_cache = {}
311
+ if 'username' not in st.session_state or not st.session_state.username:
312
+ st.session_state.username = random.choice(list(FUN_USERNAMES.keys()))
313
+ save_username(st.session_state.username)
314
+
315
+ # ==============================================================================
316
+ # Audio / TTS / Chat / File Handling Helpers
317
+ # ==============================================================================
318
+
319
+ def clean_text_for_tts(text):
320
+ if not isinstance(text, str):
321
+ return "No text"
322
+ text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
323
+ text = re.sub(r'[#*_`!]', '', text)
324
+ text = ' '.join(text.split())
325
+ return text[:250] or "No text"
326
+
327
+ def create_file(content, username, file_type="md", save_path=None):
328
+ if not save_path:
329
+ filename = generate_filename(content, username, file_type)
330
+ save_path = os.path.join(MEDIA_DIR, filename)
331
+ ensure_dir(os.path.dirname(save_path))
332
+ try:
333
+ with open(save_path, 'w', encoding='utf-8') as f:
334
+ f.write(content)
335
+ return save_path
336
+ except Exception as e:
337
+ print(f"Error creating file {save_path}: {e}")
338
+ return None
339
+
340
+ def get_download_link(file_path, file_type="md"):
341
+ if not file_path or not os.path.exists(file_path):
342
+ basename = os.path.basename(file_path) if file_path else "N/A"
343
+ return f"<small>Not found: {basename}</small>"
344
+ try:
345
+ mtime = os.path.getmtime(file_path)
346
+ except OSError:
347
+ mtime = 0
348
+ cache_key = f"dl_{file_path}_{mtime}"
349
+ if 'download_link_cache' not in st.session_state:
350
+ st.session_state.download_link_cache = {}
351
+ if cache_key not in st.session_state.download_link_cache:
352
+ try:
353
+ with open(file_path, "rb") as f:
354
+ b64 = base64.b64encode(f.read()).decode()
355
+ mime_types = {"md": "text/markdown", "mp3": "audio/mpeg", "png": "image/png", "mp4": "video/mp4", "zip": "application/zip", "json": "application/json"}
356
+ basename = os.path.basename(file_path)
357
+ link_html = f'<a href="data:{mime_types.get(file_type, "application/octet-stream")};base64,{b64}" download="{basename}" title="Download {basename}">{FILE_EMOJIS.get(file_type, "๐Ÿ“„")}</a>'
358
+ st.session_state.download_link_cache[cache_key] = link_html
359
+ except Exception as e:
360
+ print(f"Error generating DL link for {file_path}: {e}")
361
+ return f"<small>Err</small>"
362
+ return st.session_state.download_link_cache.get(cache_key, "<small>CacheErr</small>")
363
+
364
+ async def async_edge_tts_generate(text, voice, username):
365
+ if not text:
366
+ return None
367
+ cache_key = hashlib.md5(f"{text[:150]}_{voice}".encode()).hexdigest()
368
+ if 'audio_cache' not in st.session_state:
369
+ st.session_state.audio_cache = {}
370
+ cached_path = st.session_state.audio_cache.get(cache_key)
371
+ if cached_path and os.path.exists(cached_path):
372
+ return cached_path
373
+ text_cleaned = clean_text_for_tts(text)
374
+ if not text_cleaned or text_cleaned == "No text":
375
+ return None
376
+ filename_base = generate_filename(text_cleaned, username, "mp3")
377
+ save_path = os.path.join(AUDIO_DIR, filename_base)
378
+ ensure_dir(AUDIO_DIR)
379
+ try:
380
+ communicate = edge_tts.Communicate(text_cleaned, voice)
381
+ await communicate.save(save_path)
382
+ if os.path.exists(save_path) and os.path.getsize(save_path) > 0:
383
+ st.session_state.audio_cache[cache_key] = save_path
384
+ return save_path
385
+ else:
386
+ print(f"Audio file {save_path} failed generation.")
387
+ return None
388
+ except Exception as e:
389
+ print(f"Edge TTS Error: {e}")
390
+ return None
391
+
392
+ def play_and_download_audio(file_path):
393
+ if file_path and os.path.exists(file_path):
394
+ try:
395
+ st.audio(file_path)
396
+ file_type = file_path.split('.')[-1]
397
+ st.markdown(get_download_link(file_path, file_type), unsafe_allow_html=True)
398
+ except Exception as e:
399
+ st.error(f"Audio display error for {os.path.basename(file_path)}: {e}")
400
+
401
+ async def save_chat_entry(username, message, voice, is_markdown=False):
402
+ if not message.strip():
403
+ return None, None
404
+ timestamp_str = get_current_time_str()
405
+ entry = f"[{timestamp_str}] {username} ({voice}): {message}" if not is_markdown else f"[{timestamp_str}] {username} ({voice}):\n```markdown\n{message}\n```"
406
+ md_filename_base = generate_filename(message, username, "md")
407
+ md_file_path = os.path.join(CHAT_DIR, md_filename_base)
408
+ md_file = create_file(entry, username, "md", save_path=md_file_path)
409
+ if 'chat_history' not in st.session_state:
410
+ st.session_state.chat_history = []
411
+ st.session_state.chat_history.append(entry)
412
+ audio_file = None
413
+ if st.session_state.get('enable_audio', True):
414
+ tts_message = message
415
+ audio_file = await async_edge_tts_generate(tts_message, voice, username)
416
+ return md_file, audio_file
417
+
418
+ async def load_chat_history():
419
+ if 'chat_history' not in st.session_state:
420
+ st.session_state.chat_history = []
421
+ if not st.session_state.chat_history:
422
+ ensure_dir(CHAT_DIR)
423
+ print("Loading chat history from files...")
424
+ chat_files = sorted(glob.glob(os.path.join(CHAT_DIR, "*.md")), key=os.path.getmtime)
425
+ loaded_count = 0
426
+ temp_history = []
427
+ for f_path in chat_files:
428
+ try:
429
+ with open(f_path, 'r', encoding='utf-8') as file:
430
+ temp_history.append(file.read().strip())
431
+ loaded_count += 1
432
+ except Exception as e:
433
+ print(f"Err read chat {f_path}: {e}")
434
+ st.session_state.chat_history = temp_history
435
+ print(f"Loaded {loaded_count} chat entries from files.")
436
+ return st.session_state.chat_history
437
+
438
+ def create_zip_of_files(files_to_zip, prefix="Archive"):
439
+ if not files_to_zip:
440
+ st.warning("No files provided to zip.")
441
+ return None
442
+ timestamp = format_timestamp_prefix(f"Zip_{prefix}")
443
+ zip_name = f"{prefix}_{timestamp}.zip"
444
+ try:
445
+ print(f"Creating zip: {zip_name}...")
446
+ with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as z:
447
+ for f in files_to_zip:
448
+ if os.path.exists(f):
449
+ z.write(f, os.path.basename(f))
450
+ else:
451
+ print(f"Skip zip missing: {f}")
452
+ print("Zip success.")
453
+ st.success(f"Created {zip_name}")
454
+ return zip_name
455
+ except Exception as e:
456
+ print(f"Zip failed: {e}")
457
+ st.error(f"Zip failed: {e}")
458
+ return None
459
+
460
+ def delete_files(file_patterns, exclude_files=None):
461
+ protected = [STATE_FILE, "app.py", "index.html", "requirements.txt", "README.md"]
462
+ if exclude_files:
463
+ protected.extend(exclude_files)
464
+ deleted_count = 0
465
+ errors = 0
466
+ for pattern in file_patterns:
467
+ pattern_path = pattern
468
+ print(f"Attempting to delete files matching: {pattern_path}")
469
+ try:
470
+ files_to_delete = glob.glob(pattern_path)
471
+ if not files_to_delete:
472
+ print(f"No files found for pattern: {pattern}")
473
+ continue
474
+ for f_path in files_to_delete:
475
+ basename = os.path.basename(f_path)
476
+ if os.path.isfile(f_path) and basename not in protected:
477
+ try:
478
+ os.remove(f_path)
479
+ print(f"Deleted: {f_path}")
480
+ deleted_count += 1
481
+ except Exception as e:
482
+ print(f"Failed delete {f_path}: {e}")
483
+ errors += 1
484
+ elif os.path.isdir(f_path):
485
+ print(f"Skipping directory: {f_path}")
486
+ except Exception as glob_e:
487
+ print(f"Error matching pattern {pattern}: {glob_e}")
488
+ errors += 1
489
+ msg = f"Deleted {deleted_count} files."
490
+ if errors > 0:
491
+ msg += f" Encountered {errors} errors."
492
+ st.warning(msg) if errors > 0 else st.success(msg) if deleted_count > 0 else st.info("No matching files found to delete.")
493
+ st.session_state['download_link_cache'] = {}
494
+ st.session_state['audio_cache'] = {}
495
+
496
+ async def save_pasted_image(image, username):
497
+ if not image:
498
+ return None
499
+ try:
500
+ img_hash = hashlib.md5(image.tobytes()).hexdigest()[:8]
501
+ timestamp = format_timestamp_prefix(username)
502
+ filename = f"{timestamp}_pasted_{img_hash}.png"
503
+ filepath = os.path.join(MEDIA_DIR, filename)
504
+ image.save(filepath, "PNG")
505
+ print(f"Pasted image saved: {filepath}")
506
+ return filepath
507
+ except Exception as e:
508
+ print(f"Failed image save: {e}")
509
+ return None
510
+
511
+ def paste_image_component():
512
+ pasted_img = None
513
+ img_type = None
514
+ paste_input = st.text_area("Paste Image Data Here", key="paste_input_area", height=50, value="")
515
+ if st.button("Process Pasted Image ๐Ÿ“‹", key="paste_form_button"):
516
+ if paste_input and paste_input.startswith('data:image'):
517
+ try:
518
+ mime_type = paste_input.split(';')[0].split(':')[1]
519
+ base64_str = paste_input.split(',')[1]
520
+ img_bytes = base64.b64decode(base64_str)
521
+ pasted_img = Image.open(io.BytesIO(img_bytes))
522
+ img_type = mime_type.split('/')[1]
523
+ st.image(pasted_img, caption=f"Pasted ({img_type.upper()})", width=150)
524
+ st.session_state.paste_image_base64 = base64_str
525
+ except ImportError:
526
+ st.error("Pillow library needed for image pasting.")
527
+ except Exception as e:
528
+ st.error(f"Img decode err: {e}")
529
+ st.session_state.paste_image_base64 = ""
530
+ else:
531
+ st.warning("No valid image data pasted.")
532
+ st.session_state.paste_image_base64 = ""
533
+ return pasted_img
534
+
535
+ class AudioProcessor:
536
+ def __init__(self):
537
+ self.cache_dir = AUDIO_CACHE_DIR
538
+ ensure_dir(self.cache_dir)
539
+ self.metadata = json.load(open(f"{self.cache_dir}/metadata.json", 'r')) if os.path.exists(f"{self.cache_dir}/metadata.json") else {}
540
+ def _save_metadata(self):
541
+ try:
542
+ with open(f"{self.cache_dir}/metadata.json", 'w') as f:
543
+ json.dump(self.metadata, f, indent=2)
544
+ except Exception as e:
545
+ print(f"Failed metadata save: {e}")
546
+ async def create_audio(self, text, voice='en-US-AriaNeural'):
547
+ cache_key = hashlib.md5(f"{text[:150]}:{voice}".encode()).hexdigest()
548
+ cache_path = os.path.join(self.cache_dir, f"{cache_key}.mp3")
549
+ if cache_key in self.metadata and os.path.exists(cache_path):
550
+ return cache_path
551
+ text_cleaned = clean_text_for_tts(text)
552
+ if not text_cleaned:
553
+ return None
554
+ ensure_dir(os.path.dirname(cache_path))
555
+ try:
556
+ communicate = edge_tts.Communicate(text_cleaned, voice)
557
+ await communicate.save(cache_path)
558
+ if os.path.exists(cache_path) and os.path.getsize(cache_path) > 0:
559
+ self.metadata[cache_key] = {'timestamp': datetime.now().isoformat(), 'text_length': len(text_cleaned), 'voice': voice}
560
+ self._save_metadata()
561
+ return cache_path
562
+ else:
563
+ return None
564
+ except Exception as e:
565
+ print(f"TTS Create Audio Error: {e}")
566
+ return None
567
+
568
+ def process_pdf_tab(pdf_file, max_pages, voice):
569
+ st.subheader("PDF Processing Results")
570
+ if pdf_file is None:
571
+ st.info("Upload a PDF file and click 'Process PDF' to begin.")
572
+ return
573
+ audio_processor = AudioProcessor()
574
+ try:
575
+ reader = PdfReader(pdf_file)
576
+ if reader.is_encrypted:
577
+ st.warning("PDF is encrypted.")
578
+ return
579
+ total_pages = min(len(reader.pages), max_pages)
580
+ st.write(f"Processing first {total_pages} pages of '{pdf_file.name}'...")
581
+ texts, audios = {}, {}
582
+ page_threads = []
583
+ results_lock = threading.Lock()
584
+
585
+ def process_page_sync(page_num, page_text):
586
+ async def run_async_audio():
587
+ return await audio_processor.create_audio(page_text, voice)
588
+ try:
589
+ audio_path = asyncio.run(run_async_audio())
590
+ if audio_path:
591
+ with results_lock:
592
+ audios[page_num] = audio_path
593
+ except Exception as page_e:
594
+ print(f"Err process page {page_num+1}: {page_e}")
595
+
596
+ for i in range(total_pages):
597
+ try:
598
+ page = reader.pages[i]
599
+ text = page.extract_text()
600
+ if text and text.strip():
601
+ texts[i] = text
602
+ thread = threading.Thread(target=process_page_sync, args=(i, text))
603
+ page_threads.append(thread)
604
+ thread.start()
605
+ else:
606
+ texts[i] = "[No text extracted]"
607
+ except Exception as extract_e:
608
+ texts[i] = f"[Error extract: {extract_e}]"
609
+ print(f"Error page {i+1} extract: {extract_e}")
610
+
611
+ progress_bar = st.progress(0.0, text="Processing pages...")
612
+ total_threads = len(page_threads)
613
+ start_join_time = time.time()
614
+ while any(t.is_alive() for t in page_threads):
615
+ completed_threads = total_threads - sum(t.is_alive() for t in page_threads)
616
+ progress = completed_threads / total_threads if total_threads > 0 else 1.0
617
+ progress_bar.progress(min(progress, 1.0), text=f"Processed {completed_threads}/{total_threads} pages...")
618
+ if time.time() - start_join_time > 600:
619
+ print("PDF processing timed out.")
620
+ break
621
+ time.sleep(0.5)
622
+ progress_bar.progress(1.0, text="Processing complete.")
623
+
624
+ for i in range(total_pages):
625
+ with st.expander(f"Page {i+1}"):
626
+ st.markdown(texts.get(i, "[Error getting text]"))
627
+ audio_file = audios.get(i)
628
+ if audio_file:
629
+ play_and_download_audio(audio_file)
630
+ else:
631
+ st.caption("Audio generation failed or was skipped.")
632
+
633
+ except Exception as pdf_e:
634
+ st.error(f"Err read PDF: {pdf_e}")
635
+ st.exception(pdf_e)
636
+
637
+ # ==============================================================================
638
+ # WebSocket Server Logic
639
+ # ==============================================================================
640
+
641
+ async def register_client(websocket):
642
+ client_id = str(websocket.id)
643
+ connected_clients.add(client_id)
644
+ if 'active_connections' not in st.session_state:
645
+ st.session_state.active_connections = defaultdict(dict)
646
+ st.session_state.active_connections[client_id] = websocket
647
+ print(f"Client registered: {client_id}. Total: {len(connected_clients)}")
648
+
649
+ async def unregister_client(websocket):
650
+ client_id = str(websocket.id)
651
+ connected_clients.discard(client_id)
652
+ if 'active_connections' in st.session_state:
653
+ st.session_state.active_connections.pop(client_id, None)
654
+ print(f"Client unregistered: {client_id}. Remaining: {len(connected_clients)}")
655
+
656
+ async def send_safely(websocket, message, client_id):
657
+ try:
658
+ await websocket.send(message)
659
+ except websockets.ConnectionClosed:
660
+ print(f"WS Send failed (Closed) client {client_id}")
661
+ raise
662
+ except RuntimeError as e:
663
+ print(f"WS Send failed (Runtime {e}) client {client_id}")
664
+ raise
665
+ except Exception as e:
666
+ print(f"WS Send failed (Other {e}) client {client_id}")
667
+ raise
668
+
669
+ async def broadcast_message(message, exclude_id=None):
670
+ if not connected_clients:
671
+ return
672
+ tasks = []
673
+ current_client_ids = list(connected_clients)
674
+ active_connections_copy = st.session_state.active_connections.copy()
675
+ for client_id in current_client_ids:
676
+ if client_id == exclude_id:
677
+ continue
678
+ websocket = active_connections_copy.get(client_id)
679
+ if websocket:
680
+ tasks.append(asyncio.create_task(send_safely(websocket, message, client_id)))
681
+ if tasks:
682
+ await asyncio.gather(*tasks, return_exceptions=True)
683
+
684
+ async def broadcast_world_update():
685
+ with world_objects_lock:
686
+ current_state_payload = dict(world_objects)
687
+ update_msg = json.dumps({"type": "initial_state", "payload": current_state_payload})
688
+ print(f"Broadcasting full world update ({len(current_state_payload)} objects)...")
689
+ await broadcast_message(update_msg)
690
+
691
+ async def websocket_handler(websocket, path):
692
+ await register_client(websocket)
693
+ client_id = str(websocket.id)
694
+ username = st.session_state.get('username', f"User_{client_id[:4]}")
695
+ try:
696
+ with world_objects_lock:
697
+ initial_state_payload = dict(world_objects)
698
+ initial_state_msg = json.dumps({"type": "initial_state", "payload": initial_state_payload})
699
+ await websocket.send(initial_state_msg)
700
+ print(f"Sent initial state ({len(initial_state_payload)} objs) to {client_id}")
701
+ await broadcast_message(json.dumps({"type": "user_join", "payload": {"username": username, "id": client_id}}), exclude_id=client_id)
702
+ except Exception as e:
703
+ print(f"Error initial phase {client_id}: {e}")
704
+
705
+ try:
706
+ async for message in websocket:
707
+ try:
708
+ data = json.loads(message)
709
+ msg_type = data.get("type")
710
+ payload = data.get("payload", {})
711
+ sender_username = payload.get("username", username)
712
+
713
+ if msg_type == "chat_message":
714
+ chat_text = payload.get('message', '')
715
+ voice = payload.get('voice', FUN_USERNAMES.get(sender_username, "en-US-AriaNeural"))
716
+ run_async(save_chat_entry, sender_username, chat_text, voice)
717
+ await broadcast_message(message, exclude_id=client_id)
718
+
719
+ elif msg_type == "place_object":
720
+ obj_data = payload.get("object_data")
721
+ if obj_data and 'obj_id' in obj_data and 'type' in obj_data:
722
+ with world_objects_lock:
723
+ world_objects[obj_data['obj_id']] = obj_data
724
+ broadcast_payload = json.dumps({"type": "object_placed", "payload": {"object_data": obj_data, "username": sender_username}})
725
+ await broadcast_message(broadcast_payload, exclude_id=client_id)
726
+ current_file = st.session_state.get('current_world_file')
727
+ if current_file:
728
+ run_async(save_world_state_to_md, current_file)
729
+ else:
730
+ new_filename = generate_world_save_filename(f"AutoSave_{sender_username}")
731
+ if run_async(save_world_state_to_md, new_filename):
732
+ st.session_state.current_world_file = new_filename
733
+ log_action(sender_username, "place", obj_data)
734
+
735
+ elif msg_type == "delete_object":
736
+ obj_id = payload.get("obj_id")
737
+ removed = False
738
+ if obj_id:
739
+ with world_objects_lock:
740
+ if obj_id in world_objects:
741
+ del world_objects[obj_id]
742
+ removed = True
743
+ if removed:
744
+ broadcast_payload = json.dumps({"type": "object_deleted", "payload": {"obj_id": obj_id, "username": sender_username}})
745
+ await broadcast_message(broadcast_payload, exclude_id=client_id)
746
+ current_file = st.session_state.get('current_world_file')
747
+ if current_file:
748
+ run_async(save_world_state_to_md, current_file)
749
+ else:
750
+ new_filename = generate_world_save_filename(f"AutoSave_{sender_username}")
751
+ if run_async(save_world_state_to_md, new_filename):
752
+ st.session_state.current_world_file = new_filename
753
+ log_action(sender_username, "delete", {"obj_id": obj_id})
754
+
755
+ elif msg_type == "player_position":
756
+ pos_data = payload.get("position")
757
+ rot_data = payload.get("rotation")
758
+ if pos_data:
759
+ broadcast_payload = json.dumps({"type": "player_moved", "payload": {"username": sender_username, "id": client_id, "position": pos_data, "rotation": rot_data}})
760
+ await broadcast_message(broadcast_payload, exclude_id=client_id)
761
+
762
+ except json.JSONDecodeError:
763
+ print(f"WS Invalid JSON from {client_id}: {message[:100]}...")
764
+ except Exception as e:
765
+ print(f"WS Error processing msg from {client_id}: {e}")
766
+ except websockets.ConnectionClosed:
767
+ print(f"WS Client disconnected: {client_id} ({username})")
768
+ except Exception as e:
769
+ print(f"WS Unexpected handler error {client_id}: {e}")
770
+ finally:
771
+ await broadcast_message(json.dumps({"type": "user_leave", "payload": {"username": username, "id": client_id}}), exclude_id=client_id)
772
+ await unregister_client(websocket)
773
+
774
+ async def run_websocket_server():
775
+ if st.session_state.get('server_running_flag', False):
776
+ return
777
+ st.session_state['server_running_flag'] = True
778
+ print("Attempting start WS server 0.0.0.0:8765...")
779
+ stop_event = asyncio.Event()
780
+ st.session_state['websocket_stop_event'] = stop_event
781
+ server = None
782
+ try:
783
+ server = await websockets.serve(websocket_handler, "0.0.0.0", 8765)
784
+ st.session_state['server_instance'] = server
785
+ print(f"WS server started: {server.sockets[0].getsockname()}. Waiting for stop signal...")
786
+ await stop_event.wait()
787
+ except OSError as e:
788
+ print(f"### FAILED START WS SERVER: {e}")
789
+ st.session_state['server_running_flag'] = False
790
+ except Exception as e:
791
+ print(f"### UNEXPECTED WS SERVER ERROR: {e}")
792
+ st.session_state['server_running_flag'] = False
793
+ finally:
794
+ print("WS server task finishing...")
795
+ if server:
796
+ server.close()
797
+ await server.wait_closed()
798
+ print("WS server closed.")
799
+ st.session_state['server_running_flag'] = False
800
+ st.session_state['server_instance'] = None
801
+ st.session_state['websocket_stop_event'] = None
802
+
803
+ def start_websocket_server_thread():
804
+ if st.session_state.get('server_task') and st.session_state.server_task.is_alive():
805
+ return
806
+ if st.session_state.get('server_running_flag', False):
807
+ return
808
+ print("Creating/starting new server thread.")
809
+ def run_loop():
810
+ loop = None
811
+ try:
812
+ loop = asyncio.get_running_loop()
813
+ except RuntimeError:
814
+ loop = asyncio.new_event_loop()
815
+ asyncio.set_event_loop(loop)
816
+ try:
817
+ loop.run_until_complete(run_websocket_server())
818
+ finally:
819
+ if loop and not loop.is_closed():
820
+ tasks = asyncio.all_tasks(loop)
821
+ for task in tasks:
822
+ task.cancel()
823
+ try:
824
+ loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
825
+ except asyncio.CancelledError:
826
+ pass
827
+ finally:
828
+ loop.close()
829
+ print("Server thread loop closed.")
830
+ else:
831
+ print("Server thread loop already closed or None.")
832
+ st.session_state.server_task = threading.Thread(target=run_loop, daemon=True)
833
+ st.session_state.server_task.start()
834
+ time.sleep(1.5)
835
+ if not st.session_state.server_task.is_alive():
836
+ print("### Server thread failed to stay alive!")
837
+
838
+ # ==============================================================================
839
+ # Streamlit UI Layout Functions
840
+ # ==============================================================================
841
+
842
+ def render_sidebar():
843
+ with st.sidebar:
844
+ st.header("๐Ÿ’พ World Versions")
845
+ st.caption("Load or save named world states.")
846
+
847
+ saved_worlds = get_saved_worlds()
848
+ world_options_display = {
849
+ os.path.basename(w['filename']): (
850
+ f"{w['name']} ({w['timestamp']})" if not w['filename'].startswith(clean_filename_part(st.session_state.get('username', '')))
851
+ else f"{w['name']} ({w['timestamp']}) [Your Save]"
852
+ ) for w in saved_worlds
853
+ }
854
+ radio_options_basenames = [None] + [os.path.basename(w['filename']) for w in saved_worlds]
855
+ current_selection_basename = st.session_state.get('current_world_file', None)
856
+ current_radio_index = 0
857
+ if current_selection_basename and current_selection_basename in radio_options_basenames:
858
+ try:
859
+ current_radio_index = radio_options_basenames.index(current_selection_basename)
860
+ except ValueError:
861
+ current_radio_index = 0
862
+
863
+ selected_basename = st.radio(
864
+ "Load World:",
865
+ options=radio_options_basenames,
866
+ index=current_radio_index,
867
+ format_func=lambda x: "Live State (Unsaved)" if x is None else world_options_display.get(x, x),
868
+ key="world_selector_radio"
869
+ )
870
+
871
+ if selected_basename != current_selection_basename:
872
+ st.session_state.current_world_file = selected_basename
873
+ if selected_basename:
874
+ with st.spinner(f"Loading {selected_basename}..."):
875
+ if load_world_state_from_md(selected_basename):
876
+ run_async(broadcast_world_update)
877
+ st.toast("World loaded!", icon="โœ…")
878
+ else:
879
+ st.error("Failed to load world.")
880
+ st.session_state.current_world_file = None
881
+ else:
882
+ print("Switched to live state.")
883
+ st.toast("Switched to Live State.")
884
+ st.rerun()
885
+
886
+ st.caption("Download:")
887
+ cols = st.columns([4, 1])
888
+ with cols[0]:
889
+ st.write("**Name** (Timestamp)")
890
+ with cols[1]:
891
+ st.write("**DL**")
892
+ display_limit = 10
893
+ for i, world_info in enumerate(saved_worlds):
894
+ if i >= display_limit and len(saved_worlds) > display_limit + 1:
895
+ with st.expander(f"Show {len(saved_worlds)-display_limit} more..."):
896
+ for world_info_more in saved_worlds[display_limit:]:
897
+ f_basename = os.path.basename(world_info_more['filename'])
898
+ f_fullpath = os.path.join(SAVED_WORLDS_DIR, f_basename)
899
+ display_name = world_info_more.get('name', f_basename)
900
+ timestamp = world_info_more.get('timestamp', 'N/A')
901
+ colA, colB = st.columns([4, 1])
902
+ with colA:
903
+ st.write(f"<small>{display_name} ({timestamp})</small>", unsafe_allow_html=True)
904
+ with colB:
905
+ st.markdown(get_download_link(f_fullpath, "md"), unsafe_allow_html=True)
906
+ break
907
+ f_basename = os.path.basename(world_info['filename'])
908
+ f_fullpath = os.path.join(SAVED_WORLDS_DIR, f_basename)
909
+ display_name = world_info.get('name', f_basename)
910
+ timestamp = world_info.get('timestamp', 'N/A')
911
+ col1, col2 = st.columns([4, 1])
912
+ with col1:
913
+ st.write(f"<small>{display_name} ({timestamp})</small>", unsafe_allow_html=True)
914
+ with col2:
915
+ st.markdown(get_download_link(f_fullpath, "md"), unsafe_allow_html=True)
916
+
917
+ st.markdown("---")
918
+ st.header("๐Ÿ—๏ธ Build Tools")
919
+ st.caption("Select an object to place.")
920
+ cols = st.columns(5)
921
+ col_idx = 0
922
+ current_tool = st.session_state.get('selected_object', 'None')
923
+ for emoji, name in PRIMITIVE_MAP.items():
924
+ button_key = f"primitive_{name}"
925
+ button_type = "primary" if current_tool == name else "secondary"
926
+ if cols[col_idx % 5].button(emoji, key=button_key, help=name, type=button_type, use_container_width=True):
927
+ if st.session_state.get('selected_object', 'None') != name:
928
+ st.session_state.selected_object = name
929
+ run_async(lambda name_arg=name: streamlit_js_eval(
930
+ f"updateSelectedObjectType({json.dumps(name_arg)});",
931
+ key=f"update_tool_js_{name_arg}"
932
+ ))
933
+ run_async(broadcast_world_update)
934
+ st.rerun()
935
+ col_idx += 1
936
+ st.markdown("---")
937
+ if st.button("๐Ÿšซ Clear Tool", key="clear_tool", use_container_width=True):
938
+ if st.session_state.get('selected_object', 'None') != 'None':
939
+ st.session_state.selected_object = 'None'
940
+ run_async(lambda: streamlit_js_eval(
941
+ "updateSelectedObjectType('None');",
942
+ key="update_tool_js_none"
943
+ ))
944
+ run_async(broadcast_world_update)
945
+ st.rerun()
946
+
947
+ st.markdown("---")
948
+ st.header("๐Ÿ—ฃ๏ธ Voice & User")
949
+ current_username = st.session_state.get('username', list(FUN_USERNAMES.keys())[0])
950
+ username_options = list(FUN_USERNAMES.keys())
951
+ current_index = 0
952
+ try:
953
+ current_index = username_options.index(current_username)
954
+ except ValueError:
955
+ current_index = 0
956
+ new_username = st.selectbox("Change Name/Voice", options=username_options, index=current_index, key="username_select", format_func=lambda x: x.split(" ")[0])
957
+ if new_username != st.session_state.username:
958
+ old_username = st.session_state.username
959
+ change_msg = json.dumps({"type":"user_rename", "payload": {"old_username": old_username, "new_username": new_username}})
960
+ run_async(broadcast_message, change_msg)
961
+ st.session_state.username = new_username
962
+ st.session_state.tts_voice = FUN_USERNAMES[new_username]
963
+ save_username(st.session_state.username)
964
+ st.rerun()
965
+ st.session_state['enable_audio'] = st.toggle("Enable TTS Audio", value=st.session_state.get('enable_audio', True))
966
+
967
+ def render_main_content():
968
+ st.title(f"{Site_Name} - User: {st.session_state.username}")
969
+
970
+ tab_world, tab_chat, tab_pdf, tab_files = st.tabs(["๐Ÿ—๏ธ World Builder", "๐Ÿ—ฃ๏ธ Chat", "๐Ÿ“š PDF Tools", "๐Ÿ“‚ Files & Settings"])
971
+
972
+ with tab_world:
973
+ st.header("Shared 3D World")
974
+ st.caption("Place objects using the sidebar tools. Changes are shared live!")
975
+ current_file_basename = st.session_state.get('current_world_file', None)
976
+ if current_file_basename:
977
+ parsed = parse_world_filename(os.path.join(SAVED_WORLDS_DIR, current_file_basename))
978
+ st.info(f"Current World: **{parsed['name']}** (`{current_file_basename}`)")
979
+ else:
980
+ st.info("Live State Active (Unsaved changes only persist if saved)")
981
+
982
+ html_file_path = 'index.html'
983
+ try:
984
+ with open(html_file_path, 'r', encoding='utf-8') as f:
985
+ html_template = f.read()
986
+ ws_url = "ws://localhost:8765"
987
+ try:
988
+ from streamlit.web.server.server import Server
989
+ session_info = Server.get_current()._get_session_info(st.runtime.scriptrunner.get_script_run_ctx().session_id)
990
+ server_host = session_info.ws.stream.request.host.split(':')[0]
991
+ ws_url = f"ws://{server_host}:8765"
992
+ except Exception as e:
993
+ print(f"WS URL detection failed ({e}), using localhost.")
994
+ js_injection_script = f"""<script>
995
+ window.USERNAME = {json.dumps(st.session_state.username)};
996
+ window.WEBSOCKET_URL = {json.dumps(ws_url)};
997
+ window.SELECTED_OBJECT_TYPE = {json.dumps(st.session_state.selected_object)};
998
+ window.PLOT_WIDTH = {json.dumps(PLOT_WIDTH)};
999
+ window.PLOT_DEPTH = {json.dumps(PLOT_DEPTH)};
1000
+ console.log("Streamlit State Injected:", {{ username: window.USERNAME, websocketUrl: window.WEBSOCKET_URL, selectedObject: window.SELECTED_OBJECT_TYPE }});
1001
+ </script>"""
1002
+ html_content_with_state = html_template.replace('</head>', js_injection_script + '\n</head>', 1)
1003
+ components.html(html_content_with_state, height=700, scrolling=False)
1004
+ except FileNotFoundError:
1005
+ st.error(f"CRITICAL ERROR: Could not find '{html_file_path}'.")
1006
+ except Exception as e:
1007
+ st.error(f"Error loading 3D component: {e}")
1008
+ st.exception(e)
1009
+
1010
+ with tab_chat:
1011
+ st.header(f"{START_ROOM} Chat")
1012
+ chat_history_task = run_async(load_chat_history)
1013
+ chat_history = chat_history_task.result() if chat_history_task else st.session_state.chat_history
1014
+ chat_container = st.container(height=500)
1015
+ with chat_container:
1016
+ if chat_history:
1017
+ st.markdown("----\n".join(reversed(chat_history[-50:])))
1018
+ else:
1019
+ st.caption("No chat messages yet.")
1020
+
1021
+ message_value = st.text_input("Your Message:", key="message_input", label_visibility="collapsed")
1022
+ send_button_clicked = st.button("Send Chat ๐Ÿ’ฌ", key="send_chat_button")
1023
+ should_autosend = st.session_state.get('autosend', False) and message_value
1024
+
1025
+ if send_button_clicked or should_autosend:
1026
+ message_to_send = message_value
1027
+ if message_to_send.strip() and message_to_send != st.session_state.get('last_message', ''):
1028
+ st.session_state.last_message = message_to_send
1029
+ voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
1030
+ ws_message = json.dumps({"type": "chat_message", "payload": {"username": st.session_state.username, "message": message_to_send, "voice": voice}})
1031
+ run_async(broadcast_message, ws_message)
1032
+ run_async(save_chat_entry, st.session_state.username, message_to_send, voice)
1033
+ st.session_state.message_input = ""
1034
+ st.rerun()
1035
+ elif send_button_clicked:
1036
+ st.toast("Message empty or same as last.")
1037
+ st.checkbox("Autosend Chat", key="autosend")
1038
+
1039
+ with tab_pdf:
1040
+ st.header("๐Ÿ“š PDF Tools")
1041
+ pdf_file = st.file_uploader("Upload PDF for Audio Conversion", type="pdf", key="pdf_upload")
1042
+ max_pages = st.slider('Max Pages to Process', 1, 50, 10, key="pdf_pages")
1043
+ if pdf_file:
1044
+ if st.button("Process PDF to Audio", key="process_pdf_button"):
1045
+ with st.spinner("Processing PDF... This may take time."):
1046
+ process_pdf_tab(pdf_file, max_pages, st.session_state.tts_voice)
1047
+
1048
+ with tab_files:
1049
+ st.header("๐Ÿ“‚ Files & Settings")
1050
+ st.subheader("๐Ÿ’พ World State Management")
1051
+ current_file_basename = st.session_state.get('current_world_file', None)
1052
+ if current_file_basename:
1053
+ parsed = parse_world_filename(os.path.join(SAVED_WORLDS_DIR, current_file_basename))
1054
+ save_label = f"Save Changes to '{parsed['name']}'"
1055
+ if st.button(save_label, key="save_current_world", help=f"Overwrite '{current_file_basename}'"):
1056
+ with st.spinner(f"Overwriting {็พๅœจใฎ_file_basename}..."):
1057
+ if save_world_state_to_md(current_file_basename):
1058
+ st.success("Current world saved!")
1059
+ else:
1060
+ st.error("Failed to save world state.")
1061
+ else:
1062
+ st.info("Load a world from the sidebar to enable saving changes to it.")
1063
+
1064
+ st.subheader("Save As New Version")
1065
+ new_name_files = st.text_input("New World Name:", key="new_world_name_files", value=st.session_state.get('new_world_name', 'MyWorld'))
1066
+ if st.button("๐Ÿ’พ Save Live State as New Version", key="save_new_version_files"):
1067
+ if new_name_files.strip():
1068
+ new_filename_base = generate_world_save_filename(new_name_files)
1069
+ with st.spinner(f"Saving new version '{new_name_files}'..."):
1070
+ if save_world_state_to_md(new_filename_base):
1071
+ st.success(f"Saved as {new_filename_base}")
1072
+ st.session_state.current_world_file = new_filename_base
1073
+ st.session_state.new_world_name = "MyWorld"
1074
+ st.rerun()
1075
+ else:
1076
+ st.error("Failed to save new version.")
1077
+ else:
1078
+ st.warning("Please enter a name.")
1079
+
1080
+ st.subheader("โš™๏ธ Server Status")
1081
+ col_ws, col_clients = st.columns(2)
1082
+ with col_ws:
1083
+ server_alive = st.session_state.get('server_task') and st.session_state.server_task.is_alive()
1084
+ ws_status = "Running" if server_alive else "Stopped"
1085
+ st.metric("WebSocket Server", ws_status)
1086
+ if not server_alive and st.button("Restart Server Thread", key="restart_ws"):
1087
+ start_websocket_server_thread()
1088
+ st.rerun()
1089
+ with col_clients:
1090
+ st.metric("Connected Clients", len(connected_clients))
1091
+
1092
+ st.subheader("๐Ÿ—‘๏ธ Delete Files")
1093
+ st.warning("Deletion is permanent!", icon="โš ๏ธ")
1094
+ col_del1, col_del2, col_del3, col_del4 = st.columns(4)
1095
+ with col_del1:
1096
+ if st.button("๐Ÿ—‘๏ธ Chats", key="del_chat_md"):
1097
+ delete_files([os.path.join(CHAT_DIR, "*.md")])
1098
+ st.session_state.chat_history = []
1099
+ st.rerun()
1100
+ with col_del2:
1101
+ if st.button("๐Ÿ—‘๏ธ Audio", key="del_audio_mp3"):
1102
+ delete_files([os.path.join(AUDIO_DIR, "*.mp3"), os.path.join(AUDIO_CACHE_DIR, "*.mp3")])
1103
+ st.session_state.audio_cache = {}
1104
+ st.rerun()
1105
+ with col_del3:
1106
+ if st.button("๐Ÿ—‘๏ธ Worlds", key="del_worlds_md"):
1107
+ delete_files([os.path.join(SAVED_WORLDS_DIR, f"{WORLD_STATE_FILE_MD_PREFIX}*.md")])
1108
+ st.session_state.current_world_file = None
1109
+ st.rerun()
1110
+ with col_del4:
1111
+ if st.button("๐Ÿ—‘๏ธ All Gen", key="del_all_gen"):
1112
+ delete_files([os.path.join(CHAT_DIR, "*.md"), os.path.join(AUDIO_DIR, "*.mp3"), os.path.join(AUDIO_CACHE_DIR, "*.mp3"), os.path.join(SAVED_WORLDS_DIR, "*.md"), "*.zip"])
1113
+ st.session_state.chat_history = []
1114
+ st.session_state.audio_cache = {}
1115
+ st.session_state.current_world_file = None
1116
+ st.rerun()
1117
+
1118
+ st.subheader("๐Ÿ“ฆ Download Archives")
1119
+ zip_files = sorted(glob.glob(os.path.join(MEDIA_DIR,"*.zip")), key=os.path.getmtime, reverse=True)
1120
+ if zip_files:
1121
+ col_zip1, col_zip2, col_zip3 = st.columns(3)
1122
+ with col_zip1:
1123
+ if st.button("Zip Worlds"):
1124
+ create_zip_of_files([w['filename'] for w in get_saved_worlds()], "Worlds")
1125
+ with col_zip2:
1126
+ if st.button("Zip Chats"):
1127
+ create_zip_of_files(glob.glob(os.path.join(CHAT_DIR, "*.md")), "Chats")
1128
+ with col_zip3:
1129
+ if st.button("Zip Audio"):
1130
+ create_zip_of_files(glob.glob(os.path.join(AUDIO_DIR, "*.mp3")) + glob.glob(os.path.join(AUDIO_CACHE_DIR, "*.mp3")), "Audio")
1131
+ st.caption("Existing Zip Files:")
1132
+ for zip_file in zip_files:
1133
+ st.markdown(get_download_link(zip_file, "zip"), unsafe_allow_html=True)
1134
+ else:
1135
+ st.caption("No zip archives found.")
1136
+
1137
+ # ==============================================================================
1138
+ # Main Execution Logic
1139
+ # ==============================================================================
1140
+
1141
+ def initialize_world():
1142
+ if not st.session_state.get('initial_world_state_loaded', False):
1143
+ print("Performing initial world load for session...")
1144
+ saved_worlds = get_saved_worlds()
1145
+ loaded_successfully = False
1146
+ if saved_worlds:
1147
+ latest_world_file_basename = os.path.basename(saved_worlds[0]['filename'])
1148
+ print(f"Loading most recent world on startup: {latest_world_file_basename}")
1149
+ if load_world_state_from_md(latest_world_file_basename):
1150
+ loaded_successfully = True
1151
+ else:
1152
+ print("Failed to load most recent world, starting empty.")
1153
+ else:
1154
+ print("No saved worlds found, starting with empty state.")
1155
+ if not loaded_successfully:
1156
+ with world_objects_lock:
1157
+ world_objects.clear()
1158
+ st.session_state.current_world_file = None
1159
+ st.session_state.initial_world_state_loaded = True
1160
+ print("Initial world load process complete.")
1161
+
1162
+ if __name__ == "__main__":
1163
+ init_session_state()
1164
+ server_thread = st.session_state.get('server_task')
1165
+ server_alive = server_thread is not None and server_thread.is_alive()
1166
+ if not st.session_state.get('server_running_flag', False) and not server_alive:
1167
+ start_websocket_server_thread()
1168
+ elif server_alive and not st.session_state.get('server_running_flag', False):
1169
+ st.session_state.server_running_flag = True
1170
+ initialize_world()
1171
+ render_sidebar()
1172
+ render_main_content()