import argparse from safetensors import safe_open import numpy as np import cv2 import matplotlib.pyplot as plt from pathlib import Path from matplotlib.widgets import Slider import tkinter as tk from tkinter import ttk from tkinter import messagebox import glob import os from datetime import datetime import time def display_demo_data(safetensor_path, action_format="actions/gripper/base_frame_delta"): """Display camera frames and action data from a safetensor file Args: safetensor_path (str): Path to safetensor file action_format (str): One of ["actions/gripper/base_frame_delta", "actions/gripper/gripper_frame_delta", "actions/joints/angles", "actions/joints/velocities"] """ with safe_open(safetensor_path, framework="numpy") as f: # Get metadata first for window title metadata = f.metadata() task_name = metadata.get('task_name', 'Unknown Task') # Get all keys to understand what's stored keys = f.keys() metadata = f.metadata() print("\nDemo Details:") print(f" Task Name: {metadata.get('task_name', 'N/A')}") print(f" Trajectory ID: {metadata.get('trajectory_id', 'N/A')}") print(f" Style ID: {metadata.get('style_id', 'N/A')}") print("\nLoading data in safetensor...") # Print keys and their sizes in columns for key in sorted(keys): tensor = f.get_tensor(key) print(f" {key:<50} {str(tensor.shape):<20}") # Load action data based on format action_data = f.get_tensor(action_format) gripper = f.get_tensor("actions/gripper/command") # Load camera frames with original names gripper_cam = f.get_tensor("images/Camera_robot0_eye_in_hand") left_shoulder_cam = f.get_tensor("images/Camera_robot0_agentview_left") right_shoulder_cam = f.get_tensor("images/Camera_robot0_agentview_right") num_frames = len(gripper_cam) # Define labels based on action format labels = { "actions/gripper/base_frame_delta": ['Pos X', 'Pos Y', 'Pos Z', 'Rot X', 'Rot Y', 'Rot Z'], "actions/gripper/gripper_frame_delta": ['Pos X', 'Pos Y', 'Pos Z', 'Rot X', 'Rot Y', 'Rot Z'], "actions/joints/angles": [f'Joint {i}' for i in range(7)], "actions/joints/velocities": [f'Vel {i}' for i in range(7)] } # Define y-axis limits and scaling based on action format ylim_scales = { "actions/gripper/base_frame_delta": 1.1, "actions/gripper/gripper_frame_delta": 1.1, "actions/joints/angles": 0.5, # Smaller scale for joint positions "actions/joints/velocities": 2.0 # Larger scale for velocities } # Create figure fig = plt.figure(figsize=(15, 10)) file_name = os.path.basename(safetensor_path) fig.canvas.manager.set_window_title(f"{task_name} - {file_name}") # Font sizes plt.rcParams.update({ 'font.size': 12, # Base font size 'axes.titlesize': 14, # Plot titles 'axes.labelsize': 12, # Axis labels 'xtick.labelsize': 11, # X tick labels 'ytick.labelsize': 11, # Y tick labels }) # Create subplot grid grid = plt.GridSpec(3, 3, height_ratios=[3.5, 2.5, 0.5], # Keep same ratios hspace=0.3, wspace=0.1, left=0.1, # Increased left margin (was 0.05) right=0.9, # Decreased right margin (was 0.95) top=0.95, bottom=0.1) # Create all subplot axes ax_gripper = fig.add_subplot(grid[0, 0]) ax_left = fig.add_subplot(grid[0, 1]) ax_right = fig.add_subplot(grid[0, 2]) ax_action = fig.add_subplot(grid[1, :]) slider_ax = fig.add_subplot(grid[2, :]) # Adjusted to use only the middle column # Define color palette with dark theme colors = { 'positive': '#FF9F1C', # warm orange 'negative': '#2EC4B6', # teal 'neutral': '#A0A0A0', # light gray 'background': '#1E1E1E', # dark background 'text': '#FFFFFF' # white text } fig.patch.set_facecolor(colors['background']) # Style all subplots for ax in [ax_gripper, ax_left, ax_right, ax_action, slider_ax]: ax.set_facecolor(colors['background']) ax.tick_params(colors=colors['text'], labelcolor=colors['text']) ax.title.set_color(colors['text']) for ax in [ax_gripper, ax_left, ax_right]: ax.set_xticks([]) ax.set_yticks([]) for spine in ax.spines.values(): spine.set_linewidth(1) # Style action plot specifically ax_action.set_facecolor(colors['background']) ax_action.axhline(y=0, color=colors['text'], linestyle='-', alpha=0.2) ax_action.xaxis.label.set_color(colors['text']) ax_action.yaxis.label.set_color(colors['text']) for spine in ax_action.spines.values(): spine.set_linewidth(1) # Initial setup of plots img_gripper = ax_gripper.imshow(gripper_cam[0]) img_left = ax_left.imshow(left_shoulder_cam[0]) img_right = ax_right.imshow(right_shoulder_cam[0]) # Camera view titles ax_gripper.set_title("Camera_robot0_eye_in_hand", fontsize=14, loc='left', color=colors['text']) ax_left.set_title("Camera_robot0_agentview_left", fontsize=14, loc='left', color=colors['text']) ax_right.set_title("Camera_robot0_agentview_right", fontsize=14, loc='left', color=colors['text']) # Action plot title ax_action.set_title(f"{action_format}", pad=15, fontsize=14, loc='left', color=colors['text']) # Gripper info text info_text = ax_action.text(0.99, 1.0, "", # x=0.99 for right edge, y=1.0 for title line horizontalalignment='right', transform=ax_action.transAxes, color=colors['text'], fontsize=14, fontfamily='sans-serif') # Setup action plot current_labels = labels[action_format] bars = ax_action.bar(current_labels, action_data[0]) ax_action.set_facecolor(colors['background']) # Set y-limits based on action format max_val = max(abs(np.max(action_data)), abs(np.min(action_data))) scale = ylim_scales.get(action_format, 1.1) ax_action.set_ylim(-max_val*scale, max_val*scale) ax_action.axhline(y=0, color='black', linestyle='-', alpha=0.2) # Slider frame_slider = Slider( ax=slider_ax, label='Frame', valmin=0, valmax=num_frames-1, valinit=0, valstep=1, color='lightgray', initcolor='gray', ) # Slider handle frame_slider.vline.set_linewidth(60) frame_slider.vline.set_color('darkgray') # Slider text and ticks frame_slider.label.set_color(colors['text']) frame_slider.valtext.set_color(colors['text']) slider_ax.tick_params(colors=colors['text'], labelcolor=colors['text']) # Slider text and ticks frame_slider.label.set_size(12) frame_slider.valtext.set_size(12) frame_slider.label.set_fontfamily('sans-serif') frame_slider.valtext.set_fontfamily('sans-serif') def update(val): frame_idx = int(val) # Update images img_gripper.set_array(gripper_cam[frame_idx]) img_left.set_array(left_shoulder_cam[frame_idx]) img_right.set_array(right_shoulder_cam[frame_idx]) # Update action data frame_data = action_data[frame_idx] gripper_data = gripper[frame_idx] # Update bar heights for i, (bar, val) in enumerate(zip(bars, frame_data)): bar.set_height(val) if action_format in ["joint_positions", "joint_velocities"]: bar.set_color(colors['neutral']) else: if abs(val) < 1e-6: bar.set_color(colors['neutral']) elif val >= 0: bar.set_color(colors['positive']) else: bar.set_color(colors['negative']) # Update info text if action_format in ["action_deltas", "actions_gripper_frame"]: action_magnitude = np.linalg.norm(frame_data) info_str = f"Gripper: {gripper_data[0]:.3f} (-1=open, 1=closed)" else: info_str = f"Gripper: {gripper_data[0]:.3f} (-1=open, 1=closed)" info_text.set_text(info_str) # Update title with frame number #ax_action.set_title(f"{action_format} (Frame {frame_idx}/{num_frames-1})") # Use blit for faster updates fig.canvas.draw_idle() frame_slider.on_changed(update) # Initial display update(0) print("\nControls:") print(" Use slider to navigate frames or spacebar to play") print(" Close window to exit and choose a different file") # Playback functionality playing = False window_closed = False def play_animation(): nonlocal playing, window_closed import time frame_interval = 1/60 # Target frame rate while playing and not window_closed: current_frame = int(frame_slider.val) next_frame = (current_frame + 1) % num_frames try: if window_closed or not plt.fignum_exists(fig.number): playing = False break frame_slider.set_val(next_frame) fig.canvas.draw_idle() fig.canvas.flush_events() time.sleep(frame_interval) except Exception as e: playing = False break def toggle_play(event): if event.key == ' ': # spacebar nonlocal playing if not window_closed: # Only toggle if window is still open playing = not playing if playing: play_animation() def on_close(event): nonlocal window_closed, playing window_closed = True playing = False try: fig.canvas.stop_event_loop() except: pass plt.close('all') # Connect events fig.canvas.mpl_connect('close_event', on_close) fig.canvas.mpl_connect('key_press_event', toggle_play) try: plt.show(block=False) import time check_interval = 0.1 # Main event loop while not window_closed and plt.fignum_exists(fig.number): try: time.sleep(check_interval) if not playing: # Only flush events if not playing fig.canvas.flush_events() if window_closed or not plt.fignum_exists(fig.number): break except (KeyboardInterrupt, SystemExit): window_closed = True break finally: playing = False plt.close('all') del frame_slider del action_data, gripper def select_safetensor(directory, action_format="actions/gripper/base_frame_delta"): """Create a window for selecting safetensor files""" root = tk.Tk() root.title("Select File") root.geometry("1000x800") # Frame for the list frame = ttk.Frame(root) frame.pack(pady=10, padx=10, fill=tk.BOTH, expand=True) # Label ttk.Label(frame, text="Double-click to view a file:", font=('Arial', 14)).pack(anchor='w', pady=(0, 10)) # Treeview tree = ttk.Treeview(frame, columns=(), show="tree") # Configure row height and font style = ttk.Style() style.configure("Treeview", rowheight=30, font=('Arial', 20)) style.configure("Treeview.Heading", font=('Arial', 20, 'bold')) # Add scrollbar scrollbar = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview) tree.configure(yscrollcommand=scrollbar.set) # Pack the treeview and scrollbar tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) # Populate the list with safetensor files safetensor_files = glob.glob(os.path.join(directory, "**/*.safetensors"), recursive=True) for filepath in sorted(safetensor_files, key=lambda x: os.path.basename(x).lower()): # Insert just the filename tree.insert("", tk.END, text=os.path.basename(filepath), tags=(filepath,)) def on_double_click(event): item = tree.selection()[0] filepath = tree.item(item)["tags"][0] root.withdraw() try: display_demo_data(filepath, action_format) except Exception as e: messagebox.showerror("Error", f"Failed to load safetensor: {str(e)}") finally: try: root.deiconify() root.lift() root.update() root.mainloop() except tk.TclError: select_safetensor(directory, action_format) tree.bind("", on_double_click) # Add exit button with better styling exit_button = ttk.Button(root, text="Exit", command=root.destroy, style='TButton') exit_button.pack(pady=10) # Initial mainloop root.mainloop() def main(): parser = argparse.ArgumentParser(description="View safetensor demonstration files") parser.add_argument("--dir", type=str, required=True, help="Directory containing safetensor files") parser.add_argument("--action_format", type=str, default="actions/gripper/base_frame_delta", choices=["actions/gripper/base_frame_delta", "actions/gripper/gripper_frame_delta", "actions/gripper/command", "actions/joints/angles", "actions/joints/velocities"], help="Which action format to display") args = parser.parse_args() if not os.path.isdir(args.dir): print(f"Error: {args.dir} is not a directory") return # Pass action_format to select_safetensor select_safetensor(args.dir, args.action_format) if __name__ == "__main__": main()