awacke1 commited on
Commit
319aad8
·
verified ·
1 Parent(s): d40d041

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +285 -931
app.py CHANGED
@@ -1,952 +1,306 @@
1
- # app.py (Refactored & Consolidated)
2
  import streamlit as st
3
- import asyncio
4
- import websockets
5
- import uuid
6
- from datetime import datetime
7
- import os
8
- import random
9
- import time
10
- import hashlib
11
- import glob
12
- import base64
13
- import io
14
  import streamlit.components.v1 as components
15
- import edge_tts
16
- import nest_asyncio
17
- import re
18
- import pytz
19
- import shutil
20
- from PyPDF2 import PdfReader
21
- import threading
22
  import json
23
- import zipfile
24
- from dotenv import load_dotenv
25
- from streamlit_marquee import streamlit_marquee
26
- from collections import defaultdict, Counter
27
- import pandas as pd # Still used for fallback CSV load? Keep for now.
28
- from streamlit_js_eval import streamlit_js_eval
29
- from PIL import Image
30
-
31
- # ==============================================================================
32
- # Configuration & Constants
33
- # ==============================================================================
34
-
35
- # 🛠️ Patch asyncio for nesting
36
- nest_asyncio.apply()
37
-
38
- # 🎨 Page Config
39
- st.set_page_config(
40
- page_title="🤖🏗️ Shared World Builder 🏆",
41
- page_icon="🏗️",
42
- layout="wide",
43
- initial_sidebar_state="expanded"
44
- )
45
-
46
- # General Constants
47
- icons = '🤖🏗️🗣️💾'
48
- Site_Name = '🤖🏗️ Shared World Builder 🗣️'
49
- START_ROOM = "World Lobby 🌍"
50
- MEDIA_DIR = "." # Base directory for general files
51
- STATE_FILE = "user_state.txt" # For remembering username
52
-
53
- # User/Chat Constants
54
- FUN_USERNAMES = {
55
- "BuilderBot 🤖": "en-US-AriaNeural", "WorldWeaver 🕸️": "en-US-JennyNeural",
56
- "Terraformer 🌱": "en-GB-SoniaNeural", "SkyArchitect ☁️": "en-AU-NatashaNeural",
57
- "PixelPainter 🎨": "en-CA-ClaraNeural", "VoxelVortex 🌪️": "en-US-GuyNeural",
58
- "CosmicCrafter ✨": "en-GB-RyanNeural", "GeoGuru 🗺️": "en-AU-WilliamNeural",
59
- "BlockBard 🧱": "en-CA-LiamNeural", "SoundSculptor 🔊": "en-US-AnaNeural",
60
- }
61
- EDGE_TTS_VOICES = list(set(FUN_USERNAMES.values()))
62
- CHAT_DIR = "chat_logs"
63
-
64
- # Audio Constants
65
- AUDIO_CACHE_DIR = "audio_cache"
66
- AUDIO_DIR = "audio_logs"
67
-
68
- # World Builder Constants
69
- SAVED_WORLDS_DIR = "saved_worlds" # Directory for MD world files
70
- PLOT_WIDTH = 50.0 # Needed for JS injection
71
- PLOT_DEPTH = 50.0 # Needed for JS injection
72
- WORLD_STATE_FILE_MD_PREFIX = "🌍_" # Prefix for world save files
73
-
74
- # File Emojis
75
- FILE_EMOJIS = {"md": "📝", "mp3": "🎵", "png": "🖼️", "mp4": "🎥", "zip": "📦", "json": "📄"}
76
-
77
- # API Keys (Load from .env or secrets)
78
- load_dotenv()
79
- # ANTHROPIC_KEY = os.getenv('ANTHROPIC_API_KEY', st.secrets.get('ANTHROPIC_API_KEY', ""))
80
- # OPENAI_KEY = os.getenv('OPENAI_API_KEY', st.secrets.get('OPENAI_API_KEY', ""))
81
-
82
- # Mapping Emojis to Primitive Types
83
- PRIMITIVE_MAP = {
84
- "🌳": "Tree", "🗿": "Rock", "🏛️": "Simple House", "🌲": "Pine Tree", "🧱": "Brick Wall",
85
- "🔵": "Sphere", "📦": "Cube", "🧴": "Cylinder", "🍦": "Cone", "🍩": "Torus",
86
- "🍄": "Mushroom", "🌵": "Cactus", "🔥": "Campfire", "⭐": "Star", "💎": "Gem",
87
- "🗼": "Tower", "🚧": "Barrier", "⛲": "Fountain", "🏮": "Lantern", "팻": "Sign Post"
88
- }
89
-
90
- # ==============================================================================
91
- # Global State & Locks
92
- # ==============================================================================
93
-
94
- # Thread lock for accessing shared world state
95
- world_objects_lock = threading.Lock()
96
- # In-memory world state {obj_id: data} - Use defaultdict for convenience
97
- world_objects = defaultdict(dict)
98
- # Set of active WebSocket client IDs
99
- connected_clients = set()
100
-
101
- # ==============================================================================
102
- # Utility Functions
103
- # ==============================================================================
104
-
105
- def get_current_time_str(tz='UTC'):
106
- """Gets formatted timestamp string in specified timezone (default UTC)."""
107
  try:
108
- timezone = pytz.timezone(tz)
109
- # Get current datetime localized to the specified timezone
110
- now_aware = datetime.now(timezone)
111
- except pytz.UnknownTimeZoneError:
112
- # Fallback to UTC if timezone is unknown
113
- now_aware = datetime.now(pytz.utc)
114
  except Exception as e:
115
- # General fallback if timezone localization fails
116
- print(f"Timezone error ({tz}), using UTC. Error: {e}")
117
- now_aware = datetime.now(pytz.utc)
118
 
119
- return now_aware.strftime('%Y%m%d_%H%M%S')
120
-
121
-
122
- def clean_filename_part(text, max_len=30):
123
- """Cleans a string part for use in a filename."""
124
- if not isinstance(text, str): text = "invalid_name"
125
- text = re.sub(r'\s+', '_', text) # Replace spaces
126
- text = re.sub(r'[^\w\-.]', '', text) # Keep word chars, hyphen, period
127
- return text[:max_len]
128
-
129
- def run_async(async_func, *args, **kwargs):
130
- """Runs an async function safely from a sync context."""
131
- try:
132
- loop = asyncio.get_running_loop()
133
- # Schedule as task if loop is running
134
- return loop.create_task(async_func(*args, **kwargs))
135
- except RuntimeError: # No running loop
136
- # Run in a new loop (blocks until completion)
137
  try:
138
- return asyncio.run(async_func(*args, **kwargs))
139
- except Exception as e:
140
- print(f"Error running async func {async_func.__name__} in new loop: {e}")
141
- return None # Indicate error or failure
142
- except Exception as e:
143
- print(f"Error scheduling async task {async_func.__name__}: {e}")
144
- return None
145
-
146
- def ensure_dir(dir_path):
147
- """Creates directory if it doesn't exist."""
148
- os.makedirs(dir_path, exist_ok=True)
149
-
150
- # Ensure directories exist on startup
151
- for d in [CHAT_DIR, AUDIO_DIR, AUDIO_CACHE_DIR, SAVED_WORLDS_DIR]:
152
- ensure_dir(d)
153
-
154
- # ==============================================================================
155
- # World State File Handling (Markdown + JSON)
156
- # ==============================================================================
157
-
158
- def generate_world_save_filename(name="World"):
159
- """Generates a filename for saving world state MD files."""
160
- timestamp = get_current_time_str() # Use UTC for consistency
161
- clean_name = clean_filename_part(name)
162
- rand_hash = hashlib.md5(str(time.time()).encode() + name.encode()).hexdigest()[:6] # Seed hash
163
- return f"{WORLD_STATE_FILE_MD_PREFIX}{clean_name}_{timestamp}_{rand_hash}.md"
164
-
165
- def parse_world_filename(filename):
166
- """Extracts info from filename if possible, otherwise returns defaults."""
167
- basename = os.path.basename(filename)
168
- # Ensure prefix and suffix are correct
169
- if basename.startswith(WORLD_STATE_FILE_MD_PREFIX) and basename.endswith(".md"):
170
- parts = basename[len(WORLD_STATE_FILE_MD_PREFIX):-3].split('_') # Remove prefix and suffix before split
171
- if len(parts) >= 3: # Expecting Name_Timestamp_Hash
172
- timestamp_str = parts[-2]
173
- name = " ".join(parts[:-2]) # Join potentially multiple parts for name
174
- dt_obj = None
175
- try: # Try parsing timestamp
176
- dt_obj = datetime.strptime(timestamp_str, '%Y%m%d_%H%M%S')
177
- dt_obj = pytz.utc.localize(dt_obj) # Assume UTC since generated with UTC
178
- except (ValueError, pytz.exceptions.AmbiguousTimeError, pytz.exceptions.NonExistentTimeError):
179
- dt_obj = None # Parsing failed or timezone issue
180
- return {"name": name or "Untitled", "timestamp": timestamp_str, "dt": dt_obj, "filename": filename}
181
-
182
- # Fallback for unknown format or parsing failure
183
- dt_fallback = None
184
  try:
185
- mtime = os.path.getmtime(filename)
186
- dt_fallback = datetime.fromtimestamp(mtime, tz=pytz.utc)
187
- except Exception: pass # Ignore errors getting mtime
188
- return {"name": basename.replace('.md',''), "timestamp": "Unknown", "dt": dt_fallback, "filename": filename}
189
-
190
- def save_world_state_to_md(target_filename_base):
191
- """Saves the current in-memory world state to a specific MD file (basename)."""
192
- global world_objects
193
- save_path = os.path.join(SAVED_WORLDS_DIR, target_filename_base)
194
- print(f"Acquiring lock to save {len(world_objects)} objects to: {save_path}...")
195
- success = False
196
- with world_objects_lock:
197
- world_data_dict = dict(world_objects) # Create copy inside lock
198
- print(f"Saving {len(world_data_dict)} objects...")
199
- parsed_info = parse_world_filename(target_filename_base) # Use original filename for info
200
- timestamp_save = get_current_time_str()
201
- md_content = f"""# World State: {parsed_info['name']}
202
- * **File Saved:** {timestamp_save} (UTC)
203
- * **Original Timestamp:** {parsed_info['timestamp']}
204
- * **Objects:** {len(world_data_dict)}
205
-
206
- ```json
207
- {json.dumps(world_data_dict, indent=2)}
208
- ```"""
209
- try:
210
- ensure_dir(SAVED_WORLDS_DIR) # Ensure dir exists
211
- with open(save_path, 'w', encoding='utf-8') as f: f.write(md_content)
212
- print(f"World state saved successfully to {target_filename_base}")
213
- success = True
214
- except Exception as e:
215
- print(f"Error saving world state to {save_path}: {e}")
216
- # Avoid st.error in potentially non-main thread
217
- return success
218
-
219
- def load_world_state_from_md(filename_base):
220
- """Loads world state from an MD file (basename), updates global state, returns success bool."""
221
- global world_objects
222
- load_path = os.path.join(SAVED_WORLDS_DIR, filename_base)
223
- print(f"Loading world state from MD file: {load_path}...")
224
- if not os.path.exists(load_path):
225
- st.error(f"World file not found: {filename_base}")
226
  return False
227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  try:
229
- with open(load_path, 'r', encoding='utf-8') as f: content = f.read()
230
- json_match = re.search(r"```json\s*(\{.*?\})\s*```", content, re.DOTALL | re.IGNORECASE)
231
- if not json_match: st.error(f"Could not find valid JSON block in {filename_base}"); return False
232
-
233
- world_data_dict = json.loads(json_match.group(1))
234
-
235
- print(f"Acquiring lock to update world state from {filename_base}...")
236
- with world_objects_lock:
237
- world_objects.clear() # Clear previous state
238
- for k, v in world_data_dict.items(): world_objects[str(k)] = v # Update with loaded data
239
- loaded_count = len(world_objects)
240
- print(f"Loaded {loaded_count} objects from {filename_base}. Lock released.")
241
- st.session_state.current_world_file = filename_base # Track loaded file (basename)
242
  return True
 
 
 
243
 
244
- except json.JSONDecodeError as e: st.error(f"Invalid JSON found in {filename_base}: {e}"); return False
245
- except Exception as e: st.error(f"Error loading world state from {filename_base}: {e}"); st.exception(e); return False
246
-
247
- def get_saved_worlds():
248
- """Scans the saved worlds directory for MD files and parses them."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  try:
250
- ensure_dir(SAVED_WORLDS_DIR)
251
- world_files = glob.glob(os.path.join(SAVED_WORLDS_DIR, f"{WORLD_STATE_FILE_MD_PREFIX}*.md"))
252
- parsed_worlds = [parse_world_filename(f) for f in world_files]
253
- # Sort by datetime object if available (newest first)
254
- parsed_worlds.sort(key=lambda x: x['dt'] if x['dt'] else datetime.min.replace(tzinfo=pytz.utc), reverse=True)
255
- return parsed_worlds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  except Exception as e:
257
- print(f"Error scanning saved worlds: {e}")
258
- st.error(f"Could not scan saved worlds: {e}")
259
- return []
260
 
261
- # ==============================================================================
262
- # User State & Session Init
263
- # ==============================================================================
 
 
264
 
265
- def save_username(username):
266
- try:
267
- with open(STATE_FILE, 'w') as f: f.write(username)
268
- except Exception as e: print(f"Failed save username: {e}")
269
 
270
- def load_username():
271
- if os.path.exists(STATE_FILE):
272
- try:
273
- with open(STATE_FILE, 'r') as f: return f.read().strip()
274
- except Exception as e: print(f"Failed load username: {e}")
275
- return None
276
-
277
- def init_session_state():
278
- """Initializes Streamlit session state variables."""
279
- defaults = {
280
- 'server_running_flag': False, 'server_instance': None, 'server_task': None,
281
- 'active_connections': defaultdict(dict), 'last_chat_update': 0, 'message_input': "",
282
- 'audio_cache': {}, 'tts_voice': "en-US-AriaNeural", 'chat_history': [],
283
- 'marquee_settings': {"background": "#1E1E1E", "color": "#FFFFFF", "font-size": "14px", "animationDuration": "20s", "width": "100%", "lineHeight": "35px"},
284
- 'enable_audio': True, 'download_link_cache': {}, 'username': None, 'autosend': False,
285
- 'last_message': "", 'timer_start': time.time(), 'last_sent_transcript': "",
286
- 'last_refresh': time.time(), 'auto_refresh': False, 'refresh_rate': 30,
287
- 'selected_object': 'None', 'initial_world_state_loaded': False,
288
- 'current_world_file': None, # Track loaded world filename (basename)
289
- 'operation_timings': {}, 'performance_metrics': defaultdict(list),
290
- 'paste_image_base64': "", 'new_world_name': "MyWorld"
291
- }
292
- for k, v in defaults.items():
293
- if k not in st.session_state: st.session_state[k] = v
294
- # Ensure complex types initialized correctly
295
- if not isinstance(st.session_state.active_connections, defaultdict): st.session_state.active_connections = defaultdict(dict)
296
- if not isinstance(st.session_state.chat_history, list): st.session_state.chat_history = []
297
- if not isinstance(st.session_state.marquee_settings, dict): st.session_state.marquee_settings = defaults['marquee_settings']
298
- if not isinstance(st.session_state.audio_cache, dict): st.session_state.audio_cache = {}
299
- if not isinstance(st.session_state.download_link_cache, dict): st.session_state.download_link_cache = {}
300
-
301
- # ==============================================================================
302
- # Audio / TTS / Chat / File Handling Helpers
303
- # ==============================================================================
304
-
305
- # --- Text & File Helpers ---
306
- def clean_text_for_tts(text):
307
- if not isinstance(text, str): return "No text"
308
- text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text) # Remove markdown links, keep text
309
- text = re.sub(r'[#*_`!]', '', text) # Remove some markdown chars
310
- text = ' '.join(text.split()) # Normalize whitespace
311
- return text[:250] or "No text"
312
-
313
- def create_file(content, username, file_type="md", save_path=None):
314
- if not save_path:
315
- # Generate filename if specific path not given
316
- filename = generate_filename(content, username, file_type)
317
- save_path = os.path.join(MEDIA_DIR, filename) # Save to base dir by default
318
- ensure_dir(os.path.dirname(save_path)) # Ensure directory exists
319
- try:
320
- with open(save_path, 'w', encoding='utf-8') as f: f.write(content)
321
- print(f"Created file: {save_path}"); return save_path
322
- except Exception as e: print(f"Error creating file {save_path}: {e}"); return None
323
-
324
- def get_download_link(file_path, file_type="md"):
325
- """Generates a base64 download link for a given file."""
326
- if not file_path or not os.path.exists(file_path):
327
- basename = os.path.basename(file_path) if file_path else "N/A"
328
- return f"<small>Not found: {basename}</small>"
329
- try: mtime = os.path.getmtime(file_path)
330
- except OSError: mtime = 0
331
- cache_key = f"dl_{file_path}_{mtime}"
332
- if 'download_link_cache' not in st.session_state: st.session_state.download_link_cache = {}
333
- if cache_key not in st.session_state.download_link_cache:
334
- try:
335
- with open(file_path, "rb") as f: b64 = base64.b64encode(f.read()).decode()
336
- mime_types = {"md": "text/markdown", "mp3": "audio/mpeg", "png": "image/png", "mp4": "video/mp4", "zip": "application/zip", "json": "application/json"}
337
- basename = os.path.basename(file_path)
338
- link_html = f'<a href="data:{mime_types.get(file_type, "application/octet-stream")};base64,{b64}" download="{basename}">{FILE_EMOJIS.get(file_type, "📄")} DL</a>'
339
- st.session_state.download_link_cache[cache_key] = link_html
340
- except Exception as e:
341
- print(f"Error generating DL link for {file_path}: {e}")
342
- return f"<small>Err</small>"
343
- return st.session_state.download_link_cache.get(cache_key, "<small>CacheErr</small>")
344
-
345
- # --- Audio / TTS ---
346
- async def async_edge_tts_generate(text, voice, username):
347
- """Generates TTS audio using EdgeTTS and caches the result."""
348
- if not text: return None
349
- # Cache key based on text hash and voice
350
- cache_key = hashlib.md5(f"{text[:150]}_{voice}".encode()).hexdigest()
351
- if 'audio_cache' not in st.session_state: st.session_state.audio_cache = {}
352
- cached_path = st.session_state.audio_cache.get(cache_key)
353
- if cached_path and os.path.exists(cached_path): return cached_path
354
-
355
- text_cleaned = clean_text_for_tts(text);
356
- if not text_cleaned or text_cleaned == "No text": return None
357
- filename_base = generate_filename(text_cleaned, username, "mp3"); save_path = os.path.join(AUDIO_DIR, filename_base);
358
- ensure_dir(AUDIO_DIR)
359
- try:
360
- communicate = edge_tts.Communicate(text_cleaned, voice); await communicate.save(save_path);
361
- if os.path.exists(save_path) and os.path.getsize(save_path) > 0:
362
- st.session_state.audio_cache[cache_key] = save_path; return save_path
363
- else: print(f"Audio file {save_path} failed generation."); return None
364
- except Exception as e: print(f"Edge TTS Error: {e}"); return None
365
-
366
- def play_and_download_audio(file_path):
367
- """Displays audio player and download link in Streamlit."""
368
- if file_path and os.path.exists(file_path):
369
- try:
370
- st.audio(file_path)
371
- file_type = file_path.split('.')[-1]
372
- st.markdown(get_download_link(file_path, file_type), unsafe_allow_html=True)
373
- except Exception as e: st.error(f"Audio display error: {e}")
374
- else: st.warning(f"Audio file not found: {os.path.basename(file_path) if file_path else 'N/A'}")
375
-
376
- # --- Chat ---
377
- async def save_chat_entry(username, message, voice, is_markdown=False):
378
- """Saves chat entry to a file and session state, generates audio."""
379
- if not message.strip(): return None, None
380
- timestamp_str = get_current_time_str();
381
- entry = f"[{timestamp_str}] {username} ({voice}): {message}" if not is_markdown else f"[{timestamp_str}] {username} ({voice}):\n```markdown\n{message}\n```"
382
- md_filename_base = generate_filename(message, username, "md"); md_file_path = os.path.join(CHAT_DIR, md_filename_base); md_file = create_file(entry, username, "md", save_path=md_file_path)
383
- if 'chat_history' not in st.session_state: st.session_state.chat_history = [];
384
- st.session_state.chat_history.append(entry) # Add to live history
385
- audio_file = None;
386
- if st.session_state.get('enable_audio', True):
387
- tts_message = message # Use original message for TTS
388
- audio_file = await async_edge_tts_generate(tts_message, voice, username)
389
- return md_file, audio_file
390
-
391
- async def load_chat_history():
392
- """Loads chat history from files if session state is empty."""
393
- if 'chat_history' not in st.session_state: st.session_state.chat_history = []
394
- if not st.session_state.chat_history:
395
- ensure_dir(CHAT_DIR)
396
- print("Loading chat history from files...")
397
- chat_files = sorted(glob.glob(os.path.join(CHAT_DIR, "*.md")), key=os.path.getmtime); loaded_count = 0
398
- temp_history = []
399
- for f_path in chat_files:
400
- try:
401
- with open(f_path, 'r', encoding='utf-8') as file: temp_history.append(file.read().strip()); loaded_count += 1
402
- except Exception as e: print(f"Err read chat {f_path}: {e}")
403
- st.session_state.chat_history = temp_history
404
- print(f"Loaded {loaded_count} chat entries from files.")
405
- return st.session_state.chat_history
406
-
407
- # --- File Management ---
408
- def create_zip_of_files(files_to_zip, prefix="Archive"):
409
- if not files_to_zip: st.warning("No files provided to zip."); return None
410
- timestamp = format_timestamp_prefix(f"Zip_{prefix}"); zip_name = f"{prefix}_{timestamp}.zip"
411
- try:
412
- print(f"Creating zip: {zip_name}...");
413
- with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as z:
414
- for f in files_to_zip:
415
- if os.path.exists(f): z.write(f, os.path.basename(f))
416
- else: print(f"Skip zip missing: {f}")
417
- print("Zip success."); st.success(f"Created {zip_name}"); return zip_name
418
- except Exception as e: print(f"Zip failed: {e}"); st.error(f"Zip failed: {e}"); return None
419
-
420
- def delete_files(file_patterns, exclude_files=None):
421
- protected = [STATE_FILE, "app.py", "index.html", "requirements.txt", "README.md"]
422
- # Dynamically protect all currently saved world files unless explicitly targeted
423
- try:
424
- current_worlds = [os.path.basename(w['filename']) for w in get_saved_worlds()]
425
- protected.extend(current_worlds)
426
- except Exception: pass # Ignore if world listing fails
427
- if exclude_files: protected.extend(exclude_files)
428
-
429
- deleted_count = 0; errors = 0
430
- for pattern in file_patterns:
431
- pattern_path = os.path.join(MEDIA_DIR, pattern) # Assume relative to app dir
432
- try:
433
- files_to_delete = glob.glob(pattern_path)
434
- if not files_to_delete: continue
435
- for f_path in files_to_delete:
436
- basename = os.path.basename(f_path)
437
- # Check if it's a file and NOT protected
438
- if os.path.isfile(f_path) and basename not in protected:
439
- try: os.remove(f_path); print(f"Deleted: {f_path}"); deleted_count += 1
440
- except Exception as e: print(f"Failed delete {f_path}: {e}"); errors += 1
441
- elif os.path.isdir(f_path): print(f"Skipping directory: {f_path}")
442
- except Exception as glob_e: print(f"Err matching {pattern}: {glob_e}"); errors += 1
443
- msg = f"Deleted {deleted_count} files.";
444
- if errors > 0: msg += f" Encountered {errors} errors."; st.warning(msg)
445
- elif deleted_count > 0: st.success(msg)
446
- else: st.info("No matching files found to delete.")
447
- # Clear relevant caches
448
- st.session_state['download_link_cache'] = {}; st.session_state['audio_cache'] = {}
449
-
450
- # --- Image Handling ---
451
- async def save_pasted_image(image, username):
452
- if not image: return None
453
- try:
454
- img_hash = hashlib.md5(image.tobytes()).hexdigest()[:8]; timestamp = format_timestamp_prefix(username); filename = f"{timestamp}_pasted_{img_hash}.png"; filepath = os.path.join(MEDIA_DIR, filename)
455
- image.save(filepath, "PNG"); print(f"Pasted image saved: {filepath}"); return filepath
456
- except Exception as e: print(f"Failed image save: {e}"); return None
457
-
458
- def paste_image_component():
459
- pasted_img = None; img_type = None
460
- with st.form(key="paste_form"):
461
- paste_input = st.text_area("Paste Image Data Here (Ctrl+V)", key="paste_input_area", height=50); submit_button = st.form_submit_button("Paste Image 📋")
462
- if submit_button and paste_input and paste_input.startswith('data:image'):
463
- try:
464
- mime_type = paste_input.split(';')[0].split(':')[1]; base64_str = paste_input.split(',')[1]; img_bytes = base64.b64decode(base64_str); pasted_img = Image.open(io.BytesIO(img_bytes)); img_type = mime_type.split('/')[1]
465
- st.image(pasted_img, caption=f"Pasted ({img_type.upper()})", width=150); st.session_state.paste_image_base64 = base64_str
466
- except ImportError: st.error("Pillow library needed for image pasting.")
467
- except Exception as e: st.error(f"Img decode err: {e}"); st.session_state.paste_image_base64 = ""
468
- elif submit_button: st.warning("No valid img data."); st.session_state.paste_image_base64 = ""
469
- # Return the image object if successfully pasted and submitted
470
- return pasted_img if submit_button and pasted_img else None
471
-
472
-
473
- # --- PDF Processing ---
474
- # Note: Depends on PyPDF2 and potentially AudioProcessor class if generating audio
475
- class AudioProcessor:
476
- def __init__(self): self.cache_dir=AUDIO_CACHE_DIR; ensure_dir(self.cache_dir); self.metadata=json.load(open(f"{self.cache_dir}/metadata.json", 'r')) if os.path.exists(f"{self.cache_dir}/metadata.json") else {}
477
- def _save_metadata(self):
478
- try:
479
- with open(f"{self.cache_dir}/metadata.json", 'w') as f: json.dump(self.metadata, f, indent=2)
480
- except Exception as e: print(f"Failed metadata save: {e}")
481
- async def create_audio(self, text, voice='en-US-AriaNeural'):
482
- cache_key=hashlib.md5(f"{text[:150]}:{voice}".encode()).hexdigest(); cache_path=f"{self.cache_dir}/{cache_key}.mp3"
483
- if cache_key in self.metadata and os.path.exists(cache_path): return cache_path
484
- text_cleaned=clean_text_for_tts(text);
485
- if not text_cleaned: return None
486
- ensure_dir(os.path.dirname(cache_path))
487
- try:
488
- communicate=edge_tts.Communicate(text_cleaned,voice); await communicate.save(cache_path)
489
- if os.path.exists(cache_path) and os.path.getsize(cache_path) > 0:
490
- self.metadata[cache_key]={'timestamp': datetime.now().isoformat(), 'text_length': len(text_cleaned), 'voice': voice}; self._save_metadata()
491
- return cache_path
492
- else: return None
493
- except Exception as e: print(f"TTS Create Audio Error: {e}"); return None
494
-
495
- def process_pdf_tab(pdf_file, max_pages, voice):
496
- st.subheader("PDF Processing")
497
- if pdf_file is None:
498
- st.info("Upload a PDF file to begin.")
499
- return
500
- audio_processor = AudioProcessor() # Instance for this run
501
- try:
502
- reader=PdfReader(pdf_file); total_pages=min(len(reader.pages),max_pages);
503
- st.write(f"Processing first {total_pages} pages of '{pdf_file.name}'...")
504
- texts, audios={}, {}; page_threads = []; results_lock = threading.Lock()
505
-
506
- def process_page_sync(page_num, page_text):
507
- # Runs async audio generation in a separate thread
508
- async def run_async_audio(): return await audio_processor.create_audio(page_text, voice)
509
- try: audio_path = asyncio.run(run_async_audio());
510
- if audio_path:
511
- with results_lock: audios[page_num] = audio_path
512
- except Exception as page_e: print(f"Err process page {page_num+1}: {page_e}")
513
-
514
- # Start threads
515
- for i in range(total_pages):
516
- text=reader.pages[i].extract_text();
517
- if text: texts[i]=text; thread = threading.Thread(target=process_page_sync, args=(i, text)); page_threads.append(thread); thread.start()
518
- else: texts[i] = "[No text extracted]"
519
-
520
- # Display results as they become available (or after join)
521
- st.progress(0) # Placeholder for progress
522
- # Wait for threads and display - consider using st.empty() for updates
523
- for thread in page_threads: thread.join()
524
-
525
- for i in range(total_pages):
526
- with st.expander(f"Page {i+1}"):
527
- st.markdown(texts.get(i, "[Error getting text]"))
528
- audio_file = audios.get(i)
529
- if audio_file: play_and_download_audio(audio_file)
530
- else: st.caption("Audio generation failed or pending.")
531
-
532
- except Exception as pdf_e: st.error(f"Err read PDF: {pdf_e}"); st.exception(pdf_e)
533
-
534
-
535
- # ==============================================================================
536
- # WebSocket Server Logic
537
- # ==============================================================================
538
-
539
- async def register_client(websocket):
540
- client_id = str(websocket.id); connected_clients.add(client_id);
541
- if 'active_connections' not in st.session_state: st.session_state.active_connections = defaultdict(dict);
542
- st.session_state.active_connections[client_id] = websocket; print(f"Client registered: {client_id}. Total: {len(connected_clients)}")
543
-
544
- async def unregister_client(websocket):
545
- client_id = str(websocket.id); connected_clients.discard(client_id);
546
- if 'active_connections' in st.session_state: st.session_state.active_connections.pop(client_id, None);
547
- print(f"Client unregistered: {client_id}. Remaining: {len(connected_clients)}")
548
-
549
- async def send_safely(websocket, message, client_id):
550
- """Wrapper to send message and handle potential connection errors."""
551
- try: await websocket.send(message)
552
- except websockets.ConnectionClosed: print(f"WS Send failed (Closed) client {client_id}"); raise
553
- except RuntimeError as e: print(f"WS Send failed (Runtime {e}) client {client_id}"); raise
554
- except Exception as e: print(f"WS Send failed (Other {e}) client {client_id}"); raise
555
-
556
- async def broadcast_message(message, exclude_id=None):
557
- """Sends a message to all connected clients except the excluded one."""
558
- if not connected_clients: return
559
- tasks = []; current_client_ids = list(connected_clients); active_connections_copy = st.session_state.active_connections.copy()
560
- for client_id in current_client_ids:
561
- if client_id == exclude_id: continue
562
- websocket = active_connections_copy.get(client_id)
563
- if websocket: tasks.append(asyncio.create_task(send_safely(websocket, message, client_id)))
564
- if tasks: await asyncio.gather(*tasks, return_exceptions=True) # Gather results/exceptions
565
-
566
- async def broadcast_world_update():
567
- """Broadcasts the current world state to all clients."""
568
- with world_objects_lock: current_state_payload = dict(world_objects)
569
- update_msg = json.dumps({"type": "initial_state", "payload": current_state_payload}) # Force full refresh
570
- print(f"Broadcasting full world update ({len(current_state_payload)} objects)...")
571
- await broadcast_message(update_msg)
572
-
573
- async def websocket_handler(websocket, path):
574
- """Handles WebSocket connections and messages."""
575
- await register_client(websocket); client_id = str(websocket.id);
576
- username = st.session_state.get('username', f"User_{client_id[:4]}") # Get username for this session
577
- try: # Send initial state
578
- with world_objects_lock: initial_state_payload = dict(world_objects)
579
- initial_state_msg = json.dumps({"type": "initial_state", "payload": initial_state_payload}); await websocket.send(initial_state_msg)
580
- print(f"Sent initial state ({len(initial_state_payload)} objs) to {client_id}")
581
- await broadcast_message(json.dumps({"type": "user_join", "payload": {"username": username, "id": client_id}}), exclude_id=client_id)
582
- except Exception as e: print(f"Error initial phase {client_id}: {e}")
583
-
584
- try: # Message loop
585
- async for message in websocket:
586
- try:
587
- data = json.loads(message); msg_type = data.get("type"); payload = data.get("payload", {});
588
- # Use username from payload if provided, otherwise session username
589
- sender_username = payload.get("username", username)
590
-
591
- if msg_type == "chat_message":
592
- chat_text = payload.get('message', ''); voice = payload.get('voice', FUN_USERNAMES.get(sender_username, "en-US-AriaNeural"));
593
- # Schedule save/TTS, but broadcast immediately
594
- run_async(save_chat_entry, sender_username, chat_text, voice) # Fire and forget save
595
- await broadcast_message(message, exclude_id=client_id) # Forward original msg
596
-
597
- elif msg_type == "place_object":
598
- obj_data = payload.get("object_data");
599
- if obj_data and 'obj_id' in obj_data and 'type' in obj_data:
600
- with world_objects_lock: world_objects[obj_data['obj_id']] = obj_data
601
- broadcast_payload = json.dumps({"type": "object_placed", "payload": {"object_data": obj_data, "username": sender_username}});
602
- await broadcast_message(broadcast_payload, exclude_id=client_id)
603
- else: print(f"WS Invalid place_object payload: {payload}")
604
-
605
- elif msg_type == "delete_object":
606
- obj_id = payload.get("obj_id"); removed = False
607
- if obj_id:
608
- with world_objects_lock:
609
- if obj_id in world_objects: del world_objects[obj_id]; removed = True
610
- if removed:
611
- broadcast_payload = json.dumps({"type": "object_deleted", "payload": {"obj_id": obj_id, "username": sender_username}});
612
- await broadcast_message(broadcast_payload, exclude_id=client_id)
613
- else: print(f"WS Invalid delete_object payload: {payload}")
614
-
615
- elif msg_type == "player_position":
616
- pos_data = payload.get("position")
617
- rot_data = payload.get("rotation") # Optionally include rotation
618
- if pos_data:
619
- broadcast_payload = json.dumps({"type": "player_moved", "payload": {"username": sender_username, "id": client_id, "position": pos_data, "rotation": rot_data}});
620
- await broadcast_message(broadcast_payload, exclude_id=client_id)
621
-
622
- # Add more handlers here
623
-
624
- except json.JSONDecodeError: print(f"WS Invalid JSON from {client_id}: {message[:100]}...")
625
- except Exception as e: print(f"WS Error processing msg from {client_id}: {e}")
626
- except websockets.ConnectionClosed: print(f"WS Client disconnected: {client_id} ({username})")
627
- except Exception as e: print(f"WS Unexpected handler error {client_id}: {e}")
628
- finally:
629
- await broadcast_message(json.dumps({"type": "user_leave", "payload": {"username": username, "id": client_id}}), exclude_id=client_id);
630
- await unregister_client(websocket)
631
-
632
-
633
- async def run_websocket_server():
634
- """Coroutine to run the WebSocket server."""
635
- if st.session_state.get('server_running_flag', False): return
636
- st.session_state['server_running_flag'] = True; print("Attempting start WS server 0.0.0.0:8765...")
637
- stop_event = asyncio.Event(); st.session_state['websocket_stop_event'] = stop_event
638
- server = None
639
- try:
640
- server = await websockets.serve(websocket_handler, "0.0.0.0", 8765); st.session_state['server_instance'] = server
641
- print(f"WS server started: {server.sockets[0].getsockname()}. Waiting for stop signal...")
642
- await stop_event.wait() # Keep running
643
- except OSError as e: print(f"### FAILED START WS SERVER: {e}"); st.session_state['server_running_flag'] = False;
644
- except Exception as e: print(f"### UNEXPECTED WS SERVER ERROR: {e}"); st.session_state['server_running_flag'] = False;
645
- finally:
646
- print("WS server task finishing...");
647
- if server: server.close(); await server.wait_closed(); print("WS server closed.")
648
- st.session_state['server_running_flag'] = False; st.session_state['server_instance'] = None; st.session_state['websocket_stop_event'] = None
649
-
650
- def start_websocket_server_thread():
651
- """Starts the WebSocket server in a separate thread if not already running."""
652
- if st.session_state.get('server_task') and st.session_state.server_task.is_alive(): return
653
- if st.session_state.get('server_running_flag', False): return
654
- print("Creating/starting new server thread.");
655
- def run_loop():
656
- loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop)
657
- try: loop.run_until_complete(run_websocket_server())
658
- finally: loop.close(); print("Server thread loop closed.")
659
- st.session_state.server_task = threading.Thread(target=run_loop, daemon=True); st.session_state.server_task.start(); time.sleep(1.5)
660
- if not st.session_state.server_task.is_alive(): print("### Server thread failed to stay alive!")
661
-
662
-
663
- # ==============================================================================
664
- # Streamlit UI Layout
665
- # ==============================================================================
666
-
667
- def render_sidebar():
668
- """Renders the Streamlit sidebar contents."""
669
- with st.sidebar:
670
- st.header("💾 World Versions")
671
- st.caption("Load or save named world states.")
672
-
673
- # World Selector
674
- saved_worlds = get_saved_worlds()
675
- # Create display text mapping filename to formatted string
676
- world_options = {w['filename']: f"{w['name']} ({w['timestamp']})" for w in saved_worlds}
677
- # Get the currently selected filename (basename) from session state
678
- current_selection_basename = st.session_state.get('current_world_file', None)
679
-
680
- # Prepare options for radio button: None first, then filenames
681
- radio_options_list = [None] + [w['filename'] for w in saved_worlds] # Store full path initially? No, use basename.
682
- radio_options_basenames = [None] + [os.path.basename(w['filename']) for w in saved_worlds]
683
-
684
- # Find the index of the current selection in the options list
685
- current_radio_index = 0 # Default to "Live State"
686
- if current_selection_basename and current_selection_basename in radio_options_basenames:
687
- try:
688
- current_radio_index = radio_options_basenames.index(current_selection_basename)
689
- except ValueError:
690
- current_radio_index = 0 # Fallback if filename somehow not in list
691
-
692
- # Display radio buttons
693
- selected_basename = st.radio(
694
- "Load World:",
695
- options=radio_options_basenames,
696
- index=current_radio_index,
697
- format_func=lambda x: "Live State (Unsaved)" if x is None else world_options.get(os.path.join(SAVED_WORLDS_DIR, x), x), # Format using full path to get name/time? complex
698
- key="world_selector_radio"
699
- )
700
-
701
- # Handle selection change
702
- if selected_basename != current_selection_basename:
703
- st.session_state.current_world_file = selected_basename # Store basename
704
- if selected_basename:
705
- with st.spinner(f"Loading {selected_basename}..."):
706
- if load_world_state_from_md(selected_basename):
707
- run_async(broadcast_world_update) # Broadcast new state
708
- st.toast("World loaded!", icon="✅")
709
- else:
710
- st.error("Failed to load world."); st.session_state.current_world_file = None # Reset on failure
711
- else:
712
- print("Switched to live state.")
713
- # Optionally clear world or just stop tracking file? Stop tracking.
714
- # Maybe broadcast current live state if switching TO live?
715
- # run_async(broadcast_world_update) # Broadcast current live state
716
- st.toast("Switched to Live State.")
717
- st.rerun()
718
-
719
- # Display download links
720
- st.caption("Download:")
721
- cols = st.columns([3, 1]) # Columns for name and download button
722
- with cols[0]: st.write("**Name**")
723
- with cols[1]: st.write("**Link**")
724
- for world_info in saved_worlds:
725
- f_basename = os.path.basename(world_info['filename'])
726
- f_fullpath = world_info['filename'] # Full path needed for reading file
727
- display_name = world_info.get('name', f_basename)
728
- timestamp = world_info.get('timestamp', 'N/A')
729
- col1, col2 = st.columns([3, 1])
730
- with col1: st.write(f"<small>{display_name} ({timestamp})</small>", unsafe_allow_html=True)
731
- with col2: st.markdown(get_download_link(f_fullpath, "md"), unsafe_allow_html=True)
732
-
733
-
734
- st.markdown("---")
735
-
736
- # Save New Version moved to Files Tab
737
-
738
- # Build Tools section
739
- st.header("🏗️ Build Tools")
740
- st.caption("Select an object to place.")
741
- cols = st.columns(5)
742
- col_idx = 0
743
- current_tool = st.session_state.get('selected_object', 'None')
744
- for emoji, name in PRIMITIVE_MAP.items():
745
- button_key = f"primitive_{name}"; button_type = "primary" if current_tool == name else "secondary"
746
- if cols[col_idx % 5].button(emoji, key=button_key, help=name, type=button_type, use_container_width=True):
747
- if st.session_state.get('selected_object', 'None') != name:
748
- st.session_state.selected_object = name
749
- run_async(lambda: streamlit_js_eval(f"updateSelectedObjectType({json.dumps(name)});", key=f"update_tool_js_{name}")) # Fire-and-forget JS update
750
- st.rerun()
751
- col_idx += 1
752
- st.markdown("---")
753
- if st.button("🚫 Clear Tool", key="clear_tool", use_container_width=True):
754
- if st.session_state.get('selected_object', 'None') != 'None':
755
- st.session_state.selected_object = 'None'
756
- run_async(lambda: streamlit_js_eval("updateSelectedObjectType('None');", key="update_tool_js_none"))
757
- st.rerun()
758
-
759
- # Voice/User section
760
- st.markdown("---")
761
- st.header("🗣️ Voice & User")
762
- current_username = st.session_state.get('username', list(FUN_USERNAMES.keys())[0])
763
- username_options = list(FUN_USERNAMES.keys()); current_index = 0
764
- try: current_index = username_options.index(current_username)
765
- except ValueError: current_index = 0
766
- new_username = st.selectbox("Change Name/Voice", options=username_options, index=current_index, key="username_select", format_func=lambda x: x.split(" ")[0])
767
- if new_username != st.session_state.username:
768
- old_username = st.session_state.username
769
- change_msg = json.dumps({"type":"user_rename", "payload": {"old_username": old_username, "new_username": new_username}})
770
- run_async(broadcast_message, change_msg)
771
- st.session_state.username = new_username; st.session_state.tts_voice = FUN_USERNAMES[new_username]; save_username(st.session_state.username)
772
- st.rerun()
773
- st.session_state['enable_audio'] = st.toggle("Enable TTS Audio", value=st.session_state.get('enable_audio', True))
774
-
775
-
776
- def render_main_content():
777
- """Renders the main content area with tabs."""
778
- st.title(f"{Site_Name} - User: {st.session_state.username}")
779
-
780
- tab_world, tab_chat, tab_pdf, tab_files = st.tabs(["🏗️ World Builder", "🗣️ Chat", "📚 PDF Tools", "📂 Files & Settings"])
781
-
782
- # --- World Builder Tab ---
783
- with tab_world:
784
- st.header("Shared 3D World")
785
- st.caption("Place objects using the sidebar tools. Changes are shared live!")
786
- current_file = st.session_state.get('current_world_file', None)
787
- if current_file: parsed = parse_world_filename(current_file); st.info(f"Current World: **{parsed['name']}** (`{os.path.basename(current_file)}`)")
788
- else: st.info("Live State Active (Unsaved changes will be lost unless saved as new version)")
789
-
790
- # Embed HTML Component
791
- html_file_path = 'index.html'
792
- try:
793
- with open(html_file_path, 'r', encoding='utf-8') as f: html_template = f.read()
794
- try: # Get WS URL
795
- from streamlit.web.server.server import Server
796
- session_info = Server.get_current()._get_session_info(st.runtime.scriptrunner.get_script_run_ctx().session_id)
797
- server_host = session_info.ws.stream.request.host.split(':')[0]
798
- ws_url = f"ws://{server_host}:8765"
799
- except Exception: ws_url = "ws://localhost:8765"
800
-
801
- js_injection_script = f"""<script>
802
- window.USERNAME = {json.dumps(st.session_state.username)};
803
- window.WEBSOCKET_URL = {json.dumps(ws_url)};
804
  window.SELECTED_OBJECT_TYPE = {json.dumps(st.session_state.selected_object)};
805
  window.PLOT_WIDTH = {json.dumps(PLOT_WIDTH)};
806
  window.PLOT_DEPTH = {json.dumps(PLOT_DEPTH)};
807
- console.log("Streamlit State Injected:", {{ username: window.USERNAME, websocketUrl: window.WEBSOCKET_URL, selectedObject: window.SELECTED_OBJECT_TYPE }});
808
- </script>"""
809
- html_content_with_state = html_template.replace('</head>', js_injection_script + '\n</head>', 1)
810
- components.html(html_content_with_state, height=700, scrolling=False)
811
- except FileNotFoundError: st.error(f"CRITICAL ERROR: Could not find '{html_file_path}'.")
812
- except Exception as e: st.error(f"Error loading 3D component: {e}"); st.exception(e)
813
-
814
- # --- Chat Tab ---
815
- with tab_chat:
816
- st.header(f"{START_ROOM} Chat")
817
- chat_history = run_async(load_chat_history).result() if 'chat_history' not in st.session_state else st.session_state.chat_history # Load sync if needed
818
- chat_container = st.container(height=500)
819
- with chat_container:
820
- if chat_history: st.markdown("----\n".join(reversed(chat_history[-50:])))
821
- else: st.caption("No chat messages yet.")
822
-
823
- # Chat Input Area
824
- message_value = st.text_input("Your Message:", key="message_input", label_visibility="collapsed")
825
- send_button_clicked = st.button("Send Chat 💬", key="send_chat_button")
826
- should_autosend = st.session_state.get('autosend', False) and message_value
827
-
828
- if send_button_clicked or should_autosend:
829
- message_to_send = message_value
830
- if message_to_send.strip() and message_to_send != st.session_state.get('last_message', ''):
831
- st.session_state.last_message = message_to_send
832
- voice = FUN_USERNAMES.get(st.session_state.username, "en-US-AriaNeural")
833
- ws_message = json.dumps({"type": "chat_message", "payload": {"username": st.session_state.username, "message": message_to_send, "voice": voice}})
834
- run_async(broadcast_message, ws_message) # Send via WS
835
- run_async(save_chat_entry, st.session_state.username, message_to_send, voice) # Save locally
836
- st.session_state.message_input = "" # Clear state for next run
837
- st.rerun()
838
- elif send_button_clicked: st.toast("Message empty or same as last.")
839
-
840
- st.checkbox("Autosend Chat", key="autosend") # Toggle autosend
841
-
842
- # --- PDF Tab ---
843
- with tab_pdf:
844
- st.header("📚 PDF Tools")
845
- pdf_file = st.file_uploader("Upload PDF for Audio Conversion", type="pdf", key="pdf_upload")
846
- max_pages = st.slider('Max Pages to Process', 1, 50, 10, key="pdf_pages") # Limit pages
847
- if pdf_file:
848
- process_pdf_tab(pdf_file, max_pages, st.session_state.tts_voice)
849
-
850
-
851
- # --- Files & Settings Tab ---
852
- with tab_files:
853
- st.header("📂 Files & Settings")
854
- st.subheader("💾 World State Management")
855
- current_file = st.session_state.get('current_world_file', None)
856
-
857
- # Save Current Version Button
858
- if current_file:
859
- parsed = parse_world_filename(current_file); save_label = f"Save Changes to '{parsed['name']}'"
860
- if st.button(save_label, key="save_current_world", help=f"Overwrite '{os.path.basename(current_file)}' with current live state."):
861
- with st.spinner(f"Overwriting {os.path.basename(current_file)}..."):
862
- if save_world_state_to_md(current_file): st.success("Current world version saved!")
863
- else: st.error("Failed to save world state.")
864
- else:
865
- st.info("Load a world version from the sidebar or use 'Save New Version' below to save the current live state.")
866
-
867
- # Save As New Version Section
868
- st.subheader("Save As New Version")
869
- new_name_files = st.text_input("New World Name:", key="new_world_name_files") # Use different key from sidebar one if kept there
870
- if st.button("💾 Save Live State as New Version", key="save_new_version_files"):
871
- if new_name_files.strip():
872
- new_filename = generate_world_save_filename(new_name_files) # Generates basename
873
- with st.spinner(f"Saving new version '{new_name_files}'..."):
874
- if save_world_state_to_md(new_filename): # Pass basename
875
- st.success(f"Saved as {new_filename}")
876
- st.session_state.current_world_file = new_filename # Switch to new file automatically
877
- st.session_state.new_world_name_files = "" # Reset input
878
- st.rerun()
879
- else: st.error("Failed to save new version.")
880
- else: st.warning("Please enter a name for the new world version.")
881
-
882
- st.subheader("⚙️ Server Status")
883
- col_ws, col_clients = st.columns(2)
884
- with col_ws:
885
- server_alive = st.session_state.get('server_task') and st.session_state.server_task.is_alive(); ws_status = "Running" if server_alive else "Stopped"; st.metric("WebSocket Server", ws_status)
886
- if not server_alive and st.button("Restart Server Thread", key="restart_ws"): start_websocket_server_thread(); st.rerun()
887
- with col_clients: st.metric("Connected Clients", len(connected_clients))
888
-
889
- # File Deletion
890
- st.subheader("🗑️ Delete Files")
891
- st.warning("Deletion is permanent!", icon="⚠️")
892
- col_del1, col_del2, col_del3, col_del4 = st.columns(4)
893
- with col_del1:
894
- if st.button("🗑️ Chats", key="del_chat_md"): delete_files([os.path.join(CHAT_DIR, "*.md")]); st.session_state.chat_history = []; st.rerun()
895
- with col_del2:
896
- if st.button("🗑️ Audio", key="del_audio_mp3"): delete_files([os.path.join(AUDIO_DIR, "*.mp3"), os.path.join(AUDIO_CACHE_DIR, "*.mp3")]); st.session_state.audio_cache = {}; st.rerun()
897
- with col_del3:
898
- if st.button("🗑️ Worlds", key="del_worlds_md", help="Deletes world save files (.md) in saved_worlds"): delete_files([os.path.join(SAVED_WORLDS_DIR, f"{WORLD_STATE_FILE_MD_PREFIX}*.md")]); st.session_state.current_world_file = None; st.rerun()
899
- with col_del4:
900
- if st.button("🗑️ All Gen", key="del_all_gen", help="Deletes Chats, Audio, Worlds, Zips"): 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"]); st.session_state.chat_history = []; st.session_state.audio_cache = {}; st.session_state.current_world_file = None; st.rerun()
901
-
902
- # Download Archives
903
- st.subheader("📦 Download Archives")
904
- zip_files = sorted(glob.glob("*.zip"), key=os.path.getmtime, reverse=True)
905
- if zip_files:
906
- for zip_file in zip_files: st.markdown(get_download_link(zip_file, "zip"), unsafe_allow_html=True)
907
- else: st.caption("No zip archives found.")
908
-
909
-
910
- # ==============================================================================
911
- # Main Execution Logic
912
- # ==============================================================================
913
-
914
- def initialize_world():
915
- """Loads initial world state (most recent) if not already loaded."""
916
- if not st.session_state.get('initial_world_state_loaded', False):
917
- print("Performing initial world load...")
918
- saved_worlds = get_saved_worlds()
919
- if saved_worlds:
920
- latest_world_file_basename = os.path.basename(saved_worlds[0]['filename'])
921
- print(f"Loading most recent world on startup: {latest_world_file_basename}")
922
- load_world_state_from_md(latest_world_file_basename) # This updates global state and sets session state 'current_world_file'
923
- else:
924
- print("No saved worlds found, starting with empty state.")
925
- with world_objects_lock: world_objects.clear() # Ensure empty state
926
- st.session_state.current_world_file = None # Ensure no file is marked as loaded
927
- st.session_state.initial_world_state_loaded = True
928
- print("Initial world load complete.")
929
-
930
-
931
- if __name__ == "__main__":
932
- # 1. Initialize session state first
933
- init_session_state()
934
-
935
- # 2. Start WebSocket server thread if needed
936
- # Use server_running_flag to prevent multiple start attempts within one session
937
- if not st.session_state.get('server_running_flag', False):
938
- if 'server_task' not in st.session_state or not st.session_state.server_task.is_alive():
939
- start_websocket_server_thread()
940
- else:
941
- # If task exists but flag is false, maybe update flag?
942
- if st.session_state.server_task.is_alive():
943
- st.session_state.server_running_flag = True
944
- print("Corrected server_running_flag based on alive thread.")
945
-
946
-
947
- # 3. Load initial world state from disk if needed
948
- initialize_world()
949
-
950
- # 4. Render the UI (Sidebar and Main Content)
951
- render_sidebar()
952
- render_main_content()
 
1
+ # app.py
2
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
3
  import streamlit.components.v1 as components
4
+ import os
 
 
 
 
 
 
5
  import json
6
+ import pandas as pd
7
+ import uuid
8
+ import math # For floor function
9
+ # from PIL import Image, ImageDraw # No longer needed for minimap
10
+ from streamlit_js_eval import streamlit_js_eval # For JS communication
11
+
12
+ # --- Constants ---
13
+ SAVE_DIR = "saved_worlds"
14
+ PLOT_WIDTH = 50.0 # Width of each plot in 3D space
15
+ PLOT_DEPTH = 50.0 # Depth of each plot (can be same as width)
16
+ CSV_COLUMNS = ['obj_id', 'type', 'pos_x', 'pos_y', 'pos_z', 'rot_x', 'rot_y', 'rot_z', 'rot_order']
17
+
18
+ # --- Ensure Save Directory Exists ---
19
+ os.makedirs(SAVE_DIR, exist_ok=True)
20
+
21
+ # --- Helper Functions ---
22
+
23
+ @st.cache_data(ttl=3600) # Cache plot list
24
+ def load_plot_metadata():
25
+ """Scans save dir for plot_X*_Z*.csv, sorts, calculates metadata."""
26
+ plots = []
27
+ plot_files = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  try:
29
+ plot_files = [f for f in os.listdir(SAVE_DIR) if f.endswith(".csv") and f.startswith("plot_X")]
30
+ except FileNotFoundError:
31
+ st.error(f"Save directory '{SAVE_DIR}' not found.")
32
+ return []
 
 
33
  except Exception as e:
34
+ st.error(f"Error listing save directory '{SAVE_DIR}': {e}")
35
+ return []
 
36
 
37
+ # Parse filenames to get grid coordinates
38
+ parsed_plots = []
39
+ for filename in plot_files:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  try:
41
+ parts = filename[:-4].split('_') # Remove .csv
42
+ grid_x = int(parts[1][1:]) # Extract number after X
43
+ grid_z = int(parts[2][1:]) # Extract number after Z
44
+ # Extract name if present (parts after Z coordinate)
45
+ plot_name = " ".join(parts[3:]) if len(parts) > 3 else f"Plot ({grid_x},{grid_z})"
46
+
47
+ parsed_plots.append({
48
+ 'id': filename[:-4], # Use filename base as unique ID
49
+ 'filename': filename,
50
+ 'grid_x': grid_x,
51
+ 'grid_z': grid_z,
52
+ 'name': plot_name,
53
+ 'x_offset': grid_x * PLOT_WIDTH,
54
+ 'z_offset': grid_z * PLOT_DEPTH # Use PLOT_DEPTH for Z offset
55
+ })
56
+ except (IndexError, ValueError):
57
+ st.warning(f"Could not parse grid coordinates from filename: {filename}. Skipping.")
58
+ continue
59
+
60
+ # Sort primarily by X, then by Z
61
+ parsed_plots.sort(key=lambda p: (p['grid_x'], p['grid_z']))
62
+
63
+ return parsed_plots
64
+
65
+ def load_plot_objects(filename, x_offset, z_offset):
66
+ """Loads objects from a CSV, applying the plot's world offsets."""
67
+ file_path = os.path.join(SAVE_DIR, filename)
68
+ objects = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  try:
70
+ df = pd.read_csv(file_path)
71
+ # Check required columns
72
+ if not all(col in df.columns for col in ['type', 'pos_x', 'pos_y', 'pos_z']):
73
+ st.warning(f"CSV '{filename}' missing essential columns. Skipping.")
74
+ return []
75
+ # Add defaults for optional columns
76
+ df['obj_id'] = df.get('obj_id', pd.Series([str(uuid.uuid4()) for _ in range(len(df))]))
77
+ for col, default in [('rot_x', 0.0), ('rot_y', 0.0), ('rot_z', 0.0), ('rot_order', 'XYZ')]:
78
+ if col not in df.columns: df[col] = default
79
+
80
+ for _, row in df.iterrows():
81
+ obj_data = row.to_dict()
82
+ # Apply world offset
83
+ obj_data['pos_x'] += x_offset
84
+ obj_data['pos_z'] += z_offset # Apply Z offset too
85
+ objects.append(obj_data)
86
+ return objects
87
+ except FileNotFoundError:
88
+ st.error(f"File not found during object load: {filename}")
89
+ return []
90
+ except pd.errors.EmptyDataError:
91
+ return [] # Empty file is valid
92
+ except Exception as e:
93
+ st.error(f"Error loading objects from {filename}: {e}")
94
+ return []
95
+
96
+ def save_plot_data(filename, objects_data_list, plot_x_offset, plot_z_offset):
97
+ """Saves object data list to a CSV, making positions relative to plot origin."""
98
+ file_path = os.path.join(SAVE_DIR, filename)
99
+ relative_objects = []
100
+ if not isinstance(objects_data_list, list):
101
+ st.error("Invalid data format received for saving (expected a list).")
 
 
 
 
 
 
 
 
 
102
  return False
103
 
104
+ for obj in objects_data_list:
105
+ pos = obj.get('position', {})
106
+ rot = obj.get('rotation', {})
107
+ obj_type = obj.get('type', 'Unknown')
108
+ obj_id = obj.get('obj_id', str(uuid.uuid4()))
109
+
110
+ if not all(k in pos for k in ['x', 'y', 'z']) or obj_type == 'Unknown':
111
+ print(f"Skipping malformed object during save prep: {obj}")
112
+ continue
113
+
114
+ relative_obj = {
115
+ 'obj_id': obj_id, 'type': obj_type,
116
+ 'pos_x': pos.get('x', 0.0) - plot_x_offset, # Make relative X
117
+ 'pos_y': pos.get('y', 0.0),
118
+ 'pos_z': pos.get('z', 0.0) - plot_z_offset, # Make relative Z
119
+ 'rot_x': rot.get('_x', 0.0), 'rot_y': rot.get('_y', 0.0), 'rot_z': rot.get('_z', 0.0),
120
+ 'rot_order': rot.get('_order', 'XYZ')
121
+ }
122
+ relative_objects.append(relative_obj)
123
+
124
  try:
125
+ df = pd.DataFrame(relative_objects, columns=CSV_COLUMNS)
126
+ df.to_csv(file_path, index=False)
127
+ st.success(f"Saved {len(relative_objects)} objects to {filename}")
 
 
 
 
 
 
 
 
 
 
128
  return True
129
+ except Exception as e:
130
+ st.error(f"Failed to save plot data to {filename}: {e}")
131
+ return False
132
 
133
+ # --- Page Config ---
134
+ st.set_page_config( page_title="Infinite World Builder", layout="wide")
135
+
136
+ # --- Initialize Session State ---
137
+ if 'selected_object' not in st.session_state: st.session_state.selected_object = 'None'
138
+ if 'new_plot_name' not in st.session_state: st.session_state.new_plot_name = "" # No longer used for filename
139
+ if 'js_save_data_result' not in st.session_state: st.session_state.js_save_data_result = None
140
+
141
+ # --- Load Plot Metadata ---
142
+ # This is now the source of truth for saved plots
143
+ plots_metadata = load_plot_metadata()
144
+
145
+ # --- Load ALL Objects for Rendering ---
146
+ all_initial_objects = []
147
+ for plot in plots_metadata:
148
+ all_initial_objects.extend(load_plot_objects(plot['filename'], plot['x_offset'], plot['z_offset']))
149
+
150
+ # --- Sidebar ---
151
+ with st.sidebar:
152
+ st.title("🏗️ World Controls")
153
+
154
+ st.header("Navigation (Plots)")
155
+ st.caption("Click to teleport player to a plot.")
156
+ max_cols = 2 # Adjust columns for potentially more buttons
157
+ cols = st.columns(max_cols)
158
+ col_idx = 0
159
+ # Sort buttons by grid coords for logical layout
160
+ sorted_plots_for_nav = sorted(plots_metadata, key=lambda p: (p['grid_x'], p['grid_z']))
161
+ for plot in sorted_plots_for_nav:
162
+ button_label = f"➡️ {plot.get('name', plot['id'])} ({plot['grid_x']},{plot['grid_z']})"
163
+ if cols[col_idx].button(button_label, key=f"nav_{plot['id']}"):
164
+ target_x = plot['x_offset']
165
+ target_z = plot['z_offset'] # Use Z offset too
166
+ try:
167
+ # Tell JS where to teleport (center of plot approx)
168
+ js_code = f"teleportPlayer({target_x + PLOT_WIDTH/2}, {target_z + PLOT_DEPTH/2});"
169
+ streamlit_js_eval(js_code=js_code, key=f"teleport_{plot['id']}")
170
+ except Exception as e:
171
+ st.error(f"Failed to send teleport command: {e}")
172
+ col_idx = (col_idx + 1) % max_cols
173
+
174
+ st.markdown("---")
175
+
176
+ # --- Object Placement ---
177
+ st.header("Place Objects")
178
+ object_types = ["None", "Simple House", "Tree", "Rock", "Fence Post"]
179
+ current_object_index = object_types.index(st.session_state.selected_object) if st.session_state.selected_object in object_types else 0
180
+ selected_object_type_widget = st.selectbox(
181
+ "Select Object:", options=object_types, index=current_object_index, key="selected_object_widget"
182
+ )
183
+ if selected_object_type_widget != st.session_state.selected_object:
184
+ st.session_state.selected_object = selected_object_type_widget
185
+ # Rerun will happen, JS reloads state via sessionStorage, Python injects new selection
186
+
187
+ st.markdown("---")
188
+
189
+ # --- Saving ---
190
+ st.header("Save Work")
191
+ st.caption("Saves newly placed objects to the plot the player is currently in. If it's a new area, a new plot file is created.")
192
+ if st.button("💾 Save Current Work", key="save_button"):
193
+ # Trigger JS to get data AND player position
194
+ js_get_data_code = "getSaveDataAndPosition();" # JS function needs update
195
+ streamlit_js_eval(js_code=js_get_data_code, key="js_save_processor")
196
+ st.rerun() # Rerun to process result
197
+
198
+
199
+ # --- Process Save Data ---
200
+ save_data_from_js = st.session_state.get("js_save_processor", None)
201
+
202
+ if save_data_from_js is not None:
203
+ st.info("Received save data from client...")
204
+ save_processed_successfully = False
205
  try:
206
+ # Expecting { playerPosition: {x,y,z}, objectsToSave: [...] }
207
+ payload = json.loads(save_data_from_js) if isinstance(save_data_from_js, str) else save_data_from_js
208
+
209
+ if isinstance(payload, dict) and 'playerPosition' in payload and 'objectsToSave' in payload:
210
+ player_pos = payload['playerPosition']
211
+ objects_to_save = payload['objectsToSave']
212
+
213
+ if isinstance(objects_to_save, list): # Allow saving empty list (clears new objects)
214
+ # Determine target plot based on player position
215
+ target_grid_x = math.floor(player_pos.get('x', 0.0) / PLOT_WIDTH)
216
+ target_grid_z = math.floor(player_pos.get('z', 0.0) / PLOT_DEPTH) # Use Z pos too
217
+
218
+ target_filename = f"plot_X{target_grid_x}_Z{target_grid_z}.csv"
219
+ target_plot_x_offset = target_grid_x * PLOT_WIDTH
220
+ target_plot_z_offset = target_grid_z * PLOT_DEPTH
221
+
222
+ st.write(f"Attempting to save plot: {target_filename} (Player at: x={player_pos.get('x', 0):.1f}, z={player_pos.get('z', 0):.1f})")
223
+
224
+ # Check if this plot already exists in metadata (for logging/future logic)
225
+ is_new_plot_file = not os.path.exists(os.path.join(SAVE_DIR, target_filename))
226
+
227
+ save_ok = save_plot_data(target_filename, objects_to_save, target_plot_x_offset, target_plot_z_offset)
228
+
229
+ if save_ok:
230
+ load_plot_metadata.clear() # Clear cache to force reload metadata
231
+ try: # Tell JS to clear its unsaved state
232
+ streamlit_js_eval(js_code="resetNewlyPlacedObjects();", key="reset_js_state")
233
+ except Exception as js_e:
234
+ st.warning(f"Could not reset JS state after save: {js_e}")
235
+
236
+ if is_new_plot_file:
237
+ st.success(f"New plot created and saved: {target_filename}")
238
+ else:
239
+ st.success(f"Updated existing plot: {target_filename}")
240
+ save_processed_successfully = True
241
+ else:
242
+ st.error(f"Failed to save plot data to file: {target_filename}")
243
+ else:
244
+ st.error("Invalid 'objectsToSave' format received (expected list).")
245
+ else:
246
+ st.error("Invalid save payload structure received from client.")
247
+ print("Received payload:", payload) # Log for debugging
248
+
249
+ except json.JSONDecodeError:
250
+ st.error("Failed to decode save data from client.")
251
+ print("Received raw data:", save_data_from_js)
252
  except Exception as e:
253
+ st.error(f"Error processing save: {e}")
254
+ st.exception(e)
 
255
 
256
+ # Clear the trigger data from session state
257
+ st.session_state.js_save_processor = None
258
+ # Rerun after processing to reflect changes
259
+ if save_processed_successfully:
260
+ st.rerun()
261
 
 
 
 
 
262
 
263
+ # --- Main Area ---
264
+ st.header("Infinite Shared 3D World")
265
+ st.caption("Move to empty areas to expand the world. Use sidebar 'Save' to save work to current plot.")
266
+
267
+ # --- Load and Prepare HTML ---
268
+ html_file_path = 'index.html'
269
+ html_content_with_state = None
270
+
271
+ try:
272
+ with open(html_file_path, 'r', encoding='utf-8') as f:
273
+ html_template = f.read()
274
+
275
+ # --- Inject Python state into JavaScript ---
276
+ js_injection_script = f"""
277
+ <script>
278
+ window.ALL_INITIAL_OBJECTS = {json.dumps(all_initial_objects)};
279
+ window.PLOTS_METADATA = {json.dumps(plots_metadata)}; // Send plot info to JS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  window.SELECTED_OBJECT_TYPE = {json.dumps(st.session_state.selected_object)};
281
  window.PLOT_WIDTH = {json.dumps(PLOT_WIDTH)};
282
  window.PLOT_DEPTH = {json.dumps(PLOT_DEPTH)};
283
+ console.log("Streamlit State Injected:", {{
284
+ selectedObject: window.SELECTED_OBJECT_TYPE,
285
+ initialObjectsCount: window.ALL_INITIAL_OBJECTS ? window.ALL_INITIAL_OBJECTS.length : 0,
286
+ plotCount: window.PLOTS_METADATA ? window.PLOTS_METADATA.length : 0,
287
+ plotWidth: window.PLOT_WIDTH,
288
+ plotDepth: window.PLOT_DEPTH
289
+ }});
290
+ </script>
291
+ """
292
+ html_content_with_state = html_template.replace('</head>', js_injection_script + '\n</head>', 1)
293
+
294
+ # --- Embed HTML Component ---
295
+ components.html(
296
+ html_content_with_state,
297
+ height=750,
298
+ scrolling=False
299
+ )
300
+
301
+ except FileNotFoundError:
302
+ st.error(f"CRITICAL ERROR: Could not find the file '{html_file_path}'.")
303
+ st.warning(f"Make sure `{html_file_path}` is in the same directory as `app.py` and `{SAVE_DIR}` exists.")
304
+ except Exception as e:
305
+ st.error(f"An critical error occurred during HTML preparation or component rendering: {e}")
306
+ st.exception(e)