MVPavanKumar commited on
Commit
ef1061f
·
verified ·
1 Parent(s): 3370762

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +336 -508
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, ASSET_ID1 = "3051047", "2859571"
27
-
28
- # DBSCAN defaults (auto-tuned below)
29
  DBSCAN_MIN_SAMPLES_DEFAULT = 12
30
- EPS_SCALE = 1.15
31
-
32
- # sampling priority: fraction of top-saturation points to always include
33
- SAT_PRIORITY_FRAC = 0.5
34
-
35
- # region grow radius factor (grow clusters on full green set)
36
- REGION_GROW_FACTOR = 1.2
37
 
38
- # minimal cluster volume to accept (m^3)
39
- MIN_VOLUME = 0.001
40
 
41
- # minimal density (points per cubic meter) to accept cluster
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
- Converts a .pts file to a numpy array for faster processing,
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
- while True:
59
- chunk_pts = []
60
- chunk_cols = []
61
- lines_read = 0
62
- for row in reader:
63
- if not row or row[0].startswith('#'):
64
- continue
65
- try:
66
- x, y, z = map(float, row[:3])
67
- r, g, b = map(int, row[3:6])
68
- chunk_pts.append((x, y, z))
69
- chunk_cols.append((r, g, b))
70
- lines_read += 1
71
- except (ValueError, IndexError):
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, axis=1)
94
- minc = np.min(rgb, axis=1)
95
- v = maxc
96
  diff = maxc - minc
97
-
98
  s = np.zeros_like(maxc)
99
- s[maxc > 0] = diff[maxc > 0] / maxc[maxc > 0]
100
-
101
  h = np.zeros_like(maxc)
102
-
103
- # Create masks to determine which color channel is dominant
104
- mask_r = (rgb[:, 0] == maxc) & (diff > 0)
105
- mask_g = (rgb[:, 1] == maxc) & (diff > 0)
106
- mask_b = (rgb[:, 2] == maxc) & (diff > 0)
107
-
108
- # Calculate hue based on dominant channel
109
- h[mask_r] = (rgb[mask_r, 1] - rgb[mask_r, 2]) / diff[mask_r]
110
- h[mask_g] = 2.0 + (rgb[mask_g, 2] - rgb[mask_g, 0]) / diff[mask_g]
111
- h[mask_b] = 4.0 + (rgb[mask_b, 0] - rgb[mask_b, 1]) / diff[mask_b]
112
-
113
- h = (h / 6.0) % 1.0
114
-
115
- return np.stack([h, s, v], axis=1)
116
-
117
- def is_green_mask_from_rgb(colors_uint8):
118
- """Generates a boolean mask to identify green points based on HSV values."""
119
- hsv = rgb_to_hsv_array(colors_uint8)
120
- h, s, v = hsv[:, 0], hsv[:, 1], hsv[:, 2]
121
- return (h > 0.22) & (h < 0.48) & (s > 0.22) & (v > 0.12)
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], min_pt[1], min_pt[2]],
133
- [min_pt[0], min_pt[1], max_pt[2]],
134
- [min_pt[0], max_pt[1], min_pt[2]],
135
- [min_pt[0], max_pt[1], max_pt[2]],
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, width, height, float(min_pt[2]), float(max_pt[2])
 
142
 
143
  def add_bbox_to_fig(fig, corners, color='red', width=4):
144
- """Adds a 3D bounding box to a Plotly figure."""
145
- 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)]
146
- for s, e in edges:
147
- fig.add_trace(go.Scatter3d(
148
- x=[corners[s][0], corners[e][0]],
149
- y=[corners[s][1], corners[e][1]],
150
- z=[corners[s][2], corners[e][2]],
151
- mode='lines',
152
- line=dict(color=color, width=width),
153
- showlegend=False
154
- ))
155
-
156
- def save_cluster_preview_png(cluster_pts, cluster_cols, out_path, size=(500, 500), downsample=200000):
157
- """Creates and saves a preview PNG of a point cluster."""
158
- n = cluster_pts.shape[0]
159
- if n > downsample:
160
- rng = np.random.default_rng(0)
161
- idx = rng.choice(n, size=downsample, replace=False)
162
- pts, cols = cluster_pts[idx], cluster_cols[idx]
163
- else:
164
- pts, cols = cluster_pts, cluster_cols
165
- fig = go.Figure()
166
- fig.add_trace(go.Scatter3d(
167
- x=pts[:, 0], y=pts[:, 1], z=pts[:, 2],
168
- mode='markers', marker=dict(size=2, color=["rgb(%d,%d,%d)" % tuple(c) for c in cols]),
169
- showlegend=False
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
- """Creates a styled Excel file with cluster information and images."""
180
- wb = openpyxl.Workbook()
181
- ws = wb.active
182
- ws.title = "Detected Green Objects"
183
-
184
- # Updated color palette
185
- gray_fill = PatternFill(start_color="F2F2F2", end_color="F2F2F2", fill_type="solid")
186
- header_fill = PatternFill(start_color="E0E0E0", end_color="E0E0E0", fill_type="solid")
187
-
188
- bold = Font(bold=True)
189
- center = Alignment(horizontal="center", vertical="center")
190
- thin = Side(border_style="thin", color="000000")
191
- border = Border(left=thin, right=thin, top=thin, bottom=thin)
192
- row = 1
193
- for idx, info in enumerate(clusters_info, start=1):
194
- ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=19)
195
- ws.cell(row=row, column=1, value="Cloud Point Creation").font = Font(bold=True, size=12)
196
- row += 1
197
- ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=19)
198
- ws.cell(row=row, column=1, value=f"Object {idx}").font = Font(bold=True, size=11)
199
- row += 1
200
- headers = ["S.No", "Point X", "Coordinate X", "Point Y", "Coordinate Y", "Point Z", "Coordinate Z",
201
- "CloudPoint Image", "CX1", "CY2", "CZ3", "Length", "Width", "Height",
202
- "Assest Name", "Assest ID", "Assest Img", "Remarks", "Check"] # Added "Check"
203
- for c, h in enumerate(headers, start=1):
204
- cell = ws.cell(row=row, column=c, value=h)
205
- cell.font = bold
206
- cell.fill = header_fill
207
- cell.alignment = center
208
- cell.border = border
209
- row += 1
210
- corners = info["corners"]
211
- centroid = info["centroid"]
212
- length, width, height = info["length"], info["width"], info["height"]
213
- for i in range(8):
214
- c = corners[i]
215
- ws.cell(row=row, column=1, value=i + 1)
216
- ws.cell(row=row, column=2, value=c[0])
217
- ws.cell(row=row, column=3, value=c[0])
218
- ws.cell(row=row, column=4, value=c[1])
219
- ws.cell(row=row, column=5, value=c[1])
220
- ws.cell(row=row, column=6, value=c[2])
221
- ws.cell(row=row, column=7, value=c[2])
222
- ws.cell(row=row, column=9, value=round(centroid[0], 4))
223
- ws.cell(row=row, column=10, value=round(centroid[1], 4))
224
- ws.cell(row=row, column=11, value=round(centroid[2], 4))
225
- ws.cell(row=row, column=12, value=round(length, 4))
226
- ws.cell(row=row, column=13, value=round(width, 4))
227
- ws.cell(row=row, column=14, value=round(height, 4))
228
- ws.cell(row=row, column=15, value=ASSET_NAME)
229
- ws.cell(row=row, column=16, value=ASSET_ID)
230
- ws.cell(row=row, column=17, value="")
231
- ws.cell(row=row, column=18, value="")
232
- ws.cell(row=row, column=19, value="") # Added blank "Check" column
233
- for col_idx in range(1, 20):
234
- ws.cell(row=row, column=col_idx).fill = gray_fill
235
- ws.cell(row=row, column=col_idx).border = border
236
- row += 1
237
- img_path = info.get("preview_path")
238
- if img_path and os.path.exists(img_path):
239
- image = XLImage(img_path)
240
- for r_i in range(row - 8, row):
241
- ws.row_dimensions[r_i].height = 60
242
- ws.column_dimensions['H'].width = 20
243
- ws.add_image(image, f"H{row - 8}")
244
- row += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  wb.save(out_xlsx_path)
246
  return out_xlsx_path
247
 
248
- # ---- Utility: estimate eps robustly using k-distance percentile ----
249
- def estimate_eps(points_for_estimate, sample_size=3000, k=8):
250
- """Estimates the optimal epsilon value for DBSCAN."""
251
- n = points_for_estimate.shape[0]
252
- if n <= k:
253
- return 0.3
254
- if n > sample_size:
255
- rng = np.random.default_rng(42)
256
- sample_idx = rng.choice(n, size=sample_size, replace=False)
257
- pts_sample = points_for_estimate[sample_idx]
258
- else:
259
- pts_sample = points_for_estimate
260
- neigh = NearestNeighbors(n_neighbors=k)
261
- neigh.fit(pts_sample)
262
- dists, _ = neigh.kneighbors(pts_sample)
263
- kth = dists[:, -1]
264
- return float(np.percentile(kth, 75))
265
-
266
- # ---- Main processing function for Gradio ----
267
- def handle_file_upload(uploaded_file, last_file_info):
268
- """
269
- Handles file upload by converting the .pts file to .npy for faster processing.
270
- Now uses Gradio State for persistent caching.
271
- """
272
- if uploaded_file is None:
273
- return "No file uploaded.", gr.update(interactive=False), gr.update(visible=False), [None, None], {}
274
-
275
- file_path = uploaded_file.name
276
-
277
- # Check if the file path is valid before proceeding
278
- if not file_path or not os.path.exists(file_path):
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(file_path, pts_npy_path, cols_npy_path)
316
  except Exception as e:
317
- error_message = f"Error: Failed to convert .pts file. Please check file format. Details: {e}"
318
- print(error_message)
319
- return error_message, gr.update(interactive=False), gr.update(visible=False), [None, None], {}
320
-
321
- # Store info for future re-uploads in the state dictionary
322
- new_file_info = {
323
- 'file_path': file_path,
324
- 'file_size': current_file_size,
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 "Please upload a file and wait for it to load before starting the analysis.", None, None, gr.update(interactive=False)
344
-
345
- pts_npy_path, cols_npy_path = file_state
346
-
347
- if not (pts_npy_path and cols_npy_path and os.path.exists(pts_npy_path)):
348
- return "Please upload a file first.", None, None, gr.update(interactive=False)
349
-
350
- progress(0.1, desc="Loading point cloud data...")
351
- points = np.load(pts_npy_path, mmap_mode='r')
352
- colors = np.load(cols_npy_path, mmap_mode='r')
353
- n_points = points.shape[0]
354
- output_text = f"Total points: {n_points:,}\n"
355
-
356
- progress(0.25, desc="Identifying green points...")
357
- chunk = 1_000_000
358
- green_mask = np.zeros(n_points, dtype=bool)
359
- for i in progress.tqdm(range(0, n_points, chunk), desc="Processing chunks..."):
360
- j = min(n_points, i + chunk)
361
- green_mask[i:j] = is_green_mask_from_rgb(colors[i:j])
362
- green_indices = np.nonzero(green_mask)[0]
363
- green_count = green_indices.shape[0]
364
- output_text += f"Green-colored points: {green_count:,}\n"
365
-
366
- if green_count == 0:
367
- return "No green points detected.", None, None, gr.update(interactive=True)
368
-
369
- progress(0.5, desc="Clustering green points...")
370
- if green_count <= 1000:
371
- max_dbscan_points = green_count
372
- elif green_count <= 5000:
373
- max_dbscan_points = 1000
374
- elif green_count <= 50000:
375
- max_dbscan_points = 2000
376
  else:
377
- max_dbscan_points = 5000
378
-
379
- hsv_all = rgb_to_hsv_array(colors[green_indices])
380
- saturation = hsv_all[:, 1]
381
- order_by_sat = np.argsort(-saturation)
382
- n_priority = int(len(order_by_sat) * SAT_PRIORITY_FRAC)
383
- priority_idx = order_by_sat[:n_priority]
384
-
385
- if green_count > max_dbscan_points:
386
- remaining = order_by_sat[n_priority:]
387
- rng = np.random.default_rng(123)
388
- n_remaining_needed = max_dbscan_points - n_priority
389
- if n_remaining_needed > 0 and remaining.size > 0:
390
- chosen_remaining = rng.choice(remaining, size=min(n_remaining_needed, remaining.size), replace=False)
391
- chosen = np.concatenate([priority_idx, chosen_remaining])
392
- else:
393
- chosen = priority_idx[:max_dbscan_points]
394
- sample_inds = green_indices[chosen]
395
- dbscan_pts = points[sample_inds]
396
- dbscan_map = sample_inds
397
- else:
398
- dbscan_pts = points[green_indices]
399
- dbscan_map = green_indices
400
-
401
- est_eps = estimate_eps(dbscan_pts, sample_size=3000, k=8)
402
- eps1 = max(0.15, min(0.45, est_eps))
403
- eps2 = min(0.9, eps1 * 1.6)
404
- min_samples = DBSCAN_MIN_SAMPLES_DEFAULT
405
-
406
- output_text += f"Estimated base eps: {eps1:.3f} (second-pass eps: {eps2:.3f}), min_samples: {min_samples}\n"
407
-
408
- clust1 = DBSCAN(eps=eps1, min_samples=min_samples).fit(dbscan_pts)
409
- labels1 = clust1.labels_
410
- clust2 = DBSCAN(eps=eps2, min_samples=max(6, int(min_samples / 2))).fit(dbscan_pts)
411
- labels2 = clust2.labels_
412
-
413
- combined_labels = labels1.copy()
414
- noise_mask = combined_labels == -1
415
- combined_labels[noise_mask] = labels2[noise_mask]
416
- unique = np.unique(combined_labels)
417
- label_map = {lab: i for i, lab in enumerate(unique) if lab != -1}
418
- norm_labels = np.full_like(combined_labels, fill_value=-1)
419
- for lab, nid in label_map.items():
420
- if lab == -1:
421
- continue
422
- norm_labels[combined_labels == lab] = nid
423
-
424
- progress(0.75, desc="Refining clusters with region growing...")
425
- sampled_map = dbscan_map
426
- valid_labels = [lab for lab in np.unique(norm_labels) if lab != -1]
427
- green_pts_full = points[green_indices]
428
- bt = BallTree(green_pts_full, leaf_size=40)
429
- global_to_greenpos = {int(g): i for i, g in enumerate(green_indices)}
430
- full_label_assignment = np.full(green_count, -1, dtype=int)
431
-
432
- for lab in valid_labels:
433
- mask_sample = (norm_labels == lab)
434
- if mask_sample.sum() == 0:
435
- continue
436
- sample_pos_in_db = np.nonzero(mask_sample)[0]
437
- global_idxs = sampled_map[sample_pos_in_db]
438
- green_positions = [global_to_greenpos[int(g)] for g in global_idxs if int(g) in global_to_greenpos]
439
- if len(green_positions) == 0:
440
- continue
441
- seeds = green_pts_full[green_positions]
442
- radius = eps1 * REGION_GROW_FACTOR
443
- neigh_lists = bt.query_radius(seeds, r=radius)
444
- for neigh in neigh_lists:
445
- for gp in neigh:
446
- full_label_assignment[int(gp)] = int(lab)
447
-
448
- final_label_positions = {}
449
- for pos, lab in enumerate(full_label_assignment):
450
- if lab == -1:
451
- continue
452
- final_label_positions.setdefault(int(lab), []).append(int(pos))
453
-
454
- clusters_info = []
455
- for lab, green_positions in final_label_positions.items():
456
- abs_indices = green_indices[green_positions]
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 to analyze the point cloud data.")
 
 
 
529
 
530
- file_state = gr.State(value=[None, None])
531
- last_file_info_state = gr.State(value={})
532
-
533
  with gr.Row():
534
- file_input = gr.File(label="Upload .pts (X Y Z R G B)")
535
  with gr.Column():
536
- output_text = gr.Textbox(label="Processing Log", lines=10)
537
- analysis_button = gr.Button("Start Analysis", interactive=False)
538
- download_button = gr.DownloadButton("Download styled Excel", visible=False)
539
-
540
- output_plot = gr.Plot(label="Interactive 3D Preview (downsampled)")
541
-
542
- file_input.upload(
543
- fn=handle_file_upload,
544
- inputs=[file_input, last_file_info_state],
545
- outputs=[output_text, analysis_button, download_button, file_state, last_file_info_state],
546
- queue=False
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()