awacke1 commited on
Commit
41c1a97
·
verified ·
1 Parent(s): 306b4d6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from PIL import Image, ImageDraw # For minimap (using buttons instead now)
9
+ from streamlit_js_eval import streamlit_js_eval, sync # For JS communication
10
+
11
+ # --- Constants ---
12
+ SAVE_DIR = "saved_worlds"
13
+ PLOT_WIDTH = 50.0 # Width of each plot in 3D space (adjust as needed)
14
+ CSV_COLUMNS = ['obj_id', 'type', 'pos_x', 'pos_y', 'pos_z', 'rot_x', 'rot_y', 'rot_z', 'rot_order']
15
+
16
+ # --- Ensure Save Directory Exists ---
17
+ os.makedirs(SAVE_DIR, exist_ok=True)
18
+
19
+ # --- Helper Functions ---
20
+
21
+ @st.cache_data(ttl=3600) # Cache plot list for an hour, or clear manually
22
+ def load_plot_metadata():
23
+ """Scans save dir, sorts plots, calculates metadata."""
24
+ plots = []
25
+ plot_files = sorted([f for f in os.listdir(SAVE_DIR) if f.endswith(".csv")])
26
+
27
+ current_x_offset = 0.0
28
+ for i, filename in enumerate(plot_files):
29
+ # Extract name - assumes format like 'plot_001_MyName.csv' or just 'plot_001.csv'
30
+ parts = filename[:-4].split('_') # Remove .csv and split by underscore
31
+ plot_id = parts[0] # Assume first part is ID/order
32
+ plot_name = " ".join(parts[1:]) if len(parts) > 1 else f"Plot {i+1}"
33
+
34
+ plots.append({
35
+ 'id': plot_id,
36
+ 'name': plot_name,
37
+ 'filename': filename,
38
+ 'x_offset': current_x_offset
39
+ })
40
+ current_x_offset += PLOT_WIDTH
41
+ return plots, current_x_offset # Return plots and the next available offset
42
+
43
+ def load_plot_objects(filename, x_offset):
44
+ """Loads objects from a CSV, applying the plot's x_offset."""
45
+ file_path = os.path.join(SAVE_DIR, filename)
46
+ objects = []
47
+ try:
48
+ df = pd.read_csv(file_path)
49
+ if not all(col in df.columns for col in CSV_COLUMNS):
50
+ st.warning(f"CSV '{filename}' missing expected columns. Skipping.")
51
+ return []
52
+
53
+ for _, row in df.iterrows():
54
+ obj_data = row.to_dict()
55
+ # Apply world offset
56
+ obj_data['pos_x'] += x_offset
57
+ objects.append(obj_data)
58
+ return objects
59
+ except FileNotFoundError:
60
+ st.error(f"File not found during object load: {filename}")
61
+ return []
62
+ except pd.errors.EmptyDataError:
63
+ st.info(f"Plot file '{filename}' is empty.")
64
+ return [] # Empty file is valid
65
+ except Exception as e:
66
+ st.error(f"Error loading objects from {filename}: {e}")
67
+ return []
68
+
69
+
70
+ def save_plot_data(filename, objects_data_list, plot_x_offset):
71
+ """Saves object data list to a new CSV file, making positions relative."""
72
+ file_path = os.path.join(SAVE_DIR, filename)
73
+ relative_objects = []
74
+ for obj in objects_data_list:
75
+ # Ensure required fields exist before proceeding
76
+ if not all(k in obj for k in ['position', 'rotation', 'type', 'obj_id']):
77
+ print(f"Skipping malformed object during save: {obj}")
78
+ continue
79
+
80
+ relative_obj = {
81
+ 'obj_id': obj.get('obj_id', str(uuid.uuid4())), # Generate ID if missing
82
+ 'type': obj.get('type', 'Unknown'),
83
+ 'pos_x': obj['position'].get('x', 0.0) - plot_x_offset, # Make relative
84
+ 'pos_y': obj['position'].get('y', 0.0),
85
+ 'pos_z': obj['position'].get('z', 0.0),
86
+ 'rot_x': obj['rotation'].get('_x', 0.0),
87
+ 'rot_y': obj['rotation'].get('_y', 0.0),
88
+ 'rot_z': obj['rotation'].get('_z', 0.0),
89
+ 'rot_order': obj['rotation'].get('_order', 'XYZ')
90
+ }
91
+ relative_objects.append(relative_obj)
92
+
93
+ try:
94
+ df = pd.DataFrame(relative_objects, columns=CSV_COLUMNS)
95
+ df.to_csv(file_path, index=False)
96
+ st.success(f"Saved plot data to {filename}")
97
+ return True
98
+ except Exception as e:
99
+ st.error(f"Failed to save plot data to {filename}: {e}")
100
+ return False
101
+
102
+ # --- Page Config ---
103
+ st.set_page_config(
104
+ page_title="Shared World Builder",
105
+ layout="wide"
106
+ )
107
+
108
+ # --- Initialize Session State ---
109
+ if 'selected_object' not in st.session_state:
110
+ st.session_state.selected_object = 'None'
111
+ if 'new_plot_name' not in st.session_state:
112
+ st.session_state.new_plot_name = ""
113
+ if 'save_request_data' not in st.session_state: # To store data back from JS
114
+ st.session_state.save_request_data = None
115
+
116
+ # --- Load Plot Metadata ---
117
+ # Cached function returns list of plots and the next starting x_offset
118
+ plots_metadata, next_plot_x_offset = load_plot_metadata()
119
+
120
+ # --- Load ALL Objects for Rendering ---
121
+ # This could be slow with many plots! Consider optimization later.
122
+ all_initial_objects = []
123
+ for plot in plots_metadata: