YashsharmaPhD commited on
Commit
87933a4
Β·
verified Β·
1 Parent(s): ae34a04

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -90
app.py CHANGED
@@ -6,14 +6,14 @@ import tempfile
6
  import gradio as gr
7
  import time
8
 
9
- # Initialize PyBullet
10
  p.connect(p.DIRECT)
11
  p.setAdditionalSearchPath(pybullet_data.getDataPath())
12
  p.setGravity(0, 0, -9.8)
13
  p.loadURDF("plane.urdf")
14
  robot = p.loadURDF("franka_panda/panda.urdf", basePosition=[0, 0, 0], useFixedBase=True)
15
 
16
- # Add object (default: black cube)
17
  cube_id = p.loadURDF("cube_small.urdf", basePosition=[0.6, 0, 0.02])
18
  p.changeVisualShape(cube_id, -1, rgbaColor=[0, 0, 0, 1])
19
 
@@ -32,134 +32,134 @@ def get_panda_joints(robot):
32
 
33
  arm_joints, finger_joints = get_panda_joints(robot)
34
 
 
35
  def add_joint_labels():
36
  for i in range(len(arm_joints)):
37
  pos = p.getLinkState(robot, arm_joints[i])[0]
38
  p.addUserDebugText(f"J{i+1}", pos, textColorRGB=[1, 0, 0], textSize=1.2)
39
 
40
- # Camera config (yaw, pitch, dist)
41
- camera_angles = [45, -30, 1.5] # Default values
42
- def render_sim(joint_values, gripper_val, cube_color):
43
  for idx, tgt in zip(arm_joints, joint_values):
44
  p.setJointMotorControl2(robot, idx, p.POSITION_CONTROL, targetPosition=tgt)
45
-
46
- for _ in range(5):
47
  for fj in finger_joints:
48
  p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=gripper_val)
49
- p.stepSimulation()
50
-
51
- # Cube color update
52
- p.changeVisualShape(cube_id, -1, rgbaColor=cube_color + [1])
53
-
54
- # View camera
55
- view_matrix = p.computeViewMatrixFromYawPitchRoll(
56
- cameraTargetPosition=[0, 0, 0.5],
57
- distance=camera_angles[2],
58
- yaw=camera_angles[0],
59
- pitch=camera_angles[1],
60
- roll=0,
61
- upAxisIndex=2,
62
- )
63
- proj_matrix = p.computeProjectionMatrixFOV(60, 1, 0.1, 3.1)
64
- _, _, img, _, _ = p.getCameraImage(640, 640, view_matrix, proj_matrix)
65
- rgb = np.reshape(img, (640, 640, 4))[:, :, :3]
66
-
67
- fig, ax = plt.subplots()
68
  ax.imshow(rgb.astype(np.uint8))
69
  ax.axis("off")
70
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
71
- plt.savefig(tmp.name, bbox_inches='tight', dpi=150)
72
  plt.close()
73
 
74
- return tmp.name, f"Joint Angles: {[round(j,2) for j in joint_values]}, Gripper: {round(gripper_val, 3)}"
 
 
75
 
 
76
  def move_to_input_angles(joint_str):
77
  try:
78
  target_angles = [float(x.strip()) for x in joint_str.split(",")]
79
  if len(target_angles) != 7:
80
- return None, "❌ Please enter exactly 7 joint angles."
81
-
82
  current = [p.getJointState(robot, idx)[0] for idx in arm_joints]
83
- for i in range(50):
84
- blend = [(1 - i/50) * c + (i/50) * t for c, t in zip(current, target_angles)]
 
85
  for idx, val in zip(arm_joints, blend):
86
  p.setJointMotorControl2(robot, idx, p.POSITION_CONTROL, targetPosition=val)
87
  p.stepSimulation()
88
- time.sleep(0.005)
89
-
90
- grip = p.getJointState(robot, finger_joints[0])[0]
91
- return render_sim(target_angles, grip, current_cube_color)
92
  except Exception as e:
93
- return None, str(e)
94
-
95
- # Pick and place
96
- current_cube_color = [0, 0, 0] # Default black
97
 
 
98
  def pick_and_place(position_str, approach_str, place_str):
99
- position = [float(x) for x in position_str.split(",")]
100
- approach = [float(x) for x in approach_str.split(",")]
101
- place = [float(x) for x in place_str.split(",")]
102
 
103
- move_to_input_angles(','.join(map(str, approach)))
 
 
104
 
105
- for _ in range(30):
106
- for fj in finger_joints:
107
- p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=0.0)
108
- p.stepSimulation()
109
- time.sleep(0.01)
110
 
111
- move_to_input_angles(','.join([str(x + 0.1) for x in approach]))
112
- move_to_input_angles(','.join(map(str, place)))
113
 
114
- for _ in range(30):
115
- for fj in finger_joints:
116
- p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=0.04)
117
- p.stepSimulation()
118
- time.sleep(0.01)
 
 
 
119
 
120
- return render_sim(place, 0.04, current_cube_color)
121
 
122
- # UI
123
- with gr.Blocks(title="Franka Arm Control with Pick & Place") as demo:
124
- gr.Markdown("# πŸ€– Franka 7-DOF + Pick & Place")
 
 
 
 
125
 
126
- # Camera controls
127
- yaw = gr.Slider(-180, 180, value=camera_angles[0], label="Yaw")
128
- pitch = gr.Slider(-90, 90, value=camera_angles[1], label="Pitch")
129
- dist = gr.Slider(0.5, 3.0, value=camera_angles[2], label="Camera Distance")
130
 
131
- def update_camera(y, p_, d):
132
- camera_angles[0], camera_angles[1], camera_angles[2] = y, p_, d
133
- return "Camera updated"
 
134
 
135
- gr.Button("πŸŽ₯ Update Camera").click(update_camera, [yaw, pitch, dist], outputs=gr.Textbox(label="Status"))
 
136
 
137
- # Cube color
138
- cube_color_picker = gr.ColorPicker(label="Pick Cube Color", value="#000000")
139
 
140
- def update_color(color_hex):
141
- global current_cube_color
142
- rgb = tuple(int(color_hex[i:i+2], 16)/255. for i in (1, 3, 5))
143
- current_cube_color = list(rgb)
144
- return f"Updated color to {rgb}"
145
 
146
- cube_color_picker.change(fn=update_color, inputs=cube_color_picker, outputs=gr.Textbox(label="Color Info"))
 
147
 
148
- # Manual joints + gripper
149
- joint_sliders = [gr.Slider(-3.14, 3.14, value=0, label=f"Joint {i+1}") for i in range(7)]
150
- gripper = gr.Slider(0.0, 0.04, value=0.02, step=0.001, label="Gripper")
151
 
152
- def live_update(*vals):
153
- return render_sim(list(vals[:-1]), vals[-1], current_cube_color)
 
154
 
155
- for s in joint_sliders + [gripper]:
156
- s.change(fn=live_update, inputs=joint_sliders + [gripper], outputs=[gr.Image(type="filepath"), gr.Textbox()])
 
 
 
 
 
 
 
157
 
158
- # Pick and Place Inputs
159
- gr.Markdown("## 🧠 Pick & Place Inputs")
160
- pos_box = gr.Textbox(label="Position Angles")
161
- approach_box = gr.Textbox(label="Approach Angles")
162
- place_box = gr.Textbox(label="Place Angles")
163
- gr.Button("🚚 Run Pick & Place").click(pick_and_place, [pos_box, approach_box, place_box], outputs=[gr.Image(type="filepath"), gr.Textbox()])
164
 
165
- demo.launch(debug=True)
 
 
 
6
  import gradio as gr
7
  import time
8
 
9
+ # Setup PyBullet
10
  p.connect(p.DIRECT)
11
  p.setAdditionalSearchPath(pybullet_data.getDataPath())
12
  p.setGravity(0, 0, -9.8)
13
  p.loadURDF("plane.urdf")
14
  robot = p.loadURDF("franka_panda/panda.urdf", basePosition=[0, 0, 0], useFixedBase=True)
15
 
16
+ # Add a cube to pick (black color)
17
  cube_id = p.loadURDF("cube_small.urdf", basePosition=[0.6, 0, 0.02])
18
  p.changeVisualShape(cube_id, -1, rgbaColor=[0, 0, 0, 1])
19
 
 
32
 
33
  arm_joints, finger_joints = get_panda_joints(robot)
34
 
35
+ # Add 3D debug labels to joints
36
  def add_joint_labels():
37
  for i in range(len(arm_joints)):
38
  pos = p.getLinkState(robot, arm_joints[i])[0]
39
  p.addUserDebugText(f"J{i+1}", pos, textColorRGB=[1, 0, 0], textSize=1.2)
40
 
41
+ # Render simulation view
42
+ def render_sim(joint_values, gripper_val):
 
43
  for idx, tgt in zip(arm_joints, joint_values):
44
  p.setJointMotorControl2(robot, idx, p.POSITION_CONTROL, targetPosition=tgt)
45
+ if len(finger_joints) == 2:
 
46
  for fj in finger_joints:
47
  p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=gripper_val)
48
+
49
+ for _ in range(10): p.stepSimulation()
50
+
51
+ width, height = 640, 640
52
+ view_matrix = p.computeViewMatrix(cameraEyePosition=[1.5, 0, 1],
53
+ cameraTargetPosition=[0, 0, 0.5],
54
+ cameraUpVector=[0, 0, 1])
55
+ proj_matrix = p.computeProjectionMatrixFOV(fov=60, aspect=1.0, nearVal=0.1, farVal=3.1)
56
+ _, _, img, _, _ = p.getCameraImage(width, height, view_matrix, proj_matrix)
57
+ rgb = np.reshape(img, (height, width, 4))[:, :, :3]
58
+
59
+ fig, ax = plt.subplots(figsize=(4, 4))
 
 
 
 
 
 
 
60
  ax.imshow(rgb.astype(np.uint8))
61
  ax.axis("off")
62
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
63
+ plt.savefig(tmp.name, bbox_inches='tight')
64
  plt.close()
65
 
66
+ joint_text = "Joint Angles:\n" + "\n".join([f"J{i+1} = {v:.2f} rad" for i, v in enumerate(joint_values)])
67
+ joint_text += f"\nGripper = {gripper_val:.3f} m"
68
+ return tmp.name, joint_text
69
 
70
+ # Move smoothly to given joint angles
71
  def move_to_input_angles(joint_str):
72
  try:
73
  target_angles = [float(x.strip()) for x in joint_str.split(",")]
74
  if len(target_angles) != 7:
75
+ return None, "❌ Enter exactly 7 joint angles."
 
76
  current = [p.getJointState(robot, idx)[0] for idx in arm_joints]
77
+ steps = 100
78
+ for i in range(steps):
79
+ blend = [(1 - i/steps) * c + (i/steps) * t for c, t in zip(current, target_angles)]
80
  for idx, val in zip(arm_joints, blend):
81
  p.setJointMotorControl2(robot, idx, p.POSITION_CONTROL, targetPosition=val)
82
  p.stepSimulation()
83
+ time.sleep(0.01)
84
+ current_grip = p.getJointState(robot, finger_joints[0])[0]
85
+ return render_sim(target_angles, current_grip)
 
86
  except Exception as e:
87
+ return None, f"❌ Error: {str(e)}"
 
 
 
88
 
89
+ # Pick and Place with validation
90
  def pick_and_place(position_str, approach_str, place_str):
91
+ try:
92
+ if not position_str or not approach_str or not place_str:
93
+ return None, "❌ Fill in all three joint angle sets."
94
 
95
+ position = [float(x) for x in position_str.split(",")]
96
+ approach = [float(x) for x in approach_str.split(",")]
97
+ place = [float(x) for x in place_str.split(",")]
98
 
99
+ if not all(len(lst) == 7 for lst in [position, approach, place]):
100
+ return None, "❌ Each input must have 7 values."
 
 
 
101
 
102
+ move_to_input_angles(",".join(map(str, approach)))
 
103
 
104
+ for _ in range(50):
105
+ for fj in finger_joints:
106
+ p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=0.0)
107
+ p.stepSimulation()
108
+ time.sleep(0.01)
109
+
110
+ lifted = [x + 0.1 for x in approach]
111
+ move_to_input_angles(",".join(map(str, lifted)))
112
 
113
+ move_to_input_angles(",".join(map(str, place)))
114
 
115
+ for _ in range(50):
116
+ for fj in finger_joints:
117
+ p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=0.04)
118
+ p.stepSimulation()
119
+ time.sleep(0.01)
120
+
121
+ return render_sim(place, 0.04)
122
 
123
+ except ValueError:
124
+ return None, "❌ Invalid format. Use comma-separated numbers."
125
+ except Exception as e:
126
+ return None, f"❌ Error: {str(e)}"
127
 
128
+ # Gradio UI
129
+ def build_ui():
130
+ with gr.Blocks(title="Franka Pick & Place") as demo:
131
+ gr.Markdown("## πŸ€– Franka 7-DOF Pick & Place Arm")
132
 
133
+ joint_sliders = [gr.Slider(-3.14, 3.14, value=0, label=f"Joint {i+1}") for i in range(7)]
134
+ gripper_slider = gr.Slider(0.0, 0.04, value=0.02, step=0.001, label="Gripper Opening")
135
 
136
+ img_output = gr.Image(type="filepath", label="Simulation View")
137
+ text_output = gr.Textbox(label="Joint Info")
138
 
139
+ def live_update(*vals):
140
+ return render_sim(list(vals[:-1]), vals[-1])
 
 
 
141
 
142
+ for s in joint_sliders + [gripper_slider]:
143
+ s.change(fn=live_update, inputs=joint_sliders + [gripper_slider], outputs=[img_output, text_output])
144
 
145
+ gr.Button("πŸ”„ Reset").click(lambda: render_sim([0]*7, 0.02), outputs=[img_output, text_output])
 
 
146
 
147
+ gr.Markdown("### 🎯 Move to Joint Angles")
148
+ joint_input = gr.Textbox(label="Joint Angles (7 values)", placeholder="e.g. 0.1, -0.5, 0.3, -1.0, 0.0, 1.5, 0.8")
149
+ gr.Button("▢️ Move").click(fn=move_to_input_angles, inputs=joint_input, outputs=[img_output, text_output])
150
 
151
+ gr.Markdown("### πŸ“¦ Pick and Place")
152
+ position_input = gr.Textbox(label="Position Angles (7 values)")
153
+ approach_input = gr.Textbox(label="Approach Angles (7 values)")
154
+ place_input = gr.Textbox(label="Place Angles (7 values)")
155
+ gr.Button("πŸ€– Execute Pick & Place").click(
156
+ fn=pick_and_place,
157
+ inputs=[position_input, approach_input, place_input],
158
+ outputs=[img_output, text_output]
159
+ )
160
 
161
+ return demo
 
 
 
 
 
162
 
163
+ if __name__ == '__main__':
164
+ demo = build_ui()
165
+ demo.launch(debug=True)