Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,181 +1,51 @@
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
-
from
|
3 |
-
import
|
|
|
|
|
|
|
|
|
|
|
4 |
import time
|
5 |
-
import os
|
6 |
import random
|
7 |
-
import
|
8 |
-
import requests # To simulate API calls (though we won't make real ones here)
|
9 |
-
import uuid # For job IDs
|
10 |
-
|
11 |
-
# ------------------------------------------------------------------------------
|
12 |
-
# Page Configuration
|
13 |
-
# ------------------------------------------------------------------------------
|
14 |
-
st.set_page_config(
|
15 |
-
page_title="AI Real Estate Visualization Suite [PRO]",
|
16 |
-
layout="wide",
|
17 |
-
page_icon="π",
|
18 |
-
initial_sidebar_state="expanded"
|
19 |
-
)
|
20 |
-
|
21 |
-
# ------------------------------------------------------------------------------
|
22 |
-
# Simulated Backend API Interaction
|
23 |
-
# ------------------------------------------------------------------------------
|
24 |
-
# Replace with your actual backend API endpoint
|
25 |
-
BACKEND_API_URL = "http://your-production-backend.com/api/v1/visualize"
|
26 |
-
# Replace with your actual status check endpoint
|
27 |
-
STATUS_API_URL = "http://your-production-backend.com/api/v1/status/{job_id}"
|
28 |
-
|
29 |
-
# --- Simulate API Call ---
|
30 |
-
def submit_visualization_job(payload: dict) -> tuple[str | None, str | None]:
|
31 |
-
"""
|
32 |
-
Simulates submitting a job to the backend API.
|
33 |
-
In reality, this would use 'requests.post'.
|
34 |
-
|
35 |
-
Args:
|
36 |
-
payload (dict): Data to send (params, input reference, etc.)
|
37 |
-
|
38 |
-
Returns:
|
39 |
-
tuple[str | None, str | None]: (job_id, error_message)
|
40 |
-
"""
|
41 |
-
st.info("Submitting job to backend simulation...")
|
42 |
-
print(f"SIMULATING API SUBMIT to {BACKEND_API_URL}")
|
43 |
-
print("Payload (summary):")
|
44 |
-
print(f" Mode: {payload.get('output_mode')}")
|
45 |
-
print(f" Style: {payload.get('style')}")
|
46 |
-
print(f" Input Type: {payload.get('input_type')}")
|
47 |
-
# Omit potentially large data like image bytes from console log in real scenario
|
48 |
-
# print(json.dumps(payload, indent=2)) # Don't print potentially large data
|
49 |
-
|
50 |
-
# Simulate network latency & backend processing start
|
51 |
-
time.sleep(1.5)
|
52 |
-
|
53 |
-
# Simulate success/failure
|
54 |
-
if random.random() < 0.95: # 95% success rate
|
55 |
-
job_id = f"job_{uuid.uuid4()}"
|
56 |
-
print(f"API Submit Simulation SUCCESS: Job ID = {job_id}")
|
57 |
-
# In a real app, store job_id associated with user/session
|
58 |
-
return job_id, None
|
59 |
-
else:
|
60 |
-
error_msg = "Simulated API Error: Failed to submit job (e.g., server busy, invalid params)."
|
61 |
-
print(f"API Submit Simulation FAILED: {error_msg}")
|
62 |
-
return None, error_msg
|
63 |
-
|
64 |
-
# --- Simulate Status Check ---
|
65 |
-
def check_job_status(job_id: str) -> tuple[str, str | None, str | None]:
|
66 |
-
"""
|
67 |
-
Simulates checking the status of a job via the backend API.
|
68 |
-
In reality, this would use 'requests.get'.
|
69 |
-
|
70 |
-
Args:
|
71 |
-
job_id (str): The ID of the job to check.
|
72 |
-
|
73 |
-
Returns:
|
74 |
-
tuple[str, str | None, str | None]: (status, result_url, error_message)
|
75 |
-
status: 'PENDING', 'PROCESSING', 'COMPLETED', 'FAILED'
|
76 |
-
"""
|
77 |
-
status_url = STATUS_API_URL.format(job_id=job_id)
|
78 |
-
print(f"SIMULATING API STATUS CHECK for {job_id} at {status_url}")
|
79 |
-
time.sleep(0.5) # Simulate network latency
|
80 |
-
|
81 |
-
# Simulate different states based on time or random chance
|
82 |
-
# This is highly simplified; a real backend manages state.
|
83 |
-
if job_id not in st.session_state.job_progress:
|
84 |
-
st.session_state.job_progress[job_id] = 0 # Start progress counter
|
85 |
|
86 |
-
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
-
|
89 |
-
status = "PENDING"
|
90 |
-
elif st.session_state.job_progress[job_id] < 0.8:
|
91 |
-
status = "PROCESSING"
|
92 |
-
elif st.session_state.job_progress[job_id] < 1.0:
|
93 |
-
# Simulate occasional failure during processing
|
94 |
-
if random.random() < 0.05: # 5% chance of failure during processing
|
95 |
-
print(f"API Status Simulation: Job {job_id} FAILED during processing.")
|
96 |
-
st.session_state.job_progress[job_id] = 99 # Mark as failed state
|
97 |
-
return "FAILED", None, "Simulated AI Processing Error."
|
98 |
-
else:
|
99 |
-
status = "PROCESSING" # Still processing
|
100 |
-
else:
|
101 |
-
status = "COMPLETED"
|
102 |
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
return "COMPLETED", result_placeholder, None
|
109 |
-
elif status == "FAILED":
|
110 |
-
print(f"API Status Simulation: Job {job_id} FAILED.")
|
111 |
-
# Error message might have been set earlier
|
112 |
-
error = st.session_state.job_errors.get(job_id, "Unknown processing error.")
|
113 |
-
return "FAILED", None, error
|
114 |
-
else:
|
115 |
-
print(f"API Status Simulation: Job {job_id} is {status}.")
|
116 |
-
return status, None, None
|
117 |
-
|
118 |
-
# --- Simulate Fetching Result Image ---
|
119 |
-
def fetch_result_image(image_path_or_url: str) -> Image.Image | None:
|
120 |
-
"""
|
121 |
-
Simulates fetching the result image from a URL or path.
|
122 |
-
In reality, this would use requests.get for a URL.
|
123 |
-
For this demo, we just load from the local placeholder path.
|
124 |
-
"""
|
125 |
-
print(f"SIMULATING Fetching result image from: {image_path_or_url}")
|
126 |
-
if os.path.exists(image_path_or_url):
|
127 |
-
try:
|
128 |
-
img = Image.open(image_path_or_url).convert("RGB")
|
129 |
-
return img
|
130 |
-
except UnidentifiedImageError:
|
131 |
-
print(f"ERROR: Placeholder at '{image_path_or_url}' is not a valid image.")
|
132 |
-
return None
|
133 |
-
except Exception as e:
|
134 |
-
print(f"ERROR: Failed to load placeholder '{image_path_or_url}': {e}")
|
135 |
-
return None
|
136 |
-
else:
|
137 |
-
print(f"ERROR: Placeholder image not found at '{image_path_or_url}'.")
|
138 |
-
return None
|
139 |
|
140 |
-
#
|
141 |
-
# Authentication Simulation
|
142 |
-
# ------------------------------------------------------------------------------
|
143 |
-
def show_login_form():
|
144 |
-
st.warning("Please log in to use the Visualization Suite.")
|
145 |
-
with st.form("login_form"):
|
146 |
-
username = st.text_input("Username")
|
147 |
-
password = st.text_input("Password", type="password")
|
148 |
-
submitted = st.form_submit_button("Login")
|
149 |
-
if submitted:
|
150 |
-
# --- !!! WARNING: NEVER use hardcoded passwords in production !!! ---
|
151 |
-
# --- This is purely for demonstration. Use secure auth libraries ---
|
152 |
-
# --- like streamlit-authenticator or integrate with OAuth/etc. ---
|
153 |
-
if username == "admin" and password == "password123":
|
154 |
-
st.session_state.logged_in = True
|
155 |
-
st.session_state.username = username
|
156 |
-
st.success("Login successful!")
|
157 |
-
time.sleep(1) # Give user time to see success message
|
158 |
-
st.rerun() # Rerun to show the main app
|
159 |
-
else:
|
160 |
-
st.error("Invalid username or password.")
|
161 |
|
162 |
-
# ------------------------------------------------------------------------------
|
163 |
-
# Initialize Session State (More Robust)
|
164 |
-
# ------------------------------------------------------------------------------
|
165 |
def initialize_state():
|
|
|
166 |
defaults = {
|
167 |
'logged_in': False,
|
168 |
'username': None,
|
169 |
-
'input_data_bytes': None, # Store raw bytes
|
170 |
-
'input_image_preview': None, # Store PIL for display if image
|
171 |
-
'input_type': None,
|
172 |
-
'uploaded_filename': None,
|
173 |
'current_job_id': None,
|
174 |
-
'job_status':
|
175 |
-
'job_progress': {}, #
|
176 |
-
'job_errors': {},
|
177 |
-
'
|
178 |
-
'
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
}
|
180 |
for key, value in defaults.items():
|
181 |
if key not in st.session_state:
|
@@ -183,259 +53,464 @@ def initialize_state():
|
|
183 |
|
184 |
initialize_state()
|
185 |
|
186 |
-
|
187 |
-
|
188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
189 |
|
190 |
# --- Authentication Gate ---
|
191 |
if not st.session_state.logged_in:
|
192 |
show_login_form()
|
193 |
-
st.stop()
|
194 |
|
195 |
-
#
|
196 |
-
st.title("π AI Real Estate Visualization Suite [PRO]")
|
197 |
-
st.caption(f"Welcome, {st.session_state.username}! Advanced AI tools at your fingertips.")
|
198 |
-
st.markdown("---")
|
199 |
|
200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
with st.sidebar:
|
202 |
-
st.header("
|
203 |
st.caption(f"User: {st.session_state.username}")
|
204 |
-
if st.button("Logout"):
|
205 |
-
|
|
|
|
|
206 |
del st.session_state[key]
|
207 |
-
initialize_state()
|
208 |
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
209 |
|
210 |
st.markdown("---")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
211 |
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
processed = True
|
241 |
-
elif file_ext in ['.dxf', '.dwg']:
|
242 |
-
input_type = 'floorplan'
|
243 |
-
processed = True
|
244 |
-
st.warning("Floor plan processing is simulated.")
|
245 |
-
elif file_ext in ['.obj', '.fbx']:
|
246 |
-
input_type = '3dmodel'
|
247 |
-
processed = True
|
248 |
-
st.warning("3D model processing is simulated.")
|
249 |
-
else:
|
250 |
-
st.error(f"Unsupported file type: {file_ext}")
|
251 |
-
|
252 |
-
if processed:
|
253 |
-
st.session_state.input_data_bytes = file_bytes # Store bytes for API
|
254 |
-
st.session_state.input_image_preview = input_image_preview
|
255 |
-
st.session_state.input_type = input_type
|
256 |
-
st.session_state.uploaded_filename = input_file.name
|
257 |
-
# Reset job state
|
258 |
-
st.session_state.current_job_id = None
|
259 |
-
st.session_state.job_status = None
|
260 |
-
st.session_state.ai_result_image = None
|
261 |
-
st.session_state.last_run_params = {}
|
262 |
-
st.success(f"File '{input_file.name}' ({input_type}) loaded.")
|
263 |
-
st.rerun() # Rerun to reflect loaded state
|
264 |
-
else:
|
265 |
-
st.session_state.input_data_bytes = None
|
266 |
-
st.session_state.input_image_preview = None
|
267 |
-
st.session_state.input_type = None
|
268 |
-
st.session_state.uploaded_filename = None
|
269 |
-
|
270 |
-
except UnidentifiedImageError:
|
271 |
-
st.error("Uploaded file is not a valid image or is corrupted.")
|
272 |
-
except Exception as e:
|
273 |
-
st.error(f"Error processing file: {e}")
|
274 |
-
st.session_state.input_data_bytes = None
|
275 |
-
st.session_state.input_image_preview = None
|
276 |
-
st.session_state.input_type = None
|
277 |
-
st.session_state.uploaded_filename = None
|
278 |
-
|
279 |
-
|
280 |
-
# --- Configuration Options ---
|
281 |
-
if st.session_state.input_type is not None:
|
282 |
-
st.markdown("---")
|
283 |
-
st.subheader("2. Visualization Mode")
|
284 |
-
output_mode = st.selectbox(
|
285 |
-
"Select Mode:",
|
286 |
-
options=['Virtual Staging', 'Renovation Preview', 'Material Swap', 'Layout Variation'],
|
287 |
-
key='output_mode_select',
|
288 |
-
disabled=input_disabled
|
289 |
-
).lower().replace(' ', '_')
|
290 |
-
|
291 |
-
st.markdown("---")
|
292 |
-
st.subheader("3. Scene Parameters")
|
293 |
-
room_type = st.selectbox("Room Type:", ["Living Room", "Bedroom", "Kitchen", "Dining Room", "Office", "Bathroom", "Other"], key="room_select", disabled=input_disabled)
|
294 |
-
style = st.selectbox("Primary Style:", ["Modern", "Contemporary", "Minimalist", "Scandinavian", "Industrial", "Traditional", "Coastal", "Farmhouse", "Bohemian"], key="style_select", disabled=input_disabled)
|
295 |
-
|
296 |
-
# Advanced Controls
|
297 |
-
with st.expander("β¨ Advanced Controls", expanded=False):
|
298 |
-
furniture_prefs = st.text_input("Furniture Preferences", placeholder="e.g., 'Large velvet green sofa'", key="furniture_input", disabled=input_disabled)
|
299 |
-
wall_color = st.color_picker("Wall Color (Approx.)", value="#FFFFFF", key="wall_color_picker", disabled=input_disabled)
|
300 |
-
floor_type = st.selectbox("Floor Type", ["(Auto)", "Oak Wood", "Dark Wood", "Light Wood", "Carpet (Neutral)", "Concrete", "Tile (Light)", "Tile (Dark)"], key="floor_select", disabled=input_disabled)
|
301 |
-
lighting_time = st.slider("Time of Day", 0.0, 1.0, 0.5, 0.1, "%.1f", key="lighting_slider", help="0.0=Dawn, 0.5=Midday, 1.0=Dusk", disabled=input_disabled)
|
302 |
-
camera_angle = st.selectbox("Camera Angle", ["Eye-Level", "High Angle", "Low Angle", "Wide (Simulated)"], key="camera_select", disabled=input_disabled)
|
303 |
-
remove_objects = st.checkbox("Attempt Remove Existing Objects", value=False, key="remove_obj_check", disabled=input_disabled)
|
304 |
-
renovation_instructions = ""
|
305 |
-
if output_mode == 'renovation_preview':
|
306 |
-
renovation_instructions = st.text_input("Renovation Instructions", placeholder="e.g., 'Remove center wall'", key="renovation_input", disabled=input_disabled)
|
307 |
-
|
308 |
-
st.markdown("---")
|
309 |
-
st.subheader("4. Generate Visualization")
|
310 |
-
|
311 |
-
# Disable button if no input or job already running
|
312 |
-
disable_generate = st.session_state.input_type is None or st.session_state.job_status in ["PENDING", "PROCESSING"]
|
313 |
-
if st.button("π Submit Visualization Job", key="generate_button", use_container_width=True, disabled=disable_generate):
|
314 |
-
# Prepare payload for the backend
|
315 |
-
# In production, you'd likely upload the file to S3 first and send a URL/key
|
316 |
-
# For image data, you might send base64 encoded string or upload separately
|
317 |
-
payload = {
|
318 |
-
"user_id": st.session_state.username, # Identify the user
|
319 |
-
# "input_reference": "s3://bucket/user_uploads/filename.jpg", # Example
|
320 |
-
"input_filename": st.session_state.uploaded_filename, # For info
|
321 |
-
"input_type": st.session_state.input_type,
|
322 |
-
"output_mode": output_mode,
|
323 |
-
"room_type": room_type,
|
324 |
-
"style": style,
|
325 |
-
"furniture_prefs": furniture_prefs,
|
326 |
-
"materials": {'wall_color': wall_color, 'floor_type': floor_type},
|
327 |
-
"lighting_time": lighting_time,
|
328 |
-
"camera_angle": camera_angle,
|
329 |
-
"remove_objects": remove_objects,
|
330 |
-
"renovation_instructions": renovation_instructions,
|
331 |
-
}
|
332 |
-
# Attach input data - simplistic approach for demo, REAL API would handle uploads better
|
333 |
-
# Never send large files directly in JSON payload in production!
|
334 |
-
# payload['input_data_b64'] = base64.b64encode(st.session_state.input_data_bytes).decode()
|
335 |
-
|
336 |
-
job_id, error = submit_visualization_job(payload)
|
337 |
-
|
338 |
-
if job_id:
|
339 |
-
st.session_state.current_job_id = job_id
|
340 |
-
st.session_state.job_status = "PENDING"
|
341 |
-
st.session_state.ai_result_image = None # Clear previous result
|
342 |
-
st.session_state.last_run_params = payload # Store params for display
|
343 |
-
st.session_state.job_progress = {job_id: 0} # Reset progress for new job
|
344 |
-
st.session_state.job_errors = {} # Clear old errors
|
345 |
-
st.success(f"Job submitted successfully! Job ID: {job_id}")
|
346 |
-
st.rerun() # Start polling
|
347 |
-
else:
|
348 |
-
st.error(f"Failed to submit job: {error}")
|
349 |
-
st.session_state.current_job_id = None
|
350 |
-
st.session_state.job_status = "FAILED" # Mark status
|
351 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
352 |
else:
|
353 |
-
st.
|
354 |
-
|
355 |
-
# --- Main Display Area ---
|
356 |
-
col1, col2 = st.columns(2)
|
357 |
-
|
358 |
-
with col1:
|
359 |
-
st.subheader("Input")
|
360 |
-
if st.session_state.input_type is not None:
|
361 |
-
if st.session_state.input_type == 'image' and st.session_state.input_image_preview:
|
362 |
-
st.image(st.session_state.input_image_preview, caption=f"Input: {st.session_state.uploaded_filename}", use_column_width=True)
|
363 |
-
elif st.session_state.input_type != 'image':
|
364 |
-
# Display info for non-image types
|
365 |
-
st.info(f"{st.session_state.input_type.capitalize()} File:\n**{st.session_state.uploaded_filename}**")
|
366 |
-
st.caption("(Preview not available for non-image inputs in this demo)")
|
367 |
-
else:
|
368 |
-
st.warning("Input loaded, but preview unavailable.")
|
369 |
-
else:
|
370 |
-
st.markdown("<div style='height: 400px; border: 2px dashed #ccc; ...'>Upload Input File</div>", unsafe_allow_html=True)
|
371 |
|
372 |
|
373 |
-
|
374 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
375 |
|
376 |
-
job_id = st.session_state.current_job_id
|
377 |
-
status = st.session_state.job_status
|
378 |
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
st.
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
434 |
|
435 |
|
|
|
436 |
st.markdown("---")
|
437 |
st.warning("""
|
438 |
-
**Disclaimer:** This is
|
439 |
-
|
440 |
-
|
441 |
""")
|
|
|
1 |
+
# advanced_archsketch_app.py
|
2 |
+
import os
|
3 |
import streamlit as st
|
4 |
+
from streamlit_drawable_canvas import st_canvas
|
5 |
+
from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError
|
6 |
+
import requests # For potential real API calls later
|
7 |
+
import openai # Used notionally
|
8 |
+
from io import BytesIO
|
9 |
+
import json
|
10 |
+
import uuid
|
11 |
import time
|
|
|
12 |
import random
|
13 |
+
import base64 # For potential image encoding if needed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
# βββ 1. Configuration & Secrets βββββββββββββββββββββββββββββββββββββββββββββ
|
16 |
+
try:
|
17 |
+
openai.api_key = st.secrets["OPENAI_API_KEY"]
|
18 |
+
except Exception:
|
19 |
+
st.error("OpenAI API Key not found. Please set it in Streamlit secrets.")
|
20 |
+
# openai.api_key = "YOUR_FALLBACK_KEY_FOR_LOCAL_TESTING" # Or load from env
|
21 |
|
22 |
+
st.set_page_config(page_title="ArchSketch AI [Advanced]", layout="wide", page_icon="ποΈ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
+
# --- Simulated Backend API Endpoints ---
|
25 |
+
# Replace with your actual endpoints if building a real backend
|
26 |
+
API_SUBMIT_URL = "http://your-backend.com/api/v1/submit_arch_job"
|
27 |
+
API_STATUS_URL = "http://your-backend.com/api/v1/job_status/{job_id}"
|
28 |
+
API_RESULT_URL = "http://your-backend.com/api/v1/job_result/{job_id}" # Might return data directly or a URL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
+
# βββ 2. State Initialization & Authentication βββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
|
|
|
|
|
|
32 |
def initialize_state():
|
33 |
+
"""Initializes all necessary session state variables."""
|
34 |
defaults = {
|
35 |
'logged_in': False,
|
36 |
'username': None,
|
|
|
|
|
|
|
|
|
37 |
'current_job_id': None,
|
38 |
+
'job_status': 'IDLE', # IDLE, SUBMITTED, PENDING, PROCESSING, COMPLETED, FAILED
|
39 |
+
'job_progress': {}, # Progress dict per job_id
|
40 |
+
'job_errors': {}, # Error dict per job_id
|
41 |
+
'job_results': {}, # Stores result data/references per job_id {job_id: {'type': 'image'/'svg'/'json', 'data': path_or_data, 'params':{...}, 'prompt': '...'}}
|
42 |
+
'selected_history_job_id': None,
|
43 |
+
'annotations': {}, # {job_id: [annotation_objects]}
|
44 |
+
# Input specific state
|
45 |
+
'input_prompt': "",
|
46 |
+
'input_staging_image_bytes': None,
|
47 |
+
'input_staging_image_preview': None,
|
48 |
+
'input_filename': None, # Store filename of uploaded staging image
|
49 |
}
|
50 |
for key, value in defaults.items():
|
51 |
if key not in st.session_state:
|
|
|
53 |
|
54 |
initialize_state()
|
55 |
|
56 |
+
def show_login_form():
|
57 |
+
"""Displays the login form."""
|
58 |
+
st.warning("Login Required")
|
59 |
+
with st.form("login_form"):
|
60 |
+
username = st.text_input("Username", key="login_user")
|
61 |
+
password = st.text_input("Password", type="password", key="login_pass")
|
62 |
+
submitted = st.form_submit_button("Login")
|
63 |
+
if submitted:
|
64 |
+
# --- !!! INSECURE - DEMO ONLY !!! ---
|
65 |
+
if username == "arch_user" and password == "pass123":
|
66 |
+
st.session_state.logged_in = True
|
67 |
+
st.session_state.username = username
|
68 |
+
st.success("Login successful!")
|
69 |
+
time.sleep(1)
|
70 |
+
st.rerun()
|
71 |
+
else:
|
72 |
+
st.error("Invalid credentials.")
|
73 |
|
74 |
# --- Authentication Gate ---
|
75 |
if not st.session_state.logged_in:
|
76 |
show_login_form()
|
77 |
+
st.stop()
|
78 |
|
79 |
+
# βββ 3. Simulated Backend Interaction Functions βββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
80 |
|
81 |
+
def submit_job_to_backend(payload: dict) -> tuple[str | None, str | None]:
|
82 |
+
"""Simulates submitting job, returns (job_id, error)."""
|
83 |
+
st.info("Submitting job to backend simulation...")
|
84 |
+
print(f"SIMULATING API SUBMIT to {API_SUBMIT_URL}")
|
85 |
+
# In reality: response = requests.post(API_SUBMIT_URL, json=payload, headers=auth_headers)
|
86 |
+
time.sleep(1.5) # Simulate network + queue time
|
87 |
+
if random.random() < 0.95:
|
88 |
+
job_id = f"archjob_{uuid.uuid4().hex[:12]}"
|
89 |
+
print(f"API Submit SUCCESS: Job ID = {job_id}")
|
90 |
+
st.session_state.job_progress[job_id] = 0
|
91 |
+
st.session_state.job_errors[job_id] = None
|
92 |
+
# Store essential info with job immediately
|
93 |
+
st.session_state.job_results[job_id] = {
|
94 |
+
'type': None, 'data': None, # Will be filled on completion
|
95 |
+
'params': payload.get('parameters', {}), # Store settings used
|
96 |
+
'prompt': payload.get('prompt', '')
|
97 |
+
}
|
98 |
+
return job_id, None
|
99 |
+
else:
|
100 |
+
error_msg = "Simulated API Error: Failed to submit (server busy/invalid payload)."
|
101 |
+
print(f"API Submit FAILED: {error_msg}")
|
102 |
+
return None, error_msg
|
103 |
+
|
104 |
+
def check_job_status_backend(job_id: str) -> tuple[str, dict | None]:
|
105 |
+
"""Simulates checking job status, returns (status, result_info | None)."""
|
106 |
+
status_url = API_STATUS_URL.format(job_id=job_id)
|
107 |
+
print(f"SIMULATING API STATUS CHECK: {status_url}")
|
108 |
+
# In reality: response = requests.get(status_url, headers=auth_headers)
|
109 |
+
time.sleep(0.7) # Simulate network latency
|
110 |
+
|
111 |
+
if job_id not in st.session_state.job_progress:
|
112 |
+
st.session_state.job_progress[job_id] = 0
|
113 |
+
|
114 |
+
current_progress = st.session_state.job_progress[job_id]
|
115 |
+
status = "UNKNOWN"
|
116 |
+
result_info = None
|
117 |
+
|
118 |
+
# Simulate progress and potential states
|
119 |
+
if current_progress < 0.1:
|
120 |
+
status = "PENDING"
|
121 |
+
st.session_state.job_progress[job_id] += random.uniform(0.05, 0.15)
|
122 |
+
elif current_progress < 0.9:
|
123 |
+
status = "PROCESSING"
|
124 |
+
st.session_state.job_progress[job_id] += random.uniform(0.1, 0.3)
|
125 |
+
# Simulate potential failure during processing
|
126 |
+
if random.random() < 0.03: # 3% chance of failure mid-run
|
127 |
+
status = "FAILED"
|
128 |
+
st.session_state.job_errors[job_id] = "Simulated AI failure during processing."
|
129 |
+
print(f"API Status SIMULATION: Job {job_id} FAILED processing.")
|
130 |
+
elif current_progress >= 0.9: # Consider it done
|
131 |
+
status = "COMPLETED"
|
132 |
+
print(f"API Status SIMULATION: Job {job_id} COMPLETED.")
|
133 |
+
# Determine simulated result type based on original request stored in job_results
|
134 |
+
job_mode = st.session_state.job_results.get(job_id, {}).get('params', {}).get('mode', 'Unknown')
|
135 |
+
|
136 |
+
if job_mode == "Floor Plan":
|
137 |
+
# Simulate returning path to an SVG or structured JSON data
|
138 |
+
placeholder_path = "assets/placeholder_floorplan.svg" # Need this file
|
139 |
+
if not os.path.exists(placeholder_path): placeholder_path = "assets/placeholder_floorplan.json" # Fallback - need JSON too
|
140 |
+
result_info = {'type': 'svg' if '.svg' in placeholder_path else 'json', 'data_path': placeholder_path}
|
141 |
+
else: # Virtual Staging
|
142 |
+
placeholder_path = "assets/placeholder_image.png" # Need this file
|
143 |
+
result_info = {'type': 'image', 'data_path': placeholder_path}
|
144 |
+
|
145 |
+
print(f"API Status SIMULATION: Job {job_id} Status={status}, Progress={st.session_state.job_progress.get(job_id, 0):.2f}")
|
146 |
+
return status, result_info
|
147 |
+
|
148 |
+
def fetch_result_data(result_info: dict):
|
149 |
+
"""Simulates fetching/loading result data based on info from status check."""
|
150 |
+
result_type = result_info['type']
|
151 |
+
data_path = result_info['data_path'] # In real app, might be URL
|
152 |
+
print(f"SIMULATING Fetching {result_type} result from: {data_path}")
|
153 |
+
# In reality: if URL, use requests.get(data_path).content
|
154 |
+
|
155 |
+
if not os.path.exists(data_path):
|
156 |
+
print(f"ERROR: Result placeholder not found at {data_path}")
|
157 |
+
raise FileNotFoundError(f"Result file missing: {data_path}")
|
158 |
+
|
159 |
+
try:
|
160 |
+
if result_type == 'image':
|
161 |
+
img = Image.open(data_path).convert("RGB")
|
162 |
+
return img
|
163 |
+
elif result_type == 'svg':
|
164 |
+
with open(data_path, 'r', encoding='utf-8') as f:
|
165 |
+
svg_content = f.read()
|
166 |
+
return svg_content # Return raw SVG string
|
167 |
+
elif result_type == 'json':
|
168 |
+
with open(data_path, 'r', encoding='utf-8') as f:
|
169 |
+
json_data = json.load(f)
|
170 |
+
return json_data # Return parsed JSON
|
171 |
+
else:
|
172 |
+
raise ValueError(f"Unsupported result type: {result_type}")
|
173 |
+
except Exception as e:
|
174 |
+
print(f"ERROR loading result from {data_path}: {e}")
|
175 |
+
raise
|
176 |
+
|
177 |
+
# βββ 4. Sidebar UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
178 |
with st.sidebar:
|
179 |
+
st.header(f"ποΈ ArchSketch AI")
|
180 |
st.caption(f"User: {st.session_state.username}")
|
181 |
+
if st.button("Logout", key="logout_btn"):
|
182 |
+
# Clear sensitive parts of state, re-initialize others
|
183 |
+
keys_to_clear = list(st.session_state.keys())
|
184 |
+
for key in keys_to_clear:
|
185 |
del st.session_state[key]
|
186 |
+
initialize_state()
|
187 |
st.rerun()
|
188 |
+
st.markdown("---")
|
189 |
+
|
190 |
+
st.header("βοΈ Project Configuration")
|
191 |
+
|
192 |
+
# Disable controls while job is active
|
193 |
+
ui_disabled = st.session_state.job_status in ["SUBMITTED", "PENDING", "PROCESSING"]
|
194 |
+
|
195 |
+
mode = st.radio("Mode", ["Floor Plan", "Virtual Staging"], key="mode_radio", disabled=ui_disabled)
|
196 |
+
|
197 |
+
# --- Conditional Input for Staging ---
|
198 |
+
if mode == "Virtual Staging":
|
199 |
+
staging_image_file = st.file_uploader(
|
200 |
+
"Upload Empty Room Image:",
|
201 |
+
type=["png", "jpg", "jpeg", "webp"],
|
202 |
+
key="staging_uploader",
|
203 |
+
disabled=ui_disabled,
|
204 |
+
help="Required for Virtual Staging mode."
|
205 |
+
)
|
206 |
+
if staging_image_file:
|
207 |
+
if staging_image_file.name != st.session_state.input_filename: # Detect new upload
|
208 |
+
st.info("Processing staging image...")
|
209 |
+
try:
|
210 |
+
img_bytes = staging_image_file.getvalue()
|
211 |
+
image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
212 |
+
image.thumbnail((1024, 1024), Image.Resampling.LANCZOS) # Resize preview
|
213 |
+
st.session_state.input_staging_image_bytes = img_bytes # Store bytes for API
|
214 |
+
st.session_state.input_staging_image_preview = image
|
215 |
+
st.session_state.input_filename = staging_image_file.name
|
216 |
+
st.success("Staging image loaded.")
|
217 |
+
# Don't rerun here, let user configure other options
|
218 |
+
except UnidentifiedImageError:
|
219 |
+
st.error("Invalid image file.")
|
220 |
+
st.session_state.input_staging_image_bytes = None
|
221 |
+
st.session_state.input_staging_image_preview = None
|
222 |
+
st.session_state.input_filename = None
|
223 |
+
except Exception as e:
|
224 |
+
st.error(f"Error loading image: {e}")
|
225 |
+
st.session_state.input_staging_image_bytes = None
|
226 |
+
st.session_state.input_staging_image_preview = None
|
227 |
+
st.session_state.input_filename = None
|
228 |
+
|
229 |
+
elif st.session_state.input_filename: # User cleared the uploader
|
230 |
+
st.session_state.input_staging_image_bytes = None
|
231 |
+
st.session_state.input_staging_image_preview = None
|
232 |
+
st.session_state.input_filename = None
|
233 |
+
|
234 |
|
235 |
st.markdown("---")
|
236 |
+
st.header("β¨ AI Parameters")
|
237 |
+
# Note: Different models might be chosen by the backend based on mode/style
|
238 |
+
model_hint = st.selectbox("Model Preference (Hint for Backend)", ["Auto", "GPTβ4o (Text/Layout)", "Stable Diffusion (Image Gen)", "ControlNet (Editing)"], key="model_select", disabled=ui_disabled)
|
239 |
+
style = st.selectbox("Style Preset", ["Modern", "Minimalist", "Rustic", "Industrial", "Coastal", "Custom"], key="style_select", disabled=ui_disabled)
|
240 |
+
resolution = st.select_slider("Target Resolution (Approx.)", options=[512, 768, 1024], value=768, key="res_slider", disabled=ui_disabled)
|
241 |
+
|
242 |
+
with st.expander("Optional Metadata"):
|
243 |
+
project_id = st.text_input("Project ID", key="proj_id_input", disabled=ui_disabled)
|
244 |
+
location = st.text_input("Location / Address", key="loc_input", disabled=ui_disabled)
|
245 |
+
client_notes = st.text_area("Client Notes", key="notes_area", disabled=ui_disabled)
|
246 |
+
|
247 |
+
# βββ 5. Main Area UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
248 |
+
|
249 |
+
st.title("Advanced AI Architectural Visualizer")
|
250 |
+
|
251 |
+
# --- Prompt Input Area ---
|
252 |
+
st.subheader("π Describe Your Request")
|
253 |
+
prompt_text = st.text_area(
|
254 |
+
"Enter detailed prompt:",
|
255 |
+
placeholder=(
|
256 |
+
"Floor Plan Example: 'Generate a detailed 2D floor plan SVG for a 4-bedroom modern farmhouse, approx 2500 sq ft, main floor master suite, large open concept kitchen/living area, separate office, mudroom entrance.'\n"
|
257 |
+
"Staging Example: 'Virtually stage the uploaded living room image in a minimalist Scandinavian style. Include a light grey sectional sofa, a geometric rug, light wood coffee table, and several potted plants. Ensure bright, natural lighting.'"
|
258 |
+
),
|
259 |
+
height=150,
|
260 |
+
key="prompt_input",
|
261 |
+
disabled=ui_disabled # Disable if job running
|
262 |
+
)
|
263 |
+
st.session_state.input_prompt = prompt_text # Keep state updated
|
264 |
+
|
265 |
+
# --- Submit Button ---
|
266 |
+
can_submit = bool(st.session_state.input_prompt.strip())
|
267 |
+
if mode == "Virtual Staging":
|
268 |
+
can_submit = can_submit and (st.session_state.input_staging_image_bytes is not None)
|
269 |
+
|
270 |
+
submit_button = st.button(
|
271 |
+
"π Submit Visualization Job",
|
272 |
+
key="submit_btn",
|
273 |
+
use_container_width=True,
|
274 |
+
disabled=ui_disabled or not can_submit,
|
275 |
+
help="Requires a prompt. Staging mode also requires an uploaded image."
|
276 |
+
)
|
277 |
|
278 |
+
if not can_submit and not ui_disabled:
|
279 |
+
if mode == "Virtual Staging" and not st.session_state.input_staging_image_bytes:
|
280 |
+
st.warning("Please upload an image for Virtual Staging mode.")
|
281 |
+
elif not st.session_state.input_prompt.strip():
|
282 |
+
st.warning("Please enter a prompt describing your request.")
|
283 |
+
|
284 |
+
|
285 |
+
# --- Job Submission Logic ---
|
286 |
+
if submit_button:
|
287 |
+
st.session_state.job_status = "SUBMITTED"
|
288 |
+
st.session_state.current_job_id = None # Clear old ID before new submission attempt
|
289 |
+
st.session_state.ai_result_image = None # Clear old result display
|
290 |
+
|
291 |
+
# Prepare Payload
|
292 |
+
api_payload = {
|
293 |
+
"prompt": st.session_state.input_prompt,
|
294 |
+
"parameters": {
|
295 |
+
"mode": mode,
|
296 |
+
"model_preference": model_hint,
|
297 |
+
"style": style,
|
298 |
+
"resolution": resolution,
|
299 |
+
"project_id": project_id,
|
300 |
+
"location": location,
|
301 |
+
"client_notes": client_notes,
|
302 |
+
},
|
303 |
+
"user_id": st.session_state.username,
|
304 |
+
}
|
305 |
|
306 |
+
# Add image data for staging mode (handle carefully in production!)
|
307 |
+
if mode == "Virtual Staging" and st.session_state.input_staging_image_bytes:
|
308 |
+
# Option 1: Send as base64 (simpler for demo, BAD for large files)
|
309 |
+
api_payload["base_image_b64"] = base64.b64encode(st.session_state.input_staging_image_bytes).decode('utf-8')
|
310 |
+
api_payload["base_image_filename"] = st.session_state.input_filename
|
311 |
+
# Option 2 (Production): Upload to S3/GCS first, send URL/key
|
312 |
+
# api_payload["base_image_url"] = "s3://bucket/path/to/uploaded_image.jpg"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
313 |
|
314 |
+
job_id, error = submit_job_to_backend(api_payload)
|
315 |
+
|
316 |
+
if job_id:
|
317 |
+
st.session_state.current_job_id = job_id
|
318 |
+
st.session_state.job_status = "PENDING" # Move to pending after successful submit
|
319 |
+
st.session_state.selected_history_job_id = job_id # Auto-select the new job
|
320 |
+
# Store params with result structure immediately
|
321 |
+
if job_id in st.session_state.job_results:
|
322 |
+
st.session_state.job_results[job_id]['params'] = api_payload['parameters']
|
323 |
+
st.session_state.job_results[job_id]['prompt'] = api_payload['prompt']
|
324 |
+
|
325 |
+
st.success(f"Job submitted! ID: {job_id}. Status will update below.")
|
326 |
+
st.rerun() # Start the polling loop
|
327 |
else:
|
328 |
+
st.error(f"Job submission failed: {error}")
|
329 |
+
st.session_state.job_status = "FAILED"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
330 |
|
331 |
|
332 |
+
# --- Status & Result Display Area ---
|
333 |
+
st.markdown("---")
|
334 |
+
st.subheader("π Job Status & Result")
|
335 |
+
|
336 |
+
current_job_id = st.session_state.current_job_id
|
337 |
+
status = st.session_state.job_status
|
338 |
+
|
339 |
+
if not current_job_id:
|
340 |
+
st.info("Submit a job using the controls above.")
|
341 |
+
else:
|
342 |
+
# Display status updates
|
343 |
+
if status == "SUBMITTED":
|
344 |
+
st.warning(f"Job Status: Submitted... Waiting for confirmation (ID: {current_job_id})")
|
345 |
+
time.sleep(2) # Short delay before first poll
|
346 |
+
st.rerun()
|
347 |
+
elif status == "PENDING":
|
348 |
+
st.info(f"Job Status: Pending in queue... (ID: {current_job_id})")
|
349 |
+
time.sleep(5) # Poll interval
|
350 |
+
st.rerun()
|
351 |
+
elif status == "PROCESSING":
|
352 |
+
progress = st.session_state.job_progress.get(current_job_id, 0)
|
353 |
+
st.progress(min(progress, 1.0), text=f"Job Status: Processing... ({int(min(progress,1.0)*100)}%) (ID: {current_job_id})")
|
354 |
+
time.sleep(3) # Poll interval during processing
|
355 |
+
st.rerun()
|
356 |
+
elif status == "COMPLETED":
|
357 |
+
st.success(f"Job Status: Completed! (ID: {current_job_id})")
|
358 |
+
# Result display handled below in results/history section
|
359 |
+
elif status == "FAILED":
|
360 |
+
error_msg = st.session_state.job_errors.get(current_job_id, "Unknown error")
|
361 |
+
st.error(f"Job Status: Failed! (ID: {current_job_id}) - Error: {error_msg}")
|
362 |
+
elif status == "IDLE":
|
363 |
+
st.info("Submit a job to see status.")
|
364 |
+
else: # Should not happen
|
365 |
+
st.error(f"Unknown Job Status: {status}")
|
366 |
+
|
367 |
+
# --- Status Update Logic (if job is active) ---
|
368 |
+
if status in ["SUBMITTED", "PENDING", "PROCESSING"]:
|
369 |
+
new_status, result_info = check_job_status_backend(current_job_id)
|
370 |
+
st.session_state.job_status = new_status
|
371 |
+
|
372 |
+
if new_status == "COMPLETED" and result_info:
|
373 |
+
try:
|
374 |
+
result_data = fetch_result_data(result_info)
|
375 |
+
# Store result data associated with job_id
|
376 |
+
st.session_state.job_results[current_job_id]['type'] = result_info['type']
|
377 |
+
st.session_state.job_results[current_job_id]['data'] = result_data
|
378 |
+
st.session_state.selected_history_job_id = current_job_id # Ensure completed job is selected
|
379 |
+
st.rerun() # Rerun to display result
|
380 |
+
except Exception as e:
|
381 |
+
st.error(f"Failed to load result data: {e}")
|
382 |
+
st.session_state.job_status = "FAILED"
|
383 |
+
st.session_state.job_errors[current_job_id] = f"Failed to load result: {e}"
|
384 |
+
st.rerun()
|
385 |
+
elif new_status == "FAILED":
|
386 |
+
if not st.session_state.job_errors.get(current_job_id):
|
387 |
+
st.session_state.job_errors[current_job_id] = "Job failed during processing (unknown reason)."
|
388 |
+
st.rerun() # Rerun to show failed status
|
389 |
|
|
|
|
|
390 |
|
391 |
+
# --- Result Display / History / Annotation Area ---
|
392 |
+
st.markdown("---")
|
393 |
+
col_results, col_history = st.columns([3, 1]) # Main area for result, smaller sidebar for history
|
394 |
+
|
395 |
+
with col_history:
|
396 |
+
st.subheader("π History")
|
397 |
+
if not st.session_state.job_results:
|
398 |
+
st.caption("No jobs run yet in this session.")
|
399 |
+
else:
|
400 |
+
# Display history items (most recent first)
|
401 |
+
sorted_job_ids = sorted(st.session_state.job_results.keys(), reverse=True)
|
402 |
+
for job_id in sorted_job_ids:
|
403 |
+
job_info = st.session_state.job_results[job_id]
|
404 |
+
prompt_short = job_info.get('prompt', 'No Prompt')[:40] + "..." if len(job_info.get('prompt', '')) > 40 else job_info.get('prompt', 'No Prompt')
|
405 |
+
mode_display = job_info.get('params',{}).get('mode', '?')
|
406 |
+
item_label = f"[{mode_display}] {prompt_short}"
|
407 |
+
|
408 |
+
# Use button to select history item
|
409 |
+
if st.button(item_label, key=f"history_{job_id}", use_container_width=True,
|
410 |
+
help=f"View result for Job ID: {job_id}\nPrompt: {job_info.get('prompt', '')}"):
|
411 |
+
st.session_state.selected_history_job_id = job_id
|
412 |
+
st.rerun() # Rerun to update the main display
|
413 |
+
|
414 |
+
if st.session_state.job_results:
|
415 |
+
st.download_button(
|
416 |
+
"β¬οΈ Export History (JSON)",
|
417 |
+
data=json.dumps(st.session_state.job_results, indent=2, default=str), # Default=str for non-serializable
|
418 |
+
file_name="archsketch_history.json",
|
419 |
+
mime="application/json"
|
420 |
+
)
|
421 |
+
|
422 |
+
|
423 |
+
with col_results:
|
424 |
+
selected_job_id = st.session_state.selected_history_job_id
|
425 |
+
if not selected_job_id or selected_job_id not in st.session_state.job_results:
|
426 |
+
st.info("Select a job from the history panel to view details and annotate.")
|
427 |
+
else:
|
428 |
+
result_info = st.session_state.job_results[selected_job_id]
|
429 |
+
result_type = result_info.get('type')
|
430 |
+
result_data = result_info.get('data')
|
431 |
+
result_params = result_info.get('params', {})
|
432 |
+
result_prompt = result_info.get('prompt', 'N/A')
|
433 |
+
|
434 |
+
st.subheader(f"π Viewing Result: {selected_job_id}")
|
435 |
+
st.caption(f"**Mode:** {result_params.get('mode', 'N/A')} | **Style:** {result_params.get('style', 'N/A')}")
|
436 |
+
st.markdown(f"**Prompt:** *{result_prompt}*")
|
437 |
+
|
438 |
+
display_image = None # Image to use for canvas background
|
439 |
+
|
440 |
+
if result_type == 'image' and isinstance(result_data, Image.Image):
|
441 |
+
st.image(result_data, caption="Generated Visualization", use_column_width=True)
|
442 |
+
display_image = result_data
|
443 |
+
# Add image download button
|
444 |
+
buf = BytesIO(); result_data.save(buf, format="PNG")
|
445 |
+
st.download_button("β¬οΈ Download Image (PNG)", buf.getvalue(), f"{selected_job_id}_result.png", "image/png")
|
446 |
+
|
447 |
+
elif result_type == 'svg' and isinstance(result_data, str):
|
448 |
+
st.image(result_data, caption="Generated Floor Plan (SVG)", use_column_width=True)
|
449 |
+
# SVG Download
|
450 |
+
st.download_button("β¬οΈ Download SVG", result_data, f"{selected_job_id}_floorplan.svg", "image/svg+xml")
|
451 |
+
# Cannot easily use SVG as canvas background directly - maybe render SVG to PNG first?
|
452 |
+
st.warning("Annotation on SVG is not directly supported in this demo. Showing base image if available.")
|
453 |
+
# If staging mode produced SVG somehow (unlikely), use the input image for annotation context
|
454 |
+
if result_params.get('mode') == 'Virtual Staging' and st.session_state.input_staging_image_preview:
|
455 |
+
display_image = st.session_state.input_staging_image_preview
|
456 |
+
|
457 |
+
elif result_type == 'json' and isinstance(result_data, dict):
|
458 |
+
st.json(result_data, expanded=False)
|
459 |
+
st.caption("Generated Structured Data (JSON)")
|
460 |
+
# JSON Download
|
461 |
+
st.download_button("β¬οΈ Download JSON", json.dumps(result_data, indent=2), f"{selected_job_id}_data.json", "application/json")
|
462 |
+
st.warning("Annotation not applicable for JSON results. Showing base image if available.")
|
463 |
+
if result_params.get('mode') == 'Virtual Staging' and st.session_state.input_staging_image_preview:
|
464 |
+
display_image = st.session_state.input_staging_image_preview
|
465 |
+
elif result_data is None:
|
466 |
+
st.warning("Result data is not available for this job (may still be processing or failed).")
|
467 |
+
else:
|
468 |
+
st.error("Result type or data is invalid.")
|
469 |
+
|
470 |
+
|
471 |
+
# --- Annotation Canvas ---
|
472 |
+
if display_image:
|
473 |
+
st.markdown("---")
|
474 |
+
st.subheader("βοΈ Annotate / Edit")
|
475 |
+
# Load existing annotations for this job_id if they exist
|
476 |
+
initial_drawing = {"objects": st.session_state.annotations.get(selected_job_id, [])}
|
477 |
+
|
478 |
+
canvas = st_canvas(
|
479 |
+
fill_color="rgba(255, 0, 0, 0.2)", # Red annotation
|
480 |
+
stroke_width=3,
|
481 |
+
stroke_color="#FF0000",
|
482 |
+
background_image=display_image,
|
483 |
+
update_streamlit=[" Mosul", "mouseup"], # Update on drawing release
|
484 |
+
height=500, # Adjust height as needed
|
485 |
+
width=700, # Adjust width as needed
|
486 |
+
drawing_mode=st.selectbox("Drawing tool:", ("freedraw", "line", "rect", "circle", "transform"), key=f"draw_mode_{selected_job_id}"),
|
487 |
+
key=f"canvas_{selected_job_id}" # Key tied to job ID
|
488 |
+
# Removed initial_drawing for simplicity now, add back if needed carefully
|
489 |
+
)
|
490 |
+
|
491 |
+
# Save annotations when canvas updates
|
492 |
+
if canvas.json_data is not None and canvas.json_data["objects"]:
|
493 |
+
st.session_state.annotations[selected_job_id] = canvas.json_data["objects"]
|
494 |
+
|
495 |
+
# Display current annotations (optional) & Export
|
496 |
+
current_annotations = st.session_state.annotations.get(selected_job_id)
|
497 |
+
if current_annotations:
|
498 |
+
with st.expander("View/Export Current Annotations (JSON)"):
|
499 |
+
st.json(current_annotations)
|
500 |
+
st.download_button(
|
501 |
+
"β¬οΈ Export Annotations",
|
502 |
+
data=json.dumps({selected_job_id: current_annotations}, indent=2),
|
503 |
+
file_name=f"{selected_job_id}_annotations.json",
|
504 |
+
mime="application/json"
|
505 |
+
)
|
506 |
+
else:
|
507 |
+
st.caption("Annotation requires a viewable image result.")
|
508 |
|
509 |
|
510 |
+
# βββ Footer & Disclaimer βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
511 |
st.markdown("---")
|
512 |
st.warning("""
|
513 |
+
**Disclaimer:** This is an **advanced conceptual blueprint**. User authentication is **not secure**.
|
514 |
+
Backend API calls, asynchronous job handling, status polling, AI model execution (image generation, floor plan logic, staging),
|
515 |
+
and result data fetching are **simulated**. Building the real backend requires substantial AI and infrastructure expertise.
|
516 |
""")
|