Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
| 3 |
-
import os
|
| 4 |
-
import uuid
|
| 5 |
-
import tempfile
|
| 6 |
import plotly.graph_objects as go
|
| 7 |
import plotly.io as pio
|
| 8 |
from sklearn.cluster import DBSCAN
|
|
@@ -10,546 +9,375 @@ from sklearn.neighbors import NearestNeighbors, BallTree
|
|
| 10 |
import openpyxl
|
| 11 |
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
| 12 |
from openpyxl.drawing.image import Image as XLImage
|
|
|
|
| 13 |
import math
|
| 14 |
-
import csv
|
| 15 |
-
|
| 16 |
-
# ---- Hardcoded parameters (RELAXED for broader detection) ----
|
| 17 |
-
PREVIEW_MAX_POINTS = 80_000
|
| 18 |
-
PREVIEW_GREEN_MAX = 50_000
|
| 19 |
-
|
| 20 |
-
# Relaxed physical filters to catch more clusters
|
| 21 |
-
MIN_HEIGHT = 0.05
|
| 22 |
-
MAX_LENGTH = 2.0
|
| 23 |
-
MAX_WIDTH = 2.0
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
ASSET_NAME, ASSET_NAME1 = "Green Object", "AIS Box"
|
| 26 |
-
ASSET_ID,
|
| 27 |
-
|
| 28 |
-
# DBSCAN defaults (auto-tuned below)
|
| 29 |
DBSCAN_MIN_SAMPLES_DEFAULT = 12
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
|
| 38 |
-
# minimal cluster volume to accept (m^3)
|
| 39 |
-
MIN_VOLUME = 0.001
|
| 40 |
|
| 41 |
-
#
|
| 42 |
-
MIN_DENSITY = 5
|
| 43 |
-
|
| 44 |
-
# Chunk size for memory-efficient file reading
|
| 45 |
-
CHUNK_SIZE = 1_000_000 # lines
|
| 46 |
-
|
| 47 |
-
# ---- Helper functions ----
|
| 48 |
def pts_to_npy(file_path, pts_npy, cols_npy):
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
reading in chunks to handle very large files efficiently.
|
| 52 |
-
"""
|
| 53 |
-
total_pts = []
|
| 54 |
-
total_cols = []
|
| 55 |
-
|
| 56 |
-
with open(file_path, 'r') as f:
|
| 57 |
reader = csv.reader(f, delimiter=' ')
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
continue
|
| 73 |
-
if lines_read >= CHUNK_SIZE:
|
| 74 |
-
break
|
| 75 |
-
|
| 76 |
-
if not chunk_pts:
|
| 77 |
-
break
|
| 78 |
-
|
| 79 |
-
total_pts.extend(chunk_pts)
|
| 80 |
-
total_cols.extend(chunk_cols)
|
| 81 |
-
|
| 82 |
-
pts_arr = np.array(total_pts, dtype=np.float32)
|
| 83 |
-
cols_arr = np.array(total_cols, dtype=np.uint8)
|
| 84 |
-
|
| 85 |
-
np.save(pts_npy, pts_arr)
|
| 86 |
-
np.save(cols_npy, cols_arr)
|
| 87 |
-
|
| 88 |
return pts_npy, cols_npy
|
| 89 |
|
|
|
|
|
|
|
| 90 |
def rgb_to_hsv_array(rgb_uint8):
|
| 91 |
-
"""Converts an array of RGB values to HSV."""
|
| 92 |
rgb = rgb_uint8.astype(np.float32) / 255.0
|
| 93 |
-
maxc = np.max(rgb,
|
| 94 |
-
minc = np.min(rgb, axis=1)
|
| 95 |
-
v = maxc
|
| 96 |
diff = maxc - minc
|
| 97 |
-
|
| 98 |
s = np.zeros_like(maxc)
|
| 99 |
-
s[maxc
|
| 100 |
-
|
| 101 |
h = np.zeros_like(maxc)
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
h =
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def get_bbox_and_metrics(cluster_pts):
|
| 124 |
-
"""Calculates the bounding box, centroid, and dimensions of a point cluster."""
|
| 125 |
-
min_pt = cluster_pts.min(axis=0)
|
| 126 |
-
max_pt = cluster_pts.max(axis=0)
|
| 127 |
-
centroid = cluster_pts.mean(axis=0)
|
| 128 |
-
length = float(max_pt[0] - min_pt[0])
|
| 129 |
-
width = float(max_pt[1] - min_pt[1])
|
| 130 |
-
height = float(max_pt[2] - min_pt[2])
|
| 131 |
corners = np.array([
|
| 132 |
-
[min_pt[0],
|
| 133 |
-
[min_pt[0],
|
| 134 |
-
[
|
| 135 |
-
[min_pt[0],
|
| 136 |
-
[max_pt[0], min_pt[1], min_pt[2]],
|
| 137 |
-
[max_pt[0], min_pt[1], max_pt[2]],
|
| 138 |
-
[max_pt[0], max_pt[1], min_pt[2]],
|
| 139 |
-
[max_pt[0], max_pt[1], max_pt[2]],
|
| 140 |
])
|
| 141 |
-
return corners, centroid, length,
|
|
|
|
| 142 |
|
| 143 |
def add_bbox_to_fig(fig, corners, color='red', width=4):
|
| 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 |
-
fig.update_layout(scene=dict(aspectmode='data', xaxis=dict(visible=False), yaxis=dict(visible=False), zaxis=dict(visible=False)),
|
| 172 |
-
margin=dict(l=0, r=0, t=0, b=0), width=size[0], height=size[1], paper_bgcolor='white')
|
| 173 |
-
img_bytes = pio.to_image(fig, format='png')
|
| 174 |
-
with open(out_path, 'wb') as f:
|
| 175 |
-
f.write(img_bytes)
|
| 176 |
return out_path
|
| 177 |
|
|
|
|
|
|
|
| 178 |
def create_styled_excel(clusters_info, out_xlsx_path):
|
| 179 |
-
|
| 180 |
-
wb =
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
row
|
| 197 |
-
ws.
|
| 198 |
-
ws.
|
| 199 |
-
row
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
cell.
|
| 207 |
-
cell.alignment =
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
corners
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
ws.cell(row
|
| 218 |
-
ws.cell(row
|
| 219 |
-
ws.cell(row
|
| 220 |
-
ws.cell(row
|
| 221 |
-
ws.cell(row
|
| 222 |
-
ws.cell(row
|
| 223 |
-
ws.cell(row
|
| 224 |
-
ws.cell(row
|
| 225 |
-
ws.cell(row
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
ws.cell(row
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
ws.cell(row
|
| 232 |
-
ws.cell(row
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
row
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
for
|
| 241 |
-
ws.
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
wb.save(out_xlsx_path)
|
| 246 |
return out_xlsx_path
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
n
|
| 252 |
-
if n
|
| 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 |
-
return "Error: Uploaded file not found or invalid.", gr.update(interactive=False), gr.update(visible=False), [None, None], {}
|
| 280 |
-
|
| 281 |
-
current_file_size = os.path.getsize(file_path)
|
| 282 |
-
current_mod_time = os.path.getmtime(file_path)
|
| 283 |
-
|
| 284 |
-
# Check if the file has been processed before using the cached state
|
| 285 |
-
if (last_file_info and
|
| 286 |
-
last_file_info.get('file_path') == file_path and
|
| 287 |
-
last_file_info.get('file_size') == current_file_size and
|
| 288 |
-
last_file_info.get('mod_time') == current_mod_time):
|
| 289 |
-
|
| 290 |
-
pts_npy_path = last_file_info.get('pts_npy_path')
|
| 291 |
-
cols_npy_path = last_file_info.get('cols_npy_path')
|
| 292 |
-
|
| 293 |
-
if os.path.exists(pts_npy_path) and os.path.exists(cols_npy_path):
|
| 294 |
-
print("Detected same file. Skipping conversion.")
|
| 295 |
-
return (f"File reloaded instantly from cache. Click 'Start Analysis' to continue.",
|
| 296 |
-
gr.update(interactive=True),
|
| 297 |
-
gr.update(visible=False),
|
| 298 |
-
[pts_npy_path, cols_npy_path],
|
| 299 |
-
last_file_info)
|
| 300 |
-
|
| 301 |
-
# If new file or a different version, proceed with conversion
|
| 302 |
-
temp_root = os.path.join(tempfile.gettempdir(), f"temp_pts_{uuid.uuid4().hex}")
|
| 303 |
-
|
| 304 |
-
try:
|
| 305 |
-
os.makedirs(temp_root, exist_ok=True)
|
| 306 |
-
except OSError as e:
|
| 307 |
-
error_message = f"Error: Failed to create a temporary directory at '{temp_root}'. Details: {e}"
|
| 308 |
-
print(error_message)
|
| 309 |
-
return error_message, gr.update(interactive=False), gr.update(visible=False), [None, None], {}
|
| 310 |
-
|
| 311 |
-
pts_npy_path = os.path.join(temp_root, "cloud_points.npy")
|
| 312 |
-
cols_npy_path = os.path.join(temp_root, "cloud_colors.npy")
|
| 313 |
-
|
| 314 |
try:
|
| 315 |
-
pts_to_npy(
|
| 316 |
except Exception as e:
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
'mod_time': current_mod_time,
|
| 326 |
-
'pts_npy_path': pts_npy_path,
|
| 327 |
-
'cols_npy_path': cols_npy_path
|
| 328 |
-
}
|
| 329 |
-
|
| 330 |
-
return (f"File loaded successfully. Click 'Start Analysis' to continue.",
|
| 331 |
-
gr.update(interactive=True),
|
| 332 |
-
gr.update(visible=False),
|
| 333 |
-
[pts_npy_path, cols_npy_path],
|
| 334 |
-
new_file_info)
|
| 335 |
|
| 336 |
def start_analysis(file_state, progress=gr.Progress(track_tqdm=True)):
|
| 337 |
-
"""
|
| 338 |
-
Performs the full analysis on the pre-loaded .npy files.
|
| 339 |
-
Uses 'yield' to provide progressive updates to the UI.
|
| 340 |
-
"""
|
| 341 |
-
# Defensive check to prevent the TypeError
|
| 342 |
if not file_state or not file_state[0]:
|
| 343 |
-
return "
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
elif green_count <= 5000:
|
| 373 |
-
max_dbscan_points = 1000
|
| 374 |
-
elif green_count <= 50000:
|
| 375 |
-
max_dbscan_points = 2000
|
| 376 |
else:
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 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 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
cluster_pts = np.asarray(points[abs_indices])
|
| 458 |
-
cluster_cols = np.asarray(colors[abs_indices])
|
| 459 |
-
corners, centroid, length, width, height, zmin, zmax = get_bbox_and_metrics(cluster_pts)
|
| 460 |
-
volume = length * width * height
|
| 461 |
-
if height < MIN_HEIGHT or length > MAX_LENGTH or width > MAX_WIDTH:
|
| 462 |
-
continue
|
| 463 |
-
if volume < MIN_VOLUME:
|
| 464 |
-
continue
|
| 465 |
-
density = cluster_pts.shape[0] / (volume + 1e-9)
|
| 466 |
-
if density < MIN_DENSITY:
|
| 467 |
-
continue
|
| 468 |
-
|
| 469 |
-
temp_root = os.path.dirname(pts_npy_path)
|
| 470 |
-
preview_fn = os.path.join(temp_root, f"obj_preview_lab{lab}_{uuid.uuid4().hex}.png")
|
| 471 |
-
save_cluster_preview_png(cluster_pts, cluster_cols, preview_fn)
|
| 472 |
-
clusters_info.append({
|
| 473 |
-
"cluster_id": int(lab) + 1,
|
| 474 |
-
"centroid": centroid.tolist(),
|
| 475 |
-
"corners": corners,
|
| 476 |
-
"length": length,
|
| 477 |
-
"width": width,
|
| 478 |
-
"height": height,
|
| 479 |
-
"points_count": int(cluster_pts.shape[0]),
|
| 480 |
-
"preview_path": preview_fn
|
| 481 |
-
})
|
| 482 |
-
|
| 483 |
-
output_text += f"Detected {len(clusters_info)} object-shaped clusters after filtering\n"
|
| 484 |
-
|
| 485 |
-
progress(0.9, desc="Generating 3D plot and Excel report...")
|
| 486 |
-
if n_points > PREVIEW_MAX_POINTS:
|
| 487 |
-
rng = np.random.default_rng(1)
|
| 488 |
-
idx_preview = rng.choice(n_points, size=PREVIEW_MAX_POINTS, replace=False)
|
| 489 |
-
preview_points = points[idx_preview]
|
| 490 |
-
preview_colors = colors[idx_preview]
|
| 491 |
-
else:
|
| 492 |
-
preview_points = points[:]
|
| 493 |
-
preview_colors = colors[:]
|
| 494 |
-
preview_rgb = ["rgb(%d,%d,%d)" % tuple(c) for c in preview_colors]
|
| 495 |
-
|
| 496 |
-
if green_count > PREVIEW_GREEN_MAX:
|
| 497 |
-
rng = np.random.default_rng(2)
|
| 498 |
-
idxg = rng.choice(green_indices, size=PREVIEW_GREEN_MAX, replace=False)
|
| 499 |
-
preview_green_points = points[idxg]
|
| 500 |
-
preview_green_colors = colors[idxg]
|
| 501 |
-
else:
|
| 502 |
-
preview_green_points = points[green_indices]
|
| 503 |
-
preview_green_colors = colors[green_indices]
|
| 504 |
-
preview_green_rgb = ["rgb(%d,%d,%d)" % tuple(c) for c in preview_green_colors]
|
| 505 |
-
|
| 506 |
-
fig = go.Figure()
|
| 507 |
-
fig.add_trace(go.Scatter3d(x=preview_points[:, 0], y=preview_points[:, 1], z=preview_points[:, 2],
|
| 508 |
-
mode='markers', marker=dict(size=1, color=preview_rgb), name='All (preview)',
|
| 509 |
-
hoverinfo='none'))
|
| 510 |
-
fig.add_trace(go.Scatter3d(x=preview_green_points[:, 0], y=preview_green_points[:, 1], z=preview_green_points[:, 2],
|
| 511 |
-
mode='markers', marker=dict(size=2, color=preview_green_rgb), name='Green (preview)',
|
| 512 |
-
hoverinfo='none'))
|
| 513 |
-
for info in clusters_info:
|
| 514 |
-
add_bbox_to_fig(fig, info["corners"], color='red', width=4)
|
| 515 |
-
fig.update_layout(scene=dict(aspectmode='data'), height=800, margin=dict(l=0, r=0, t=0, b=0))
|
| 516 |
-
|
| 517 |
-
out_xlsx = None
|
| 518 |
-
if clusters_info:
|
| 519 |
-
out_xlsx = os.path.join(temp_root, "detected_objects_styled.xlsx")
|
| 520 |
-
create_styled_excel(clusters_info, out_xlsx)
|
| 521 |
-
|
| 522 |
-
progress(1.0, desc="Analysis complete.")
|
| 523 |
-
return "Analysis complete.", fig, out_xlsx, gr.update(interactive=True)
|
| 524 |
-
|
| 525 |
-
# Gradio Interface
|
| 526 |
with gr.Blocks(title="Detection") as demo:
|
| 527 |
gr.Markdown("# Green Dustbin & AIS Box Detection")
|
| 528 |
-
gr.Markdown("Upload a `.pts` file
|
|
|
|
|
|
|
|
|
|
| 529 |
|
| 530 |
-
file_state = gr.State(value=[None, None])
|
| 531 |
-
last_file_info_state = gr.State(value={})
|
| 532 |
-
|
| 533 |
with gr.Row():
|
| 534 |
-
|
| 535 |
with gr.Column():
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
analysis_button.click(
|
| 550 |
-
fn=start_analysis,
|
| 551 |
-
inputs=[file_state],
|
| 552 |
-
outputs=[output_text, output_plot, download_button, analysis_button]
|
| 553 |
-
)
|
| 554 |
|
| 555 |
demo.launch()
|
|
|
|
| 1 |
+
# app.py ── complete, self-contained
|
| 2 |
import gradio as gr
|
| 3 |
import numpy as np
|
| 4 |
+
import os, uuid, tempfile, csv
|
|
|
|
|
|
|
| 5 |
import plotly.graph_objects as go
|
| 6 |
import plotly.io as pio
|
| 7 |
from sklearn.cluster import DBSCAN
|
|
|
|
| 9 |
import openpyxl
|
| 10 |
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
| 11 |
from openpyxl.drawing.image import Image as XLImage
|
| 12 |
+
from openpyxl.worksheet.datavalidation import DataValidation # <- needed for dropdowns
|
| 13 |
import math
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# ── Tunables ─────────────────────────────────────────────────────────
|
| 16 |
+
PREVIEW_MAX_POINTS = 80_000
|
| 17 |
+
PREVIEW_GREEN_MAX = 50_000
|
| 18 |
+
MIN_HEIGHT, MAX_LENGTH, MAX_WIDTH = 0.05, 2.0, 2.0
|
| 19 |
ASSET_NAME, ASSET_NAME1 = "Green Object", "AIS Box"
|
| 20 |
+
ASSET_ID, ASSET_ID1 = "3051047", "2859571"
|
|
|
|
|
|
|
| 21 |
DBSCAN_MIN_SAMPLES_DEFAULT = 12
|
| 22 |
+
SAT_PRIORITY_FRAC = 0.5
|
| 23 |
+
REGION_GROW_FACTOR = 1.2
|
| 24 |
+
MIN_VOLUME, MIN_DENSITY = 0.001, 5
|
| 25 |
+
CHUNK_SIZE = 1_000_000
|
| 26 |
+
Z_THRESHOLD_ELEVATED = 0.5 # m
|
| 27 |
+
CONFIDENCE_SCORE_PLACEHOLDER = 1.0
|
| 28 |
+
# ─────────────────────────────────────────────────────────────────────
|
| 29 |
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# ------------- Helper: read .pts in chunks --------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
def pts_to_npy(file_path, pts_npy, cols_npy):
|
| 33 |
+
pts, cols = [], []
|
| 34 |
+
with open(file_path, newline='') as f:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
reader = csv.reader(f, delimiter=' ')
|
| 36 |
+
for row in reader:
|
| 37 |
+
if not row or row[0].startswith('#'):
|
| 38 |
+
continue
|
| 39 |
+
try:
|
| 40 |
+
x,y,z = map(float, row[:3])
|
| 41 |
+
r,g,b = map(int, row[3:6])
|
| 42 |
+
except (ValueError, IndexError):
|
| 43 |
+
continue
|
| 44 |
+
pts.append((x,y,z))
|
| 45 |
+
cols.append((r,g,b))
|
| 46 |
+
if len(pts) >= CHUNK_SIZE:
|
| 47 |
+
break # remove this if you really want to read >1 M lines per chunk
|
| 48 |
+
np.save(pts_npy, np.asarray(pts, dtype=np.float32))
|
| 49 |
+
np.save(cols_npy, np.asarray(cols, dtype=np.uint8))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
return pts_npy, cols_npy
|
| 51 |
|
| 52 |
+
|
| 53 |
+
# ------------- Color utilities --------------------------------------
|
| 54 |
def rgb_to_hsv_array(rgb_uint8):
|
|
|
|
| 55 |
rgb = rgb_uint8.astype(np.float32) / 255.0
|
| 56 |
+
maxc, minc = np.max(rgb,1), np.min(rgb,1)
|
|
|
|
|
|
|
| 57 |
diff = maxc - minc
|
|
|
|
| 58 |
s = np.zeros_like(maxc)
|
| 59 |
+
s[maxc>0] = diff[maxc>0] / maxc[maxc>0]
|
|
|
|
| 60 |
h = np.zeros_like(maxc)
|
| 61 |
+
mask_r = (rgb[:,0]==maxc)&(diff>0)
|
| 62 |
+
mask_g = (rgb[:,1]==maxc)&(diff>0)
|
| 63 |
+
mask_b = (rgb[:,2]==maxc)&(diff>0)
|
| 64 |
+
h[mask_r] = (rgb[mask_r,1]-rgb[mask_r,2]) / diff[mask_r]
|
| 65 |
+
h[mask_g] = 2 + (rgb[mask_g,2]-rgb[mask_g,0]) / diff[mask_g]
|
| 66 |
+
h[mask_b] = 4 + (rgb[mask_b,0]-rgb[mask_b,1]) / diff[mask_b]
|
| 67 |
+
h = (h/6.0) % 1.0
|
| 68 |
+
return np.stack([h,s,maxc],1)
|
| 69 |
+
|
| 70 |
+
def is_green_mask_from_rgb(cols):
|
| 71 |
+
hsv = rgb_to_hsv_array(cols)
|
| 72 |
+
h,s,v = hsv[:,0],hsv[:,1],hsv[:,2]
|
| 73 |
+
return (h>0.22)&(h<0.48)&(s>0.22)&(v>0.12)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# ------------- Geometry helpers -------------------------------------
|
| 77 |
+
def get_bbox_and_metrics(pts):
|
| 78 |
+
min_pt, max_pt = pts.min(0), pts.max(0)
|
| 79 |
+
centroid = pts.mean(0)
|
| 80 |
+
length, width, height = max_pt - min_pt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
corners = np.array([
|
| 82 |
+
[min_pt[0],min_pt[1],min_pt[2]],[min_pt[0],min_pt[1],max_pt[2]],
|
| 83 |
+
[min_pt[0],max_pt[1],min_pt[2]],[min_pt[0],max_pt[1],max_pt[2]],
|
| 84 |
+
[max_pt[0],min_pt[1],min_pt[2]],[max_pt[0],min_pt[1],max_pt[2]],
|
| 85 |
+
[max_pt[0],max_pt[1],min_pt[2]],[max_pt[0],max_pt[1],max_pt[2]],
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
])
|
| 87 |
+
return (corners, centroid, float(length), float(width), float(height),
|
| 88 |
+
float(min_pt[2]), float(max_pt[2]))
|
| 89 |
|
| 90 |
def add_bbox_to_fig(fig, corners, color='red', width=4):
|
| 91 |
+
edges=[(0,1),(1,3),(3,2),(2,0),(4,5),(5,7),(7,6),(6,4),(0,4),(1,5),(2,6),(3,7)]
|
| 92 |
+
for s,e in edges:
|
| 93 |
+
fig.add_trace(go.Scatter3d(x=[corners[s][0],corners[e][0]],
|
| 94 |
+
y=[corners[s][1],corners[e][1]],
|
| 95 |
+
z=[corners[s][2],corners[e][2]],
|
| 96 |
+
mode='lines',
|
| 97 |
+
line=dict(color=color,width=width),
|
| 98 |
+
showlegend=False))
|
| 99 |
+
|
| 100 |
+
def save_cluster_preview_png(pts, cols, out_path, size=(500,500), downsample=200_000):
|
| 101 |
+
n=len(pts)
|
| 102 |
+
if n>downsample:
|
| 103 |
+
idx=np.random.default_rng(0).choice(n,downsample,False)
|
| 104 |
+
pts,cols=pts[idx],cols[idx]
|
| 105 |
+
fig = go.Figure(go.Scatter3d(x=pts[:,0],y=pts[:,1],z=pts[:,2],
|
| 106 |
+
mode='markers',
|
| 107 |
+
marker=dict(size=2,
|
| 108 |
+
color=[f'rgb({r},{g},{b})' for r,g,b in cols])))
|
| 109 |
+
fig.update_layout(scene=dict(aspectmode='data',
|
| 110 |
+
xaxis=dict(visible=False),
|
| 111 |
+
yaxis=dict(visible=False),
|
| 112 |
+
zaxis=dict(visible=False)),
|
| 113 |
+
margin=dict(l=0,r=0,t=0,b=0),
|
| 114 |
+
width=size[0],height=size[1],paper_bgcolor='white')
|
| 115 |
+
with open(out_path,'wb') as f:
|
| 116 |
+
f.write(pio.to_image(fig, format='png'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
return out_path
|
| 118 |
|
| 119 |
+
|
| 120 |
+
# ------------- Excel creation (fixed) -------------------------------
|
| 121 |
def create_styled_excel(clusters_info, out_xlsx_path):
|
| 122 |
+
wb=openpyxl.Workbook()
|
| 123 |
+
ws=wb.active; ws.title="Detected Green Objects"
|
| 124 |
+
|
| 125 |
+
header_fill = PatternFill("solid","E0E0E0")
|
| 126 |
+
data_fill = PatternFill("solid","F2F2F2")
|
| 127 |
+
bold,center = Font(bold=True), Alignment(horizontal="center",vertical="center")
|
| 128 |
+
thin = Side("thin","000000")
|
| 129 |
+
border = Border(top=thin,bottom=thin,left=thin,right=thin)
|
| 130 |
+
|
| 131 |
+
# Dropdown definition (inline list is simpler than a hidden sheet)
|
| 132 |
+
dv_check = DataValidation(type="list", formula1='"Ok,Not Ok"', allow_blank=True)
|
| 133 |
+
dv_nx = DataValidation(type="list", formula1='"Ok,Not Ok"', allow_blank=True)
|
| 134 |
+
ws.add_data_validation(dv_check)
|
| 135 |
+
ws.add_data_validation(dv_nx)
|
| 136 |
+
|
| 137 |
+
row=1
|
| 138 |
+
for idx,info in enumerate(clusters_info,1):
|
| 139 |
+
ws.merge_cells(start_row=row,end_row=row,start_column=1,end_column=22)
|
| 140 |
+
ws.cell(row,1,"Cloud Point Creation").font=Font(bold=True,size=12); row+=1
|
| 141 |
+
ws.merge_cells(start_row=row,end_row=row,start_column=1,end_column=22)
|
| 142 |
+
ws.cell(row,1,f"Object {idx}").font=Font(bold=True,size=11); row+=1
|
| 143 |
+
|
| 144 |
+
headers=["S.No","Point X","Coordinate X","Point Y","Coordinate Y","Point Z","Coordinate Z",
|
| 145 |
+
"CloudPoint Image","CX1","CY2","CZ3","Length","Width","Height",
|
| 146 |
+
"Asset Name","Asset ID","Asset Img","Remarks",
|
| 147 |
+
"Check","NX","Class Name","Confidence Score"]
|
| 148 |
+
for c,h in enumerate(headers,1):
|
| 149 |
+
cell=ws.cell(row,row,column=c,value=h)
|
| 150 |
+
cell.font=bold; cell.alignment=center; cell.fill=header_fill; cell.border=border
|
| 151 |
+
row+=1
|
| 152 |
+
|
| 153 |
+
corners,centroid=info["corners"],info["centroid"]
|
| 154 |
+
length,width,height = info["length"],info["width"],info["height"]
|
| 155 |
+
zmin = info["zmin"]
|
| 156 |
+
class_name = "AIS Box" if zmin>=Z_THRESHOLD_ELEVATED else "Green Dustbin"
|
| 157 |
+
start_data_row=row
|
| 158 |
+
|
| 159 |
+
for i,corner in enumerate(corners,1):
|
| 160 |
+
ws.cell(row,1,i)
|
| 161 |
+
ws.cell(row,2,corner[0]); ws.cell(row,3,corner[0])
|
| 162 |
+
ws.cell(row,4,corner[1]); ws.cell(row,5,corner[1])
|
| 163 |
+
ws.cell(row,6,corner[2]); ws.cell(row,7,corner[2])
|
| 164 |
+
ws.cell(row,9, round(centroid[0],4))
|
| 165 |
+
ws.cell(row,10,round(centroid[1],4))
|
| 166 |
+
ws.cell(row,11,round(centroid[2],4))
|
| 167 |
+
ws.cell(row,12,round(length,4)); ws.cell(row,13,round(width,4)); ws.cell(row,14,round(height,4))
|
| 168 |
+
ws.cell(row,15,ASSET_NAME); ws.cell(row,16,ASSET_ID)
|
| 169 |
+
|
| 170 |
+
# preset blank for image / remarks
|
| 171 |
+
ws.cell(row,17,""); ws.cell(row,18,"")
|
| 172 |
+
|
| 173 |
+
# Check & NX dropdowns
|
| 174 |
+
chk = ws.cell(row,19,"")
|
| 175 |
+
nx = ws.cell(row,20,"")
|
| 176 |
+
dv_check.add(chk.coordinate)
|
| 177 |
+
dv_nx.add(nx.coordinate)
|
| 178 |
+
|
| 179 |
+
ws.cell(row,21,class_name)
|
| 180 |
+
ws.cell(row,22,CONFIDENCE_SCORE_PLACEHOLDER)
|
| 181 |
+
|
| 182 |
+
# styling
|
| 183 |
+
for col in range(1,23):
|
| 184 |
+
c=ws.cell(row,col); c.fill=data_fill; c.border=border
|
| 185 |
+
row+=1
|
| 186 |
+
|
| 187 |
+
# embed preview
|
| 188 |
+
if info["preview_path"] and os.path.exists(info["preview_path"]):
|
| 189 |
+
img = XLImage(info["preview_path"])
|
| 190 |
+
for r in range(start_data_row,start_data_row+8):
|
| 191 |
+
ws.row_dimensions[r].height=60
|
| 192 |
+
ws.column_dimensions['H'].width=20
|
| 193 |
+
ws.add_image(img, f'H{start_data_row}')
|
| 194 |
+
row+=1
|
| 195 |
+
|
| 196 |
+
# adjust widths for new columns
|
| 197 |
+
ws.column_dimensions['S'].width=10
|
| 198 |
+
ws.column_dimensions['T'].width=10
|
| 199 |
+
ws.column_dimensions['U'].width=15
|
| 200 |
+
ws.column_dimensions['V'].width=15
|
| 201 |
wb.save(out_xlsx_path)
|
| 202 |
return out_xlsx_path
|
| 203 |
|
| 204 |
+
|
| 205 |
+
# ------------- Clustering utilities ---------------------------------
|
| 206 |
+
def estimate_eps(pts, sample_size=3000, k=8):
|
| 207 |
+
n=len(pts)
|
| 208 |
+
if n<=k: return 0.3
|
| 209 |
+
if n>sample_size:
|
| 210 |
+
idx=np.random.default_rng(42).choice(n,sample_size,False)
|
| 211 |
+
pts=pts[idx]
|
| 212 |
+
neigh=NearestNeighbors(n_neighbors=k).fit(pts)
|
| 213 |
+
kth=neigh.kneighbors(pts)[0][:,-1]
|
| 214 |
+
return float(np.percentile(kth,75))
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
# ------------- Gradio callbacks -------------------------------------
|
| 218 |
+
def handle_file_upload(uploaded, last_info):
|
| 219 |
+
if uploaded is None:
|
| 220 |
+
return "No file uploaded.", gr.update(interactive=False), gr.update(visible=False), [None,None], {}
|
| 221 |
+
|
| 222 |
+
path=uploaded.name
|
| 223 |
+
if not os.path.exists(path):
|
| 224 |
+
return "Error: file path invalid.", gr.update(interactive=False), gr.update(visible=False), [None,None], {}
|
| 225 |
+
|
| 226 |
+
size, mtime = os.path.getsize(path), os.path.getmtime(path)
|
| 227 |
+
if last_info.get('file_path')==path and last_info.get('file_size')==size and last_info.get('mod_time')==mtime:
|
| 228 |
+
return ("File reloaded from cache. Click 'Start Analysis'.",
|
| 229 |
+
gr.update(interactive=True), gr.update(visible=False),
|
| 230 |
+
[last_info['pts_npy_path'], last_info['cols_npy_path']], last_info)
|
| 231 |
+
|
| 232 |
+
# new/changed file
|
| 233 |
+
tmp_dir = tempfile.mkdtemp(prefix="pts_")
|
| 234 |
+
pts_npy, cols_npy = os.path.join(tmp_dir,"pts.npy"), os.path.join(tmp_dir,"cols.npy")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
try:
|
| 236 |
+
pts_to_npy(path, pts_npy, cols_npy)
|
| 237 |
except Exception as e:
|
| 238 |
+
return f"Conversion error: {e}", gr.update(interactive=False), gr.update(visible=False), [None,None], {}
|
| 239 |
+
|
| 240 |
+
new_info={'file_path':path,'file_size':size,'mod_time':mtime,
|
| 241 |
+
'pts_npy_path':pts_npy,'cols_npy_path':cols_npy}
|
| 242 |
+
return ("File loaded. Click 'Start Analysis'.",
|
| 243 |
+
gr.update(interactive=True), gr.update(visible=False),
|
| 244 |
+
[pts_npy,cols_npy], new_info)
|
| 245 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
def start_analysis(file_state, progress=gr.Progress(track_tqdm=True)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
if not file_state or not file_state[0]:
|
| 249 |
+
return "Upload a file first.", None, None, gr.update(interactive=False)
|
| 250 |
+
|
| 251 |
+
pts=np.load(file_state[0],mmap_mode='r')
|
| 252 |
+
cols=np.load(file_state[1],mmap_mode='r')
|
| 253 |
+
n=len(pts); out=f"Total points: {n:,}\n"
|
| 254 |
+
|
| 255 |
+
progress(0.2, desc="Filtering green points")
|
| 256 |
+
green_mask=is_green_mask_from_rgb(cols)
|
| 257 |
+
g_idx=np.nonzero(green_mask)[0]
|
| 258 |
+
g_cnt=len(g_idx)
|
| 259 |
+
out+=f"Green-colored points: {g_cnt:,}\n"
|
| 260 |
+
if g_cnt==0:
|
| 261 |
+
return "No green points.",None,None,gr.update(interactive=True)
|
| 262 |
+
|
| 263 |
+
# DBSCAN sampling
|
| 264 |
+
if g_cnt<=1000: max_pts=g_cnt
|
| 265 |
+
elif g_cnt<=5000: max_pts=1000
|
| 266 |
+
elif g_cnt<=50_000: max_pts=2000
|
| 267 |
+
else: max_pts=5000
|
| 268 |
+
|
| 269 |
+
hsv=rgb_to_hsv_array(cols[g_idx]); sat=hsv[:,1]
|
| 270 |
+
order=np.argsort(-sat)
|
| 271 |
+
n_pri=int(len(order)*SAT_PRIORITY_FRAC)
|
| 272 |
+
pri=order[:n_pri]
|
| 273 |
+
if g_cnt>max_pts:
|
| 274 |
+
rng=np.random.default_rng(123)
|
| 275 |
+
rest=order[n_pri:]; need=max_pts-n_pri
|
| 276 |
+
choose=rng.choice(rest,need,False) if need>0 else []
|
| 277 |
+
sample_idx=g_idx[np.concatenate([pri,choose])]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
else:
|
| 279 |
+
sample_idx=g_idx
|
| 280 |
+
db_pts=pts[sample_idx]
|
| 281 |
+
|
| 282 |
+
progress(0.4, desc="Clustering")
|
| 283 |
+
eps1=max(0.15,min(0.45,estimate_eps(db_pts)))
|
| 284 |
+
eps2=min(0.9,eps1*1.6)
|
| 285 |
+
ms=DBSCAN_MIN_SAMPLES_DEFAULT
|
| 286 |
+
lab1=DBSCAN(eps=eps1,min_samples=ms).fit(db_pts).labels_
|
| 287 |
+
lab2=DBSCAN(eps=eps2,min_samples=max(6,ms//2)).fit(db_pts).labels_
|
| 288 |
+
comb=lab1.copy(); comb[comb==-1]=lab2[comb==-1]
|
| 289 |
+
u=np.unique(comb); maplab={l:i for i,l in enumerate(u) if l!=-1}
|
| 290 |
+
norm=np.full_like(comb,-1)
|
| 291 |
+
for l,nid in maplab.items():
|
| 292 |
+
norm[comb==l]=nid
|
| 293 |
+
|
| 294 |
+
# region grow
|
| 295 |
+
bt=BallTree(pts[g_idx],leaf_size=40)
|
| 296 |
+
label_full=np.full(len(g_idx),-1,int)
|
| 297 |
+
for l in np.unique(norm):
|
| 298 |
+
if l==-1: continue
|
| 299 |
+
seeds_idx=sample_idx[norm==l]
|
| 300 |
+
seeds_pos=[np.where(g_idx==gi)[0][0] for gi in seeds_idx]
|
| 301 |
+
radii=bt.query_radius(pts[g_idx][seeds_pos], r=eps1*REGION_GROW_FACTOR)
|
| 302 |
+
for neigh in radii:
|
| 303 |
+
label_full[neigh]=l
|
| 304 |
+
|
| 305 |
+
# gather clusters
|
| 306 |
+
clusters=[]
|
| 307 |
+
for l in np.unique(label_full):
|
| 308 |
+
if l==-1: continue
|
| 309 |
+
pos=np.where(label_full==l)[0]
|
| 310 |
+
abs_idx=g_idx[pos]
|
| 311 |
+
c_pts=pts[abs_idx]; c_cols=cols[abs_idx]
|
| 312 |
+
corners,centroid,L,W,H,zmin,zmax=get_bbox_and_metrics(c_pts)
|
| 313 |
+
vol=L*W*H
|
| 314 |
+
if H<MIN_HEIGHT or L>MAX_LENGTH or W>MAX_WIDTH or vol<MIN_VOLUME: continue
|
| 315 |
+
if len(c_pts)/(vol+1e-9)<MIN_DENSITY: continue
|
| 316 |
+
prev=os.path.join(os.path.dirname(file_state[0]),
|
| 317 |
+
f"preview_{l}_{uuid.uuid4().hex}.png")
|
| 318 |
+
save_cluster_preview_png(c_pts,c_cols,prev)
|
| 319 |
+
clusters.append(dict(corners=corners,centroid=centroid,
|
| 320 |
+
length=L,width=W,height=H,
|
| 321 |
+
zmin=zmin,
|
| 322 |
+
preview_path=prev))
|
| 323 |
+
|
| 324 |
+
out+=f"Detected {len(clusters)} objects after filtering\n"
|
| 325 |
+
|
| 326 |
+
# plot
|
| 327 |
+
progress(0.8, desc="Building 3-D preview / Excel")
|
| 328 |
+
if n>PREVIEW_MAX_POINTS:
|
| 329 |
+
idx=np.random.default_rng(1).choice(n,PREVIEW_MAX_POINTS,False)
|
| 330 |
+
p_pts,p_cols=pts[idx],cols[idx]
|
| 331 |
+
else: p_pts,p_cols=pts,cols
|
| 332 |
+
p_rgb=[f'rgb({r},{g},{b})' for r,g,b in p_cols]
|
| 333 |
+
|
| 334 |
+
g_show=g_idx if g_cnt<=PREVIEW_GREEN_MAX else np.random.default_rng(2).choice(g_idx,PREVIEW_GREEN_MAX,False)
|
| 335 |
+
g_pts,g_cols=pts[g_show],cols[g_show]
|
| 336 |
+
g_rgb=[f'rgb({r},{g},{b})' for r,g,b in g_cols]
|
| 337 |
+
|
| 338 |
+
fig=go.Figure()
|
| 339 |
+
fig.add_trace(go.Scatter3d(x=p_pts[:,0],y=p_pts[:,1],z=p_pts[:,2],
|
| 340 |
+
mode='markers',marker=dict(size=1,color=p_rgb),
|
| 341 |
+
name='All',hoverinfo='none'))
|
| 342 |
+
fig.add_trace(go.Scatter3d(x=g_pts[:,0],y=g_pts[:,1],z=g_pts[:,2],
|
| 343 |
+
mode='markers',marker=dict(size=2,color=g_rgb),
|
| 344 |
+
name='Green',hoverinfo='none'))
|
| 345 |
+
for c in clusters: add_bbox_to_fig(fig,c["corners"])
|
| 346 |
+
fig.update_layout(scene=dict(aspectmode='data'),height=800,
|
| 347 |
+
margin=dict(l=0,r=0,t=0,b=0))
|
| 348 |
+
|
| 349 |
+
xlsx=None
|
| 350 |
+
if clusters:
|
| 351 |
+
xlsx=os.path.join(os.path.dirname(file_state[0]),"objects.xlsx")
|
| 352 |
+
create_styled_excel(clusters,xlsx)
|
| 353 |
+
|
| 354 |
+
progress(1.0, desc="Done")
|
| 355 |
+
return out,fig,xlsx,gr.update(interactive=True)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
# ------------- UI ----------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
with gr.Blocks(title="Detection") as demo:
|
| 360 |
gr.Markdown("# Green Dustbin & AIS Box Detection")
|
| 361 |
+
gr.Markdown("Upload a `.pts` file (X Y Z R G B).")
|
| 362 |
+
|
| 363 |
+
file_state = gr.State([None,None])
|
| 364 |
+
last_file_state = gr.State({})
|
| 365 |
|
|
|
|
|
|
|
|
|
|
| 366 |
with gr.Row():
|
| 367 |
+
file_in = gr.File(label="Upload .pts")
|
| 368 |
with gr.Column():
|
| 369 |
+
log = gr.Textbox(lines=10,label="Log")
|
| 370 |
+
analyse = gr.Button("Start Analysis",interactive=False)
|
| 371 |
+
dl_btn = gr.DownloadButton("Download Excel",visible=False)
|
| 372 |
+
plot = gr.Plot(label="3-D preview (down-sampled)")
|
| 373 |
+
|
| 374 |
+
file_in.upload(handle_file_upload,
|
| 375 |
+
inputs=[file_in,last_file_state],
|
| 376 |
+
outputs=[log,analyse,dl_btn,file_state,last_file_state],
|
| 377 |
+
queue=False)
|
| 378 |
+
|
| 379 |
+
analyse.click(start_analysis,
|
| 380 |
+
inputs=[file_state],
|
| 381 |
+
outputs=[log,plot,dl_btn,analyse])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
|
| 383 |
demo.launch()
|