vasileiosbalntas commited on
Commit
e1e96e6
·
verified ·
1 Parent(s): ce6e718

fix: follow the v0.3+ layout (walkthroughs/<id>/) and add a walkthrough picker

Browse files
Files changed (1) hide show
  1. app.py +73 -69
app.py CHANGED
@@ -2,17 +2,22 @@
2
  Staer Warehouses — interactive dataset previewer.
3
 
4
  Pulls per-scene artefacts from `staerrobotics/warehouses` (the dataset)
5
- and renders a Gradio app that lets a user pick a scene and inspect:
 
6
 
7
  - The 4-modality preview video (RGB / depth / semantic / instance)
8
  - A representative thumbnail frame
9
  - Top OBB classes + counts
10
  - A 3D scatter of every OBB centre, coloured by class
11
- - The first 12 camera poses as a quick trajectory check
 
 
 
 
 
12
  """
13
  from __future__ import annotations
14
 
15
- import io
16
  import json
17
  import os
18
  from collections import Counter
@@ -28,7 +33,7 @@ SCENES = [f"scene{i:02d}" for i in range(1, 16)]
28
  HF_TOKEN = os.environ.get("HF_TOKEN") # injected by the Space at runtime
29
 
30
 
31
- @lru_cache(maxsize=64)
32
  def fetch(path: str) -> str:
33
  """Cache + return a local path for a file from the dataset."""
34
  return hf_hub_download(
@@ -46,50 +51,58 @@ def _safe_read_json(path: str) -> dict:
46
  return {"_error": str(exc)}
47
 
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  def scene_table_lazy() -> pd.DataFrame:
50
- """Lightweight scene catalogue using only manifest + metadata JSON
51
- (each <2 KB). Avoids touching scene_graph.json so the Space starts
52
- quickly — full per-scene counts are loaded on demand by `render_scene`.
53
- """
54
  rows = []
55
  for s in SCENES:
56
- try:
57
- mf = _safe_read_json(f"{s}/manifest.json")
58
- md = _safe_read_json(f"{s}/metadata.json")
59
- rows.append(
60
- {
61
- "scene": s,
62
- "frames": mf.get("frameCount", "?"),
63
- "duration_s": mf.get("durationSeconds", "?"),
64
- "modalities": ", ".join(
65
- md.get("metadata", {}).get("modalities", []) or []
66
- ),
67
- "resolution": "x".join(
68
- str(v) for v in md.get("metadata", {}).get("resolution", []) or []
69
- ),
70
- }
71
- )
72
- except Exception as exc: # noqa: BLE001
73
- rows.append({"scene": s, "_error": str(exc)})
74
  return pd.DataFrame(rows)
75
 
76
 
77
- def render_scene(scene: str):
78
- if not scene:
79
- return None, None, None, None, "Pick a scene from the dropdown."
 
 
 
80
 
81
- preview = fetch(f"{scene}/preview.mp4")
82
- thumb = fetch(f"{scene}/thumbnail.jpg")
83
- sg = _safe_read_json(f"{scene}/scene_graph.json")
 
 
 
 
 
 
84
 
85
- # Class histogram (top 15)
86
  classes = Counter(o.get("class", "unknown") for o in sg.get("objects", []))
87
  class_df = pd.DataFrame(
88
  sorted(classes.items(), key=lambda kv: -kv[1])[:15],
89
  columns=["class", "count"],
90
  )
91
 
92
- # 3D OBB-centre scatter
93
  pts = []
94
  for obj in sg.get("objects", []):
95
  c = (obj.get("obb_world_m") or {}).get("center")
@@ -99,12 +112,7 @@ def render_scene(scene: str):
99
  pts_df = pd.DataFrame(pts)
100
  fig = (
101
  px.scatter_3d(
102
- pts_df,
103
- x="x",
104
- y="y",
105
- z="z",
106
- color="class",
107
- opacity=0.7,
108
  title=f"{scene} — {len(pts_df)} OBB centres",
109
  )
110
  if not pts_df.empty
@@ -118,16 +126,13 @@ def render_scene(scene: str):
118
  height=520,
119
  )
120
 
121
- # Header
122
- n_obj = len(sg.get("objects", []))
123
- n_classes = len(classes)
124
  summary = (
125
- f"### {scene}\n"
126
- f"- **objects**: {n_obj:,}\n"
127
- f"- **distinct classes**: {n_classes}\n"
128
- f"- **frames**: {sg.get('frame_count', '?')}\n"
 
129
  )
130
-
131
  return preview, thumb, class_df, fig, summary
132
 
133
 
@@ -135,51 +140,50 @@ with gr.Blocks(title="Staer Warehouses") as demo:
135
  gr.Markdown(
136
  "# Staer Warehouses — dataset previewer\n"
137
  f"Interactive view of [{DATASET_ID}](https://huggingface.co/datasets/{DATASET_ID}). "
138
- "Pick a scene to inspect the 4-modality preview, OBB class distribution, "
139
- "and a 3D scatter of every annotated object."
140
  )
141
 
142
  with gr.Row():
143
- catalogue = gr.Dataframe(
144
- interactive=False,
145
- wrap=True,
146
- label="Scene catalogue",
147
- )
148
 
149
  with gr.Row():
150
  scene_picker = gr.Dropdown(
151
- choices=SCENES,
152
- value=SCENES[0],
153
- label="Scene",
154
- interactive=True,
155
- scale=1,
156
  )
157
 
158
  summary_md = gr.Markdown()
159
  with gr.Row():
160
  with gr.Column(scale=2):
161
- preview_video = gr.Video(label="4-modality preview (RGB | depth | semantic | instance)")
 
 
162
  with gr.Column(scale=1):
163
  thumb_image = gr.Image(label="Thumbnail", type="filepath")
164
 
165
  with gr.Row():
166
  with gr.Column():
167
  class_table = gr.Dataframe(
168
- label="Top 15 classes by OBB count",
169
- wrap=True,
170
- interactive=False,
171
  )
172
  with gr.Column(scale=2):
173
  scatter_plot = gr.Plot(label="OBB centres (world frame)")
174
 
 
175
  scene_picker.change(
176
- fn=render_scene,
177
- inputs=scene_picker,
178
- outputs=[preview_video, thumb_image, class_table, scatter_plot, summary_md],
 
179
  )
180
- # Defer expensive lookups to first user interaction; load only the
181
- # cheap catalogue when the page mounts.
 
182
  demo.load(fn=scene_table_lazy, inputs=None, outputs=catalogue)
 
183
 
184
 
185
  if __name__ == "__main__":
 
2
  Staer Warehouses — interactive dataset previewer.
3
 
4
  Pulls per-scene artefacts from `staerrobotics/warehouses` (the dataset)
5
+ and renders a Gradio app that lets a user pick a scene and a walkthrough
6
+ and inspect:
7
 
8
  - The 4-modality preview video (RGB / depth / semantic / instance)
9
  - A representative thumbnail frame
10
  - Top OBB classes + counts
11
  - A 3D scatter of every OBB centre, coloured by class
12
+ - Frame/duration metadata for the selected walkthrough
13
+
14
+ Layout note: since v0.3 every scene holds many walkthroughs under
15
+ `sceneNN/walkthroughs/<id>/`, and the old per-scene copies at the scene
16
+ root (preview.mp4, manifest.json, metadata.json) are gone. Only
17
+ `scene_graph.json` and `thumbnail.jpg` still live at the scene root.
18
  """
19
  from __future__ import annotations
20
 
 
21
  import json
22
  import os
23
  from collections import Counter
 
33
  HF_TOKEN = os.environ.get("HF_TOKEN") # injected by the Space at runtime
34
 
35
 
36
+ @lru_cache(maxsize=128)
37
  def fetch(path: str) -> str:
38
  """Cache + return a local path for a file from the dataset."""
39
  return hf_hub_download(
 
51
  return {"_error": str(exc)}
52
 
53
 
54
+ @lru_cache(maxsize=1)
55
+ def _repo_files() -> tuple[str, ...]:
56
+ api = HfApi(token=HF_TOKEN)
57
+ return tuple(api.list_repo_files(DATASET_ID, repo_type="dataset"))
58
+
59
+
60
+ @lru_cache(maxsize=32)
61
+ def walkthroughs_of(scene: str) -> tuple[str, ...]:
62
+ """Walkthrough ids present for a scene, e.g. ('001', '002', ...)."""
63
+ prefix = f"{scene}/walkthroughs/"
64
+ ids = {f[len(prefix):].split("/")[0] for f in _repo_files() if f.startswith(prefix)}
65
+ return tuple(sorted(ids))
66
+
67
+
68
  def scene_table_lazy() -> pd.DataFrame:
69
+ """Lightweight scene catalogue: walkthrough counts + object counts come
70
+ from the file listing and the per-scene scene_graph, both cheap."""
 
 
71
  rows = []
72
  for s in SCENES:
73
+ walks = walkthroughs_of(s)
74
+ row = {"scene": s, "walkthroughs": len(walks)}
75
+ md = _safe_read_json(f"{s}/walkthroughs/{walks[0]}/metadata.json") if walks else {}
76
+ inner = md.get("metadata", {}) if isinstance(md, dict) else {}
77
+ row["modalities"] = ", ".join(inner.get("modalities", []) or [])
78
+ row["resolution"] = "x".join(str(v) for v in (inner.get("resolution") or []))
79
+ rows.append(row)
 
 
 
 
 
 
 
 
 
 
 
80
  return pd.DataFrame(rows)
81
 
82
 
83
+ def on_scene_change(scene: str):
84
+ """Repopulate the walkthrough picker, then render the first one."""
85
+ walks = walkthroughs_of(scene)
86
+ first = walks[0] if walks else None
87
+ return (gr.update(choices=list(walks), value=first), *render(scene, first))
88
+
89
 
90
+ def render(scene: str, walk: str | None):
91
+ if not scene or not walk:
92
+ return None, None, None, None, "Pick a scene and walkthrough."
93
+
94
+ base = f"{scene}/walkthroughs/{walk}"
95
+ preview = fetch(f"{base}/preview.mp4")
96
+ thumb = fetch(f"{scene}/thumbnail.jpg") # still at the scene root
97
+ sg = _safe_read_json(f"{scene}/scene_graph.json") # shared by all walkthroughs
98
+ mf = _safe_read_json(f"{base}/manifest.json")
99
 
 
100
  classes = Counter(o.get("class", "unknown") for o in sg.get("objects", []))
101
  class_df = pd.DataFrame(
102
  sorted(classes.items(), key=lambda kv: -kv[1])[:15],
103
  columns=["class", "count"],
104
  )
105
 
 
106
  pts = []
107
  for obj in sg.get("objects", []):
108
  c = (obj.get("obb_world_m") or {}).get("center")
 
112
  pts_df = pd.DataFrame(pts)
113
  fig = (
114
  px.scatter_3d(
115
+ pts_df, x="x", y="y", z="z", color="class", opacity=0.7,
 
 
 
 
 
116
  title=f"{scene} — {len(pts_df)} OBB centres",
117
  )
118
  if not pts_df.empty
 
126
  height=520,
127
  )
128
 
 
 
 
129
  summary = (
130
+ f"### {scene} — walkthrough {walk} ({len(walkthroughs_of(scene))} available)\n"
131
+ f"- **objects**: {len(sg.get('objects', [])):,}\n"
132
+ f"- **distinct classes**: {len(classes)}\n"
133
+ f"- **frames**: {mf.get('frameCount', '?')} "
134
+ f"(**{mf.get('durationSeconds', '?')} s** at {mf.get('fps', '?')} fps)\n"
135
  )
 
136
  return preview, thumb, class_df, fig, summary
137
 
138
 
 
140
  gr.Markdown(
141
  "# Staer Warehouses — dataset previewer\n"
142
  f"Interactive view of [{DATASET_ID}](https://huggingface.co/datasets/{DATASET_ID}). "
143
+ "Pick a scene and one of its walkthroughs to inspect the 4-modality preview, "
144
+ "the OBB class distribution, and a 3D scatter of every annotated object."
145
  )
146
 
147
  with gr.Row():
148
+ catalogue = gr.Dataframe(interactive=False, wrap=True, label="Scene catalogue")
 
 
 
 
149
 
150
  with gr.Row():
151
  scene_picker = gr.Dropdown(
152
+ choices=SCENES, value=SCENES[0], label="Scene", interactive=True, scale=1
153
+ )
154
+ walk_picker = gr.Dropdown(
155
+ choices=[], value=None, label="Walkthrough", interactive=True, scale=1
 
156
  )
157
 
158
  summary_md = gr.Markdown()
159
  with gr.Row():
160
  with gr.Column(scale=2):
161
+ preview_video = gr.Video(
162
+ label="4-modality preview (RGB | depth | semantic | instance)"
163
+ )
164
  with gr.Column(scale=1):
165
  thumb_image = gr.Image(label="Thumbnail", type="filepath")
166
 
167
  with gr.Row():
168
  with gr.Column():
169
  class_table = gr.Dataframe(
170
+ label="Top 15 classes by OBB count", wrap=True, interactive=False
 
 
171
  )
172
  with gr.Column(scale=2):
173
  scatter_plot = gr.Plot(label="OBB centres (world frame)")
174
 
175
+ outputs = [preview_video, thumb_image, class_table, scatter_plot, summary_md]
176
  scene_picker.change(
177
+ fn=on_scene_change, inputs=scene_picker, outputs=[walk_picker, *outputs]
178
+ )
179
+ walk_picker.change(
180
+ fn=render, inputs=[scene_picker, walk_picker], outputs=outputs
181
  )
182
+
183
+ # Defer expensive lookups to first user interaction; on mount load only
184
+ # the cheap catalogue and populate the walkthrough picker for scene 1.
185
  demo.load(fn=scene_table_lazy, inputs=None, outputs=catalogue)
186
+ demo.load(fn=on_scene_change, inputs=scene_picker, outputs=[walk_picker, *outputs])
187
 
188
 
189
  if __name__ == "__main__":