salma-remyx commited on
Commit
0d09a3a
·
1 Parent(s): 1762eb4

update w/ vqasynth

Browse files
Files changed (2) hide show
  1. app.py +106 -422
  2. requirements.txt +1 -20
app.py CHANGED
@@ -1,468 +1,150 @@
1
  import os
2
- import sys
3
  import uuid
4
- import spaces
5
- import torch
6
- import random
7
- import numpy as np
8
- from PIL import Image
9
- import open3d as o3d
10
- import matplotlib.pyplot as plt
11
 
12
- from transformers import AutoProcessor, AutoModelForCausalLM
13
- from transformers import SamModel, SamProcessor
 
 
14
 
15
- import depth_pro
 
 
 
16
 
17
- import spacy
18
  import gradio as gr
 
19
 
20
- try:
21
- nlp = spacy.load("en_core_web_sm")
22
- except OSError:
23
- # Download the model if it's not already available
24
- from spacy.cli import download
25
- download("en_core_web_sm")
26
- nlp = spacy.load("en_core_web_sm")
27
-
28
- # Load Florence and SAM models once at the top for reuse
29
- DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
30
-
31
- def load_florence2(model_id="microsoft/Florence-2-base-ft", device=DEVICE):
32
- torch_dtype = torch.float16 if device == 'cuda' else torch.float32
33
- florence_model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch_dtype, trust_remote_code=True).to(device)
34
- florence_processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
35
- return florence_model, florence_processor
36
-
37
- florence_model, florence_processor = load_florence2() # Loaded globally for reuse
38
-
39
- def load_sam_model(model_id="facebook/sam-vit-base", device=DEVICE):
40
- sam_model = SamModel.from_pretrained(model_id).to(device)
41
- sam_processor = SamProcessor.from_pretrained(model_id)
42
- return sam_model, sam_processor
43
-
44
- sam_model, sam_processor = load_sam_model() # Loaded globally for reuse
45
-
46
- # Depth model, transform, and other assets
47
- model, transform = depth_pro.create_model_and_transforms(device=DEVICE)
48
-
49
- def find_subject(doc):
50
- for token in doc:
51
- # Check if the token is a subject
52
- if "subj" in token.dep_:
53
- return token.text, token.head
54
- return None, None
55
-
56
- def extract_descriptions(doc, head):
57
- descriptions = []
58
- for chunk in doc.noun_chunks:
59
- # Check if the chunk is directly related to the subject's verb or is an attribute
60
- if chunk.root.head == head or chunk.root.dep_ == 'attr':
61
- descriptions.append(chunk.text)
62
- return descriptions
63
-
64
- @spaces.GPU
65
- def caption_refiner(caption):
66
- doc = nlp(caption)
67
- subject, action_verb = find_subject(doc)
68
- if action_verb:
69
- descriptions = extract_descriptions(doc, action_verb)
70
- return ', '.join(descriptions)
71
- else:
72
- return caption
73
-
74
- @spaces.GPU
75
- def sam2(image, input_boxes, model_id="facebook/sam-vit-base"):
76
- inputs = sam_processor(image, input_boxes=[[input_boxes]], return_tensors="pt").to(DEVICE)
77
- with torch.no_grad():
78
- outputs = sam_model(**inputs)
79
-
80
- masks = sam_processor.image_processor.post_process_masks(
81
- outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu()
82
- )
83
- return masks
84
-
85
-
86
- @spaces.GPU
87
- def florence2(image, prompt="", task="<OD>"):
88
- torch_dtype = florence_model.dtype
89
- inputs = florence_processor(text=task + prompt, images=image, return_tensors="pt").to(DEVICE, torch_dtype)
90
- generated_ids = florence_model.generate(
91
- input_ids=inputs["input_ids"],
92
- pixel_values=inputs["pixel_values"],
93
- max_new_tokens=1024,
94
- num_beams=3,
95
- do_sample=False
96
- )
97
- generated_text = florence_processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
98
- parsed_answer = florence_processor.post_process_generation(generated_text, task=task, image_size=(image.width, image.height))
99
- return parsed_answer[task]
100
-
101
-
102
- @spaces.GPU
103
- def depth_estimation(image_path):
104
- model.eval()
105
- image, _, f_px = depth_pro.load_rgb(image_path)
106
- image = transform(image)
107
-
108
- # Run inference.
109
- prediction = model.infer(image, f_px=f_px)
110
- depth = prediction["depth"] # Depth in [m].
111
- focallength_px = prediction["focallength_px"] # Focal length in pixels.
112
- depth = depth.cpu().numpy()
113
- return depth, focallength_px
114
-
115
-
116
- def create_point_cloud_from_rgbd(rgb, depth, intrinsic_parameters):
117
- rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
118
- o3d.geometry.Image(rgb),
119
- o3d.geometry.Image(depth),
120
- depth_scale=10.0,
121
- depth_trunc=100.0,
122
- convert_rgb_to_intensity=False
123
- )
124
- intrinsic = o3d.camera.PinholeCameraIntrinsic()
125
- intrinsic.set_intrinsics(intrinsic_parameters['width'], intrinsic_parameters['height'],
126
- intrinsic_parameters['fx'], intrinsic_parameters['fy'],
127
- intrinsic_parameters['cx'], intrinsic_parameters['cy'])
128
- pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image, intrinsic)
129
- return pcd
130
-
131
-
132
- def canonicalize_point_cloud(pcd, canonicalize_threshold=0.3):
133
- # Segment the largest plane, assumed to be the floor
134
- plane_model, inliers = pcd.segment_plane(distance_threshold=0.01, ransac_n=3, num_iterations=1000)
135
-
136
- canonicalized = False
137
- if len(inliers) / len(pcd.points) > canonicalize_threshold:
138
- canonicalized = True
139
-
140
- # Ensure the plane normal points upwards
141
- if np.dot(plane_model[:3], [0, 1, 0]) < 0:
142
- plane_model = -plane_model
143
-
144
- # Normalize the plane normal vector
145
- normal = plane_model[:3] / np.linalg.norm(plane_model[:3])
146
-
147
- # Compute the new basis vectors
148
- new_y = normal
149
- new_x = np.cross(new_y, [0, 0, -1])
150
- new_x /= np.linalg.norm(new_x)
151
- new_z = np.cross(new_x, new_y)
152
-
153
- # Create the transformation matrix
154
- transformation = np.identity(4)
155
- transformation[:3, :3] = np.vstack((new_x, new_y, new_z)).T
156
- transformation[:3, 3] = -np.dot(transformation[:3, :3], pcd.points[inliers[0]])
157
-
158
-
159
- # Apply the transformation
160
- pcd.transform(transformation)
161
-
162
- # Additional 180-degree rotation around the Z-axis
163
- rotation_z_180 = np.array([[np.cos(np.pi), -np.sin(np.pi), 0],
164
- [np.sin(np.pi), np.cos(np.pi), 0],
165
- [0, 0, 1]])
166
- pcd.rotate(rotation_z_180, center=(0, 0, 0))
167
-
168
- return pcd, canonicalized, transformation
169
- else:
170
- return pcd, canonicalized, None
171
-
172
-
173
- def compute_iou(box1, box2):
174
- # Extract the coordinates
175
- x1_min, y1_min, x1_max, y1_max = box1
176
- x2_min, y2_min, x2_max, y2_max = box2
177
-
178
- # Compute the intersection rectangle
179
- x_inter_min = max(x1_min, x2_min)
180
- y_inter_min = max(y1_min, y2_min)
181
- x_inter_max = min(x1_max, x2_max)
182
- y_inter_max = min(y1_max, y2_max)
183
-
184
- # Intersection width and height
185
- inter_width = max(0, x_inter_max - x_inter_min)
186
- inter_height = max(0, y_inter_max - y_inter_min)
187
-
188
- # Intersection area
189
- inter_area = inter_width * inter_height
190
-
191
- # Boxes areas
192
- box1_area = (x1_max - x1_min) * (y1_max - y1_min)
193
- box2_area = (x2_max - x2_min) * (y2_max - y2_min)
194
-
195
- # Union area
196
- union_area = box1_area + box2_area - inter_area
197
-
198
- # Intersection over Union
199
- iou = inter_area / union_area if union_area != 0 else 0
200
-
201
- return iou
202
-
203
-
204
- def human_like_distance(distance_meters, scale_factor=10):
205
- # Define the choices with units included, focusing on the 0.1 to 10 meters range
206
- distance_meters *= scale_factor
207
- if distance_meters < 1: # For distances less than 1 meter
208
- choices = [
209
- (
210
- round(distance_meters * 100, 2),
211
- "centimeters",
212
- 0.2,
213
- ), # Centimeters for very small distances
214
- (
215
- round(distance_meters, 2),
216
- "inches",
217
- 0.8,
218
- ), # Inches for the majority of cases under 1 meter
219
- ]
220
- elif distance_meters < 3: # For distances less than 3 meters
221
- choices = [
222
- (round(distance_meters, 2), "meters", 0.5),
223
- (
224
- round(distance_meters, 2),
225
- "feet",
226
- 0.5,
227
- ), # Feet as a common unit within indoor spaces
228
- ]
229
- else: # For distances from 3 up to 10 meters
230
- choices = [
231
- (
232
- round(distance_meters, 2),
233
- "meters",
234
- 0.7,
235
- ), # Meters for clarity and international understanding
236
- (
237
- round(distance_meters, 2),
238
- "feet",
239
- 0.3,
240
- ), # Feet for additional context
241
- ]
242
- # Normalize probabilities and make a selection
243
- total_probability = sum(prob for _, _, prob in choices)
244
- cumulative_distribution = []
245
- cumulative_sum = 0
246
- for value, unit, probability in choices:
247
- cumulative_sum += probability / total_probability # Normalize probabilities
248
- cumulative_distribution.append((cumulative_sum, value, unit))
249
-
250
- # Randomly choose based on the cumulative distribution
251
- r = random.random()
252
- for cumulative_prob, value, unit in cumulative_distribution:
253
- if r < cumulative_prob:
254
- return f"{value} {unit}"
255
-
256
- # Fallback to the last choice if something goes wrong
257
- return f"{choices[-1][0]} {choices[-1][1]}"
258
-
259
-
260
- def filter_bboxes(data, iou_threshold=0.5):
261
- filtered_bboxes = []
262
- filtered_labels = []
263
-
264
- for i in range(len(data['bboxes'])):
265
- current_box = data['bboxes'][i]
266
- current_label = data['labels'][i]
267
- is_duplicate = False
268
-
269
- for j in range(len(filtered_bboxes)):
270
- if current_label == filtered_labels[j]:# and compute_iou(current_box, filtered_bboxes[j]) > iou_threshold:
271
- is_duplicate = True
272
- break
273
-
274
- if not is_duplicate:
275
- filtered_bboxes.append(current_box)
276
- filtered_labels.append(current_label)
277
-
278
- return {'bboxes': filtered_bboxes, 'labels': filtered_labels, 'caption': data['caption']}
279
-
280
- @spaces.GPU
281
- def process_image(image_path: str):
282
- depth, fx = depth_estimation(image_path)
283
-
284
- img = Image.open(image_path).convert('RGB')
285
- width, height = img.size
286
-
287
- description = florence2(img, task="<MORE_DETAILED_CAPTION>")
288
- print(description)
289
-
290
- regions = []
291
- for cap in description.split('.'):
292
- if cap:
293
- roi = florence2(img, prompt=" " + cap, task="<CAPTION_TO_PHRASE_GROUNDING>")
294
- roi["caption"] = caption_refiner(cap.lower())
295
- roi = filter_bboxes(roi)
296
- if len(roi['bboxes']) > 1:
297
- flip = random.choice(['heads', 'tails'])
298
- if flip == 'heads':
299
- idx = random.randint(1, len(roi['bboxes']) - 1)
300
- else:
301
- idx = 0
302
- if idx > 0: # test bbox IOU
303
- roi['caption'] = roi['labels'][idx].lower() + ' with ' + roi['labels'][0].lower()
304
- roi['bboxes'] = [roi['bboxes'][idx]]
305
- roi['labels'] = [roi['labels'][idx]]
306
-
307
- if roi['bboxes']:
308
- regions.append(roi)
309
- print(roi)
310
-
311
- bboxes = [item['bboxes'][0] for item in regions]
312
- n = len(bboxes)
313
- distance_matrix = np.zeros((n, n))
314
- for i in range(n):
315
- for j in range(n):
316
  if i != j:
317
- distance_matrix[i][j] = 1 - compute_iou(bboxes[i], bboxes[j])
318
-
319
- scores = np.sum(distance_matrix, axis=1)
320
- selected_indices = np.argsort(scores)[-3:]
321
- regions = [(regions[i]['bboxes'][0], regions[i]['caption']) for i in selected_indices][:2]
322
-
323
- # Create point cloud
324
- camera_intrinsics = intrinsic_parameters = {
325
- 'width': width,
326
- 'height': height,
327
- 'fx': fx,
328
- 'fy': fx * height / width,
329
- 'cx': width / 2,
330
- 'cy': height / 2,
331
- }
332
-
333
- pcd = create_point_cloud_from_rgbd(np.array(img).copy(), depth, camera_intrinsics)
334
- normed_pcd, canonicalized, transformation = canonicalize_point_cloud(pcd)
335
-
336
-
337
- masks = []
338
- for box, cap in regions:
339
- masks.append((cap, sam2(img, box)))
340
-
341
-
342
- point_clouds = []
343
- for cap, mask in masks:
344
- m = mask[0].numpy()[0].squeeze().transpose((1, 2, 0))
345
- mask = np.any(m, axis=2)
346
-
347
- try:
348
- points = np.asarray(normed_pcd.points)
349
- colors = np.asarray(normed_pcd.colors)
350
- masked_points = points[mask.ravel()]
351
- masked_colors = colors[mask.ravel()]
352
-
353
- masked_point_cloud = o3d.geometry.PointCloud()
354
- masked_point_cloud.points = o3d.utility.Vector3dVector(masked_points)
355
- masked_point_cloud.colors = o3d.utility.Vector3dVector(masked_colors)
356
-
357
- point_clouds.append((cap, masked_point_cloud))
358
- except:
359
- pass
360
-
361
- boxes3D = []
362
- centers = []
363
- pcd = o3d.geometry.PointCloud()
364
- for cap, pc in point_clouds[:2]:
365
- cl, ind = pc.remove_statistical_outlier(nb_neighbors=20, std_ratio=2.0)
366
- inlier_cloud = pc.select_by_index(ind)
367
- pcd += inlier_cloud
368
- obb = inlier_cloud.get_axis_aligned_bounding_box()
369
- obb.color = (1, 0, 0)
370
- centers.append(obb.get_center())
371
- boxes3D.append(obb)
372
-
373
-
374
- lines = [[0, 1]]
375
- points = [centers[0], centers[1]]
376
- distance = human_like_distance(np.asarray(point_clouds[0][1].compute_point_cloud_distance(point_clouds[-1][1])).mean())
377
- text_output = "Distance between {} and {} is: {}".format(point_clouds[0][0], point_clouds[-1][0], distance)
378
- print(text_output)
379
-
380
- colors = [[1, 0, 0] for i in range(len(lines))] # Red color for lines
381
- line_set = o3d.geometry.LineSet(
382
- points=o3d.utility.Vector3dVector(points),
383
- lines=o3d.utility.Vector2iVector(lines)
384
- )
385
- line_set.colors = o3d.utility.Vector3dVector(colors)
386
-
387
- boxes3D.append(line_set)
388
-
389
 
390
  uuid_out = str(uuid.uuid4())
391
- ply_file = f"output_{uuid_out}.ply"
392
- obj_file = f"output_{uuid_out}.obj"
393
- o3d.io.write_point_cloud(ply_file, pcd)
 
394
 
395
  mesh = o3d.io.read_triangle_mesh(ply_file)
396
-
397
  o3d.io.write_triangle_mesh(obj_file, mesh)
398
 
399
- return obj_file, text_output
400
-
401
 
402
 
403
- def custom_draw_geometry_with_rotation(pcd):
 
 
 
 
 
 
 
 
 
 
 
404
 
405
- def rotate_view(vis):
406
- ctr = vis.get_view_control()
407
- vis.get_render_option().background_color = [0, 0, 0]
408
- ctr.rotate(1.0, 0.0)
409
- # https://github.com/isl-org/Open3D/issues/1483
410
- #parameters = o3d.io.read_pinhole_camera_parameters("ScreenCamera_2024-10-24-10-03-57.json")
411
- #ctr.convert_from_pinhole_camera_parameters(parameters)
412
- return False
413
 
414
- o3d.visualization.draw_geometries_with_animation_callback([pcd] + boxes3D,
415
- rotate_view)
 
 
 
 
416
 
417
 
418
  def build_demo():
419
  with gr.Blocks() as demo:
420
- # Title and introductory Markdown
421
- gr.Markdown("""
422
  # Synthesizing SpatialVQA Samples with VQASynth
423
  This space helps test the full [VQASynth](https://github.com/remyxai/VQASynth) scene reconstruction pipeline on a single image with visualizations.
424
-
425
  ### [Github](https://github.com/remyxai/VQASynth) | [Collection](https://huggingface.co/collections/remyxai/spacevlms-66a3dbb924756d98e7aec678)
426
- """)
 
427
 
428
- # Description for users
429
- gr.Markdown("""
430
  ## Instructions
431
  Upload an image, and the tool will generate a corresponding 3D point cloud visualization of the objects found and an example prompt and response describing a spatial relationship between the objects.
432
- """)
 
433
 
434
  with gr.Row():
435
- # Left Column: Inputs
436
  with gr.Column():
437
- # Image upload and processing button in the left column
438
  image_input = gr.Image(type="filepath", label="Upload an Image")
439
  generate_button = gr.Button("Generate")
440
 
441
- # Right Column: Outputs
442
  with gr.Column():
443
- # 3D Model and Caption Outputs
444
  model_output = gr.Model3D(label="3D Point Cloud") # Only used as output
445
  caption_output = gr.Text(label="Caption")
446
 
447
- # Link the button to process the image and display the outputs
448
  generate_button.click(
449
- process_image, # Your processing function
450
- inputs=image_input,
451
- outputs=[model_output, caption_output]
452
  )
453
 
454
- # Examples section at the bottom
455
  gr.Examples(
456
- examples=[
457
- ["./examples/warehouse_rgb.jpg"], ["./examples/spooky_doggy.png"], ["./examples/bee_and_flower.jpg"], ["./examples/road-through-dense-forest.jpg"], ["./examples/gears.png"] # Update with the path to your example image
458
- ],
459
  inputs=image_input,
460
  label="Example Images",
461
- examples_per_page=5
462
  )
463
 
464
- # Citations
465
- gr.Markdown("""
466
  ## Citation
467
  ```
468
  @article{chen2024spatialvlm,
@@ -473,10 +155,12 @@ def build_demo():
473
  url = {https://arxiv.org/abs/2401.12168},
474
  }
475
  ```
476
- """)
 
477
 
478
  return demo
479
 
480
- if __name__ == "__main__":
 
481
  demo = build_demo()
482
- demo.launch()
 
1
  import os
 
2
  import uuid
3
+ import tempfile
 
 
 
 
 
 
4
 
5
+ import cv2
6
+ import open3d as o3d
7
+ import PIL
8
+ from PIL import Image
9
 
10
+ from vqasynth.depth import DepthEstimator
11
+ from vqasynth.localize import Localizer
12
+ from vqasynth.scene_fusion import SpatialSceneConstructor
13
+ from vqasynth.prompts import PromptGenerator
14
 
15
+ import numpy as np
16
  import gradio as gr
17
+ import spaces
18
 
19
+ depth = DepthEstimator(from_onnx=False)
20
+ localizer = Localizer()
21
+ spatial_scene_constructor = SpatialSceneConstructor()
22
+ prompt_generator = PromptGenerator()
23
+
24
+
25
+ def combine_segmented_pointclouds(
26
+ pointcloud_ply_files: list, captions: list, prompts: list, cache_dir: str
27
+ ):
28
+ """
29
+ Process a list of segmented point clouds to combine two based on captions and return the resulting 3D point cloud and the identified prompt.
30
+
31
+ Args:
32
+ pointcloud_ply_files (list): List of file paths to `.pcd` files representing segmented point clouds.
33
+ captions (list): List of captions corresponding to the segmented point clouds.
34
+ prompts (list): List of prompts containing questions and answers about the captions.
35
+ cache_dir (str): Directory to save the final `.ply` and `.obj` files.
36
+
37
+ Returns:
38
+ tuple: The path to the generated `.obj` file and the identified prompt text.
39
+ """
40
+ selected_prompt = None
41
+ selected_indices = None
42
+ for i, caption1 in enumerate(captions):
43
+ for j, caption2 in enumerate(captions):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  if i != j:
45
+ for prompt in prompts:
46
+ if caption1 in prompt and caption2 in prompt:
47
+ selected_prompt = prompt
48
+ selected_indices = (i, j)
49
+ break
50
+ if selected_prompt:
51
+ break
52
+ if selected_prompt:
53
+ break
54
+
55
+ if not selected_prompt or not selected_indices:
56
+ raise ValueError("No prompt found containing two captions.")
57
+
58
+ idx1, idx2 = selected_indices
59
+ pointcloud_files = [pointcloud_ply_files[idx1], pointcloud_ply_files[idx2]]
60
+ captions = [captions[idx1], captions[idx2]]
61
+
62
+ combined_point_cloud = o3d.geometry.PointCloud()
63
+ for idx, pointcloud_file in enumerate(pointcloud_files):
64
+ pcd = o3d.io.read_point_cloud(pointcloud_file)
65
+ if pcd.is_empty():
66
+ continue
67
+
68
+ combined_point_cloud += pcd
69
+
70
+ if combined_point_cloud.is_empty():
71
+ raise ValueError(
72
+ "Combined point cloud is empty after loading the selected segments."
73
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  uuid_out = str(uuid.uuid4())
76
+ ply_file = os.path.join(cache_dir, f"combined_output_{uuid_out}.ply")
77
+ obj_file = os.path.join(cache_dir, f"combined_output_{uuid_out}.obj")
78
+
79
+ o3d.io.write_point_cloud(ply_file, combined_point_cloud)
80
 
81
  mesh = o3d.io.read_triangle_mesh(ply_file)
 
82
  o3d.io.write_triangle_mesh(obj_file, mesh)
83
 
84
+ return obj_file, selected_prompt
 
85
 
86
 
87
+ @spaces.GPU
88
+ def run_vqasynth_pipeline(image: PIL.Image, cache_dir: str):
89
+ depth_map, focal_length = depth.run(image)
90
+ masks, bounding_boxes, captions = localizer.run(image)
91
+ pointcloud_data, cannonicalized = spatial_scene_constructor.run(
92
+ str(0), image, depth_map, focal_length, masks, cache_dir
93
+ )
94
+ prompts = prompt_generator.run(captions, pointcloud_data, cannonicalized)
95
+ obj_file, selected_prompt = combine_segmented_pointclouds(
96
+ pointcloud_data, captions, prompts, cache_dir
97
+ )
98
+ return obj_file, selected_prompt
99
 
 
 
 
 
 
 
 
 
100
 
101
+ def process_image(image: str):
102
+ # Use a persistent temporary directory to keep the .obj file accessible by Gradio
103
+ temp_dir = tempfile.mkdtemp()
104
+ image = Image.open(image).convert("RGB")
105
+ obj_file, prompt = run_vqasynth_pipeline(image, temp_dir)
106
+ return obj_file, prompt
107
 
108
 
109
  def build_demo():
110
  with gr.Blocks() as demo:
111
+ gr.Markdown(
112
+ """
113
  # Synthesizing SpatialVQA Samples with VQASynth
114
  This space helps test the full [VQASynth](https://github.com/remyxai/VQASynth) scene reconstruction pipeline on a single image with visualizations.
 
115
  ### [Github](https://github.com/remyxai/VQASynth) | [Collection](https://huggingface.co/collections/remyxai/spacevlms-66a3dbb924756d98e7aec678)
116
+ """
117
+ )
118
 
119
+ gr.Markdown(
120
+ """
121
  ## Instructions
122
  Upload an image, and the tool will generate a corresponding 3D point cloud visualization of the objects found and an example prompt and response describing a spatial relationship between the objects.
123
+ """
124
+ )
125
 
126
  with gr.Row():
 
127
  with gr.Column():
 
128
  image_input = gr.Image(type="filepath", label="Upload an Image")
129
  generate_button = gr.Button("Generate")
130
 
 
131
  with gr.Column():
 
132
  model_output = gr.Model3D(label="3D Point Cloud") # Only used as output
133
  caption_output = gr.Text(label="Caption")
134
 
 
135
  generate_button.click(
136
+ process_image, inputs=image_input, outputs=[model_output, caption_output]
 
 
137
  )
138
 
 
139
  gr.Examples(
140
+ examples=[["./assets/warehouse_rgb.jpg"], ["./assets/spooky_doggy.png"]],
 
 
141
  inputs=image_input,
142
  label="Example Images",
143
+ examples_per_page=5,
144
  )
145
 
146
+ gr.Markdown(
147
+ """
148
  ## Citation
149
  ```
150
  @article{chen2024spatialvlm,
 
155
  url = {https://arxiv.org/abs/2401.12168},
156
  }
157
  ```
158
+ """
159
+ )
160
 
161
  return demo
162
 
163
+
164
+ if __name__ == "__main__":
165
  demo = build_demo()
166
+ demo.launch(share=True)
requirements.txt CHANGED
@@ -7,29 +7,10 @@ torchaudio==2.4.0
7
  transformers>=4.41.0
8
  Pillow
9
  gradio==5.5.0
10
- accelerate==0.34.2
11
- numpy==1.26.3
12
- timm==1.0.9
13
- einops==0.7.0
14
- open3d==0.18.0
15
- opencv-python==4.7.0.72
16
- tqdm>=4.66.3
17
- torchprofile==0.0.4
18
- matplotlib==3.6.2
19
- huggingface-hub==0.25.1
20
- onnx==1.13.1
21
- onnxruntime==1.14.1
22
- onnxsim==0.4.35
23
- scipy==1.12.0
24
- litellm==1.25.2
25
- pycocotools==2.0.6
26
- datasets==3.1.0
27
  spacy==3.7.5
28
- onnxruntime-gpu
29
- pandas
30
- html5lib
31
  spaces
32
 
 
33
  git+https://github.com/apple/ml-depth-pro.git
34
  git+https://github.com/facebookresearch/sam2.git
35
  git+https://github.com/openai/CLIP.git
 
7
  transformers>=4.41.0
8
  Pillow
9
  gradio==5.5.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  spacy==3.7.5
 
 
 
11
  spaces
12
 
13
+ git+https://github.com/remyxai/VQASynth.git
14
  git+https://github.com/apple/ml-depth-pro.git
15
  git+https://github.com/facebookresearch/sam2.git
16
  git+https://github.com/openai/CLIP.git