yuanze1024 commited on
Commit
def39ee
1 Parent(s): ff4d2cd

update app.py

Browse files
Files changed (2) hide show
  1. README.md +5 -0
  2. app.py +103 -30
README.md CHANGED
@@ -7,6 +7,11 @@ sdk: docker
7
  app_port: 7860
8
  app_file: app.py
9
  pinned: false
 
 
 
 
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
7
  app_port: 7860
8
  app_file: app.py
9
  pinned: false
10
+ models:
11
+ - timm/eva02_enormous_patch14_plus_clip_224.laion2b_s9b_b144k
12
+ - BAAI/Uni3D
13
+ datasets:
14
+ - VAST-AI/LD-T3D
15
  ---
16
 
17
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,8 +1,9 @@
1
  import os
 
2
  import gradio as gr
3
- import numpy as np
4
  import torch
5
  import functools
 
6
  from datasets import load_dataset
7
  from feature_extractors.uni3d_embedding_encoder import Uni3dEmbeddingEncoder
8
 
@@ -19,6 +20,7 @@ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
  source_id_list = torch.load("data/source_id_list.pt")
20
  source_to_id = {source_id: i for i, source_id in enumerate(source_id_list)}
21
  dataset = load_dataset("VAST-AI/LD-T3D", name=f"rendered_imgs_diag_above", split="base", cache_dir=cache_dir)
 
22
 
23
  @functools.lru_cache()
24
  def get_embedding(option, modality, angle=None):
@@ -34,8 +36,8 @@ def predict(xb, xq, top_k):
34
  _, indices = sim.topk(k=top_k, largest=True)
35
  return indices
36
 
37
- def get_image(index):
38
- return dataset[index]["image"]
39
 
40
  def retrieve_3D_models(textual_query, top_k, modality_list):
41
  if textual_query == "":
@@ -88,35 +90,106 @@ def retrieve_3D_models(textual_query, top_k, modality_list):
88
  return pred_ind_list[0].cpu().tolist() # we have only one query
89
 
90
  indices = _retrieve_3D_models(textual_query, top_k, modality_list)
91
- return [get_image(index) for index in indices]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  def launch():
94
- with gr.Blocks() as demo:
95
- with gr.Row():
96
- textual_query = gr.Textbox(label="Textual Query", autofocus=True,
97
- placeholder="A chair with a wooden frame and a cushioned seat")
98
- modality_list = gr.CheckboxGroup(label="Modality List", value=[],
99
- choices=["text", "front", "back", "left", "right", "above",
100
- "below", "diag_above", "diag_below", "3D"])
101
- with gr.Row():
102
- top_k = gr.Slider(minimum=1, maximum=MAX_K_RETRIEVAL, step=1, label="Top K Retrieval Result",
103
- value=5, scale=2)
104
- run = gr.Button("Search", scale=1)
105
- clear_button = gr.ClearButton(scale=1)
106
- with gr.Row():
107
- output = gr.Gallery(format="webp", label="Retrieval Result", columns=5, type="pil")
108
- run.click(retrieve_3D_models, [textual_query, top_k, modality_list], output,
109
- # batch=True, max_batch_size=MAX_BATCH_SIZE
110
- )
111
- clear_button.click(lambda: ["", 5, [], []], outputs=[textual_query, top_k, modality_list, output])
112
- examples = gr.Examples(examples=[["An ice cream with a cherry on top", 10, ["text", "front", "back", "left", "right", "above", "below", "diag_above", "diag_below", "3D"]],
113
- ["A mid-age castle", 10, ["text", "front", "back", "left", "right", "above", "below", "diag_above", "diag_below", "3D"]],
114
- ["A coke", 10, ["text", "front", "back", "left", "right", "above", "below", "diag_above", "diag_below", "3D"]]],
115
- inputs=[textual_query, top_k, modality_list],
116
- # cache_examples=True,
117
- outputs=output,
118
- fn=retrieve_3D_models)
119
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  demo.queue(max_size=10)
121
 
122
  os.environ.pop('HTTP_PROXY')
 
1
  import os
2
+ import random
3
  import gradio as gr
 
4
  import torch
5
  import functools
6
+ from PIL import Image
7
  from datasets import load_dataset
8
  from feature_extractors.uni3d_embedding_encoder import Uni3dEmbeddingEncoder
9
 
 
20
  source_id_list = torch.load("data/source_id_list.pt")
21
  source_to_id = {source_id: i for i, source_id in enumerate(source_id_list)}
22
  dataset = load_dataset("VAST-AI/LD-T3D", name=f"rendered_imgs_diag_above", split="base", cache_dir=cache_dir)
23
+ relation = load_dataset("VAST-AI/LD-T3D", split="full", cache_dir=cache_dir)
24
 
25
  @functools.lru_cache()
26
  def get_embedding(option, modality, angle=None):
 
36
  _, indices = sim.topk(k=top_k, largest=True)
37
  return indices
38
 
39
+ def get_image_and_id(index):
40
+ return dataset[index]["image"], dataset[index]["source_id"]
41
 
42
  def retrieve_3D_models(textual_query, top_k, modality_list):
43
  if textual_query == "":
 
90
  return pred_ind_list[0].cpu().tolist() # we have only one query
91
 
92
  indices = _retrieve_3D_models(textual_query, top_k, modality_list)
93
+ return [get_image_and_id(index) for index in indices]
94
+
95
+ def get_sub_dataset(sub_dataset_id):
96
+ """
97
+ get sub-dataset by sub_dataset_id [1, 1000]
98
+
99
+ Returns:
100
+ caption: str
101
+ difficulty: str
102
+ images: list of tuple (PIL.Image, str)
103
+ """
104
+ rel = relation[sub_dataset_id - 1]
105
+ target_ids, GT_ids, caption, difficulty = set(rel["target_ids"]), set(rel["GT_ids"]), rel["caption"], rel["difficulty"]
106
+ negative_ids = target_ids - GT_ids
107
+
108
+ def handle_image(image, is_gt=False):
109
+ "image is a PIL.Image object, surround the image with green border if is_gt, else red border"
110
+ border_color = (0, 255, 0) if is_gt else (255, 0, 0)
111
+ border_width = 5
112
+ new_image = Image.new("RGBA", (image.width + 2 * border_width, image.height + 2 * border_width), border_color)
113
+ new_image.paste(image, (border_width, border_width))
114
+ return new_image
115
+
116
+ results = []
117
+ for gt_id in GT_ids:
118
+ image, source_id = get_image_and_id(source_to_id[gt_id])
119
+ results.append((handle_image(image, True), source_id))
120
+ for neg_id in negative_ids:
121
+ image, source_id = get_image_and_id(source_to_id[neg_id])
122
+ results.append((handle_image(image, False), source_id))
123
+
124
+ return caption, difficulty, results
125
+
126
+ def feel_lucky():
127
+ sub_dataset_id = random.randint(1, 1000)
128
+ return sub_dataset_id, *get_sub_dataset(sub_dataset_id)
129
 
130
  def launch():
131
+ with gr.Blocks() as demo: # https://sketchfab.com/3d-models/fd30f87848c9454c9225eccc39726787
132
+ md = gr.Markdown(r"""## LD-T3D: A Large-scale and Diverse Benchmark for Text-based 3D Model Retrieval
133
+ **Official 🤗 Gradio demo** for [LD-T3D: A Large-scale and Diverse Benchmark for Text-based 3D Model Retrieval](arxiv.org)""")
134
+ with gr.Tab("Retrieval Visualization"):
135
+ with gr.Row():
136
+ md2 = gr.Markdown(r"""### Visualization for Text-Based-3D Model Retrieval
137
+ We build a visualization demo to demonstrate the text-based-3D model retrievals. Due to the memory limitation of HF Space, we only support the [Uni3D](https://github.com/baaivision/Uni3D) which has shown an excellent performance in our benchmark.
138
+
139
+ **Note**:
140
+
141
+ The *Modality List* refers to the features ensembled by the retrieval methods. According to our experiment results, basically the more modalities, the better performance the methods gets.""")
142
+ with gr.Row():
143
+ textual_query = gr.Textbox(label="Textual Query", autofocus=True,
144
+ placeholder="A chair with a wooden frame and a cushioned seat")
145
+ modality_list = gr.CheckboxGroup(label="Modality List", value=[],
146
+ choices=["text", "front", "back", "left", "right", "above",
147
+ "below", "diag_above", "diag_below", "3D"])
148
+ with gr.Row():
149
+ top_k = gr.Slider(minimum=1, maximum=MAX_K_RETRIEVAL, step=1, label="Top K Retrieval Result",
150
+ value=5, scale=2)
151
+ run = gr.Button("Search", scale=1, variant='primary')
152
+ clear_button = gr.ClearButton(scale=1)
153
+ with gr.Row():
154
+ output = gr.Gallery(format="webp", label="Retrieval Result", columns=5, type="pil", interactive=False)
155
+ run.click(retrieve_3D_models, [textual_query, top_k, modality_list], output,
156
+ # batch=True, max_batch_size=MAX_BATCH_SIZE
157
+ )
158
+ clear_button.click(lambda: ["", 5, [], []], outputs=[textual_query, top_k, modality_list, output])
159
+ examples = gr.Examples(examples=[["An ice cream with a cherry on top", 10, ["text", "front", "back", "left", "right", "above", "below", "diag_above", "diag_below", "3D"]],
160
+ ["A mid-age castle", 10, ["text", "front", "back", "left", "right", "above", "below", "diag_above", "diag_below", "3D"]],
161
+ ["A coke", 10, ["text", "front", "back", "left", "right", "above", "below", "diag_above", "diag_below", "3D"]]],
162
+ inputs=[textual_query, top_k, modality_list],
163
+ outputs=output,
164
+ fn=retrieve_3D_models)
165
+ with gr.Tab("Federated Dataset"):
166
+ md3 = gr.Markdown(r"""### Visualization for Federated Dataset
167
+ We provide a federated dataset that contains **1000** textual queries and **89K** 3D models, which corresponds to **1000** sub-datasets with around **100** 3D models.
168
+ In total, there is 100K pairs of text-to-3D model relationships.
169
+
170
+ Here is a visualization of the dataset.
171
+
172
+ **Usage:**
173
+
174
+ 1. You can click the "I'm Feeling Lucky !" button to randomly select a sub-dataset.
175
+ 2. Or you can **Enter** to submit a Sub-dataset ID in **[1, 1000]**, which you can find details in our dataset [LD-T3D](https://huggingface.co/datasets/VAST-AI/LD-T3D), to search for the corresponding sub-dataset.
176
+
177
+ **Note:**
178
+
179
+ The *Query* is used in this sub-dataset. The *Difficulty* is a coarse label for the textual query, which is divided into **easy**, **medium**, and **hard**, basically submit to the rule in our paper.
180
+ The color surrounding the 3D model indicates whether it is a good fit for the textual query. A **<span style="color:#00FF00">green</span>** color suggests a Ground Truth, while a **<span style="color:#FF0000">red</span>** color indicates a mismatch.""")
181
+ with gr.Row():
182
+ lucky = gr.Button("I'm Feeling Lucky !", scale=1, variant='primary')
183
+ query_id = gr.Number(label="Sub-dataset ID", scale=1, minimum=1, maximum=1000, step=1, interactive=True)
184
+ query = gr.Textbox(label="Textual Query", scale=3, interactive=False)
185
+ difficulty = gr.Textbox(label="Query Difficulty", scale=1, interactive=False)
186
+ # model3d = gr.Model3D(interactive=False, scale=1)
187
+ with gr.Row():
188
+ output2 = gr.Gallery(format="webp", label="3D Models in Sub-dataset", columns=5, type="pil", interactive=False)
189
+
190
+ lucky.click(feel_lucky, outputs=[query_id, query, difficulty, output2])
191
+ query_id.submit(get_sub_dataset, query_id, [query, difficulty, output2])
192
+
193
  demo.queue(max_size=10)
194
 
195
  os.environ.pop('HTTP_PROXY')