Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import pybullet as p
|
| 2 |
import pybullet_data
|
| 3 |
import numpy as np
|
|
@@ -15,7 +17,7 @@ robot = p.loadURDF("franka_panda/panda.urdf", basePosition=[0, 0, 0], useFixedBa
|
|
| 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 |
|
| 20 |
# Get joint indices
|
| 21 |
def get_panda_joints(robot):
|
|
@@ -32,47 +34,50 @@ def get_panda_joints(robot):
|
|
| 32 |
|
| 33 |
arm_joints, finger_joints = get_panda_joints(robot)
|
| 34 |
|
| 35 |
-
# Add
|
|
|
|
| 36 |
def add_joint_labels():
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
p.
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 =
|
| 52 |
-
view_matrix = p.computeViewMatrix(
|
| 53 |
-
|
| 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
|
| 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, "❌
|
| 76 |
current = [p.getJointState(robot, idx)[0] for idx in arm_joints]
|
| 77 |
steps = 100
|
| 78 |
for i in range(steps):
|
|
@@ -84,82 +89,101 @@ def move_to_input_angles(joint_str):
|
|
| 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"
|
| 88 |
|
| 89 |
-
# Pick
|
| 90 |
def pick_and_place(position_str, approach_str, place_str):
|
| 91 |
try:
|
| 92 |
-
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
place = [float(x) for x in place_str.split(",")]
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
|
| 102 |
-
|
| 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 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
|
|
|
|
| 114 |
|
| 115 |
-
|
|
|
|
| 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(
|
| 122 |
-
|
| 123 |
-
except ValueError:
|
| 124 |
-
return None, "❌ Invalid format. Use comma-separated numbers."
|
| 125 |
except Exception as e:
|
| 126 |
-
return None, f"
|
| 127 |
-
|
| 128 |
-
#
|
| 129 |
-
def
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
img_output = gr.Image(type="filepath", label="Simulation View")
|
| 137 |
-
text_output = gr.Textbox(label="Joint
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
| 1 |
+
# Full adapted pick-and-place demo with consistent style
|
| 2 |
+
|
| 3 |
import pybullet as p
|
| 4 |
import pybullet_data
|
| 5 |
import numpy as np
|
|
|
|
| 17 |
|
| 18 |
# Add a cube to pick (black color)
|
| 19 |
cube_id = p.loadURDF("cube_small.urdf", basePosition=[0.6, 0, 0.02])
|
| 20 |
+
p.changeVisualShape(cube_id, -1, rgbaColor=[0, 0, 0, 1]) # black
|
| 21 |
|
| 22 |
# Get joint indices
|
| 23 |
def get_panda_joints(robot):
|
|
|
|
| 34 |
|
| 35 |
arm_joints, finger_joints = get_panda_joints(robot)
|
| 36 |
|
| 37 |
+
# Add debug labels
|
| 38 |
+
debug_labels = []
|
| 39 |
def add_joint_labels():
|
| 40 |
+
global debug_labels
|
| 41 |
+
for i in debug_labels:
|
| 42 |
+
p.removeUserDebugItem(i)
|
| 43 |
+
debug_labels.clear()
|
| 44 |
+
for idx in arm_joints:
|
| 45 |
+
link_state = p.getLinkState(robot, idx)
|
| 46 |
+
pos = link_state[0]
|
| 47 |
+
lbl = f"J{arm_joints.index(idx)+1}"
|
| 48 |
+
text_id = p.addUserDebugText(lbl, pos, textColorRGB=[1, 0, 0], textSize=1.2)
|
| 49 |
+
debug_labels.append(text_id)
|
| 50 |
+
|
| 51 |
+
# Render simulation image
|
| 52 |
def render_sim(joint_values, gripper_val):
|
| 53 |
for idx, tgt in zip(arm_joints, joint_values):
|
| 54 |
p.setJointMotorControl2(robot, idx, p.POSITION_CONTROL, targetPosition=tgt)
|
| 55 |
if len(finger_joints) == 2:
|
| 56 |
for fj in finger_joints:
|
| 57 |
p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=gripper_val)
|
|
|
|
| 58 |
for _ in range(10): p.stepSimulation()
|
| 59 |
+
add_joint_labels()
|
| 60 |
+
width, height = 1280, 1280
|
| 61 |
+
view_matrix = p.computeViewMatrix([1.5, 0, 1], [0, 0, 0.5], [0, 0, 1])
|
| 62 |
+
proj_matrix = p.computeProjectionMatrixFOV(60, width / height, 0.1, 3.1)
|
|
|
|
|
|
|
| 63 |
_, _, img, _, _ = p.getCameraImage(width, height, view_matrix, proj_matrix)
|
| 64 |
rgb = np.reshape(img, (height, width, 4))[:, :, :3]
|
| 65 |
+
fig, ax = plt.subplots(figsize=(5, 5))
|
|
|
|
| 66 |
ax.imshow(rgb.astype(np.uint8))
|
| 67 |
ax.axis("off")
|
| 68 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
| 69 |
+
plt.savefig(tmp.name, bbox_inches='tight', dpi=200)
|
| 70 |
plt.close()
|
|
|
|
| 71 |
joint_text = "Joint Angles:\n" + "\n".join([f"J{i+1} = {v:.2f} rad" for i, v in enumerate(joint_values)])
|
| 72 |
joint_text += f"\nGripper = {gripper_val:.3f} m"
|
| 73 |
return tmp.name, joint_text
|
| 74 |
|
| 75 |
+
# Move robot to given angles smoothly
|
| 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 |
current = [p.getJointState(robot, idx)[0] for idx in arm_joints]
|
| 82 |
steps = 100
|
| 83 |
for i in range(steps):
|
|
|
|
| 89 |
current_grip = p.getJointState(robot, finger_joints[0])[0]
|
| 90 |
return render_sim(target_angles, current_grip)
|
| 91 |
except Exception as e:
|
| 92 |
+
return None, f"Error: {str(e)}"
|
| 93 |
|
| 94 |
+
# Pick-and-place sequence
|
| 95 |
def pick_and_place(position_str, approach_str, place_str):
|
| 96 |
try:
|
| 97 |
+
position_angles = [float(x.strip()) for x in position_str.split(",")]
|
| 98 |
+
approach_angles = [float(x.strip()) for x in approach_str.split(",")]
|
| 99 |
+
place_angles = [float(x.strip()) for x in place_str.split(",")]
|
| 100 |
|
| 101 |
+
if len(position_angles) != 7 or len(approach_angles) != 7 or len(place_angles) != 7:
|
| 102 |
+
return None, "❌ All inputs must have 7 joint angles."
|
|
|
|
| 103 |
|
| 104 |
+
# Move to approach
|
| 105 |
+
move_to_input_angles(approach_str)
|
| 106 |
|
| 107 |
+
# Grasp
|
| 108 |
+
for _ in range(30):
|
|
|
|
| 109 |
for fj in finger_joints:
|
| 110 |
p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=0.0)
|
| 111 |
p.stepSimulation()
|
| 112 |
time.sleep(0.01)
|
| 113 |
|
| 114 |
+
# Lift slightly
|
| 115 |
+
lifted = [a + 0.1 for a in approach_angles]
|
| 116 |
+
for i in range(100):
|
| 117 |
+
blended = [(1 - i/100) * approach_angles[j] + (i/100) * lifted[j] for j in range(7)]
|
| 118 |
+
for idx, val in zip(arm_joints, blended):
|
| 119 |
+
p.setJointMotorControl2(robot, idx, p.POSITION_CONTROL, targetPosition=val)
|
| 120 |
+
p.stepSimulation()
|
| 121 |
+
time.sleep(0.01)
|
| 122 |
|
| 123 |
+
# Move to place
|
| 124 |
+
move_to_input_angles(place_str)
|
| 125 |
|
| 126 |
+
# Release
|
| 127 |
+
for _ in range(30):
|
| 128 |
for fj in finger_joints:
|
| 129 |
p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=0.04)
|
| 130 |
p.stepSimulation()
|
| 131 |
time.sleep(0.01)
|
| 132 |
|
| 133 |
+
return render_sim(place_angles, 0.04)
|
|
|
|
|
|
|
|
|
|
| 134 |
except Exception as e:
|
| 135 |
+
return None, f"Error: {str(e)}"
|
| 136 |
+
|
| 137 |
+
# Gripper selection stub
|
| 138 |
+
def switch_gripper(gripper_type):
|
| 139 |
+
return f"Switched to: {gripper_type}"
|
| 140 |
+
|
| 141 |
+
# Gradio Interface
|
| 142 |
+
with gr.Blocks(title="Franka Arm Control with Pick and Place") as demo:
|
| 143 |
+
gr.Markdown("## 🤖 Franka 7-DOF Control")
|
| 144 |
+
|
| 145 |
+
gripper_selector = gr.Dropdown(["Two-Finger", "Suction"], value="Two-Finger", label="Select Gripper")
|
| 146 |
+
gripper_feedback = gr.Textbox(label="Gripper Status", interactive=False)
|
| 147 |
+
gripper_selector.change(fn=switch_gripper, inputs=gripper_selector, outputs=gripper_feedback)
|
| 148 |
+
|
| 149 |
+
joint_sliders = []
|
| 150 |
+
with gr.Row():
|
| 151 |
+
for i in range(4):
|
| 152 |
+
joint_sliders.append(gr.Slider(-3.14, 3.14, value=0, label=f"Joint {i+1}"))
|
| 153 |
+
with gr.Row():
|
| 154 |
+
for i in range(4, 7):
|
| 155 |
+
joint_sliders.append(gr.Slider(-3.14, 3.14, value=0, label=f"Joint {i+1}"))
|
| 156 |
+
gripper = gr.Slider(0.0, 0.04, value=0.02, step=0.001, label="Gripper")
|
| 157 |
+
|
| 158 |
+
with gr.Row():
|
| 159 |
img_output = gr.Image(type="filepath", label="Simulation View")
|
| 160 |
+
text_output = gr.Textbox(label="Joint States")
|
| 161 |
+
|
| 162 |
+
def live_update(*vals):
|
| 163 |
+
joints = list(vals[:-1])
|
| 164 |
+
grip = vals[-1]
|
| 165 |
+
return render_sim(joints, grip)
|
| 166 |
+
|
| 167 |
+
for s in joint_sliders + [gripper]:
|
| 168 |
+
s.change(fn=live_update, inputs=joint_sliders + [gripper], outputs=[img_output, text_output])
|
| 169 |
+
|
| 170 |
+
gr.Button("🔄 Reset Robot").click(
|
| 171 |
+
fn=lambda: render_sim([0]*7, 0.02),
|
| 172 |
+
inputs=[], outputs=[img_output, text_output]
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
gr.Markdown("### 🧾 Enter Joint Angles (comma-separated)")
|
| 176 |
+
joint_input = gr.Textbox(label="Joint Angles (7 values)", placeholder="e.g. 0.0, -0.5, 0.3, -1.2, 0.0, 1.5, 0.8")
|
| 177 |
+
gr.Button("▶️ Move to Angles").click(fn=move_to_input_angles, inputs=joint_input, outputs=[img_output, text_output])
|
| 178 |
+
|
| 179 |
+
gr.Markdown("### 🧾 Pick and Place Input (3 sets of joint angles)")
|
| 180 |
+
position_input = gr.Textbox(label="Object Position Angles", placeholder="e.g. 0.1, -0.3, 0.2, -1.0, 0.0, 1.2, 0.5")
|
| 181 |
+
approach_input = gr.Textbox(label="Approach Angles", placeholder="e.g. 0.1, -0.5, 0.25, -1.2, 0.0, 1.3, 0.5")
|
| 182 |
+
place_input = gr.Textbox(label="Place Angles", placeholder="e.g. 0.3, -0.4, 0.15, -1.4, 0.0, 1.4, 0.4")
|
| 183 |
+
gr.Button("🤖 Perform Pick and Place").click(
|
| 184 |
+
fn=pick_and_place,
|
| 185 |
+
inputs=[position_input, approach_input, place_input],
|
| 186 |
+
outputs=[img_output, text_output]
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
demo.launch(debug=True)
|