Spaces:
Paused
Paused
File size: 11,965 Bytes
3b08f11 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff f3ebc82 88bdcff f3ebc82 88bdcff f3ebc82 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff f3ebc82 88bdcff 3b08f11 f3ebc82 3b08f11 f3ebc82 88bdcff 3b08f11 88bdcff f3ebc82 88bdcff f3ebc82 3b08f11 88bdcff 3b08f11 88bdcff f3ebc82 88bdcff f3ebc82 3b08f11 f3ebc82 88bdcff f3ebc82 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff 3b08f11 88bdcff |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
"""Tab 2: Images.
Upload and manage fire damage images for AI analysis.
MVP Simplification: Single room - images auto-assigned to the room.
"""
import uuid
import gradio as gr
from typing import Any
from PIL import Image
import io
from ui.state import SessionState, ImageFormData
from ui.components import image_store
from config.settings import settings
def create_tab() -> dict[str, Any]:
"""Create Tab 2 UI components.
Returns:
Dictionary of component references for event wiring.
"""
gr.Markdown("### Fire Damage Images")
gr.Markdown(
f"*Upload up to {settings.max_images_per_assessment} images for AI analysis.*"
)
with gr.Row():
with gr.Column(scale=2):
image_upload = gr.Files(
label="Upload Images (select multiple)",
file_count="multiple",
file_types=["image"],
elem_id="image_upload",
)
image_description = gr.Textbox(
label="Description (optional)",
placeholder="e.g., View of ceiling deck from center aisle",
elem_id="image_description",
info="Applied to all images in batch",
)
with gr.Row():
add_image_btn = gr.Button("Add Images", variant="primary")
clear_upload_btn = gr.Button("Clear", variant="secondary")
with gr.Column(scale=3):
images_gallery = gr.Gallery(
label="Images Added",
columns=3,
height="auto",
elem_id="images_gallery",
)
with gr.Row():
remove_last_btn = gr.Button("Remove Last Image", variant="secondary")
clear_all_btn = gr.Button("Clear All Images", variant="stop")
# Image count and status
with gr.Row():
image_count = gr.Textbox(
label="Images Added",
value="0 / 20",
interactive=False,
)
# Validation status
with gr.Row():
validation_status = gr.HTML(
value="",
elem_id="tab2_validation",
)
# Resume warning (shown when images need re-upload)
with gr.Row():
resume_warning = gr.HTML(
value="",
elem_id="resume_warning",
visible=False,
)
with gr.Row():
back_btn = gr.Button("← Back to Room")
validate_btn = gr.Button(
"Validate & Continue to Observations →",
variant="primary",
)
return {
"image_upload": image_upload,
"image_description": image_description,
"add_image_btn": add_image_btn,
"clear_upload_btn": clear_upload_btn,
"images_gallery": images_gallery,
"remove_last_btn": remove_last_btn,
"clear_all_btn": clear_all_btn,
"image_count": image_count,
"validation_status": validation_status,
"resume_warning": resume_warning,
"back_btn": back_btn,
"validate_btn": validate_btn,
}
def add_image(
session: SessionState,
files: list | None,
description: str,
) -> tuple[SessionState, list[tuple], str, str, None, str]:
"""Add one or more images to the session (batch upload).
Images are automatically associated with the single room.
Args:
session: Current session state.
files: List of uploaded file objects from gr.Files, each with a `name` attribute.
description: Optional description applied to all images.
Returns:
Tuple of (session, gallery_data, validation_html, image_count,
cleared_files, cleared_description).
"""
validation_html = ""
# Validate input
errors = []
if not files or len(files) == 0:
errors.append("Please upload at least one image")
# Check capacity
current_count = len(session.images)
max_allowed = settings.max_images_per_assessment
if files and current_count + len(files) > max_allowed:
remaining = max_allowed - current_count
if remaining <= 0:
errors.append(f"Maximum of {max_allowed} images allowed (already at limit)")
else:
errors.append(f"Can only add {remaining} more image(s) (limit: {max_allowed})")
if errors:
error_items = "".join(f"<li>{e}</li>" for e in errors)
validation_html = f"""
<div style="background: #ffebee; border: 1px solid #ef5350; border-radius: 4px; padding: 10px;">
<ul style="margin: 0; padding-left: 20px; color: #c62828;">
{error_items}
</ul>
</div>
"""
gallery_data = _get_gallery_data(session)
count_str = f"{len(session.images)} / {max_allowed}"
return session, gallery_data, validation_html, count_str, files, description
# Get room info from session (single room)
room_id = session.room.id
room_name = session.room.name.replace(" ", "_")[:20] if session.room.name else "room"
# Process each uploaded file
added_count = 0
for file_obj in files:
# Check if we've hit the limit
if len(session.images) >= max_allowed:
break
try:
# Open image from file path
img = Image.open(file_obj.name)
# Generate image ID
image_id = f"img-{uuid.uuid4().hex[:8]}"
# Store image bytes in memory
img_bytes = io.BytesIO()
img.save(img_bytes, format="PNG")
image_store.store(image_id, img_bytes.getvalue())
# Add image metadata to session
img_meta = ImageFormData(
id=image_id,
filename=f"{room_name}_{image_id}.png",
room_id=room_id,
description=description.strip() if description else "",
)
session.images.append(img_meta)
added_count += 1
except Exception:
# Skip files that can't be opened as images
continue
session.update_timestamp()
# Success message
if added_count > 0:
validation_html = f"""
<div style="background: #e8f5e9; border: 1px solid #66bb6a; border-radius: 4px; padding: 10px;">
<span style="color: #2e7d32;">✓ {added_count} image(s) added for {room_name}</span>
</div>
"""
else:
validation_html = """
<div style="background: #fff3e0; border: 1px solid #ffb74d; border-radius: 4px; padding: 10px;">
<span style="color: #e65100;">No images could be processed</span>
</div>
"""
gallery_data = _get_gallery_data(session)
count_str = f"{len(session.images)} / {max_allowed}"
# Clear form
return session, gallery_data, validation_html, count_str, None, ""
def remove_last_image(session: SessionState) -> tuple[SessionState, list[tuple], str, str]:
"""Remove the last image from the session."""
validation_html = ""
if session.images:
removed = session.images.pop()
image_store.remove(removed.id)
session.update_timestamp()
validation_html = f"""
<div style="background: #fff3e0; border: 1px solid #ffb74d; border-radius: 4px; padding: 10px;">
<span style="color: #e65100;">Removed image: {removed.filename}</span>
</div>
"""
gallery_data = _get_gallery_data(session)
count_str = f"{len(session.images)} / {settings.max_images_per_assessment}"
return session, gallery_data, validation_html, count_str
def clear_all_images(session: SessionState) -> tuple[SessionState, list[tuple], str, str]:
"""Clear all images from the session."""
count = len(session.images)
# Clear from store
for img in session.images:
image_store.remove(img.id)
session.images = []
session.update_timestamp()
validation_html = ""
if count > 0:
validation_html = f"""
<div style="background: #fff3e0; border: 1px solid #ffb74d; border-radius: 4px; padding: 10px;">
<span style="color: #e65100;">Cleared {count} image(s)</span>
</div>
"""
count_str = f"0 / {settings.max_images_per_assessment}"
return session, [], validation_html, count_str
def validate_and_continue(session: SessionState) -> tuple[SessionState, str, int]:
"""Validate Tab 2 and proceed to Tab 3.
Returns:
Tuple of (session, validation_html, next_tab_index).
"""
# Check if images need re-upload (session restored but images not in memory)
expected_ids = [img.id for img in session.images]
missing_ids = image_store.get_missing_ids(expected_ids)
if missing_ids:
missing_count = len(missing_ids)
html = f"""
<div style="background: #fff3e0; border: 1px solid #ffb74d; border-radius: 4px; padding: 10px;">
<strong style="color: #e65100;">⚠ {missing_count} image(s) need to be re-uploaded</strong>
<p style="color: #e65100; margin: 5px 0 0 0;">
Images are not stored in browser storage. Please re-upload the missing images
or clear the image list and start fresh.
</p>
</div>
"""
return session, html, gr.update(selected=1) # Stay on Images tab (index 1)
is_valid, errors = session.validate_tab2()
if is_valid:
session.tab2_complete = True
session.update_timestamp()
html = """
<div style="background: #e8f5e9; border: 1px solid #66bb6a; border-radius: 4px; padding: 10px;">
<span style="color: #2e7d32;">✓ Images complete. Proceeding to Observations tab...</span>
</div>
"""
return session, html, gr.update(selected=2) # Go to tab index 2 (Observations)
else:
session.tab2_complete = False
error_items = "".join(f"<li>{e}</li>" for e in errors)
html = f"""
<div style="background: #ffebee; border: 1px solid #ef5350; border-radius: 4px; padding: 10px;">
<strong style="color: #c62828;">Please fix the following:</strong>
<ul style="margin: 5px 0 0 0; padding-left: 20px; color: #c62828;">
{error_items}
</ul>
</div>
"""
return session, html, gr.update(selected=1) # Stay on current tab
def load_from_session(session: SessionState) -> tuple[list[tuple], str, str]:
"""Load gallery data and count from session.
Returns:
Tuple of (gallery_data, image_count, resume_warning_html).
"""
gallery_data = _get_gallery_data(session)
count_str = f"{len(session.images)} / {settings.max_images_per_assessment}"
# Check for missing images
expected_ids = [img.id for img in session.images]
missing_ids = image_store.get_missing_ids(expected_ids)
resume_html = ""
if missing_ids and session.images:
resume_html = f"""
<div style="background: #fff3e0; border: 1px solid #ffb74d; border-radius: 4px; padding: 10px;">
<strong style="color: #e65100;">⚠ {len(missing_ids)} image(s) need to be re-uploaded</strong>
<p style="color: #e65100; margin: 5px 0 0 0;">
Session restored, but images must be re-uploaded as they are not stored in browser storage.
</p>
</div>
"""
return gallery_data, count_str, resume_html
def _get_gallery_data(session: SessionState) -> list[tuple]:
"""Get gallery data from session images.
Returns:
List of (image, caption) tuples for gallery.
"""
gallery_data = []
for img_meta in session.images:
img_bytes = image_store.get(img_meta.id)
if img_bytes:
# Convert bytes to PIL Image for gallery
pil_image = Image.open(io.BytesIO(img_bytes))
caption = img_meta.description or img_meta.filename
gallery_data.append((pil_image, caption))
return gallery_data
|