-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun_single_step_drag_benchmark.py
More file actions
1651 lines (1412 loc) · 63 KB
/
run_single_step_drag_benchmark.py
File metadata and controls
1651 lines (1412 loc) · 63 KB
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Single-Step Drag Benchmark Runner - 简化版任务执行器
执行单步动作预测任务:获取观测 -> 模型预测 -> 执行动作
"""
import json
import os
import sys
import time
import base64
import logging
import argparse
import socket
import subprocess
import copy
import re
import io
from pathlib import Path
from typing import Dict, Any, Optional, List
from datetime import datetime
from dotenv import load_dotenv
import requests
from openai import OpenAI
from PIL import Image, ImageDraw
from io import BytesIO
BENCHMARK_DIR = Path(__file__).parent / "single_step_drag_benchmark"
if str(BENCHMARK_DIR) not in sys.path:
sys.path.insert(0, str(BENCHMARK_DIR))
from single_step_drag_benchmark.connection_utils import verify_connection
from single_step_drag_benchmark.coordinate_resize import resize_action_coordinates, get_resizer, Qwen3VLResizer, UITarsResizer
# ============================================================================
# 拖拽任务的启发式知识经验
# ============================================================================
DRAG_KNOWLEDGE = """
### Experience & Heuristics for Coordinate Prediction
Note: All pixel values (px) mentioned below are in a 1280x720 coordinate system. The provided screenshots also have this 1280x720 resolution.
1. Start Point
Target: The visible body of the Source Block (or the Top Block if moving a stack).
Heuristic: Set start_point near the Left Edge of the block (e.g., 10-20px from the left).
Note: Grabbing the Top Block prevents splitting the stack; grabbing the left side facilitates alignment.
2. End Point - Vertical Stacking (Command Blocks)
Context: Connecting single blocks or entire stacks vertically.
Appending (Bottom): (Same for single blocks & stacks)
Align X with Target's Left Edge. Set Y 15-20px below Target's Bottom Edge.
Prepending (Top): (Inserting above)
Align X with Target's Left Edge.
Height Adjustment: Set Y to Target_Top_Y - Source_Height.
Reasoning: Since the cursor holds the top of the source stack, you must lift it by its total height so its bottom connects with the target's top.
3. End Point - Nesting (Inside C-Blocks)
Context: Placing a block/stack inside container blocks like "Forever".
X: Indent 15-20px to the right of Target's Left Edge.
Y: Position 15-20px below the bottom edge of the C-block's "top arm" (inside the mouth).
4. End Point - Parameter Insertion (Values & Booleans)
Context: Dropping round (Reporter) or hexagonal (Boolean) blocks into input slots.
Target: The specific empty input slot (white oval or hexagon) on the Target Block.
Heuristic: Set end_point to the geometric center of that target input slot.
"""
SYSTEM_PROMPT_SCREENSHOT = """You are an AI assistant that controls the Scratch programming environment. Your task is: INSTRUCTION
You need to perform a drag-and-drop action to complete this task.
Output the action in the following format:
drag(start_point='<point>x1 y1</point>', end_point='<point>x2 y2</point>')
Where (x1 y1) is the starting position and (x2 y2) is the ending position.
Example:
drag(start_point='<point>100 200</point>', end_point='<point>300 400</point>')
"""
SYSTEM_PROMPT_WITH_ELEMENT_LIST = """You are an AI assistant that controls the Scratch programming environment. You have access to a list of elements on the webpage. Your task is: INSTRUCTION
You need to perform a drag-and-drop action to complete this task.
You can use either element indices or coordinates:
- Use <index>number</index> for element indices (based on the element list)
- Use <point>x y</point> for screen coordinates
Output formats:
drag(start_point='<index>0</index>', end_point='<index>5</index>')
drag(start_point='<point>100 200</point>', end_point='<point>300 400</point>')
drag(start_point='<index>0</index>', end_point='<point>300 400</point>')
Example:
drag(start_point='<index>1</index>', end_point='<index>3</index>')
"""
SET_WORKSPACE_STATE_JS = """
({ ws, payload }) => {
if (!ws) return { success: false, error: "Workspace not available" };
const canvas = ws.getCanvas();
if (!canvas) return { success: false, error: "Cannot get canvas" };
const bubbleCanvas = ws.getBubbleCanvas();
const has = Object.prototype.hasOwnProperty;
const scale = (payload && has.call(payload, 'scale')) ? (parseFloat(payload.scale) || 1) : (ws.scale || 1);
if (typeof ws.setScale === 'function') {
ws.setScale(scale);
} else {
ws.scale = scale;
}
const denom = scale || 1;
let scrollX;
let scrollY;
if (payload && has.call(payload, 'scrollX')) {
scrollX = parseFloat(payload.scrollX) || 0;
} else if (payload && has.call(payload, 'tx')) {
scrollX = -(parseFloat(payload.tx) || 0) / denom;
} else {
scrollX = 0;
}
if (payload && has.call(payload, 'scrollY')) {
scrollY = parseFloat(payload.scrollY) || 0;
} else if (payload && has.call(payload, 'ty')) {
scrollY = -(parseFloat(payload.ty) || 0) / denom;
} else {
scrollY = 0;
}
const tx = -scrollX * denom;
const ty = -scrollY * denom;
let applied = false;
if (ws.scrollbar && typeof ws.scrollbar.set === 'function') {
try {
ws.scrollbar.set(scrollX, scrollY);
applied = true;
} catch (e) {
applied = false;
}
}
if (!applied && typeof ws.translate === 'function') {
ws.scrollX = scrollX;
ws.scrollY = scrollY;
ws.translate(-scrollX, -scrollY);
if (typeof ws.resizeContents === 'function') ws.resizeContents();
applied = true;
}
if (!applied && typeof ws.scroll === 'function') {
try {
const prevX = ws.scrollX || 0;
const prevY = ws.scrollY || 0;
ws.scroll(scrollX - prevX, scrollY - prevY);
ws.scrollX = scrollX;
ws.scrollY = scrollY;
applied = true;
} catch (e) {
applied = false;
}
}
const finalTransform = 'translate(' + tx + ',' + ty + ') scale(' + scale + ')';
canvas.setAttribute('transform', finalTransform);
if (bubbleCanvas) {
bubbleCanvas.setAttribute('transform', finalTransform);
}
ws.scrollX = scrollX;
ws.scrollY = scrollY;
return {
success: true,
transform: finalTransform,
tx,
ty,
scale,
scrollX: ws.scrollX,
scrollY: ws.scrollY
};
}
"""
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
# 任务目录和API目录
TASKS_DIR = BENCHMARK_DIR / "tasks"
API_DIR = Path(__file__).parent / "scratch-bench-api"
BACKEND_LOG_PATH = BENCHMARK_DIR / "run_single_step_drag_benchmark_backend.log"
# 预先动作的执行顺序
ACTION_ORDER_KEYS = [
"switch_sprite_actions",
"locate_target_actions"
]
# 低级动作列表
LOW_LEVEL_ACTIONS = {
"click",
"double_click",
"move_to",
"drag_and_drop",
"scroll",
"type",
"key",
"hold_key",
"release_key",
"hotkey",
}
# ============================================================================
# API 服务器启动和停止函数
# ============================================================================
def find_free_port():
"""找一个空闲的端口"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("", 0))
return s.getsockname()[1]
def wait_for_api(url, timeout=30):
"""等待API服务器启动"""
start_time = time.time()
while time.time() - start_time < timeout:
try:
requests.get(f"{url}/", timeout=2)
return True
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
time.sleep(0.5)
continue
raise TimeoutError(f"API server did not start at {url}")
def start_api_server(port, log_path):
"""启动Scratch后端API服务器"""
env = os.environ.copy()
env["SESSION_TTL_SECONDS"] = "3600"
cmd = [
sys.executable,
"-m",
"uvicorn",
"api.main:app",
"--host",
"127.0.0.1",
"--port",
str(port),
"--log-level",
"warning",
"--no-access-log",
]
log_file = open(log_path, "a", encoding="utf-8")
process = subprocess.Popen(
cmd,
cwd=str(API_DIR),
env=env,
stdout=log_file,
stderr=log_file,
)
return process, log_file
def stop_api_server(process, log_file):
"""停止API服务器"""
if process:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
if log_file:
log_file.close()
class SingleStepDragBenchmarkRunner:
"""单步拖拽基准执行器"""
def __init__(
self,
model_name: str,
use_element_list: bool = True,
api_url: str = "http://localhost:8081",
ground_truth_start: bool = False,
use_knowledge: bool = False,
):
"""
初始化任务执行器
Args:
model_name: LLM模型名称
use_element_list: 是否在prompt中使用element list
api_url: Scratch后端API地址
ground_truth_start: 是否在prompt中提供可行起点
use_knowledge: 是否在prompt中添加启发式知识经验
"""
self.model_name = model_name
self.api_url = api_url
self.session_id: Optional[str] = None
self.use_element_list = use_element_list
self.ground_truth_start = ground_truth_start
self.use_knowledge = use_knowledge
self._current_elements: list = [] # 存储当前观测的元素列表,用于索引解析
# 创建结果目录
safe_model_name = model_name.replace('/', '_').replace('\\', '_').replace('-', '_')
element_suffix = "_use_element_list" if use_element_list else ""
ground_truth_suffix = "_ground_truth_start" if ground_truth_start else ""
knowledge_suffix = "_knowledge" if use_knowledge else ""
self.result_dir = Path(
f"result_single_step_drag_benchmark_{safe_model_name}{element_suffix}{ground_truth_suffix}{knowledge_suffix}"
)
self.result_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"结果目录: {self.result_dir}")
logger.info(f"使用Element List: {use_element_list}")
# 初始化OpenAI客户端
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
base_url = os.environ.get("LLM_BASE_URL", "https://api.openai.com/v1")
self.client = OpenAI(api_key=api_key, base_url=base_url)
logger.info(f"使用模型: {model_name}")
logger.info(f"API地址: {base_url}")
def load_tasks_from_directory(self, task_id: Optional[str] = None) -> List[Dict[str, Any]]:
"""从 single_step_drag_benchmark/tasks/ 目录加载任务(可选单任务)"""
tasks = []
if not TASKS_DIR.exists():
logger.error(f"任务目录不存在: {TASKS_DIR}")
return tasks
if task_id:
task_name = task_id if task_id.endswith(".json") else f"{task_id}.json"
task_path = TASKS_DIR / task_name
if not task_path.exists():
logger.error(f"任务文件不存在: {task_path}")
return tasks
task_files = [task_path]
else:
task_files = sorted(TASKS_DIR.glob("*.json"))
logger.info(f"找到 {len(task_files)} 个任务文件")
for task_file in task_files:
try:
with open(task_file, 'r', encoding='utf-8') as f:
task_data = json.load(f)
tasks.append(task_data)
logger.info(f"加载任务: {task_file.name} - {task_data.get('id')}")
except Exception as e:
logger.error(f"加载任务文件失败 {task_file}: {e}")
return tasks
def build_action_plan(self, eval_config: Dict[str, Any]) -> List[tuple]:
"""从 evaluation_config 构建预先动作计划"""
plan = []
for key in ACTION_ORDER_KEYS:
actions = eval_config.get(key)
if actions:
plan.append((key, actions))
return plan
def execute_single_action(self, action: Dict[str, Any]) -> bool:
"""执行单个动作"""
api = action.get("api")
args = action.get("args", {})
if not api:
logger.warning("动作缺少 api 字段")
return False
try:
if api in LOW_LEVEL_ACTIONS:
# 低级动作直接调用
# 对于拖拽动作,设置duration为0.5
if api == "drag_and_drop":
args["duration"] = 0.5
url = self._url(f"/{api}")
resp = requests.post(url, json=args, timeout=10)
else:
# 封装动作调用 encapsulated/execute
url = self._url("/composite/execute")
payload = {"api": api, "args": args}
resp = requests.post(url, json=payload, timeout=10)
if resp.status_code == 200:
return True
else:
logger.warning(f"动作执行返回非200状态: {resp.status_code}")
return False
except Exception as e:
logger.error(f"执行动作异常 {api}: {e}")
return False
def execute_actions(self, actions: List[Dict[str, Any]]) -> bool:
"""执行一组动作"""
if not actions:
return True
success = True
for action in actions:
if not self.execute_single_action(action):
success = False
logger.warning(f"动作执行失败: {action}")
time.sleep(0.1) # 动作间短暂等待
return success
def execute_pre_actions(self, eval_config: Dict[str, Any]) -> bool:
"""执行任务中定义的预先动作"""
action_plan = self.build_action_plan(eval_config)
if not action_plan:
logger.info("没有预先动作需要执行")
return True
logger.info("开始执行预先动作...")
success = True
for key, actions in action_plan:
logger.info(f"执行 {key} ({len(actions)} 个动作)")
if not self.execute_actions(actions):
success = False
logger.warning(f"{key} 执行失败或部分失败")
if success:
logger.info("所有预先动作执行完成")
else:
logger.warning("部分预先动作执行失败")
return success
def _url(self, route: str) -> str:
"""构建API URL"""
if self.session_id:
return f"{self.api_url}/sessions/{self.session_id}{route}"
return f"{self.api_url}{route}"
def create_session(self) -> bool:
"""创建会话"""
try:
resp = requests.post(f"{self.api_url}/sessions", timeout=20)
if resp.status_code != 200:
logger.error(f"创建会话失败: {resp.status_code} {resp.text}")
return False
data = resp.json()
self.session_id = data.get("session_id") or data.get("id")
if not self.session_id:
logger.error("未返回session_id")
return False
logger.info(f"会话创建成功: {self.session_id}")
return True
except Exception as e:
logger.error(f"创建会话异常: {e}")
return False
def close_session(self) -> bool:
"""关闭会话"""
if not self.session_id:
return True
try:
resp = requests.delete(f"{self.api_url}/sessions/{self.session_id}", timeout=20)
if resp.status_code != 200:
logger.warning(f"关闭会话失败: {resp.status_code}")
else:
logger.info(f"会话已关闭: {self.session_id}")
return True
except Exception as e:
logger.error(f"关闭会话异常: {e}")
return False
def load_project(self, project_name: str) -> bool:
"""加载初始项目"""
try:
response = requests.post(
self._url("/load_project"),
params={"project_name": project_name},
timeout=30
)
if response.status_code != 200:
logger.error(f"加载项目失败: {response.text}")
return False
logger.info(f"项目加载成功: {project_name}")
return True
except Exception as e:
logger.error(f"加载项目异常: {e}")
return False
def toggle_stage(self) -> bool:
"""切换舞台大小"""
try:
response = requests.post(self._url("/toggle_stage"), timeout=10)
if response.status_code != 200:
logger.warning(f"切换舞台失败: {response.text}")
return False
logger.info("舞台已切换到小舞台")
return True
except Exception as e:
logger.warning(f"切换舞台异常: {e}")
return False
def set_workspace_state(self, state: Optional[Dict[str, Any]]) -> bool:
"""设置画布状态(平移/缩放/滚动)"""
if not state:
return True
try:
url = self._url("/composite/execute")
payload = {"api": "custom_js", "args": {"fn": SET_WORKSPACE_STATE_JS, "payload": state}}
resp = requests.post(url, json=payload, timeout=10)
if resp.status_code != 200:
logger.warning(f"设置画布状态失败: HTTP {resp.status_code}")
return False
resp_json = resp.json()
if not resp_json.get("success"):
error_info = resp_json.get("error") or resp_json.get("data", {}).get("error", "unknown error")
logger.warning(f"设置画布状态失败: {error_info}")
return False
return True
except Exception as e:
logger.warning(f"设置画布状态异常: {e}")
return False
def get_observation(self) -> Dict[str, Any]:
"""获取环境观测"""
try:
# 获取截图
screenshot_response = requests.get(
self._url("/screenshot"),
params={"format": "base64"},
timeout=30
)
screenshot_response.raise_for_status()
screenshot_data = screenshot_response.json()
result = {
"screenshot": screenshot_data["screenshot"],
"timestamp": time.time()
}
# 只在使用元素列表模式时才获取元素信息
if self.use_element_list:
# 获取元素列表
selectors = {
"stage": "[data-testid='stage']",
"canvas": ".blocklyMainBackground",
"inputs": "input",
"sprites": ".sprite-selector_sprite-wrapper_df7cJ",
"blocks": ".blocklyDraggable",
"flyout_buttons": ".blocklyFlyoutButton",
"category_menu_item": ".scratchCategoryMenuItem",
}
name_selector_pairs = [f"{name}::{sel}" for name, sel in selectors.items()]
selector_string = ",".join(name_selector_pairs)
batch_response = requests.get(
self._url("/elements_batch"),
params={"selectors": selector_string},
timeout=60
)
batch_response.raise_for_status()
batch_data = batch_response.json()
elements = batch_data.get("elements", [])
# 保存当前元素列表,用于索引解析
self._current_elements = elements if isinstance(elements, list) else []
formatted_elements = self._format_elements(elements)
result["elements"] = formatted_elements
return result
except Exception as e:
logger.error(f"获取观测失败: {e}")
return {"error": str(e)}
def _format_elements(self, elements: list) -> str:
"""格式化元素列表"""
if not elements:
return "No elements found"
lines = ["index type text position"]
for idx, element in enumerate(elements):
if not isinstance(element, dict):
continue
elem_type = element.get("type", "")
text = element.get("block_name") or element.get("text", "")
position = element.get("position") or element.get("bbox", "")
# 格式化位置信息
if isinstance(position, dict):
x = position.get("x", 0)
y = position.get("y", 0)
w = position.get("width", 0)
h = position.get("height", 0)
position_str = f"({x}, {y}) {w}x{h}"
else:
position_str = str(position)
lines.append(f"{idx} {elem_type} {text} {position_str}")
return "\n".join(lines)
def save_screenshot(self, base64_image: str, filename: str, task_dir: Path) -> str:
"""保存截图"""
try:
image_data = base64.b64decode(base64_image)
image = Image.open(BytesIO(image_data))
filepath = task_dir / filename
image.save(filepath)
logger.info(f"截图已保存: {filepath}")
return str(filepath)
except Exception as e:
logger.error(f"保存截图失败: {e}")
return ""
def _mark_screenshot(self, base64_image: str, point: tuple, radius: int = 12, outline_width: int = 4) -> str:
"""在截图上标注红色圆圈,返回新的base64截图"""
try:
image_data = base64.b64decode(base64_image)
image = Image.open(BytesIO(image_data)).convert("RGBA")
draw = ImageDraw.Draw(image)
x, y = point
left = max(0, int(x - radius))
top = max(0, int(y - radius))
right = min(image.width - 1, int(x + radius))
bottom = min(image.height - 1, int(y + radius))
draw.ellipse([left, top, right, bottom], outline=(255, 0, 0, 255), width=outline_width)
buffer = BytesIO()
image.save(buffer, format="PNG")
return base64.b64encode(buffer.getvalue()).decode("utf-8")
except Exception as e:
logger.warning(f"标注截图失败: {e}")
return base64_image
def execute_action(self, action_plan: Dict[str, Any]) -> Dict[str, Any]:
"""执行动作"""
try:
api_type = action_plan.get("api")
args = action_plan.get("args", {})
# 如果使用了 element list,需要将索引解析为坐标
if self.use_element_list:
resolved_args = self._resolve_index_args(args)
if "error" in resolved_args:
return resolved_args
args = resolved_args
# 构建请求
response = requests.post(
self._url(f"/{api_type}"),
json=args,
timeout=30
)
if response.status_code != 200:
return {
"success": False,
"error": f"HTTP {response.status_code}: {response.text}"
}
result = response.json()
return result
except Exception as e:
logger.error(f"执行动作失败: {e}")
return {"success": False, "error": str(e)}
def _resolve_index_args(self, args: Dict[str, Any]) -> Dict[str, Any]:
"""
将索引参数解析为坐标参数
Args:
args: 可能包含索引的参数字典
Returns:
解析后的参数字典(索引转换为坐标)
"""
resolved_args = dict(args)
try:
# 处理 drag_and_drop 动作
if "start_index" in resolved_args:
start_index = resolved_args.pop("start_index")
if "start_x" not in resolved_args or "start_y" not in resolved_args:
start_x, start_y = self._get_element_center_by_index(start_index)
resolved_args["start_x"] = start_x
resolved_args["start_y"] = start_y
logger.info(f"解析 start_index {start_index} 为坐标 ({start_x}, {start_y})")
if "end_index" in resolved_args:
end_index = resolved_args.pop("end_index")
if "end_x" not in resolved_args or "end_y" not in resolved_args:
end_x, end_y = self._get_element_center_by_index(end_index)
resolved_args["end_x"] = end_x
resolved_args["end_y"] = end_y
logger.info(f"解析 end_index {end_index} 为坐标 ({end_x}, {end_y})")
return resolved_args
except ValueError as e:
logger.error(f"索引解析失败: {e}")
return {"error": f"Index resolution failed: {e}"}
def _get_element_center_by_index(self, index: int) -> tuple:
"""
根据元素索引获取其中心坐标
Args:
index: 元素索引(0-based)
Returns:
(center_x, center_y) 坐标元组
Raises:
ValueError: 如果索引无效或元素没有位置信息
"""
if not isinstance(self._current_elements, list):
raise ValueError("没有可用的元素列表用于索引解析")
if index < 0 or index >= len(self._current_elements):
raise ValueError(f"索引 {index} 超出范围 (0..{len(self._current_elements)-1})")
element = self._current_elements[index]
if not isinstance(element, dict):
raise ValueError(f"索引 {index} 处的元素结构无效")
# 获取位置信息
position_data = element.get("position") or element.get("bbox")
if not position_data:
raise ValueError(f"索引 {index} 处的元素没有位置信息")
try:
# 解析位置信息
if isinstance(position_data, dict):
x = int(position_data.get('x', 0))
y = int(position_data.get('y', 0))
width = int(position_data.get('width', 0))
height = int(position_data.get('height', 0))
elif isinstance(position_data, str):
# 支持字符串格式 "(x, y) widthxheight"
parts = position_data.split(') ')
if len(parts) != 2:
raise ValueError(f"无法解析位置格式: {position_data}")
coords_part = parts[0][1:] # 移除开头的 '('
x, y = map(int, coords_part.split(', '))
dimensions_part = parts[1]
width, height = map(int, dimensions_part.split('x'))
else:
raise ValueError(f"无效的位置数据类型: {type(position_data)}")
# 计算中心坐标
center_x = int(x + width / 2)
center_y = int(y + height / 2)
return center_x, center_y
except (ValueError, IndexError, KeyError) as e:
raise ValueError(f"无法解析索引 {index} 处的位置信息: {e}")
def export_project(self, task_id: int, task_dir: Path) -> Optional[str]:
"""导出项目文件到任务目录"""
output_filename = f"task_{task_id}_{int(time.time())}.sb3"
logger.info(f"导出项目: {output_filename}")
try:
response = requests.post(
self._url("/export_project"),
params={"output_name": output_filename},
timeout=30
)
if response.status_code == 200:
result = response.json()
data_b64 = result.get("data_base64")
filename = result.get("filename", output_filename)
size = result.get("size")
if not data_b64:
logger.error(f"项目导出响应缺少data_base64: {result}")
return None
# 解码并保存文件
raw = base64.b64decode(data_b64)
target_path = task_dir / filename
target_path.write_bytes(raw)
logger.info(f"项目文件已保存: {target_path} ({len(raw)} bytes)")
if size is not None and size != len(raw):
logger.warning(f"报告的大小 {size} != 写入的大小 {len(raw)}")
return filename
else:
logger.error(f"项目导出失败: {response.text}")
return None
except Exception as e:
logger.error(f"导出项目异常: {e}")
return None
def fetch_blocks_structure(self):
"""获取块结构"""
try:
url = self._url("/composite/execute")
payload = {"api": "get_blocks_structure", "args": {}}
resp = requests.post(url, json=payload, timeout=10)
if resp.status_code == 200:
return resp.json().get("data", {})
except Exception as e:
logger.error(f"获取块结构失败: {e}")
return {}
def evaluation(self, eval_config, pre_drag_ids=None):
"""验证拖拽是否成功"""
try:
# 获取块结构
structure_data = self.fetch_blocks_structure()
if not structure_data:
logger.error("无法获取块结构")
return False
id_to_block = structure_data.get("idToBlock", {})
if not id_to_block:
logger.error("块结构中没有idToBlock")
return False
# 获取必要信息
target_block_id = eval_config.get("target_block_id")
target_block_opcode = eval_config.get("target_block_opcode")
reference_block_id = eval_config.get("reference_block_id")
connection_type = eval_config.get("connection_type")
target_input_name = eval_config.get("target_input_name")
target_stack_tail_block_id = eval_config.get("target_stack_tail_block_id")
variable_name = eval_config.get("variable_name")
if not reference_block_id:
logger.error("缺少reference_block_id")
return False
if not connection_type:
logger.error("缺少connection_type")
return False
# 获取块信息
target_info = None
if not target_block_id and target_block_opcode and pre_drag_ids:
current_ids = set(id_to_block.keys())
new_ids = current_ids - set(pre_drag_ids)
opcode_matches = [
block_id
for block_id in new_ids
if id_to_block.get(block_id, {}).get("opcode") == target_block_opcode
]
if len(opcode_matches) == 1:
target_block_id = opcode_matches[0]
elif len(new_ids) == 1:
target_block_id = list(new_ids)[0]
else:
logger.warning(
f"flyout 目标块未唯一识别: opcode={target_block_opcode}, new_ids={len(new_ids)}"
)
if target_block_id:
target_info = id_to_block.get(target_block_id)
if not target_info:
logger.warning(f"目标块 {target_block_id} 未找到")
ref_info = id_to_block.get(reference_block_id)
if not ref_info:
logger.error(f"参考块 {reference_block_id} 未找到")
return False
# 验证连接
is_valid = verify_connection(
target_info,
ref_info,
connection_type,
id_to_block,
target_input_name=target_input_name,
target_stack_tail_block_id=target_stack_tail_block_id,
variable_name=variable_name,
)
logger.info(f"连接验证结果: {is_valid} (类型: {connection_type})")
return is_valid
except Exception as e:
logger.error(f"验证过程中发生异常: {e}")
return False
def call_llm(self, messages: list, task_dir: Path) -> Optional[Dict[str, Any]]:
"""调用LLM并记录"""
try:
# 调用LLM
if "gpt-5" in self.model_name.lower():
response = self.client.chat.completions.create(
model=self.model_name,
messages=messages,
reasoning_effort="low",
extra_body={
"allowed_openai_params": ["reasoning_effort"],
},
)
else:
response = self.client.chat.completions.create(
model=self.model_name,
messages=messages,
temperature=0.7,
top_p=0.9,
)
# 提取响应
assistant_message = response.choices[0].message
content = assistant_message.content
# 解析动作
action_plan = self._parse_action(content)
# 保存调用日志
call_log = {
"model": self.model_name,
"timestamp": datetime.now().isoformat(),
"messages": self._sanitize_messages_for_log(messages),
"response": {
"content": content,
"usage": {
"prompt_tokens": response.usage.prompt_tokens,
"completion_tokens": response.usage.completion_tokens,
"total_tokens": response.usage.total_tokens
}
},
"parsed_action": action_plan
}
log_file = task_dir / "call.log"
with open(log_file, 'w', encoding='utf-8') as f:
json.dump(call_log, f, indent=2, ensure_ascii=False)
logger.info(f"LLM调用日志已保存: {log_file}")
return action_plan
except Exception as e:
logger.error(f"LLM调用失败: {e}")
return None
def _sanitize_messages_for_log(self, messages: list) -> list:
"""清理消息中的base64图片数据"""
import copy
sanitized = copy.deepcopy(messages)
for msg in sanitized:
if "content" not in msg:
continue
content = msg["content"]
if not isinstance(content, list):
continue
for item in content:
if not isinstance(item, dict):
continue
if item.get("type") == "image_url":
if "image_url" in item and isinstance(item["image_url"], dict):
url = item["image_url"].get("url", "")
if url.startswith("data:image"):
item["image_url"]["url"] = "<base64_image_data_omitted>"
return sanitized
def _parse_action(self, content: str) -> Optional[Dict[str, Any]]:
"""从LLM响应中解析动作 - 支持多种格式"""
try:
import re
logger.info(f"原始响应内容: {content}")
# 格式1: UI-TARS 标准格式 drag(start_point='<point>x1 y1</point>', end_point='<point>x2 y2</point>')
# 同时支持逗号分隔 drag(start_point='<point>x1,y1</point>', end_point='<point>x2,y2</point>')
pattern1a = r"drag\s*\(\s*start_point\s*=\s*['\"]<point>(\d+)\s+?(\d+)</point>['\"]\s*,\s*end_point\s*=\s*['\"]<point>(\d+)\s+?(\d+)</point>['\"]\s*\)"
pattern1b = r"drag\s*\(\s*start_point\s*=\s*['\"]<point>(\d+)\s*,\s*(\d+)</point>['\"]\s*,\s*end_point\s*=\s*['\"]<point>(\d+)\s*,\s*(\d+)</point>['\"]\s*\)"
match1 = re.search(pattern1a, content)
if not match1:
match1 = re.search(pattern1b, content)
if match1:
x1, y1, x2, y2 = match1.groups()
action = {
'api': 'drag_and_drop',