YashsharmaPhD commited on
Commit
9a1ac54
·
verified ·
1 Parent(s): 28d8725

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -43
app.py CHANGED
@@ -5,90 +5,107 @@ import matplotlib.pyplot as plt
5
  import tempfile
6
  import gradio as gr
7
 
8
- # Setup PyBullet simulation
9
- physicsClient = p.connect(p.DIRECT)
10
  p.setAdditionalSearchPath(pybullet_data.getDataPath())
11
  p.setGravity(0, 0, -9.8)
12
  p.loadURDF("plane.urdf")
13
-
14
- # 🔒 Fix the base of the robot to the ground
15
  robot = p.loadURDF("franka_panda/panda.urdf", basePosition=[0, 0, 0], useFixedBase=True)
16
 
 
17
  def get_panda_joints(robot):
18
- revolute, finger = [], []
19
  for i in range(p.getNumJoints(robot)):
20
- name = p.getJointInfo(robot, i)[1].decode()
21
- joint_type = p.getJointInfo(robot, i)[2]
22
- if joint_type == p.JOINT_REVOLUTE:
23
- (finger if "finger" in name else revolute).append(i)
24
- return revolute, finger
25
 
26
  arm_joints, finger_joints = get_panda_joints(robot)
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def render_sim(joint_values, gripper_val):
29
- # Set joint angles
30
- for idx, tgt in zip(arm_joints[:4], joint_values):
31
  p.setJointMotorControl2(robot, idx, p.POSITION_CONTROL, targetPosition=tgt)
32
  for fj in finger_joints:
33
  p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=gripper_val)
34
  for _ in range(10): p.stepSimulation()
35
 
36
- # Render camera
 
 
 
37
  width, height = 512, 512
38
  view_matrix = p.computeViewMatrix([1.5, 0, 1], [0, 0, 0.5], [0, 0, 1])
39
  proj_matrix = p.computeProjectionMatrixFOV(60, width / height, 0.1, 3.1)
40
  _, _, img, _, _ = p.getCameraImage(width, height, view_matrix, proj_matrix)
41
  rgb = np.reshape(img, (height, width, 4))[:, :, :3]
42
 
43
- # Plot image with joint labels
44
  fig, ax = plt.subplots(figsize=(5, 5))
45
  ax.imshow(rgb.astype(np.uint8))
46
  ax.axis("off")
47
- labels = ["J1", "J2", "J3", "J4"]
48
- positions = [(180, 400), (220, 320), (260, 240), (300, 160)]
49
- for label, pos in zip(labels, positions):
50
- ax.text(*pos, label, color="red", fontsize=12, fontweight="bold")
51
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
52
  plt.savefig(tmp.name, bbox_inches='tight')
53
  plt.close()
54
 
55
- # Joint state text
56
- joint_text = (
57
- f"Joint Angles:\n"
58
- f"J1 = {joint_values[0]:.2f} rad\n"
59
- f"J2 = {joint_values[1]:.2f} rad\n"
60
- f"J3 = {joint_values[2]:.2f} rad\n"
61
- f"J4 = {joint_values[3]:.2f} rad\n"
62
- f"Gripper = {gripper_val:.3f} m"
63
- )
64
  return tmp.name, joint_text
65
 
66
- # Launch Gradio with Blocks
67
- with gr.Blocks(title="Live Robot Control with Reset") as demo:
68
- gr.Markdown("## 🤖 Live Robot Control\nUse sliders below or click Reset to restore pose.")
 
 
 
69
 
70
- with gr.Row():
71
- j1 = gr.Slider(-3.14, 3.14, value=0, label="Joint 1", interactive=True)
72
- j2 = gr.Slider(-3.14, 3.14, value=0, label="Joint 2", interactive=True)
73
- j3 = gr.Slider(-3.14, 3.14, value=0, label="Joint 3", interactive=True)
74
- j4 = gr.Slider(-3.14, 3.14, value=0, label="Joint 4", interactive=True)
75
- gripper = gr.Slider(0.0, 0.04, value=0.02, step=0.001, label="Gripper Opening", interactive=True)
 
 
 
 
 
 
76
 
77
  with gr.Row():
78
  img_output = gr.Image(type="filepath", label="Simulation View")
79
  text_output = gr.Textbox(label="Joint States")
80
 
81
- # Live update function
82
- def live_update(j1_val, j2_val, j3_val, j4_val, grip_val):
83
- return render_sim([j1_val, j2_val, j3_val, j4_val], grip_val)
 
 
84
 
85
- # Connect sliders to live update
86
- for slider in [j1, j2, j3, j4, gripper]:
87
- slider.change(live_update, inputs=[j1, j2, j3, j4, gripper], outputs=[img_output, text_output])
88
 
89
  # Reset button
90
  def reset():
91
- return render_sim([0, 0, 0, 0], 0.02)
92
 
93
  gr.Button("🔄 Reset Robot").click(fn=reset, inputs=[], outputs=[img_output, text_output])
94
 
 
5
  import tempfile
6
  import gradio as gr
7
 
8
+ # Setup PyBullet
9
+ p.connect(p.DIRECT)
10
  p.setAdditionalSearchPath(pybullet_data.getDataPath())
11
  p.setGravity(0, 0, -9.8)
12
  p.loadURDF("plane.urdf")
 
 
13
  robot = p.loadURDF("franka_panda/panda.urdf", basePosition=[0, 0, 0], useFixedBase=True)
14
 
15
+ # Get joint indices
16
  def get_panda_joints(robot):
17
+ arm, fingers = [], []
18
  for i in range(p.getNumJoints(robot)):
19
+ info = p.getJointInfo(robot, i)
20
+ name = info[1].decode()
21
+ if info[2] == p.JOINT_REVOLUTE:
22
+ (fingers if "finger" in name else arm).append(i)
23
+ return arm, fingers
24
 
25
  arm_joints, finger_joints = get_panda_joints(robot)
26
 
27
+ # Add 3D debug labels to the robot's joints
28
+ debug_labels = []
29
+ def add_joint_labels():
30
+ global debug_labels
31
+ for i in debug_labels:
32
+ p.removeUserDebugItem(i)
33
+ debug_labels.clear()
34
+ for idx in arm_joints:
35
+ link_state = p.getLinkState(robot, idx)
36
+ pos = link_state[0]
37
+ lbl = f"J{arm_joints.index(idx)+1}"
38
+ text_id = p.addUserDebugText(lbl, pos, textColorRGB=[1, 0, 0], textSize=1.2)
39
+ debug_labels.append(text_id)
40
+
41
+ # Render image and info
42
  def render_sim(joint_values, gripper_val):
43
+ # Apply joint controls
44
+ for idx, tgt in zip(arm_joints, joint_values):
45
  p.setJointMotorControl2(robot, idx, p.POSITION_CONTROL, targetPosition=tgt)
46
  for fj in finger_joints:
47
  p.setJointMotorControl2(robot, fj, p.POSITION_CONTROL, targetPosition=gripper_val)
48
  for _ in range(10): p.stepSimulation()
49
 
50
+ # Refresh joint labels
51
+ add_joint_labels()
52
+
53
+ # Camera
54
  width, height = 512, 512
55
  view_matrix = p.computeViewMatrix([1.5, 0, 1], [0, 0, 0.5], [0, 0, 1])
56
  proj_matrix = p.computeProjectionMatrixFOV(60, width / height, 0.1, 3.1)
57
  _, _, img, _, _ = p.getCameraImage(width, height, view_matrix, proj_matrix)
58
  rgb = np.reshape(img, (height, width, 4))[:, :, :3]
59
 
60
+ # Image to file
61
  fig, ax = plt.subplots(figsize=(5, 5))
62
  ax.imshow(rgb.astype(np.uint8))
63
  ax.axis("off")
 
 
 
 
64
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
65
  plt.savefig(tmp.name, bbox_inches='tight')
66
  plt.close()
67
 
68
+ # Text output
69
+ joint_text = "Joint Angles:\n" + "\n".join([f"J{i+1} = {v:.2f} rad" for i, v in enumerate(joint_values)])
70
+ joint_text += f"\nGripper = {gripper_val:.3f} m"
 
 
 
 
 
 
71
  return tmp.name, joint_text
72
 
73
+ # Load gripper type (placeholder logic)
74
+ def switch_gripper(gripper_type):
75
+ print(f"Switching to gripper: {gripper_type}")
76
+ # In real case, remove current gripper, attach new one
77
+ # For demo, just return something to show
78
+ return f"Switched to: {gripper_type}"
79
 
80
+ # Gradio UI
81
+ with gr.Blocks(title="Franka Arm Control with 7 DoF and Gripper Options") as demo:
82
+ gr.Markdown("## 🤖 Franka 7-DOF Control\nUse the sliders to manipulate the robot arm.")
83
+
84
+ # Gripper selection
85
+ gripper_selector = gr.Dropdown(["Two-Finger", "Suction"], value="Two-Finger", label="Select Gripper")
86
+ gripper_feedback = gr.Textbox(label="Gripper Status", interactive=False)
87
+ gripper_selector.change(fn=switch_gripper, inputs=gripper_selector, outputs=gripper_feedback)
88
+
89
+ # 7 DoF sliders
90
+ joint_sliders = [gr.Slider(-3.14, 3.14, value=0, label=f"Joint {i+1}") for i in range(7)]
91
+ gripper = gr.Slider(0.0, 0.04, value=0.02, step=0.001, label="Gripper Opening")
92
 
93
  with gr.Row():
94
  img_output = gr.Image(type="filepath", label="Simulation View")
95
  text_output = gr.Textbox(label="Joint States")
96
 
97
+ # Update all joints
98
+ def live_update(*vals):
99
+ joints = list(vals[:-1]) # first 7 values
100
+ grip = vals[-1]
101
+ return render_sim(joints, grip)
102
 
103
+ for s in joint_sliders + [gripper]:
104
+ s.change(fn=live_update, inputs=joint_sliders + [gripper], outputs=[img_output, text_output])
 
105
 
106
  # Reset button
107
  def reset():
108
+ return render_sim([0]*7, 0.02)
109
 
110
  gr.Button("🔄 Reset Robot").click(fn=reset, inputs=[], outputs=[img_output, text_output])
111