tugot17 Claude Opus 4.7 (1M context) commited on
Commit
26ee000
·
1 Parent(s): 7373075

Add Gradio app for visualizing Gemini Robotics-ER 1.6 outputs

Browse files

Interactive demo supporting 2D points, bounding boxes, trajectories, grasp
points, instrument readings, and free-form spatial reasoning. API key can be
provided via UI textbox or GEMINI_API_KEY env var (Space Secret); the server
never echoes the env key back to the browser.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

README.md CHANGED
@@ -1,12 +1,49 @@
1
  ---
2
- title: Gemini Robotics Visualization
3
- emoji: 👁
4
- colorFrom: green
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.12.0
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Gemini Robotics-ER 1.6 Visualizer
3
+ emoji: 🤖
4
+ colorFrom: indigo
5
+ colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.12.0
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
+ # Gemini Robotics-ER 1.6 Visualizer
13
+
14
+ A Gradio app that visualizes the outputs of
15
+ [`gemini-robotics-er-1.6-preview`](https://ai.google.dev/gemini-api/docs/robotics-overview):
16
+ 2D points, bounding boxes, trajectories, grasp points, instrument readings,
17
+ and free-form spatial reasoning.
18
+
19
+ ![App screenshot](visualization.png)
20
+
21
+ ## Using it
22
+
23
+ Pick an image (local example or URL), choose a task, optionally edit the
24
+ prompt, then click **Run**. Points and trajectories are drawn as dots and a
25
+ polyline; bounding boxes as rectangles. Raw JSON and the raw model answer are
26
+ shown alongside.
27
+
28
+ ## API key
29
+
30
+ The app calls the Gemini API and needs a key. There are two ways to provide one:
31
+
32
+ 1. **Paste a key** into the "Gemini API key" field in the UI. It is sent only
33
+ to this server to make the API call and is not logged or persisted.
34
+ 2. **Server-side key** via the `GEMINI_API_KEY` environment variable
35
+ (Hugging Face Space Secrets, or a local `.env` file). If set, it is used as
36
+ a fallback when the textbox is empty. The server never echoes this key back
37
+ to the browser.
38
+
39
+ If you fork this Space and set `GEMINI_API_KEY` as a Secret, any visitor can
40
+ call the API on your quota — make sure that's what you want.
41
+
42
+ ## Running locally
43
+
44
+ ```bash
45
+ python -m venv .venv && . .venv/bin/activate
46
+ pip install -r requirements.txt
47
+ echo "GEMINI_API_KEY=..." > .env
48
+ python app.py
49
+ ```
app.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio webapp to visualize Gemini Robotics-ER 1.6 outputs."""
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ import json
6
+ import os
7
+ import re
8
+ from pathlib import Path
9
+
10
+ import gradio as gr
11
+ from dotenv import load_dotenv
12
+ from google import genai
13
+ from google.genai import errors as genai_errors
14
+ from google.genai import types
15
+ from PIL import Image, ImageDraw, ImageFont
16
+
17
+ load_dotenv()
18
+
19
+ MODEL = "gemini-robotics-er-1.6-preview"
20
+ EXAMPLES_DIR = Path(__file__).parent / "examples"
21
+
22
+ PALETTE = [
23
+ "#ef4444", "#22c55e", "#3b82f6", "#eab308", "#a855f7",
24
+ "#ec4899", "#06b6d4", "#f97316", "#84cc16", "#14b8a6",
25
+ ]
26
+
27
+ TASK_TEMPLATES = {
28
+ "Points (object detection)": (
29
+ "Point to the most prominent objects in this image (up to 10). "
30
+ "Output ONLY a JSON list in the form "
31
+ '[{"point": [y, x], "label": <concise object name>}] '
32
+ "with coordinates normalized to 0-1000."
33
+ ),
34
+ "Bounding boxes": (
35
+ "Detect the prominent objects and return BOUNDING BOXES (rectangles), "
36
+ "not points. Output ONLY a JSON array where every item has the key "
37
+ '"box_2d" with four integers: '
38
+ '[{"box_2d": [ymin, xmin, ymax, xmax], "label": <concise object name>}]. '
39
+ "Coordinates normalized to 0-1000. Limit to 25 objects. "
40
+ 'Do NOT use "point" — every item must have "box_2d" with exactly 4 values.'
41
+ ),
42
+ "Trajectory (path planning)": (
43
+ "Pick one salient object in the image and plan a trajectory for a "
44
+ "robot gripper to pick it up and move it to a nearby free area. "
45
+ 'Return ONLY a JSON list of ordered waypoints [{"point": [y, x], '
46
+ '"label": "<step_index>"}] with coordinates normalized to 0-1000 and '
47
+ 'labels as stringified integers starting from "0". Use ~10-15 waypoints.'
48
+ ),
49
+ "Grasp points": (
50
+ "Identify up to 3 good grasp points on objects visible in this scene. "
51
+ "Output ONLY JSON as "
52
+ '[{"point": [y, x], "label": <object + brief reason for this grasp>}] '
53
+ "with coordinates normalized to 0-1000."
54
+ ),
55
+ "Instrument reading": (
56
+ "If any gauge, meter, clock, dial, or digital display is visible, read it. "
57
+ 'Output ONLY a JSON object like {"reading": <value>, "units": <str>, '
58
+ '"explanation": <short>}. If no instrument is visible, return '
59
+ '{"reading": null, "explanation": "no instrument visible"}.'
60
+ ),
61
+ "Free-form spatial reasoning": (
62
+ "Describe the spatial layout of this scene and suggest a reasonable "
63
+ "next action for a household or warehouse robot. Be concise."
64
+ ),
65
+ }
66
+
67
+
68
+ def get_client(api_key: str | None = None) -> genai.Client:
69
+ key = (api_key or "").strip() or os.getenv("GEMINI_API_KEY")
70
+ if not key:
71
+ raise gr.Error(
72
+ "No API key. Paste one in the 'Gemini API key' field above, "
73
+ "or set GEMINI_API_KEY in .env."
74
+ )
75
+ return genai.Client(api_key=key)
76
+
77
+
78
+ def extract_json(text: str):
79
+ """Strip markdown fences and parse JSON; return None on failure."""
80
+ if not text:
81
+ return None
82
+ stripped = text.strip()
83
+ fenced = re.search(r"```(?:json)?\s*(.+?)```", stripped, re.DOTALL)
84
+ if fenced:
85
+ stripped = fenced.group(1).strip()
86
+ try:
87
+ return json.loads(stripped)
88
+ except json.JSONDecodeError:
89
+ # try to find the first [...] or {...} blob
90
+ for pattern in (r"\[.*\]", r"\{.*\}"):
91
+ m = re.search(pattern, stripped, re.DOTALL)
92
+ if m:
93
+ try:
94
+ return json.loads(m.group(0))
95
+ except json.JSONDecodeError:
96
+ continue
97
+ return None
98
+
99
+
100
+ def load_font(size: int) -> ImageFont.ImageFont:
101
+ for candidate in [
102
+ "/System/Library/Fonts/Helvetica.ttc",
103
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
104
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
105
+ ]:
106
+ if os.path.exists(candidate):
107
+ try:
108
+ return ImageFont.truetype(candidate, size)
109
+ except OSError:
110
+ continue
111
+ return ImageFont.load_default()
112
+
113
+
114
+ def draw_label(draw: ImageDraw.ImageDraw, xy, text: str, color: str, font):
115
+ x, y = xy
116
+ bbox = draw.textbbox((x, y), text, font=font)
117
+ pad = 3
118
+ draw.rectangle(
119
+ (bbox[0] - pad, bbox[1] - pad, bbox[2] + pad, bbox[3] + pad),
120
+ fill=color,
121
+ )
122
+ draw.text((x, y), text, fill="white", font=font)
123
+
124
+
125
+ def render_points(img: Image.Image, items: list) -> Image.Image:
126
+ out = img.copy().convert("RGB")
127
+ draw = ImageDraw.Draw(out)
128
+ W, H = out.size
129
+ font = load_font(max(14, W // 70))
130
+ r = max(6, W // 180)
131
+ for i, item in enumerate(items):
132
+ pt = item.get("point") or item.get("xy")
133
+ if not pt or len(pt) != 2:
134
+ continue
135
+ y, x = pt
136
+ cx, cy = x * W / 1000, y * H / 1000
137
+ color = PALETTE[i % len(PALETTE)]
138
+ draw.ellipse((cx - r, cy - r, cx + r, cy + r), fill=color, outline="white", width=2)
139
+ label = str(item.get("label", ""))
140
+ if label:
141
+ draw_label(draw, (cx + r + 4, cy - r), label, color, font)
142
+ return out
143
+
144
+
145
+ def render_boxes(img: Image.Image, items: list) -> Image.Image:
146
+ out = img.copy().convert("RGB")
147
+ draw = ImageDraw.Draw(out)
148
+ W, H = out.size
149
+ font = load_font(max(14, W // 70))
150
+ for i, item in enumerate(items):
151
+ box = item.get("box_2d") or item.get("bbox")
152
+ if not box or len(box) != 4:
153
+ continue
154
+ ymin, xmin, ymax, xmax = box
155
+ x0, y0 = xmin * W / 1000, ymin * H / 1000
156
+ x1, y1 = xmax * W / 1000, ymax * H / 1000
157
+ color = PALETTE[i % len(PALETTE)]
158
+ draw.rectangle((x0, y0, x1, y1), outline=color, width=3)
159
+ label = str(item.get("label", ""))
160
+ if label:
161
+ draw_label(draw, (x0 + 4, y0 + 4), label, color, font)
162
+ return out
163
+
164
+
165
+ def render_trajectory(img: Image.Image, items: list) -> Image.Image:
166
+ out = img.copy().convert("RGB")
167
+ draw = ImageDraw.Draw(out)
168
+ W, H = out.size
169
+ font = load_font(max(12, W // 80))
170
+
171
+ def key(item):
172
+ try:
173
+ return int(str(item.get("label", "0")))
174
+ except ValueError:
175
+ return 0
176
+
177
+ pts = []
178
+ for item in sorted(items, key=key):
179
+ p = item.get("point")
180
+ if p and len(p) == 2:
181
+ y, x = p
182
+ pts.append((x * W / 1000, y * H / 1000, str(item.get("label", ""))))
183
+
184
+ if len(pts) >= 2:
185
+ for (x0, y0, _), (x1, y1, _) in zip(pts, pts[1:]):
186
+ draw.line((x0, y0, x1, y1), fill="#3b82f6", width=4)
187
+
188
+ r = max(6, W // 200)
189
+ for i, (x, y, label) in enumerate(pts):
190
+ color = PALETTE[0] if i == 0 else PALETTE[1] if i == len(pts) - 1 else "#3b82f6"
191
+ draw.ellipse((x - r, y - r, x + r, y + r), fill=color, outline="white", width=2)
192
+ draw_label(draw, (x + r + 3, y - r - 2), label, color, font)
193
+ return out
194
+
195
+
196
+ def _as_items(payload) -> list:
197
+ if isinstance(payload, list):
198
+ return payload
199
+ if isinstance(payload, dict):
200
+ for key in ("points", "boxes", "waypoints", "items", "detections"):
201
+ v = payload.get(key)
202
+ if isinstance(v, list):
203
+ return v
204
+ return []
205
+
206
+
207
+ def visualize(img: Image.Image, task: str, payload) -> Image.Image | None:
208
+ """Render overlays. Shape-aware: falls back to whatever the payload actually
209
+ contains so the visualization still works when the model returns a different
210
+ shape than the task template requested."""
211
+ items = _as_items(payload)
212
+ if not items:
213
+ return None
214
+
215
+ has_box = any(isinstance(i, dict) and ("box_2d" in i or "bbox" in i) for i in items)
216
+ has_point = any(isinstance(i, dict) and ("point" in i or "xy" in i) for i in items)
217
+
218
+ if task.startswith("Trajectory") and has_point:
219
+ return render_trajectory(img, items)
220
+ if task.startswith("Bounding"):
221
+ if has_box:
222
+ return render_boxes(img, items)
223
+ if has_point:
224
+ return render_points(img, items) # fallback: model returned points
225
+ if has_box:
226
+ return render_boxes(img, items)
227
+ if has_point:
228
+ return render_points(img, items)
229
+ return None
230
+
231
+
232
+ def _format_gemini_error(e: genai_errors.APIError) -> str:
233
+ """Extract the useful parts of a Gemini API error into a single-line message."""
234
+ status = getattr(e, "code", None) or getattr(e, "status_code", "?")
235
+ message = getattr(e, "message", None) or str(e)
236
+ # The SDK stores the raw response JSON on the exception; try to pull retry info.
237
+ details_blob = getattr(e, "details", None) or {}
238
+ retry_hint = ""
239
+ try:
240
+ err = details_blob.get("error", details_blob) if isinstance(details_blob, dict) else {}
241
+ for d in err.get("details", []) or []:
242
+ if d.get("@type", "").endswith("RetryInfo"):
243
+ delay = d.get("retryDelay", "")
244
+ if delay:
245
+ retry_hint = f" (retry in {delay})"
246
+ break
247
+ except Exception:
248
+ pass
249
+ # Trim super-long messages for the toast.
250
+ short = message.split("\n", 1)[0].strip()
251
+ if len(short) > 400:
252
+ short = short[:397] + "..."
253
+ return f"Gemini API error {status}: {short}{retry_hint}"
254
+
255
+
256
+ def run_model(image: Image.Image | None, task: str, prompt: str, thinking_budget: int, api_key: str):
257
+ if image is None:
258
+ raise gr.Error("Please pick or upload an image first.")
259
+ if not prompt.strip():
260
+ raise gr.Error("Prompt is empty.")
261
+
262
+ pil = image if isinstance(image, Image.Image) else Image.open(image)
263
+ pil = pil.convert("RGB")
264
+ buf = io.BytesIO()
265
+ pil.save(buf, format="PNG")
266
+ img_bytes = buf.getvalue()
267
+
268
+ try:
269
+ client = get_client(api_key)
270
+ config = types.GenerateContentConfig(
271
+ temperature=1.0,
272
+ thinking_config=types.ThinkingConfig(thinking_budget=int(thinking_budget)),
273
+ )
274
+ response = client.models.generate_content(
275
+ model=MODEL,
276
+ contents=[
277
+ types.Part.from_bytes(data=img_bytes, mime_type="image/png"),
278
+ prompt,
279
+ ],
280
+ config=config,
281
+ )
282
+ except genai_errors.APIError as e:
283
+ raise gr.Error(_format_gemini_error(e))
284
+ except Exception as e:
285
+ raise gr.Error(f"Request failed: {type(e).__name__}: {e}")
286
+
287
+ text = response.text or ""
288
+ if not text.strip():
289
+ # The SDK gave us an empty response — surface whatever we can.
290
+ finish = ""
291
+ try:
292
+ finish = str(response.candidates[0].finish_reason) if response.candidates else ""
293
+ except Exception:
294
+ pass
295
+ raise gr.Error(
296
+ "Model returned an empty response"
297
+ + (f" (finish_reason={finish})" if finish else "")
298
+ + ". This can happen if the image was blocked by safety filters or "
299
+ "if the output hit the token limit."
300
+ )
301
+
302
+ parsed = extract_json(text)
303
+ overlay = visualize(pil, task, parsed) if parsed is not None else None
304
+ pretty = json.dumps(parsed, indent=2) if parsed is not None else "(no JSON parsed)"
305
+ return overlay if overlay is not None else pil, pretty, text
306
+
307
+
308
+ def on_task_change(task: str) -> str:
309
+ return TASK_TEMPLATES.get(task, "")
310
+
311
+
312
+ REMOTE_EXAMPLES = [
313
+ # Licensed/watermarked images — referenced by URL so we don't redistribute them.
314
+ "https://www.shutterstock.com/image-photo/adiyaman-turkey-aug-21-2024-260nw-2514334691.jpg",
315
+ "https://c8.alamy.com/comp/2HXT4ME/full-containers-next-to-sets-of-lego-brand-bricks-with-figurines-on-a-carpet-in-a-playroom-2HXT4ME.jpg",
316
+ "https://media.licdn.com/dms/image/v2/D5612AQF1km1N_jy66Q/article-cover_image-shrink_720_1280/B56Zh8QE__HUAI-/0/1754431246854?e=2147483647&v=beta&t=iEGQih1pUnJNFBbas0K9rCpez-VgJOxOKJ2TGQM1-tY",
317
+ ]
318
+
319
+
320
+ def build_ui() -> gr.Blocks:
321
+ local_examples = sorted(str(p) for p in EXAMPLES_DIR.glob("*.jpg"))
322
+ examples = local_examples + REMOTE_EXAMPLES
323
+
324
+ with gr.Blocks(title="Gemini Robotics-ER 1.6 Visualizer") as demo:
325
+ gr.Markdown(
326
+ "# Gemini Robotics-ER 1.6 Visualizer\n"
327
+ f"Model: `{MODEL}` — pick an image, choose a task, edit the prompt, run."
328
+ )
329
+ api_key = gr.Textbox(
330
+ label="Gemini API key",
331
+ value="",
332
+ type="password",
333
+ placeholder="Paste your key here (or leave empty if the server provides one)",
334
+ info="Sent only to this server to call Gemini; never logged or persisted.",
335
+ )
336
+ with gr.Row():
337
+ with gr.Column(scale=1):
338
+ image = gr.Image(type="pil", label="Input image", height=380)
339
+ if examples:
340
+ gr.Examples(examples=examples, inputs=image, label="Example images")
341
+ task = gr.Dropdown(
342
+ choices=list(TASK_TEMPLATES.keys()),
343
+ value="Points (object detection)",
344
+ label="Task",
345
+ )
346
+ prompt = gr.Textbox(
347
+ label="Prompt (editable)",
348
+ value=TASK_TEMPLATES["Points (object detection)"],
349
+ lines=6,
350
+ )
351
+ thinking = gr.Slider(
352
+ 0, 8192, value=0, step=256,
353
+ label="Thinking budget (0 = fast, higher = more reasoning)",
354
+ )
355
+ run = gr.Button("Run", variant="primary")
356
+ with gr.Column(scale=1):
357
+ overlay = gr.Image(type="pil", label="Result", height=480)
358
+ with gr.Accordion("Raw JSON", open=True):
359
+ parsed_out = gr.Code(label="Parsed JSON", language="json")
360
+ with gr.Accordion("Model answer (raw text)", open=True):
361
+ raw_out = gr.Textbox(label="response.text", lines=8)
362
+
363
+ task.change(on_task_change, inputs=task, outputs=prompt)
364
+ run.click(
365
+ run_model,
366
+ inputs=[image, task, prompt, thinking, api_key],
367
+ outputs=[overlay, parsed_out, raw_out],
368
+ )
369
+ return demo
370
+
371
+
372
+ if __name__ == "__main__":
373
+ build_ui().launch(theme=gr.themes.Soft())
examples/amazon.jpg ADDED

Git LFS Details

  • SHA256: e824c3888601d404d691e97adabe14f376626f8d7631585a24f8a58fc62a0e81
  • Pointer size: 130 Bytes
  • Size of remote file: 20 kB
examples/desk.jpg ADDED

Git LFS Details

  • SHA256: c1a59e50220c5f9e1f9c5e3e46e19eb423f7eaf926487d438a94e955d6743e3c
  • Pointer size: 131 Bytes
  • Size of remote file: 128 kB
examples/fruit.jpg ADDED

Git LFS Details

  • SHA256: 68039b0968fdf02a0724e0938edaf01cc07634b74885bece51c98b0c468dd66a
  • Pointer size: 131 Bytes
  • Size of remote file: 290 kB
examples/gauge.jpg ADDED

Git LFS Details

  • SHA256: 8a26219096ea9093c6bc79b59ff11f6ea7b3a5e62da230f0722330e8c691be10
  • Pointer size: 130 Bytes
  • Size of remote file: 89.9 kB
examples/kitchen.jpg ADDED

Git LFS Details

  • SHA256: 18d36559c6e71a6d58810f0c2d6ba379e33ac4006165e72ba9d60ebb5dcca040
  • Pointer size: 131 Bytes
  • Size of remote file: 149 kB
examples/pressure_gauge.jpg ADDED

Git LFS Details

  • SHA256: 813a2e998ff04b8590769e17248fbd93c9c6507b0c4795da624ef761b7fbb9ed
  • Pointer size: 131 Bytes
  • Size of remote file: 295 kB
examples/tools.jpg ADDED

Git LFS Details

  • SHA256: 59c87353b790fc6241385cb0b2f96371cdc7f0719a70213e93a46c9464717b32
  • Pointer size: 131 Bytes
  • Size of remote file: 148 kB
examples/workbench.jpg ADDED

Git LFS Details

  • SHA256: ce901e158137cb688db33a55b8a8304a30d8f27cf5d2bb1204a5e1e1ff78049c
  • Pointer size: 131 Bytes
  • Size of remote file: 139 kB
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio>=4.44
2
+ google-genai>=0.3
3
+ Pillow>=10.0
4
+ python-dotenv>=1.0
visualization.png ADDED

Git LFS Details

  • SHA256: 4bb288a32849f401e5c1320e34126783ae431a812ba4abc9a50ed6e46459b868
  • Pointer size: 132 Bytes
  • Size of remote file: 1.26 MB