ZHZisZZ commited on
Commit
762ba08
·
1 Parent(s): 6991897
cua_lite/data/interfaces/base.py CHANGED
@@ -1,5 +1,5 @@
1
  import dataclasses
2
- from typing import Callable, Any
3
 
4
  from cua_lite.data.utils import batch_proc
5
 
@@ -34,7 +34,7 @@ class BaseDataInterface:
34
  @dataclasses.dataclass
35
  class UnrolledContextDataInterface(BaseDataInterface):
36
 
37
- # useful for models support reasoning
38
 
39
  def process_context_batch(
40
  self, batch: dict[str, list[Any]]
 
1
  import dataclasses
2
+ from typing import Any
3
 
4
  from cua_lite.data.utils import batch_proc
5
 
 
34
  @dataclasses.dataclass
35
  class UnrolledContextDataInterface(BaseDataInterface):
36
 
37
+ """Useful for reasoning models"""
38
 
39
  def process_context_batch(
40
  self, batch: dict[str, list[Any]]
cua_lite/data/interfaces/qwen3_vl.py DELETED
@@ -1,256 +0,0 @@
1
- import dataclasses
2
- import json
3
- import copy
4
- from typing import Callable, Any
5
-
6
- from cua_lite.data.interfaces.base import UnrolledContextDataInterface
7
-
8
-
9
- DESCRIPTION_PROMPT = """Use a mouse and keyboard to interact with a computer, and take screenshots.
10
- * This is an interface to a desktop GUI. You do not have access to a terminal or applications menu. You must click on desktop icons to start applications.
11
- * Some applications may take time to start or process actions, so you may need to wait and take successive screenshots to see the results of your actions. For example, if you click on Firefox and a window does not open, try waiting and then taking another screenshot.
12
- * The screen resolution is 1000x1000.
13
- * Whenever you intend to move the cursor to click on an element such as an icon, consult a screenshot first to determine the element’s coordinates before moving the cursor.
14
- * If you tried clicking on a program or link but it failed to load even after waiting, adjust your cursor position so that the tip of the cursor visually falls on the element you want to click.
15
- * Make sure to click any buttons, links, icons, or other elements with the cursor tip in the center of the element. Do not click on edges unless explicitly instructed.\
16
- """
17
-
18
- ACTION_DESCRIPTION_PROMPT = """\
19
- * `key`: Performs key down presses on the arguments passed in order, then performs key releases in reverse order.
20
- * `type`: Type a string of text on the keyboard.
21
- * `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
22
- * `left_click`: Click the left mouse button at a specified (x, y) pixel coordinate on the screen.
23
- * `left_click_drag`: Click and drag the cursor to a specified (x, y) pixel coordinate on the screen.
24
- * `right_click`: Click the right mouse button at a specified (x, y) pixel coordinate on the screen.
25
- * `middle_click`: Click the middle mouse button at a specified (x, y) pixel coordinate on the screen.
26
- * `double_click`: Double-click the left mouse button at a specified (x, y) pixel coordinate on the screen.
27
- * `triple_click`: Triple-click the left mouse button at a specified (x, y) pixel coordinate on the screen (simulated as double-click since it's the closest action).
28
- * `scroll`: Performs a scroll of the mouse scroll wheel.
29
- * `hscroll`: Performs a horizontal scroll (mapped to regular scroll).
30
- * `wait`: Wait specified seconds for the change to happen.
31
- * `terminate`: Terminate the current task and report its completion status.
32
- * `answer`: Answer a question.\
33
- """
34
-
35
- TOOLS_DEF = {
36
- "type": "function",
37
- "function": {
38
- "name_for_human": "computer_use",
39
- "name": "computer_use",
40
- "description": DESCRIPTION_PROMPT,
41
- "parameters": {
42
- "properties": {
43
- "action": {
44
- "description": ACTION_DESCRIPTION_PROMPT,
45
- "enum": [
46
- "key",
47
- "type",
48
- "mouse_move",
49
- "left_click",
50
- "left_click_drag",
51
- "right_click",
52
- "middle_click",
53
- "double_click",
54
- "scroll",
55
- "wait",
56
- "terminate",
57
- ],
58
- "type": "string",
59
- },
60
- "keys": {
61
- "description": "Required only by `action=key`.",
62
- "type": "array",
63
- },
64
- "text": {
65
- "description": "Required only by `action=type`.",
66
- "type": "string",
67
- },
68
- "coordinate": {
69
- "description": "The x,y coordinates for mouse actions.",
70
- "type": "array",
71
- },
72
- "pixels": {"description": "The amount of scrolling.", "type": "number"},
73
- "time": {"description": "The seconds to wait.", "type": "number"},
74
- "status": {
75
- "description": "The status of the task.",
76
- "type": "string",
77
- "enum": ["success", "failure"],
78
- },
79
- },
80
- "required": ["action"],
81
- "type": "object",
82
- },
83
- "args_format": "Format the arguments as a JSON object.",
84
- },
85
- }
86
-
87
- SYSTEM_PROMPT = (
88
- """# Tools
89
-
90
- You may call one or more functions to assist with the user query.
91
-
92
- You are provided with function signatures within <tools></tools> XML tags:
93
- <tools>
94
- """
95
- + json.dumps(TOOLS_DEF)
96
- + """
97
- </tools>
98
-
99
- For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
100
- <tool_call>
101
- {"name": <function-name>, "arguments": <args-json-object>}
102
- </tool_call>
103
-
104
- # Response format
105
-
106
- Response format for every step:
107
- 1) Action: a short imperative describing what to do in the UI.
108
- 2) A single <tool_call>...</tool_call> block containing only the JSON: {"name": <function-name>, "arguments": <args-json-object>}.
109
-
110
- Rules:
111
- - Output exactly in the order: Action, <tool_call>.
112
- - Be brief: one sentence for Action.
113
- - Do not output anything else outside those parts.
114
- - If finishing, use action=terminate in the tool call."""
115
- )
116
-
117
-
118
- INSTRUCTION_PROMPT = """
119
- Please generate the next move according to the UI screenshot, instruction and previous actions.
120
-
121
- Instruction: {instruction}
122
-
123
- Previous actions:
124
- {previous_actions}"""
125
-
126
-
127
- @dataclasses.dataclass
128
- class Qwen3VLDataInterface(UnrolledContextDataInterface):
129
-
130
- history_n: int = 4
131
- add_system_prompt: bool = True
132
-
133
- def process_context(self, row: dict[str, Any]) -> dict[str, Any]:
134
- # 1. 基础拆分
135
- messages = row["messages"]
136
-
137
- # 2. 按 Step 分组 (User + Assistant)
138
- steps = []
139
- for i in range(0, len(messages), 2):
140
- step = {
141
- "user": messages[i],
142
- "assistant": messages[i + 1] if i + 1 < len(messages) else None,
143
- }
144
- steps.append(step)
145
-
146
- total_steps = len(steps)
147
-
148
- # 3. 计算保留逻辑
149
- steps_to_keep = self.history_n + 1
150
-
151
- # ======== FIX 1: 不要在这里 return ========
152
- # 如果总步数不够截断,就令 truncate_count=0(anchor=Step1),但仍然重写 INSTR_PROMPT
153
- truncate_count = max(0, total_steps - steps_to_keep)
154
- # =========================================
155
-
156
- # 4. 提取 Step 1 的指令
157
- step1_content = steps[0]["user"]["content"]
158
- instruction_text = next(
159
- item["text"] for item in step1_content if item.get("type") == "text"
160
- )
161
-
162
- # if "Previous actions" in instruction_text:
163
- # instruction_text = instruction_text.split("Previous actions")[0].strip()
164
-
165
- # # 规范成 “纯 instruction 内容”
166
- # if instruction_text.startswith("Instruction:"):
167
- # instruction_text = instruction_text[len("Instruction:"):].strip()
168
-
169
- # 5. 生成历史摘要(被截断掉的那些步)
170
- summary_lines = []
171
- for i in range(truncate_count):
172
- action = (
173
- steps[i]["assistant"]["content"]
174
- if isinstance(steps[i]["assistant"]["content"], str)
175
- else steps[i]["assistant"]["content"][0]["text"]
176
- )
177
- summary_lines.append(f"Step {i+1}: {action}")
178
-
179
- summary_block = "\n".join(summary_lines) if summary_lines else "None"
180
-
181
- # 生成与 QwenAgent 一致的 INSTR_PROMPT
182
- full_text_prompt = (
183
- "\nPlease generate the next move according to the UI screenshot, instruction and previous actions.\n\n"
184
- f"Instruction: {instruction_text}\n\n"
185
- "Previous actions:\n"
186
- f"{summary_block}"
187
- )
188
-
189
- # 6. 构建新消息列表
190
- processed_messages = []
191
- if self.add_system_prompt:
192
- processed_messages.append(
193
- {"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]}
194
- )
195
-
196
- # --- Anchor Step (新起点) ---
197
- anchor_step = steps[truncate_count]
198
- new_anchor_user = copy.deepcopy(anchor_step["user"])
199
-
200
- # 找到 User 消息里的 text 字段并修改,或者追加
201
- text_item = next(
202
- (item for item in new_anchor_user["content"] if item.get("type") == "text"),
203
- None,
204
- )
205
- if text_item:
206
- text_item["text"] = full_text_prompt
207
- else:
208
- new_anchor_user["content"].append(
209
- {"type": "text", "text": full_text_prompt}
210
- )
211
-
212
- processed_messages.append(new_anchor_user)
213
- if anchor_step["assistant"]:
214
- asst_msg = copy.deepcopy(anchor_step["assistant"])
215
- # Prepend "Action: " using a clean reference
216
- content_node = asst_msg["content"][0]
217
- content_node["text"] = "Action: " + content_node["text"]
218
- processed_messages.append(asst_msg)
219
-
220
- # --- 追加剩余步骤 ---
221
- for i in range(truncate_count + 1, total_steps):
222
- # ======== FIX 2: 对齐 QwenAgent:非 anchor 的 user 只保留 image 部分 ========
223
- u = copy.deepcopy(steps[i]["user"])
224
- if isinstance(u.get("content"), list):
225
- u["content"] = [it for it in u["content"] if it.get("type") != "text"]
226
- processed_messages.append(u)
227
- # ================================================================
228
- if steps[i]["assistant"]:
229
- asst_msg = copy.deepcopy(steps[i]["assistant"])
230
- # Prepend "Action: " using a clean reference
231
- content_node = asst_msg["content"][0]
232
- content_node["text"] = "Action: " + content_node["text"]
233
- processed_messages.append(asst_msg)
234
-
235
- return {"messages": processed_messages}
236
-
237
-
238
- if __name__ == "__main__":
239
- from datasets import load_from_disk
240
- from transformers import AutoProcessor
241
- from cua_lite.data.utils import clean_nones
242
-
243
- processor = AutoProcessor.from_pretrained(
244
- "/mnt/lustrenew/mllm_aligned/shared/models/huggingface/Qwen/Qwen3-VL-2B-Thinking"
245
- )
246
-
247
- dataset = load_from_disk(".data/unzipped/scalecua/ubuntu/shard-00000-of-00256")
248
- dataset.set_transform(clean_nones)
249
-
250
- qwen3vl_interface = Qwen3VLDataInterface(history_n=0)
251
- dataset_mapped = dataset.map(
252
- qwen3vl_interface.process_context_batch, batched=True, batch_size=1000
253
- )
254
-
255
- inputs = processor.apply_chat_template(dataset_mapped["messages"][1], return_dict=True)
256
- breakpoint()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cua_lite/data/interfaces/qwen3_vl/interfaces.py CHANGED
@@ -5,16 +5,17 @@ from typing import Callable, Any
5
 
6
  from cua_lite.data.interfaces.base import UnrolledContextDataInterface
7
  from cua_lite.data.interfaces.qwen3_vl.prompts import (
8
- INSTRUCTION_PROMPT, DESKTOP_SYSTEM_PROMPT_V0, DESKTOP_SYSTEM_PROMPT_V1, MOBILE_SYSTEM_PROMPT
 
 
 
9
  )
10
 
11
 
12
-
13
  @dataclasses.dataclass
14
  class Qwen3VLDataInterface(UnrolledContextDataInterface):
15
 
16
  history_n: int = 4
17
- add_system_prompt: bool = True
18
 
19
  def process_context(self, row: dict[str, Any]) -> dict[str, Any]:
20
  # 1. 基础拆分
@@ -142,5 +143,7 @@ if __name__ == "__main__":
142
  qwen3vl_interface.process_context_batch, batched=True, batch_size=1000
143
  )
144
 
145
- inputs = processor.apply_chat_template(dataset_mapped["messages"][1], return_dict=True)
 
 
146
  breakpoint()
 
5
 
6
  from cua_lite.data.interfaces.base import UnrolledContextDataInterface
7
  from cua_lite.data.interfaces.qwen3_vl.prompts import (
8
+ INSTRUCTION_PROMPT,
9
+ DESKTOP_SYSTEM_PROMPT_V0,
10
+ DESKTOP_SYSTEM_PROMPT_V1,
11
+ MOBILE_SYSTEM_PROMPT,
12
  )
13
 
14
 
 
15
  @dataclasses.dataclass
16
  class Qwen3VLDataInterface(UnrolledContextDataInterface):
17
 
18
  history_n: int = 4
 
19
 
20
  def process_context(self, row: dict[str, Any]) -> dict[str, Any]:
21
  # 1. 基础拆分
 
143
  qwen3vl_interface.process_context_batch, batched=True, batch_size=1000
144
  )
145
 
146
+ inputs = processor.apply_chat_template(
147
+ dataset_mapped["messages"][1], return_dict=True
148
+ )
149
  breakpoint()
cua_lite/data/interfaces/qwen3_vl/prompts/__init__.py CHANGED
@@ -1,8 +1,8 @@
1
  from .common import SYSTEM_PROMPT, INSTRUCTION_PROMPT
2
  from .desktop import (
3
  DESKTOP_SYSTEM_PROMPT_V0,
4
- DESKTOP_TOOLS_DEF_V0,
5
  DESKTOP_SYSTEM_PROMPT_V1,
6
- DESKTOP_TOOLS_DEF_V1,
 
7
  )
8
- from .mobile import MOBILE_SYSTEM_PROMPT, MOBILE_TOOLS_DEF
 
1
  from .common import SYSTEM_PROMPT, INSTRUCTION_PROMPT
2
  from .desktop import (
3
  DESKTOP_SYSTEM_PROMPT_V0,
 
4
  DESKTOP_SYSTEM_PROMPT_V1,
5
+ DESKTOP_TOOLS_DEFINITION_V0,
6
+ DESKTOP_TOOLS_DEFINITION_V1,
7
  )
8
+ from .mobile import MOBILE_SYSTEM_PROMPT, MOBILE_TOOLS_DEFINITION
cua_lite/data/interfaces/qwen3_vl/prompts/common.py CHANGED
@@ -6,7 +6,7 @@ You may call one or more functions to assist with the user query.
6
  You are provided with function signatures within <tools></tools> XML tags:
7
  <tools>
8
  """
9
- + "{tools_def}"
10
  + """
11
  </tools>
12
 
 
6
  You are provided with function signatures within <tools></tools> XML tags:
7
  <tools>
8
  """
9
+ + "{tools_definition}"
10
  + """
11
  </tools>
12
 
cua_lite/data/interfaces/qwen3_vl/prompts/desktop.py CHANGED
@@ -30,7 +30,7 @@ DESKTOP_ACTION_DESCRIPTION_PROMPT_V0 = """\
30
  * `answer`: Answer a question.\
31
  """
32
 
33
- DESKTOP_TOOLS_DEF_V0 = {
34
  "type": "function",
35
  "function": {
36
  "name_for_human": "desktop_use",
@@ -82,7 +82,7 @@ DESKTOP_TOOLS_DEF_V0 = {
82
  },
83
  }
84
 
85
- DESKTOP_SYSTEM_PROMPT_V0 = SYSTEM_PROMPT.format(tools_def=json.dumps(DESKTOP_TOOLS_DEF_V0))
86
 
87
 
88
  # v1
@@ -103,7 +103,7 @@ DESKTOP_ACTION_DESCRIPTION_PROMPT_V1 = """\
103
  * `answer(text="answer")`: Return a final answer in text.\
104
  """
105
 
106
- DESKTOP_TOOLS_DEF_V1 = {
107
  "type": "function",
108
  "function": {
109
  "name_for_human": "desktop_use",
@@ -168,4 +168,4 @@ DESKTOP_TOOLS_DEF_V1 = {
168
  },
169
  }
170
 
171
- DESKTOP_SYSTEM_PROMPT_V1 = SYSTEM_PROMPT.format(tools_def=json.dumps(DESKTOP_TOOLS_DEF_V1))
 
30
  * `answer`: Answer a question.\
31
  """
32
 
33
+ DESKTOP_TOOLS_DEFINITION_V0 = {
34
  "type": "function",
35
  "function": {
36
  "name_for_human": "desktop_use",
 
82
  },
83
  }
84
 
85
+ DESKTOP_SYSTEM_PROMPT_V0 = SYSTEM_PROMPT.format(tools_definition=json.dumps(DESKTOP_TOOLS_DEFINITION_V0))
86
 
87
 
88
  # v1
 
103
  * `answer(text="answer")`: Return a final answer in text.\
104
  """
105
 
106
+ DESKTOP_TOOLS_DEFINITION_V1 = {
107
  "type": "function",
108
  "function": {
109
  "name_for_human": "desktop_use",
 
168
  },
169
  }
170
 
171
+ DESKTOP_SYSTEM_PROMPT_V1 = SYSTEM_PROMPT.format(tools_definition=json.dumps(DESKTOP_TOOLS_DEFINITION_V1))
cua_lite/data/interfaces/qwen3_vl/prompts/mobile.py CHANGED
@@ -22,7 +22,7 @@ MOBILE_ACTION_DESCRIPTION_PROMPT = """\
22
  * `answer`: Answer a question.\
23
  """
24
 
25
- MOBILE_TOOLS_DEF = {
26
  "type": "function",
27
  "function": {
28
  "name_for_human": "mobile_use",
 
22
  * `answer`: Answer a question.\
23
  """
24
 
25
+ MOBILE_TOOLS_DEFINITION = {
26
  "type": "function",
27
  "function": {
28
  "name_for_human": "mobile_use",