otaviorosa commited on
Commit
9399c53
Β·
verified Β·
1 Parent(s): 2d04de4

Upload run.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. run.py +337 -0
run.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Go2 Robot Dog β€” Projector Surface Capture Script
3
+ =================================================
4
+ Workflow:
5
+ 1. Connect to Go2 camera via WebRTC
6
+ 2. Capture baseline frames (no projection)
7
+ 3. SSH into robot, project each image one-by-one using feh
8
+ 4. After each image is projected, capture camera frames
9
+ 5. Save all frames to an organized output directory
10
+
11
+ Requirements:
12
+ pip install unitree-webrtc-connect aiortc opencv-python paramiko
13
+ """
14
+ import asyncio
15
+ import logging
16
+ import threading
17
+ import time
18
+ import os
19
+ import cv2
20
+ import numpy as np
21
+ import paramiko
22
+ from queue import Queue, Empty
23
+ from pathlib import Path
24
+ from datetime import datetime
25
+ from unitree_webrtc_connect.webrtc_driver import UnitreeWebRTCConnection, WebRTCConnectionMethod
26
+ from aiortc import MediaStreamTrack
27
+
28
+ # ─────────────────────────────────────────────
29
+ # CONFIGURATION β€” edit these before running
30
+ # ─────────────────────────────────────────────
31
+
32
+ ROBOT_CAMERA_IP = "192.168.0.224" # IP for WebRTC camera stream
33
+ ROBOT_SSH_IP = "192.168.0.113" # IP for SSH access to projector
34
+ SSH_USER = "unitree"
35
+ SSH_PASSWORD = "123" # or use SSH key (see ssh_connect())
36
+
37
+ PROJECTOR_SLIDES_DIR = "~/Projector_Slides" # Folder on the robot with images to project
38
+ LOCAL_IMAGES_DIR = "./images_to_project" # Local folder β€” images here get uploaded & projected
39
+ OUTPUT_DIR = "./capture_output" # Where captured frames are saved locally
40
+
41
+ FRAMES_TO_CAPTURE = 1 # Number of frames to capture per projected image
42
+ FRAME_CAPTURE_DELAY = 0.5 # Seconds between captured frames
43
+ PROJECTION_WARMUP = 2.0 # Seconds to wait after projecting before capturing
44
+
45
+ DISPLAY = ":1" # X display for the projector
46
+ PREVIEW_WINDOW = True # Show live OpenCV preview while capturing
47
+
48
+ logging.basicConfig(level=logging.WARNING)
49
+
50
+ # ─────────────────────────────────────────────
51
+ # CAMERA STREAM
52
+ # ─────────────────────────────────────────────
53
+
54
+ class CameraStream:
55
+ def __init__(self, ip: str):
56
+ self.ip = ip
57
+ self.frame_queue: Queue = Queue(maxsize=30)
58
+ self.loop = None
59
+ self.thread = None
60
+ self.conn = None
61
+
62
+ def start(self):
63
+ self.conn = UnitreeWebRTCConnection(WebRTCConnectionMethod.LocalSTA, ip=self.ip)
64
+ self.loop = asyncio.new_event_loop()
65
+ self.thread = threading.Thread(target=self._run_loop, daemon=True)
66
+ self.thread.start()
67
+ # Wait until we get the first frame
68
+ print(" Waiting for camera stream...")
69
+ timeout = 15
70
+ start = time.time()
71
+ while self.frame_queue.empty():
72
+ if time.time() - start > timeout:
73
+ raise TimeoutError("Camera stream did not start within timeout.")
74
+ time.sleep(0.2)
75
+ print(" Camera stream active.")
76
+
77
+ def _run_loop(self):
78
+ asyncio.set_event_loop(self.loop)
79
+
80
+ async def setup():
81
+ await self.conn.connect()
82
+ self.conn.video.switchVideoChannel(True)
83
+ self.conn.video.add_track_callback(self._recv_track)
84
+
85
+ self.loop.run_until_complete(setup())
86
+ self.loop.run_forever()
87
+
88
+ def clear_queue(self):
89
+ """Empty the queue so we don't get old frames."""
90
+ while not self.frame_queue.empty():
91
+ try:
92
+ self.frame_queue.get_nowait()
93
+ except Empty:
94
+ break
95
+
96
+ async def _recv_track(self, track: MediaStreamTrack):
97
+ while True:
98
+ try:
99
+ frame = await track.recv()
100
+ img = frame.to_ndarray(format="bgr24")
101
+ except Exception as e:
102
+ logging.warning(f"Frame decode/receive error (skipping): {e}")
103
+ continue # ← keep the loop alive, don't die
104
+
105
+ if self.frame_queue.full():
106
+ try:
107
+ self.frame_queue.get_nowait()
108
+ except Empty:
109
+ pass
110
+ self.frame_queue.put(img)
111
+
112
+ def get_latest_frame(self, timeout=2.0):
113
+ """Return the most recent frame, or None if timeout reached."""
114
+ try:
115
+ # Wait for at least one frame to be available
116
+ return self.frame_queue.get(timeout=timeout)
117
+ except Empty:
118
+ logging.warning(" Camera Timeout: No frame received in queue.")
119
+ return None
120
+
121
+ def capture_frames(self, count: int, delay: float) -> list:
122
+ """Capture `count` frames spaced `delay` seconds apart."""
123
+ frames = []
124
+ for i in range(count):
125
+ frame = self.get_latest_frame()
126
+ if frame is not None:
127
+ frames.append(frame)
128
+ if PREVIEW_WINDOW:
129
+ cv2.imshow("Go2 Camera", frame)
130
+ cv2.waitKey(1)
131
+ if i < count - 1:
132
+ time.sleep(delay)
133
+ return frames
134
+
135
+ def stop(self):
136
+ if self.loop:
137
+ self.loop.call_soon_threadsafe(self.loop.stop)
138
+ if self.thread:
139
+ self.thread.join(timeout=3)
140
+ cv2.destroyAllWindows()
141
+
142
+
143
+ # ─────────────────────────────────────────────
144
+ # SSH / PROJECTOR CONTROL
145
+ # ─────────────────────────────────────────────
146
+
147
+ class ProjectorController:
148
+ def __init__(self, ip: str, user: str, password: str):
149
+ self.ip = ip
150
+ self.user = user
151
+ self.password = password
152
+ self.ssh: paramiko.SSHClient = None
153
+ self.current_pid = None
154
+
155
+ def connect(self):
156
+ print(f" Connecting via SSH to {self.user}@{self.ip}...")
157
+ self.ssh = paramiko.SSHClient()
158
+ self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
159
+ self.ssh.connect(self.ip, username=self.user, password=self.password)
160
+ print(" SSH connected.")
161
+
162
+ def _exec(self, cmd: str) -> str:
163
+ _, stdout, stderr = self.ssh.exec_command(cmd)
164
+ out = stdout.read().decode().strip()
165
+ err = stderr.read().decode().strip()
166
+ if err:
167
+ logging.debug(f"SSH stderr: {err}")
168
+ return out
169
+
170
+ def upload_images(self, local_dir: str, remote_dir: str):
171
+ """Upload local images to the robot via SCP."""
172
+ local_path = Path(local_dir)
173
+ if not local_path.exists():
174
+ print(f" Local image dir '{local_dir}' not found, skipping upload.")
175
+ return
176
+
177
+ images = sorted(local_path.glob("*"))
178
+ images = [f for f in images if f.suffix.lower() in {".jpg", ".jpeg", ".png", ".bmp", ".gif"}]
179
+ if not images:
180
+ print(f" No images found in '{local_dir}', skipping upload.")
181
+ return
182
+
183
+ print(f" Uploading {len(images)} images to robot...")
184
+ self._exec(f"mkdir -p {remote_dir}")
185
+ sftp = self.ssh.open_sftp()
186
+ for img in images:
187
+ remote_path = f"{remote_dir.rstrip('~').replace('~', '/root')}/{img.name}"
188
+ # Expand ~ properly
189
+ remote_expanded = self._exec(f"echo {remote_dir}/{img.name}")
190
+ sftp.put(str(img), remote_expanded)
191
+ print(f" Uploaded: {img.name}")
192
+ sftp.close()
193
+
194
+ def list_remote_images(self, remote_dir: str) -> list:
195
+ """Return sorted list of image filenames in the remote directory."""
196
+ out = self._exec(
197
+ f"find {remote_dir} -maxdepth 1 -type f "
198
+ r"\( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.bmp' \) | sort"
199
+ )
200
+ return [line for line in out.splitlines() if line.strip()]
201
+
202
+ def start_slideshow(self, image_paths: list):
203
+ """Launch feh once with all images. Starts on the first image."""
204
+ self.stop_projection()
205
+ files = " ".join(f"'{p}'" for p in image_paths)
206
+ cmd = (
207
+ f"DISPLAY={DISPLAY} feh --fullscreen --auto-zoom --borderless "
208
+ f"--slideshow-delay 0 {files} > /dev/null 2>&1 &"
209
+ )
210
+ self._exec(cmd)
211
+ time.sleep(0.5)
212
+ pid_out = self._exec("pgrep -n feh")
213
+ self.current_pid = pid_out if pid_out else None
214
+ print(f" Slideshow started (PID {self.current_pid}) with {len(image_paths)} images.")
215
+
216
+ def create_black_slide(self) -> str:
217
+ """Create a black image on the robot and return its path."""
218
+ path = "/tmp/black_baseline.png"
219
+ self._exec(f"python3 -c \"from PIL import Image; Image.new('RGB', (1920, 1080)).save('{path}')\"")
220
+ return path
221
+
222
+ def next_image(self):
223
+ """Advance feh to the next image with no close/reopen flash."""
224
+ if self.current_pid:
225
+ self._exec(f"kill -SIGUSR1 {self.current_pid}")
226
+
227
+ def stop_projection(self):
228
+ """Kill any running feh process."""
229
+ self._exec("pkill feh 2>/dev/null || true")
230
+ self.current_pid = None
231
+
232
+ def disconnect(self):
233
+ self.stop_projection()
234
+ if self.ssh:
235
+ self.ssh.close()
236
+
237
+
238
+ # ─────────────────────────────────────────────
239
+ # OUTPUT MANAGEMENT
240
+ # ─────────────────────────────────────────────
241
+
242
+ def save_frames(frames: list, out_dir: Path, prefix: str):
243
+ out_dir.mkdir(parents=True, exist_ok=True)
244
+ saved = []
245
+ for i, frame in enumerate(frames):
246
+ filename = out_dir / f"{prefix}_frame{i+1:03d}.png"
247
+ cv2.imwrite(str(filename), frame)
248
+ saved.append(filename)
249
+ return saved
250
+
251
+
252
+ # ─────────────────────────────────────────────
253
+ # MAIN WORKFLOW
254
+ # ─────────────────────────────────────────────
255
+
256
+ def main():
257
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
258
+ out_root = Path(OUTPUT_DIR) / f"session_{timestamp}"
259
+ out_root.mkdir(parents=True, exist_ok=True)
260
+ print(f"\n{'='*55}")
261
+ print(f" Go2 Projector Surface Capture")
262
+ print(f" Session output: {out_root}")
263
+ print(f"{'='*55}\n")
264
+
265
+ # ── 1. Start camera stream ──────────────────────────
266
+ print("[1/3] Starting camera stream...")
267
+ camera = CameraStream(ROBOT_CAMERA_IP)
268
+ try:
269
+ camera.start()
270
+ except TimeoutError as e:
271
+ print(f" ERROR: {e}")
272
+ return
273
+
274
+ # ── 2. Connect SSH / upload images ─────────────────
275
+ print("\n[2/3] Connecting to projector via SSH...")
276
+ projector = ProjectorController(ROBOT_SSH_IP, SSH_USER, SSH_PASSWORD)
277
+ try:
278
+ projector.connect()
279
+ except Exception as e:
280
+ print(f" ERROR: Could not connect via SSH: {e}")
281
+ camera.stop()
282
+ return
283
+
284
+ projector.upload_images(LOCAL_IMAGES_DIR, PROJECTOR_SLIDES_DIR)
285
+
286
+ images = projector.list_remote_images(PROJECTOR_SLIDES_DIR)
287
+ if not images:
288
+ print(f" ERROR: No images found in {PROJECTOR_SLIDES_DIR} on the robot.")
289
+ projector.disconnect()
290
+ camera.stop()
291
+ return
292
+
293
+ print(f" Found {len(images)} images to project.")
294
+
295
+ # ── 3. Project each image & capture ────────────────
296
+ print(f"\n[3/3] Projecting images and capturing frames...\n")
297
+
298
+ black_slide = projector.create_black_slide()
299
+ images = [black_slide] + images
300
+
301
+ projector.start_slideshow(images)
302
+ print(f" Waiting {PROJECTION_WARMUP}s for first image to stabilize...")
303
+ time.sleep(PROJECTION_WARMUP)
304
+
305
+ for idx, image_path in enumerate(images):
306
+ image_name = "baseline" if idx == 0 else Path(image_path).stem
307
+ label = f"{idx:03d}_{image_name}"
308
+
309
+ print(f" [{idx+1}/{len(images)}] Capturing: {Path(image_path).name}")
310
+
311
+ camera.clear_queue()
312
+ frames = camera.capture_frames(FRAMES_TO_CAPTURE, FRAME_CAPTURE_DELAY)
313
+
314
+ if not frames:
315
+ print(f" ⚠️ WARNING: No frames captured for {image_name}.")
316
+ else:
317
+ saved = save_frames(frames, out_root, label)
318
+ print(f" Saved {len(saved)} frames β†’ {out_root}")
319
+
320
+ if idx < len(images) - 1:
321
+ projector.next_image()
322
+ print(f" Waiting {PROJECTION_WARMUP}s for next image to stabilize...")
323
+ time.sleep(PROJECTION_WARMUP)
324
+
325
+ # ── Cleanup ─────────────────────────────────────────
326
+ print("\nStopping projection and cleaning up...")
327
+ projector.disconnect()
328
+ camera.stop()
329
+
330
+ print(f"\n{'='*55}")
331
+ print(f" Done! All captures saved to:")
332
+ print(f" {out_root.resolve()}")
333
+ print(f"{'='*55}\n")
334
+
335
+
336
+ if __name__ == "__main__":
337
+ main()