|
| 1 | +"""Correction capture for the correction flywheel. |
| 2 | +
|
| 3 | +Captures a human correction using openadapt-capture's Recorder (primary path) |
| 4 | +or falls back to simple periodic screenshots via PIL if openadapt-capture is |
| 5 | +not available. |
| 6 | +
|
| 7 | +The Recorder provides full input event recording (mouse + keyboard) plus |
| 8 | +action-gated screenshots, which gives the VLM parser much richer context |
| 9 | +for understanding what the human did. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import logging |
| 15 | +import os |
| 16 | +import time |
| 17 | +from dataclasses import dataclass, field |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +@dataclass |
| 23 | +class CorrectionResult: |
| 24 | + """Result of a correction capture session.""" |
| 25 | + |
| 26 | + screenshots: list[str] = field(default_factory=list) # paths |
| 27 | + capture_dir: str | None = None # openadapt-capture directory (if used) |
| 28 | + duration_seconds: float = 0.0 |
| 29 | + output_dir: str = "" |
| 30 | + |
| 31 | + |
| 32 | +def _take_screenshot(output_path: str) -> str | None: |
| 33 | + """Take a screenshot and save to output_path. Returns path or None.""" |
| 34 | + try: |
| 35 | + from PIL import ImageGrab |
| 36 | + |
| 37 | + img = ImageGrab.grab() |
| 38 | + img.save(output_path) |
| 39 | + return output_path |
| 40 | + except Exception as exc: |
| 41 | + logger.warning("Screenshot failed: %s", exc) |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +def _has_recorder() -> bool: |
| 46 | + """Check if openadapt-capture Recorder is available.""" |
| 47 | + try: |
| 48 | + from openadapt_capture.recorder import Recorder # noqa: F401 |
| 49 | + |
| 50 | + return True |
| 51 | + except ImportError: |
| 52 | + return False |
| 53 | + |
| 54 | + |
| 55 | +def _prompt_user(step_desc: str, explanation: str) -> None: |
| 56 | + """Print the correction prompt to the terminal.""" |
| 57 | + print("\n" + "=" * 60) |
| 58 | + print("CORRECTION NEEDED") |
| 59 | + print("=" * 60) |
| 60 | + print(f"Failed step: {step_desc}") |
| 61 | + if explanation: |
| 62 | + print(f"Reason: {explanation}") |
| 63 | + print("\nPlease complete this step manually.") |
| 64 | + print("Press Enter when done...") |
| 65 | + print("=" * 60 + "\n") |
| 66 | + |
| 67 | + |
| 68 | +def _wait_for_enter(timeout_seconds: int) -> None: |
| 69 | + """Block until user presses Enter or timeout expires.""" |
| 70 | + try: |
| 71 | + import select |
| 72 | + import sys |
| 73 | + |
| 74 | + if hasattr(select, "select"): |
| 75 | + remaining = timeout_seconds |
| 76 | + while remaining > 0: |
| 77 | + ready, _, _ = select.select([sys.stdin], [], [], 1.0) |
| 78 | + if ready: |
| 79 | + sys.stdin.readline() |
| 80 | + break |
| 81 | + remaining -= 1.0 |
| 82 | + else: |
| 83 | + input() |
| 84 | + except EOFError: |
| 85 | + logger.info("stdin closed, stopping capture after timeout") |
| 86 | + time.sleep(min(timeout_seconds, 10)) |
| 87 | + |
| 88 | + |
| 89 | +class CorrectionCapture: |
| 90 | + """Capture a human correction for a failed step.""" |
| 91 | + |
| 92 | + def __init__(self, output_dir: str): |
| 93 | + self.output_dir = output_dir |
| 94 | + os.makedirs(output_dir, exist_ok=True) |
| 95 | + |
| 96 | + def capture_correction( |
| 97 | + self, |
| 98 | + failure_context: dict, |
| 99 | + timeout_seconds: int = 120, |
| 100 | + interval_seconds: float = 2.0, |
| 101 | + ) -> CorrectionResult: |
| 102 | + """Capture a human correction. |
| 103 | +
|
| 104 | + Uses openadapt-capture Recorder if available (full input events + |
| 105 | + action-gated screenshots), otherwise falls back to periodic PIL |
| 106 | + screenshots. |
| 107 | + """ |
| 108 | + # Save the failure screenshot as "before" |
| 109 | + before_path = os.path.join(self.output_dir, "before.png") |
| 110 | + before_screenshots = [] |
| 111 | + if failure_context.get("screenshot_bytes"): |
| 112 | + with open(before_path, "wb") as f: |
| 113 | + f.write(failure_context["screenshot_bytes"]) |
| 114 | + before_screenshots.append(before_path) |
| 115 | + elif failure_context.get("screenshot_path"): |
| 116 | + before_screenshots.append(failure_context["screenshot_path"]) |
| 117 | + |
| 118 | + step_desc = failure_context.get("step_action", "this step") |
| 119 | + explanation = failure_context.get("explanation", "") |
| 120 | + |
| 121 | + _prompt_user(step_desc, explanation) |
| 122 | + |
| 123 | + if _has_recorder(): |
| 124 | + return self._capture_with_recorder( |
| 125 | + before_screenshots, timeout_seconds |
| 126 | + ) |
| 127 | + else: |
| 128 | + logger.info("openadapt-capture not available, using simple screenshot capture") |
| 129 | + return self._capture_simple( |
| 130 | + before_screenshots, timeout_seconds, interval_seconds |
| 131 | + ) |
| 132 | + |
| 133 | + def _capture_with_recorder( |
| 134 | + self, |
| 135 | + before_screenshots: list[str], |
| 136 | + timeout_seconds: int, |
| 137 | + ) -> CorrectionResult: |
| 138 | + """Full capture using openadapt-capture Recorder.""" |
| 139 | + from openadapt_capture.recorder import Recorder |
| 140 | + |
| 141 | + capture_dir = os.path.join(self.output_dir, "recording") |
| 142 | + start = time.monotonic() |
| 143 | + |
| 144 | + with Recorder( |
| 145 | + capture_dir, |
| 146 | + task_description="Human correction for failed agent step", |
| 147 | + capture_video=False, # screenshots only, faster |
| 148 | + capture_audio=False, |
| 149 | + ) as recorder: |
| 150 | + recorder.wait_for_ready(timeout=30) |
| 151 | + _wait_for_enter(timeout_seconds) |
| 152 | + recorder.stop() |
| 153 | + |
| 154 | + duration = time.monotonic() - start |
| 155 | + |
| 156 | + # Extract screenshots from the capture |
| 157 | + screenshot_paths = list(before_screenshots) |
| 158 | + try: |
| 159 | + from openadapt_capture.capture import CaptureSession |
| 160 | + |
| 161 | + session = CaptureSession.load(capture_dir) |
| 162 | + for i, action in enumerate(session.actions()): |
| 163 | + if action.screenshot is not None: |
| 164 | + path = os.path.join(self.output_dir, f"action_{i:04d}.png") |
| 165 | + action.screenshot.save(path) |
| 166 | + screenshot_paths.append(path) |
| 167 | + except Exception as exc: |
| 168 | + logger.warning("Failed to extract screenshots from capture: %s", exc) |
| 169 | + # Fall back to taking a final screenshot |
| 170 | + after_path = os.path.join(self.output_dir, "after.png") |
| 171 | + taken = _take_screenshot(after_path) |
| 172 | + if taken: |
| 173 | + screenshot_paths.append(taken) |
| 174 | + |
| 175 | + logger.info( |
| 176 | + "Recorder capture complete: %d screenshots in %.1fs", |
| 177 | + len(screenshot_paths), |
| 178 | + duration, |
| 179 | + ) |
| 180 | + return CorrectionResult( |
| 181 | + screenshots=screenshot_paths, |
| 182 | + capture_dir=capture_dir, |
| 183 | + duration_seconds=duration, |
| 184 | + output_dir=self.output_dir, |
| 185 | + ) |
| 186 | + |
| 187 | + def _capture_simple( |
| 188 | + self, |
| 189 | + before_screenshots: list[str], |
| 190 | + timeout_seconds: int, |
| 191 | + interval_seconds: float, |
| 192 | + ) -> CorrectionResult: |
| 193 | + """Fallback: periodic PIL screenshots.""" |
| 194 | + import threading |
| 195 | + |
| 196 | + start = time.monotonic() |
| 197 | + stop_event = threading.Event() |
| 198 | + screenshot_paths: list[str] = [] |
| 199 | + |
| 200 | + def _capture_loop(): |
| 201 | + idx = 0 |
| 202 | + while not stop_event.is_set(): |
| 203 | + stop_event.wait(interval_seconds) |
| 204 | + if stop_event.is_set(): |
| 205 | + break |
| 206 | + path = os.path.join(self.output_dir, f"capture_{idx:04d}.png") |
| 207 | + taken = _take_screenshot(path) |
| 208 | + if taken: |
| 209 | + screenshot_paths.append(taken) |
| 210 | + idx += 1 |
| 211 | + |
| 212 | + capture_thread = threading.Thread(target=_capture_loop, daemon=True) |
| 213 | + capture_thread.start() |
| 214 | + |
| 215 | + _wait_for_enter(timeout_seconds) |
| 216 | + |
| 217 | + stop_event.set() |
| 218 | + capture_thread.join(timeout=5) |
| 219 | + |
| 220 | + # Final "after" screenshot |
| 221 | + after_path = os.path.join(self.output_dir, "after.png") |
| 222 | + taken = _take_screenshot(after_path) |
| 223 | + if taken: |
| 224 | + screenshot_paths.append(taken) |
| 225 | + |
| 226 | + all_screenshots = list(before_screenshots) + screenshot_paths |
| 227 | + duration = time.monotonic() - start |
| 228 | + |
| 229 | + logger.info( |
| 230 | + "Simple capture complete: %d screenshots in %.1fs", |
| 231 | + len(all_screenshots), |
| 232 | + duration, |
| 233 | + ) |
| 234 | + return CorrectionResult( |
| 235 | + screenshots=all_screenshots, |
| 236 | + duration_seconds=duration, |
| 237 | + output_dir=self.output_dir, |
| 238 | + ) |
0 commit comments