srisola commited on
Commit
ed2c2b6
·
verified ·
1 Parent(s): baa30ec

Upload view_safetensor.py

Browse files
Files changed (1) hide show
  1. scripts/view_safetensor.py +402 -0
scripts/view_safetensor.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from safetensors import safe_open
3
+ import numpy as np
4
+ import cv2
5
+ import matplotlib.pyplot as plt
6
+ from pathlib import Path
7
+ from matplotlib.widgets import Slider
8
+ import tkinter as tk
9
+ from tkinter import ttk
10
+ from tkinter import messagebox
11
+ import glob
12
+ import os
13
+ from datetime import datetime
14
+ import time
15
+
16
+ def display_demo_data(safetensor_path, action_format="actions/gripper/base_frame_delta"):
17
+ """Display camera frames and action data from a safetensor file
18
+
19
+ Args:
20
+ safetensor_path (str): Path to safetensor file
21
+ action_format (str): One of ["actions/gripper/base_frame_delta",
22
+ "actions/gripper/gripper_frame_delta",
23
+ "actions/joints/angles",
24
+ "actions/joints/velocities"]
25
+ """
26
+
27
+ with safe_open(safetensor_path, framework="numpy") as f:
28
+ # Get metadata first for window title
29
+ metadata = f.metadata()
30
+ task_name = metadata.get('task_name', 'Unknown Task')
31
+
32
+ # Get all keys to understand what's stored
33
+ keys = f.keys()
34
+ metadata = f.metadata()
35
+ print("\nDemo Details:")
36
+ print(f" Task Name: {metadata.get('task_name', 'N/A')}")
37
+ print(f" Trajectory ID: {metadata.get('trajectory_id', 'N/A')}")
38
+ print(f" Style ID: {metadata.get('style_id', 'N/A')}")
39
+ print("\nLoading data in safetensor...")
40
+ # Print keys and their sizes in columns
41
+ for key in sorted(keys):
42
+ tensor = f.get_tensor(key)
43
+ print(f" {key:<50} {str(tensor.shape):<20}")
44
+ # Load action data based on format
45
+ action_data = f.get_tensor(action_format)
46
+ gripper = f.get_tensor("actions/gripper/command")
47
+
48
+ # Load camera frames with original names
49
+ gripper_cam = f.get_tensor("images/Camera_robot0_eye_in_hand")
50
+ left_shoulder_cam = f.get_tensor("images/Camera_robot0_agentview_left")
51
+ right_shoulder_cam = f.get_tensor("images/Camera_robot0_agentview_right")
52
+
53
+ num_frames = len(gripper_cam)
54
+
55
+ # Define labels based on action format
56
+ labels = {
57
+ "actions/gripper/base_frame_delta": ['Pos X', 'Pos Y', 'Pos Z', 'Rot X', 'Rot Y', 'Rot Z'],
58
+ "actions/gripper/gripper_frame_delta": ['Pos X', 'Pos Y', 'Pos Z', 'Rot X', 'Rot Y', 'Rot Z'],
59
+ "actions/joints/angles": [f'Joint {i}' for i in range(7)],
60
+ "actions/joints/velocities": [f'Vel {i}' for i in range(7)]
61
+ }
62
+
63
+ # Define y-axis limits and scaling based on action format
64
+ ylim_scales = {
65
+ "actions/gripper/base_frame_delta": 1.1,
66
+ "actions/gripper/gripper_frame_delta": 1.1,
67
+ "actions/joints/angles": 0.5, # Smaller scale for joint positions
68
+ "actions/joints/velocities": 2.0 # Larger scale for velocities
69
+ }
70
+
71
+ # Create figure
72
+ fig = plt.figure(figsize=(15, 10))
73
+ file_name = os.path.basename(safetensor_path)
74
+ fig.canvas.manager.set_window_title(f"{task_name} - {file_name}")
75
+
76
+ # Font sizes
77
+ plt.rcParams.update({
78
+ 'font.size': 12, # Base font size
79
+ 'axes.titlesize': 14, # Plot titles
80
+ 'axes.labelsize': 12, # Axis labels
81
+ 'xtick.labelsize': 11, # X tick labels
82
+ 'ytick.labelsize': 11, # Y tick labels
83
+ })
84
+
85
+ # Create subplot grid
86
+ grid = plt.GridSpec(3, 3,
87
+ height_ratios=[3.5, 2.5, 0.5], # Keep same ratios
88
+ hspace=0.3,
89
+ wspace=0.1,
90
+ left=0.1, # Increased left margin (was 0.05)
91
+ right=0.9, # Decreased right margin (was 0.95)
92
+ top=0.95,
93
+ bottom=0.1)
94
+
95
+ # Create all subplot axes
96
+ ax_gripper = fig.add_subplot(grid[0, 0])
97
+ ax_left = fig.add_subplot(grid[0, 1])
98
+ ax_right = fig.add_subplot(grid[0, 2])
99
+ ax_action = fig.add_subplot(grid[1, :])
100
+ slider_ax = fig.add_subplot(grid[2, :]) # Adjusted to use only the middle column
101
+
102
+ # Define color palette with dark theme
103
+ colors = {
104
+ 'positive': '#FF9F1C', # warm orange
105
+ 'negative': '#2EC4B6', # teal
106
+ 'neutral': '#A0A0A0', # light gray
107
+ 'background': '#1E1E1E', # dark background
108
+ 'text': '#FFFFFF' # white text
109
+ }
110
+
111
+ fig.patch.set_facecolor(colors['background'])
112
+
113
+ # Style all subplots
114
+ for ax in [ax_gripper, ax_left, ax_right, ax_action, slider_ax]:
115
+ ax.set_facecolor(colors['background'])
116
+ ax.tick_params(colors=colors['text'], labelcolor=colors['text'])
117
+ ax.title.set_color(colors['text'])
118
+
119
+
120
+ for ax in [ax_gripper, ax_left, ax_right]:
121
+ ax.set_xticks([])
122
+ ax.set_yticks([])
123
+ for spine in ax.spines.values():
124
+ spine.set_linewidth(1)
125
+
126
+ # Style action plot specifically
127
+ ax_action.set_facecolor(colors['background'])
128
+ ax_action.axhline(y=0, color=colors['text'], linestyle='-', alpha=0.2)
129
+ ax_action.xaxis.label.set_color(colors['text'])
130
+ ax_action.yaxis.label.set_color(colors['text'])
131
+ for spine in ax_action.spines.values():
132
+ spine.set_linewidth(1)
133
+
134
+ # Initial setup of plots
135
+ img_gripper = ax_gripper.imshow(gripper_cam[0])
136
+ img_left = ax_left.imshow(left_shoulder_cam[0])
137
+ img_right = ax_right.imshow(right_shoulder_cam[0])
138
+
139
+ # Camera view titles
140
+ ax_gripper.set_title("Camera_robot0_eye_in_hand", fontsize=14, loc='left', color=colors['text'])
141
+ ax_left.set_title("Camera_robot0_agentview_left", fontsize=14, loc='left', color=colors['text'])
142
+ ax_right.set_title("Camera_robot0_agentview_right", fontsize=14, loc='left', color=colors['text'])
143
+
144
+ # Action plot title
145
+ ax_action.set_title(f"{action_format}", pad=15, fontsize=14, loc='left', color=colors['text'])
146
+
147
+ # Gripper info text
148
+ info_text = ax_action.text(0.99, 1.0, "", # x=0.99 for right edge, y=1.0 for title line
149
+ horizontalalignment='right',
150
+ transform=ax_action.transAxes,
151
+ color=colors['text'],
152
+ fontsize=14,
153
+ fontfamily='sans-serif')
154
+
155
+ # Setup action plot
156
+ current_labels = labels[action_format]
157
+ bars = ax_action.bar(current_labels, action_data[0])
158
+ ax_action.set_facecolor(colors['background'])
159
+
160
+ # Set y-limits based on action format
161
+ max_val = max(abs(np.max(action_data)), abs(np.min(action_data)))
162
+ scale = ylim_scales.get(action_format, 1.1)
163
+ ax_action.set_ylim(-max_val*scale, max_val*scale)
164
+ ax_action.axhline(y=0, color='black', linestyle='-', alpha=0.2)
165
+
166
+ # Slider
167
+ frame_slider = Slider(
168
+ ax=slider_ax,
169
+ label='Frame',
170
+ valmin=0,
171
+ valmax=num_frames-1,
172
+ valinit=0,
173
+ valstep=1,
174
+ color='lightgray',
175
+ initcolor='gray',
176
+ )
177
+
178
+ # Slider handle
179
+ frame_slider.vline.set_linewidth(60)
180
+ frame_slider.vline.set_color('darkgray')
181
+
182
+ # Slider text and ticks
183
+ frame_slider.label.set_color(colors['text'])
184
+ frame_slider.valtext.set_color(colors['text'])
185
+ slider_ax.tick_params(colors=colors['text'], labelcolor=colors['text'])
186
+
187
+ # Slider text and ticks
188
+ frame_slider.label.set_size(12)
189
+ frame_slider.valtext.set_size(12)
190
+ frame_slider.label.set_fontfamily('sans-serif')
191
+ frame_slider.valtext.set_fontfamily('sans-serif')
192
+
193
+ def update(val):
194
+ frame_idx = int(val)
195
+
196
+ # Update images
197
+ img_gripper.set_array(gripper_cam[frame_idx])
198
+ img_left.set_array(left_shoulder_cam[frame_idx])
199
+ img_right.set_array(right_shoulder_cam[frame_idx])
200
+
201
+ # Update action data
202
+ frame_data = action_data[frame_idx]
203
+ gripper_data = gripper[frame_idx]
204
+
205
+ # Update bar heights
206
+ for i, (bar, val) in enumerate(zip(bars, frame_data)):
207
+ bar.set_height(val)
208
+ if action_format in ["joint_positions", "joint_velocities"]:
209
+ bar.set_color(colors['neutral'])
210
+ else:
211
+ if abs(val) < 1e-6:
212
+ bar.set_color(colors['neutral'])
213
+ elif val >= 0:
214
+ bar.set_color(colors['positive'])
215
+ else:
216
+ bar.set_color(colors['negative'])
217
+
218
+ # Update info text
219
+ if action_format in ["action_deltas", "actions_gripper_frame"]:
220
+ action_magnitude = np.linalg.norm(frame_data)
221
+ info_str = f"Gripper: {gripper_data[0]:.3f} (-1=open, 1=closed)"
222
+ else:
223
+ info_str = f"Gripper: {gripper_data[0]:.3f} (-1=open, 1=closed)"
224
+ info_text.set_text(info_str)
225
+
226
+ # Update title with frame number
227
+ #ax_action.set_title(f"{action_format} (Frame {frame_idx}/{num_frames-1})")
228
+
229
+ # Use blit for faster updates
230
+ fig.canvas.draw_idle()
231
+
232
+ frame_slider.on_changed(update)
233
+
234
+ # Initial display
235
+ update(0)
236
+
237
+ print("\nControls:")
238
+ print(" Use slider to navigate frames or spacebar to play")
239
+ print(" Close window to exit and choose a different file")
240
+
241
+ # Playback functionality
242
+ playing = False
243
+ window_closed = False
244
+
245
+ def play_animation():
246
+ nonlocal playing, window_closed
247
+ import time
248
+ frame_interval = 1/60 # Target frame rate
249
+
250
+ while playing and not window_closed:
251
+ current_frame = int(frame_slider.val)
252
+ next_frame = (current_frame + 1) % num_frames
253
+
254
+ try:
255
+ if window_closed or not plt.fignum_exists(fig.number):
256
+ playing = False
257
+ break
258
+
259
+ frame_slider.set_val(next_frame)
260
+ fig.canvas.draw_idle()
261
+ fig.canvas.flush_events()
262
+ time.sleep(frame_interval)
263
+
264
+ except Exception as e:
265
+ playing = False
266
+ break
267
+
268
+ def toggle_play(event):
269
+ if event.key == ' ': # spacebar
270
+ nonlocal playing
271
+ if not window_closed: # Only toggle if window is still open
272
+ playing = not playing
273
+ if playing:
274
+ play_animation()
275
+
276
+ def on_close(event):
277
+ nonlocal window_closed, playing
278
+ window_closed = True
279
+ playing = False
280
+
281
+ try:
282
+ fig.canvas.stop_event_loop()
283
+ except:
284
+ pass
285
+
286
+ plt.close('all')
287
+
288
+ # Connect events
289
+ fig.canvas.mpl_connect('close_event', on_close)
290
+ fig.canvas.mpl_connect('key_press_event', toggle_play)
291
+
292
+ try:
293
+ plt.show(block=False)
294
+
295
+ import time
296
+ check_interval = 0.1
297
+
298
+ # Main event loop
299
+ while not window_closed and plt.fignum_exists(fig.number):
300
+ try:
301
+ time.sleep(check_interval)
302
+ if not playing: # Only flush events if not playing
303
+ fig.canvas.flush_events()
304
+ if window_closed or not plt.fignum_exists(fig.number):
305
+ break
306
+ except (KeyboardInterrupt, SystemExit):
307
+ window_closed = True
308
+ break
309
+
310
+ finally:
311
+ playing = False
312
+ plt.close('all')
313
+ del frame_slider
314
+ del action_data, gripper
315
+
316
+ def select_safetensor(directory, action_format="actions/gripper/base_frame_delta"):
317
+ """Create a window for selecting safetensor files"""
318
+ root = tk.Tk()
319
+ root.title("Select File")
320
+ root.geometry("1000x800")
321
+
322
+ # Frame for the list
323
+ frame = ttk.Frame(root)
324
+ frame.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)
325
+
326
+ # Label
327
+ ttk.Label(frame, text="Double-click to view a file:",
328
+ font=('Arial', 14)).pack(anchor='w', pady=(0, 10))
329
+
330
+ # Treeview
331
+ tree = ttk.Treeview(frame, columns=(), show="tree")
332
+
333
+ # Configure row height and font
334
+ style = ttk.Style()
335
+ style.configure("Treeview", rowheight=30, font=('Arial', 20))
336
+ style.configure("Treeview.Heading", font=('Arial', 20, 'bold'))
337
+
338
+ # Add scrollbar
339
+ scrollbar = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview)
340
+ tree.configure(yscrollcommand=scrollbar.set)
341
+
342
+ # Pack the treeview and scrollbar
343
+ tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
344
+ scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
345
+
346
+ # Populate the list with safetensor files
347
+ safetensor_files = glob.glob(os.path.join(directory, "**/*.safetensors"), recursive=True)
348
+ for filepath in sorted(safetensor_files, key=lambda x: os.path.basename(x).lower()):
349
+ # Insert just the filename
350
+ tree.insert("", tk.END, text=os.path.basename(filepath), tags=(filepath,))
351
+
352
+ def on_double_click(event):
353
+ item = tree.selection()[0]
354
+ filepath = tree.item(item)["tags"][0]
355
+ root.withdraw()
356
+
357
+ try:
358
+ display_demo_data(filepath, action_format)
359
+ except Exception as e:
360
+ messagebox.showerror("Error", f"Failed to load safetensor: {str(e)}")
361
+ finally:
362
+ try:
363
+ root.deiconify()
364
+ root.lift()
365
+ root.update()
366
+ root.mainloop()
367
+ except tk.TclError:
368
+ select_safetensor(directory, action_format)
369
+
370
+ tree.bind("<Double-1>", on_double_click)
371
+
372
+ # Add exit button with better styling
373
+ exit_button = ttk.Button(root, text="Exit", command=root.destroy, style='TButton')
374
+ exit_button.pack(pady=10)
375
+
376
+ # Initial mainloop
377
+ root.mainloop()
378
+
379
+ def main():
380
+ parser = argparse.ArgumentParser(description="View safetensor demonstration files")
381
+ parser.add_argument("--dir", type=str, required=True,
382
+ help="Directory containing safetensor files")
383
+ parser.add_argument("--action_format", type=str,
384
+ default="actions/gripper/base_frame_delta",
385
+ choices=["actions/gripper/base_frame_delta",
386
+ "actions/gripper/gripper_frame_delta",
387
+ "actions/gripper/command",
388
+ "actions/joints/angles",
389
+ "actions/joints/velocities"],
390
+ help="Which action format to display")
391
+
392
+ args = parser.parse_args()
393
+
394
+ if not os.path.isdir(args.dir):
395
+ print(f"Error: {args.dir} is not a directory")
396
+ return
397
+
398
+ # Pass action_format to select_safetensor
399
+ select_safetensor(args.dir, args.action_format)
400
+
401
+ if __name__ == "__main__":
402
+ main()