1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
| from enum import Enum from dataclasses import dataclass from typing import Dict, List, Callable, Any import asyncio import json import time
class StepStatus(Enum): """步骤状态枚举""" PENDING = "pending" RUNNING = "running" SUCCESS = "success" FAILED = "failed" SKIPPED = "skipped" RETRY = "retry"
class FlowStatus(Enum): """流程状态枚举""" CREATED = "created" RUNNING = "running" PAUSED = "paused" COMPLETED = "completed" FAILED = "failed" CANCELLED = "cancelled"
@dataclass class StepResult: """步骤执行结果""" status: StepStatus data: Any = None error: str = None execution_time: float = 0.0 retry_count: int = 0
@dataclass class FlowStep: """流程步骤定义""" id: str name: str action_type: str parameters: Dict[str, Any] retry_config: Dict[str, Any] = None condition: str = None timeout: int = 30 class RPAFlowEngine: """RPA流程编排引擎""" def __init__(self): self.flows = {} self.action_registry = {} self.global_variables = {} self.event_handlers = {} self._register_builtin_actions() def register_action(self, action_type: str, action_func: Callable): """注册动作处理器""" self.action_registry[action_type] = action_func def create_flow(self, flow_id: str, steps: List[FlowStep]) -> str: """创建流程""" flow = { 'id': flow_id, 'steps': steps, 'status': FlowStatus.CREATED, 'current_step': 0, 'results': {}, 'variables': {}, 'created_time': time.time(), 'start_time': None, 'end_time': None } self.flows[flow_id] = flow return flow_id async def execute_flow(self, flow_id: str, input_data: Dict[str, Any] = None) -> Dict[str, Any]: """执行流程""" if flow_id not in self.flows: raise ValueError(f"流程不存在: {flow_id}") flow = self.flows[flow_id] flow['status'] = FlowStatus.RUNNING flow['start_time'] = time.time() if input_data: flow['variables'].update(input_data) try: for i, step in enumerate(flow['steps']): flow['current_step'] = i if not self._check_step_condition(step, flow['variables']): flow['results'][step.id] = StepResult( status=StepStatus.SKIPPED, data="条件不满足,跳过执行" ) continue result = await self._execute_step(step, flow['variables']) flow['results'][step.id] = result if result.status == StepStatus.SUCCESS and result.data: if isinstance(result.data, dict): flow['variables'].update(result.data) if result.status == StepStatus.FAILED: flow['status'] = FlowStatus.FAILED break if flow['status'] == FlowStatus.RUNNING: flow['status'] = FlowStatus.COMPLETED except Exception as e: flow['status'] = FlowStatus.FAILED flow['error'] = str(e) finally: flow['end_time'] = time.time() return { 'flow_id': flow_id, 'status': flow['status'].value, 'results': {k: { 'status': v.status.value, 'data': v.data, 'error': v.error, 'execution_time': v.execution_time } for k, v in flow['results'].items()}, 'execution_time': flow['end_time'] - flow['start_time'] } async def _execute_step(self, step: FlowStep, variables: Dict[str, Any]) -> StepResult: """执行单个步骤""" start_time = time.time() retry_count = 0 max_retries = step.retry_config.get('max_retries', 3) if step.retry_config else 3 while retry_count <= max_retries: try: if step.action_type not in self.action_registry: raise ValueError(f"未知的动作类型: {step.action_type}") action_func = self.action_registry[step.action_type] resolved_params = self._resolve_parameters(step.parameters, variables) result_data = await asyncio.wait_for( action_func(resolved_params), timeout=step.timeout ) execution_time = time.time() - start_time return StepResult( status=StepStatus.SUCCESS, data=result_data, execution_time=execution_time, retry_count=retry_count ) except asyncio.TimeoutError: error_msg = f"步骤执行超时: {step.timeout}秒" if retry_count < max_retries: retry_count += 1 await asyncio.sleep(step.retry_config.get('retry_delay', 1) if step.retry_config else 1) continue else: return StepResult( status=StepStatus.FAILED, error=error_msg, execution_time=time.time() - start_time, retry_count=retry_count ) except Exception as e: error_msg = f"步骤执行失败: {str(e)}" if retry_count < max_retries and self._is_retryable_error(e): retry_count += 1 await asyncio.sleep(step.retry_config.get('retry_delay', 1) if step.retry_config else 1) continue else: return StepResult( status=StepStatus.FAILED, error=error_msg, execution_time=time.time() - start_time, retry_count=retry_count ) def _check_step_condition(self, step: FlowStep, variables: Dict[str, Any]) -> bool: """检查步骤执行条件""" if not step.condition: return True try: condition = step.condition for var_name, var_value in variables.items(): condition = condition.replace(f"${{{var_name}}}", str(var_value)) return eval(condition) except Exception: return True def _resolve_parameters(self, parameters: Dict[str, Any], variables: Dict[str, Any]) -> Dict[str, Any]: """解析参数中的变量引用""" resolved = {} for key, value in parameters.items(): if isinstance(value, str) and value.startswith('${') and value.endswith('}'): var_name = value[2:-1] resolved[key] = variables.get(var_name, value) else: resolved[key] = value return resolved def _is_retryable_error(self, error: Exception) -> bool: """判断错误是否可重试""" retryable_errors = [ 'timeout', 'network', 'connection', 'temporary' ] error_msg = str(error).lower() return any(keyword in error_msg for keyword in retryable_errors) def _register_builtin_actions(self): """注册内置动作""" self.register_action('click', self._action_click) self.register_action('input', self._action_input) self.register_action('wait', self._action_wait) self.register_action('screenshot', self._action_screenshot) self.register_action('condition', self._action_condition) async def _action_click(self, params: Dict[str, Any]) -> Dict[str, Any]: """点击动作""" target_info = params.get('target') if not target_info: raise ValueError("缺少点击目标信息") recognizer = ElementRecognizer() element = recognizer.find_element(target_info) if not element: raise ValueError("未找到目标元素") pyautogui.click(element['position']['x'], element['position']['y']) return { 'clicked_position': element['position'], 'recognition_method': element['method'], 'confidence': element['confidence'] } async def _action_input(self, params: Dict[str, Any]) -> Dict[str, Any]: """输入动作""" text = params.get('text', '') clear_first = params.get('clear_first', True) if clear_first: pyautogui.hotkey('ctrl', 'a') await asyncio.sleep(0.1) pyautogui.write(text) return {'input_text': text, 'length': len(text)} async def _action_wait(self, params: Dict[str, Any]) -> Dict[str, Any]: """等待动作""" duration = params.get('duration', 1) await asyncio.sleep(duration) return {'waited_duration': duration} async def _action_screenshot(self, params: Dict[str, Any]) -> Dict[str, Any]: """截图动作""" save_path = params.get('save_path') screenshot = pyautogui.screenshot() if save_path: screenshot.save(save_path) return { 'screenshot_size': screenshot.size, 'save_path': save_path } async def _action_condition(self, params: Dict[str, Any]) -> Dict[str, Any]: """条件判断动作""" condition = params.get('condition') true_value = params.get('true_value') false_value = params.get('false_value') result = eval(condition) if condition else False return { 'condition_result': result, 'return_value': true_value if result else false_value }
|