ZHZisZZ commited on
Commit
9c2c8f3
·
0 Parent(s):

init save

Browse files
.gitignore ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .idea
11
+ .Python
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ applications/DeepSpeed-Chat/data
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ pip-wheel-metadata/
26
+ share/python-wheels/
27
+ *.egg-info/
28
+ .installed.cfg
29
+ *.egg
30
+ MANIFEST
31
+
32
+ # PyInstaller
33
+ # Usually these files are written by a python script from a template
34
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
35
+ *.manifest
36
+ *.spec
37
+
38
+ # Installer logs
39
+ pip-log.txt
40
+ pip-delete-this-directory.txt
41
+
42
+ # Unit test / coverage reports
43
+ htmlcov/
44
+ .tox/
45
+ .nox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ *.py,cover
53
+ .hypothesis/
54
+ .pytest_cache/
55
+
56
+ # Translations
57
+ *.mo
58
+ *.pot
59
+
60
+ # Django stuff:
61
+ *.log
62
+ local_settings.py
63
+ db.sqlite3
64
+ db.sqlite3-journal
65
+
66
+ # Flask stuff:
67
+ instance/
68
+ .webassets-cache
69
+
70
+ # Scrapy stuff:
71
+ .scrapy
72
+
73
+ # Sphinx documentation
74
+ docs/_build/
75
+
76
+ # PyBuilder
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ .python-version
88
+
89
+ # pipenv
90
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
91
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
92
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
93
+ # install all needed dependencies.
94
+ #Pipfile.lock
95
+
96
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
97
+ __pypackages__/
98
+
99
+ # Celery stuff
100
+ celerybeat-schedule
101
+ celerybeat.pid
102
+
103
+ # SageMath parsed files
104
+ *.sage.py
105
+
106
+ # Environments
107
+ .env
108
+ .venv
109
+ env/
110
+ venv/
111
+ ENV/
112
+ env.bak/
113
+ venv.bak/
114
+
115
+ # Spyder project settings
116
+ .spyderproject
117
+ .spyproject
118
+
119
+ # Rope project settings
120
+ .ropeproject
121
+
122
+ # mkdocs documentation
123
+ /site
124
+
125
+ # mypy
126
+ .mypy_cache/
127
+ .dmypy.json
128
+ dmypy.json
129
+
130
+ # Pyre type checker
131
+ .pyre/
132
+
133
+ # Others
134
+ /.vscode/
135
+ /wandb/
136
+ /.data/
137
+ /.models*/
138
+ /logs/
src/cua_data/messages_map/convert_to_glmv.py ADDED
File without changes
src/cua_data/messages_map/convert_to_qwenvl.py ADDED
File without changes
src/cua_data/messages_map/convert_to_uitars15_v1.py ADDED
File without changes
src/cua_data/messages_map/convert_to_uitars15_v2.py ADDED
File without changes
src/cua_data/preprocessing/opencua/README.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ```shell
3
+ huggingface-cli download xlangai/AgentNet --repo-type dataset --local-dir .data/huggingface/xlangai/AgentNet
4
+ ```
5
+
6
+ ```shell
7
+ # 1. Navigate to the directory
8
+ cd .data/huggingface/xlangai/AgentNet/{ubuntu_images,win_mac_images}
9
+
10
+ # 2. Merge split volumes into a single archive (images-full.zip)
11
+ zip -s 0 images.zip --out images-full.zip
12
+
13
+ # 3. Extract the merged archive
14
+ unzip images-full.zip -d ../{extracted_ubuntu_images,win_mac_images}
15
+
16
+ # 4. (Optional) Return to the parent directory
17
+ cd ..
18
+ ```
19
+
20
+ ```shell
21
+ # process 1/256 of the dataset
22
+ python src/cua_data/preprocessing/opencua/opencua.py \
23
+ --jsonl_path ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl" \
24
+ --extracted_images_dir ".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images" \
25
+ --output_path ".data/scalecua/ubuntu" \
26
+ --rank 0 --world_size 256 --overwrite
27
+ ```
src/cua_data/preprocessing/opencua/opencua.py ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert AgentNet JSONL trajectories into a HuggingFace dataset.
3
+
4
+ Each JSONL line is expected to be a single task record with at least:
5
+ - instruction: str
6
+ - traj: list[step]
7
+ - step.image: str (image filename)
8
+ - step.value.thought: str
9
+ - step.value.action: str
10
+ - step.value.code: str (pyautogui/computer action code)
11
+
12
+ Output dataset:
13
+ - images: list[PIL.Image.Image]
14
+ - messages: list[dict] in a multi-turn user/assistant format.
15
+
16
+ Error handling (strict):
17
+ 1) Raises if final action is not terminate.
18
+ 2) Raises if any referenced image file is missing/unreadable.
19
+ 3) Raises on any JSON/parsing/unexpected code formats.
20
+
21
+ Requires:
22
+ pip install datasets pillow tyro
23
+
24
+ Sharding (contiguous):
25
+ - If rank and world_size are specified (both not None), rank=0 processes the
26
+ first 1/world_size chunk of the dataset (by JSONL order), rank=1 the next
27
+ chunk, etc.
28
+ - Shards are saved to:
29
+ {output_path}/shard_{rank}of{world_size}
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import ast
35
+ import json
36
+ import shutil
37
+ from dataclasses import dataclass
38
+ from pathlib import Path
39
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
40
+
41
+ from PIL import Image as PILImage
42
+ import tqdm
43
+ import tyro
44
+
45
+
46
+ # -----------------------------
47
+ # Args
48
+ # -----------------------------
49
+
50
+ @dataclass
51
+ class ScriptArguments:
52
+ jsonl_path: str = ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl"
53
+ extracted_images_dir: str = ".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images"
54
+ output_path: str = ".data/scalecua/ubuntu"
55
+ rank: Optional[int] = None
56
+ world_size: Optional[int] = None
57
+ overwrite: bool = False
58
+
59
+
60
+ # -----------------------------
61
+ # Qwen3-VL tool call formatting
62
+ # -----------------------------
63
+
64
+ def _make_computer_use_tool_call(arguments: Dict[str, Any]) -> Dict[str, Any]:
65
+ """Wrap a computer_use tool call in Qwen3-VL tool_call structure."""
66
+ if "action" not in arguments:
67
+ raise ValueError(f"computer_use arguments must include 'action'. Got: {arguments}")
68
+ return {
69
+ "type": "function",
70
+ "function": {
71
+ "name": "computer_use",
72
+ "arguments": arguments,
73
+ },
74
+ }
75
+
76
+
77
+ # -----------------------------
78
+ # AgentNet code parsing
79
+ # -----------------------------
80
+
81
+ class AgentNetCodeParseError(RuntimeError):
82
+ pass
83
+
84
+
85
+ def _dotted_name(expr: ast.AST) -> str:
86
+ """Return dotted name for ast.Name / ast.Attribute chains, else empty string."""
87
+ if isinstance(expr, ast.Name):
88
+ return expr.id
89
+ if isinstance(expr, ast.Attribute):
90
+ base = _dotted_name(expr.value)
91
+ return f"{base}.{expr.attr}" if base else expr.attr
92
+ return ""
93
+
94
+
95
+ def _literal_eval(node: ast.AST) -> Any:
96
+ try:
97
+ return ast.literal_eval(node)
98
+ except Exception as e:
99
+ raise AgentNetCodeParseError(f"Failed literal_eval on node={ast.dump(node)}") from e
100
+
101
+
102
+ def _get_kw(call: ast.Call, name: str) -> Optional[ast.AST]:
103
+ for kw in call.keywords:
104
+ if kw.arg == name:
105
+ return kw.value
106
+ return None
107
+
108
+
109
+ def _extract_xy(call: ast.Call) -> Tuple[float, float]:
110
+ """Extract x,y from a pyautogui-like call.
111
+
112
+ Supports keyword x=, y= (preferred), or positional (x, y).
113
+ """
114
+ x_node = _get_kw(call, "x")
115
+ y_node = _get_kw(call, "y")
116
+
117
+ if x_node is None and len(call.args) >= 1:
118
+ x_node = call.args[0]
119
+ if y_node is None and len(call.args) >= 2:
120
+ y_node = call.args[1]
121
+
122
+ if x_node is None or y_node is None:
123
+ raise AgentNetCodeParseError(
124
+ f"Expected x and y arguments, got args={len(call.args)} keywords={[kw.arg for kw in call.keywords]}"
125
+ )
126
+
127
+ x = float(_literal_eval(x_node))
128
+ y = float(_literal_eval(y_node))
129
+ return x, y
130
+
131
+
132
+ def _norm01_to_0_1000(x: float, y: float) -> List[int]:
133
+ """Convert normalized [0,1] floats -> int [0,1000] with rounding."""
134
+ eps = 1e-6
135
+ if x < -eps or x > 1 + eps or y < -eps or y > 1 + eps:
136
+ raise AgentNetCodeParseError(f"Coordinates out of normalized range [0,1]: x={x}, y={y}")
137
+ xi = int(round(x * 1000))
138
+ yi = int(round(y * 1000))
139
+ xi = max(0, min(1000, xi))
140
+ yi = max(0, min(1000, yi))
141
+ return [xi, yi]
142
+
143
+
144
+ def agentnet_code_to_qwen_tool_calls(code: str) -> List[Dict[str, Any]]:
145
+ """Convert AgentNet pyautogui/computer code string into Qwen3-VL computer_use tool calls."""
146
+ if not isinstance(code, str) or not code.strip():
147
+ raise AgentNetCodeParseError(f"Expected non-empty code string. Got: {code!r}")
148
+
149
+ try:
150
+ module = ast.parse(code)
151
+ except Exception as e:
152
+ raise AgentNetCodeParseError(f"ast.parse failed for code:\n{code}") from e
153
+
154
+ tool_calls: List[Dict[str, Any]] = []
155
+
156
+ for stmt in module.body:
157
+ if not isinstance(stmt, ast.Expr) or not isinstance(stmt.value, ast.Call):
158
+ raise AgentNetCodeParseError(
159
+ f"Unsupported statement type: {type(stmt).__name__}. Only expression calls are supported.\ncode=\n{code}"
160
+ )
161
+
162
+ call: ast.Call = stmt.value
163
+ fname = _dotted_name(call.func)
164
+
165
+ # ---- Mouse clicks ----
166
+ if fname == "pyautogui.click":
167
+ x, y = _extract_xy(call)
168
+ tool_calls.append(
169
+ _make_computer_use_tool_call({"action": "left_click", "coordinate": _norm01_to_0_1000(x, y)})
170
+ )
171
+ continue
172
+
173
+ if fname == "pyautogui.rightClick":
174
+ x, y = _extract_xy(call)
175
+ tool_calls.append(
176
+ _make_computer_use_tool_call({"action": "right_click", "coordinate": _norm01_to_0_1000(x, y)})
177
+ )
178
+ continue
179
+
180
+ if fname == "pyautogui.middleClick":
181
+ x, y = _extract_xy(call)
182
+ tool_calls.append(
183
+ _make_computer_use_tool_call({"action": "middle_click", "coordinate": _norm01_to_0_1000(x, y)})
184
+ )
185
+ continue
186
+
187
+ if fname == "pyautogui.doubleClick":
188
+ x, y = _extract_xy(call)
189
+ tool_calls.append(
190
+ _make_computer_use_tool_call({"action": "double_click", "coordinate": _norm01_to_0_1000(x, y)})
191
+ )
192
+ continue
193
+
194
+ if fname in {"pyautogui.tripleClick", "computer.tripleClick"}:
195
+ x, y = _extract_xy(call)
196
+ tool_calls.append(
197
+ _make_computer_use_tool_call({"action": "double_click", "coordinate": _norm01_to_0_1000(x, y)})
198
+ )
199
+ continue
200
+
201
+ # ---- Mouse movement / drag ----
202
+ if fname == "pyautogui.moveTo":
203
+ x, y = _extract_xy(call)
204
+ tool_calls.append(
205
+ _make_computer_use_tool_call({"action": "mouse_move", "coordinate": _norm01_to_0_1000(x, y)})
206
+ )
207
+ continue
208
+
209
+ if fname == "pyautogui.dragTo":
210
+ btn_node = _get_kw(call, "button")
211
+ btn = "left" if btn_node is None else str(_literal_eval(btn_node))
212
+ if btn != "left":
213
+ raise AgentNetCodeParseError(
214
+ f"Only button='left' dragTo is supported. Got button={btn!r}.\ncode=\n{code}"
215
+ )
216
+ x, y = _extract_xy(call)
217
+ tool_calls.append(
218
+ _make_computer_use_tool_call({"action": "left_click_drag", "coordinate": _norm01_to_0_1000(x, y)})
219
+ )
220
+ continue
221
+
222
+ # ---- Scroll ----
223
+ if fname in {"pyautogui.scroll", "pyautogui.hscroll"}:
224
+ if len(call.args) < 1:
225
+ raise AgentNetCodeParseError(f"scroll/hscroll requires a pixels argument.\ncode=\n{code}")
226
+ pixels = int(_literal_eval(call.args[0]))
227
+ tool_calls.append(_make_computer_use_tool_call({"action": "scroll", "pixels": pixels}))
228
+ continue
229
+
230
+ # ---- Keyboard ----
231
+ if fname == "pyautogui.hotkey":
232
+ if len(call.args) != 1:
233
+ raise AgentNetCodeParseError(f"hotkey expected a single list argument.\ncode=\n{code}")
234
+ keys_val = _literal_eval(call.args[0])
235
+ if not isinstance(keys_val, (list, tuple)) or not keys_val:
236
+ raise AgentNetCodeParseError(f"hotkey arg must be a non-empty list/tuple. Got: {keys_val!r}")
237
+ keys = [str(k).lower() for k in keys_val]
238
+ tool_calls.append(_make_computer_use_tool_call({"action": "key", "keys": keys}))
239
+ continue
240
+
241
+ if fname == "pyautogui.press":
242
+ if len(call.args) != 1:
243
+ raise AgentNetCodeParseError(f"press expected a single key argument.\ncode=\n{code}")
244
+ key_val = _literal_eval(call.args[0])
245
+ if isinstance(key_val, (list, tuple)):
246
+ for k in key_val:
247
+ tool_calls.append(_make_computer_use_tool_call({"action": "key", "keys": [str(k).lower()]}))
248
+ else:
249
+ tool_calls.append(_make_computer_use_tool_call({"action": "key", "keys": [str(key_val).lower()]}))
250
+ continue
251
+
252
+ if fname in {"pyautogui.write", "pyautogui.typewrite"}:
253
+ msg_node = _get_kw(call, "message")
254
+ if msg_node is None and len(call.args) == 1:
255
+ msg_node = call.args[0]
256
+ if msg_node is None:
257
+ raise AgentNetCodeParseError(f"write/typewrite requires message argument.\ncode=\n{code}")
258
+ text = str(_literal_eval(msg_node))
259
+ tool_calls.append(_make_computer_use_tool_call({"action": "type", "text": text}))
260
+ continue
261
+
262
+ # ---- Wait / Terminate ----
263
+ if fname == "computer.wait":
264
+ if len(call.args) == 0 and len(call.keywords) == 0:
265
+ t = 1.0
266
+ elif len(call.args) == 1 and len(call.keywords) == 0:
267
+ t = float(_literal_eval(call.args[0]))
268
+ else:
269
+ raise AgentNetCodeParseError(f"Unsupported wait signature.\ncode=\n{code}")
270
+ tool_calls.append(_make_computer_use_tool_call({"action": "wait", "time": t}))
271
+ continue
272
+
273
+ if fname == "computer.terminate":
274
+ status_node = _get_kw(call, "status")
275
+ if status_node is None:
276
+ raise AgentNetCodeParseError(f"terminate requires status='success'|'failure'.\ncode=\n{code}")
277
+ status = str(_literal_eval(status_node))
278
+ if status not in {"success", "failure"}:
279
+ raise AgentNetCodeParseError(f"Unsupported terminate status={status!r}.\ncode=\n{code}")
280
+ tool_calls.append(_make_computer_use_tool_call({"action": "terminate", "status": status}))
281
+ continue
282
+
283
+ raise AgentNetCodeParseError(f"Unsupported function call: {fname!r}.\ncode=\n{code}")
284
+
285
+ return tool_calls
286
+
287
+
288
+ # -----------------------------
289
+ # Trajectory -> dataset example
290
+ # -----------------------------
291
+
292
+ def _load_image_or_raise(path: Path) -> PILImage.Image:
293
+ if not path.exists():
294
+ raise FileNotFoundError(f"Missing image file: {path}")
295
+ try:
296
+ with PILImage.open(path) as im:
297
+ return im.convert("RGB").copy()
298
+ except Exception as e:
299
+ raise RuntimeError(f"Failed to open image: {path}") from e
300
+
301
+
302
+ def record_to_example(record: Dict[str, Any], extracted_images_dir: Path) -> Dict[str, Any]:
303
+ """Convert one JSONL record into one dataset row with keys: images, messages."""
304
+ instruction = record.get("instruction")
305
+ if not isinstance(instruction, str) or not instruction.strip():
306
+ raise ValueError(f"Missing/invalid 'instruction' in record. Keys={list(record.keys())}")
307
+
308
+ traj = record.get("traj")
309
+ if not isinstance(traj, list) or len(traj) == 0:
310
+ raise ValueError(f"Missing/invalid 'traj' in record. task_id={record.get('task_id')}")
311
+
312
+ images: List[PILImage.Image] = []
313
+ for i, step in enumerate(traj):
314
+ img_name = step.get("image")
315
+ if not isinstance(img_name, str) or not img_name:
316
+ raise ValueError(
317
+ f"Missing/invalid step.image at traj[{i}]. task_id={record.get('task_id')} step={step}"
318
+ )
319
+ img_path = extracted_images_dir / img_name
320
+ images.append(_load_image_or_raise(img_path))
321
+
322
+ messages: List[Dict[str, Any]] = []
323
+
324
+ messages.append(
325
+ {
326
+ "role": "user",
327
+ "content": [
328
+ {"type": "image", "index": 0},
329
+ {"type": "text", "text": instruction},
330
+ ],
331
+ }
332
+ )
333
+
334
+ for i, step in enumerate(traj):
335
+ value = step.get("value")
336
+ if not isinstance(value, dict):
337
+ raise ValueError(f"Missing/invalid step.value at traj[{i}] task_id={record.get('task_id')}")
338
+
339
+ thought = value.get("thought")
340
+ action_text = value.get("action")
341
+ code = value.get("code")
342
+
343
+ if not isinstance(thought, str):
344
+ raise ValueError(f"Missing/invalid value.thought at traj[{i}] task_id={record.get('task_id')}")
345
+ if not isinstance(action_text, str):
346
+ raise ValueError(f"Missing/invalid value.action at traj[{i}] task_id={record.get('task_id')}")
347
+ if not isinstance(code, str):
348
+ raise ValueError(f"Missing/invalid value.code at traj[{i}] task_id={record.get('task_id')}")
349
+
350
+ tool_calls = agentnet_code_to_qwen_tool_calls(code)
351
+
352
+ messages.append(
353
+ {
354
+ "role": "assistant",
355
+ "reasoning_content": thought,
356
+ "content": [{"type": "text", "text": action_text}],
357
+ "tool_calls": tool_calls,
358
+ }
359
+ )
360
+
361
+ if i != len(traj) - 1:
362
+ messages.append(
363
+ {
364
+ "role": "user",
365
+ "content": [
366
+ {"type": "image", "index": i + 1},
367
+ ],
368
+ }
369
+ )
370
+
371
+ last_step_tool_calls = messages[-1].get("tool_calls")
372
+ if not isinstance(last_step_tool_calls, list) or len(last_step_tool_calls) == 0:
373
+ raise ValueError(f"Last assistant message has no tool_calls. task_id={record.get('task_id')}")
374
+
375
+ last_call = last_step_tool_calls[-1]
376
+ try:
377
+ last_action = last_call["function"]["arguments"]["action"]
378
+ except Exception:
379
+ raise ValueError(
380
+ f"Malformed tool_call structure in last step. task_id={record.get('task_id')} tool_call={last_call}"
381
+ )
382
+
383
+ if last_action != "terminate":
384
+ raise ValueError(
385
+ f"Final action is not terminate. task_id={record.get('task_id')} final_action={last_action!r}"
386
+ )
387
+
388
+ return {"images": images, "messages": messages}
389
+
390
+
391
+ def compute_shard_range(num_records: int, rank: int, world_size: int) -> Tuple[int, int]:
392
+ """Contiguous shard ranges.
393
+
394
+ Ensures:
395
+ - rank=0 gets the first chunk
396
+ - total coverage is exact (some ranks may get +1 if num_records % world_size != 0)
397
+ """
398
+ if world_size <= 0:
399
+ raise ValueError(f"Invalid world_size={world_size}")
400
+ if rank < 0 or rank >= world_size:
401
+ raise ValueError(f"Invalid rank={rank} for world_size={world_size}")
402
+
403
+ shard_size = num_records // world_size
404
+ remainder = num_records % world_size
405
+
406
+ start = rank * shard_size + min(rank, remainder)
407
+ end = start + shard_size + (1 if rank < remainder else 0)
408
+ return start, end
409
+
410
+
411
+ def _count_nonempty_lines(jsonl_path: Path) -> int:
412
+ n = 0
413
+ with jsonl_path.open("r", encoding="utf-8") as f:
414
+ for line in f:
415
+ if line.strip():
416
+ n += 1
417
+ return n
418
+
419
+
420
+ def iter_examples(
421
+ jsonl_path: Path,
422
+ extracted_images_dir: Path,
423
+ rank: Optional[int] = None,
424
+ world_size: Optional[int] = None,
425
+ ) -> Iterable[Dict[str, Any]]:
426
+ """Yield dataset rows from a JSONL file, optionally sharded contiguously by (rank, world_size)."""
427
+ if (rank is None) ^ (world_size is None):
428
+ raise ValueError("rank and world_size must be both specified or both None.")
429
+ if rank is not None:
430
+ if world_size is None:
431
+ raise ValueError("world_size must be provided if rank is provided.")
432
+ if world_size <= 0:
433
+ raise ValueError(f"Invalid world_size={world_size}")
434
+ if rank < 0 or rank >= world_size:
435
+ raise ValueError(f"Invalid rank={rank} for world_size={world_size}")
436
+
437
+ num_records = _count_nonempty_lines(jsonl_path)
438
+ if rank is not None:
439
+ start, end = compute_shard_range(num_records, rank, world_size) # [start, end)
440
+ else:
441
+ start, end = 0, num_records
442
+
443
+ record_idx = 0 # counts non-empty JSONL lines
444
+ with jsonl_path.open("r", encoding="utf-8") as f:
445
+ for line_no, line in tqdm.tqdm(enumerate(f, start=1)):
446
+ line = line.strip()
447
+ if not line:
448
+ continue
449
+
450
+ if record_idx < start:
451
+ record_idx += 1
452
+ continue
453
+ if record_idx >= end:
454
+ break
455
+
456
+ try:
457
+ record = json.loads(line)
458
+ except Exception as e:
459
+ raise ValueError(f"JSON parse error at line {line_no} (record_idx={record_idx}) in {jsonl_path}") from e
460
+
461
+ if not isinstance(record, dict):
462
+ raise ValueError(f"Expected JSON object at line {line_no} (record_idx={record_idx})")
463
+
464
+ yield record_to_example(record, extracted_images_dir=extracted_images_dir)
465
+ record_idx += 1
466
+
467
+
468
+ def build_features() -> Any:
469
+ """Define HuggingFace datasets Features for stable serialization."""
470
+ from datasets import Features, Image, Sequence, Value
471
+
472
+ return Features(
473
+ {
474
+ "images": Sequence(Image()),
475
+ "messages": Sequence(
476
+ {
477
+ "role": Value("string"),
478
+ "content": Sequence(
479
+ {
480
+ "type": Value("string"),
481
+ "text": Value("string"),
482
+ "index": Value("int64"),
483
+ }
484
+ ),
485
+ "reasoning_content": Value("string"),
486
+ "tool_calls": Sequence(
487
+ {
488
+ "type": Value("string"),
489
+ "function": {
490
+ "name": Value("string"),
491
+ "arguments": {
492
+ "action": Value("string"),
493
+ "keys": Sequence(Value("string")),
494
+ "text": Value("string"),
495
+ "coordinate": Sequence(Value("int64")),
496
+ "pixels": Value("int64"),
497
+ "time": Value("float32"),
498
+ "status": Value("string"),
499
+ },
500
+ },
501
+ }
502
+ ),
503
+ }
504
+ ),
505
+ }
506
+ )
507
+
508
+
509
+ def main() -> None:
510
+ args = tyro.cli(ScriptArguments)
511
+
512
+ jsonl_path = Path(args.jsonl_path)
513
+ extracted_images_dir = Path(args.extracted_images_dir)
514
+ output_path = Path(args.output_path)
515
+
516
+ if not jsonl_path.exists():
517
+ raise FileNotFoundError(f"jsonl_path not found: {jsonl_path}")
518
+ if not extracted_images_dir.exists():
519
+ raise FileNotFoundError(f"extracted_images_dir not found: {extracted_images_dir}")
520
+
521
+ # If sharded, save into a deterministic shard subdir so ranks don't clobber each other.
522
+ if args.rank is not None and args.world_size is not None:
523
+ output_path = output_path / f"shard-{args.rank:05d}-of-{args.world_size:05d}"
524
+
525
+ if output_path.exists():
526
+ if not args.overwrite:
527
+ raise FileExistsError(
528
+ f"output_path already exists: {output_path}. Use --overwrite to replace it."
529
+ )
530
+ shutil.rmtree(output_path)
531
+
532
+ from datasets import Dataset
533
+
534
+ features = build_features()
535
+
536
+ if hasattr(Dataset, "from_generator"):
537
+ ds = Dataset.from_generator(
538
+ iter_examples,
539
+ gen_kwargs={
540
+ "jsonl_path": jsonl_path,
541
+ "extracted_images_dir": extracted_images_dir,
542
+ "rank": args.rank,
543
+ "world_size": args.world_size,
544
+ },
545
+ )
546
+ else:
547
+ rows = list(
548
+ iter_examples(
549
+ jsonl_path=jsonl_path,
550
+ extracted_images_dir=extracted_images_dir,
551
+ rank=args.rank,
552
+ world_size=args.world_size,
553
+ )
554
+ )
555
+ ds = Dataset.from_list(rows)
556
+
557
+ ds.save_to_disk(str(output_path))
558
+ print(f"Saved dataset with {len(ds)} rows to: {output_path}")
559
+
560
+
561
+ if __name__ == "__main__":
562
+ main()
563
+
564
+
565
+
566
+
567
+ """
568
+ Attached file for GPT Pro
569
+ - `agentnet_ubuntu.jsonl` (first 100 lines from `agentnet_ubuntu_5k.jsonl`)
570
+
571
+ Prompt for GPT Pro:
572
+ # Task
573
+ Write a Python script that converts the trajectory specified in `jsonl_path`
574
+ (an example subset is provided in `agentnet_ubuntu.jsonl`) into a HuggingFace
575
+ dataset where each row has the following structure:
576
+
577
+ # Args
578
+ - jsonl_path (str = ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl"):
579
+ Path to the input JSONL file ((an example subset is provided in `agentnet_ubuntu.jsonl`)).
580
+ - extracted_images_dir (str = ".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images"):
581
+ Images are stored at `{extracted_images_dir}/{traj[i].image}`.
582
+ - output_path (str = ".data/scalecua/ubuntu"):
583
+ Path to save the resulting HuggingFace dataset.
584
+ - rank, world_size (int | None):
585
+ If specified, only process a subset of `jsonl_path`.
586
+
587
+ # Dataset row format
588
+ Each dataset row must contain exactly two keys: `images` and `messages`.
589
+
590
+ 1) images
591
+ ~~~~~~~~~
592
+ A list of PIL images loaded from the extracted image directory:
593
+
594
+ images = [
595
+ PIL(f"{extracted_images_dir}/{traj[0].image}"),
596
+ ...
597
+ PIL(f"{extracted_images_dir}/{traj[n].image}")
598
+ ]
599
+
600
+ 2) messages
601
+ ~~~~~~~~~~~
602
+ A multi-turn chat transcript that alternates user/assistant turns.
603
+ - The first user turn includes image index 0 AND the high-level instruction text.
604
+ - Each subsequent user turn includes ONLY the next image index.
605
+ - Each assistant turn includes:
606
+ - reasoning_content: traj[i].value.thought
607
+ - content: traj[i].value.action (as plain text)
608
+ - tool_calls: convert traj[i].value.code (pyauto action space) -> Qwen3-VL action space
609
+
610
+ messages = [
611
+ # Initial user instruction + first image
612
+ {
613
+ "role": "user",
614
+ "content": [
615
+ {"type": "image", "index": 0},
616
+ {"type": "text", "text": "{instruction}"},
617
+ ],
618
+ },
619
+
620
+ # Step 0 assistant response
621
+ {
622
+ "role": "assistant",
623
+ "reasoning_content": "{traj[0].value.thought}",
624
+ "content": [{"type": "text", "text": "{traj[0].value.action}"}],
625
+ # Convert raw `{traj[0].value.code}` (pyauto) -> Qwen3-VL action space
626
+ "tool_calls": [
627
+ {"type": "function", "function": {"name": "computer_use", "arguments": "..."}}
628
+ ],
629
+ },
630
+
631
+ # Step 1 user image
632
+ {
633
+ "role": "user",
634
+ "content": [
635
+ {"type": "image", "index": 1},
636
+ ],
637
+ },
638
+
639
+ # Step 1 assistant response
640
+ {
641
+ "role": "assistant",
642
+ "reasoning_content": "{traj[1].value.thought}",
643
+ "content": [{"type": "text", "text": "{traj[1].value.action}"}],
644
+ # Convert raw `{traj[1].value.code}` (pyauto) -> Qwen3-VL action space
645
+ "tool_calls": [
646
+ {"type": "function", "function": {"name": "computer_use", "arguments": "..."}}
647
+ ],
648
+ },
649
+
650
+ # ...
651
+ # Final step n
652
+ {
653
+ "role": "user",
654
+ "content": [
655
+ {"type": "image", "index": n},
656
+ ],
657
+ },
658
+ {
659
+ "role": "assistant",
660
+ "reasoning_content": "{traj[n].value.thought}",
661
+ "content": [{"type": "text", "text": "{traj[n].value.action}"}],
662
+ # Convert raw `{traj[n].value.code}` (pyauto) -> Qwen3-VL action space
663
+ "tool_calls": [
664
+ {"type": "function", "function": {"name": "computer_use", "arguments": "..."}}
665
+ ],
666
+ },
667
+ ]
668
+
669
+ # Qwen3-VL action space
670
+ description_prompt = "
671
+ * `key`: Performs key down presses on the arguments passed in order, then performs key releases in reverse order.
672
+ * `type`: Type a string of text on the keyboard.
673
+ * `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
674
+ * `left_click`: Click the left mouse button at a specified (x, y) pixel coordinate on the screen.
675
+ * `left_click_drag`: Click and drag the cursor to a specified (x, y) pixel coordinate on the screen.
676
+ * `right_click`: Click the right mouse button at a specified (x, y) pixel coordinate on the screen.
677
+ * `middle_click`: Click the middle mouse button at a specified (x, y) pixel coordinate on the screen.
678
+ * `double_click`: Double-click the left mouse button at a specified (x, y) pixel coordinate on the screen.
679
+ * `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).
680
+ * `scroll`: Performs a scroll of the mouse scroll wheel.
681
+ * `hscroll`: Performs a horizontal scroll (mapped to regular scroll).
682
+ * `wait`: Wait specified seconds for the change to happen.
683
+ * `terminate`: Terminate the current task and report its completion status.
684
+ * `answer`: Answer a question.
685
+ ** Note: all coordinates should be normalized to the range 0-1000."
686
+
687
+ tools_def = {
688
+ "type": "function",
689
+ "function": {
690
+ "name_for_human": "computer_use",
691
+ "name": "computer_use",
692
+ "description": description_prompt,
693
+ "parameters": {
694
+ "type": "object",
695
+ "required": ["action"],
696
+ "properties": {
697
+ "action": {
698
+ "type": "string",
699
+ "description": description_prompt,
700
+ "enum": [
701
+ "key",
702
+ "type",
703
+ "mouse_move",
704
+ "left_click",
705
+ "left_click_drag",
706
+ "right_click",
707
+ "middle_click",
708
+ "double_click",
709
+ "scroll",
710
+ "wait",
711
+ "terminate"
712
+ ]
713
+ },
714
+ "keys": {"type": "array", "description": "Required only by `action=key`."},
715
+ "text": {"type": "string", "description": "Required only by `action=type`."},
716
+ "coordinate": {"type": "array", "description": "The x,y coordinates for mouse actions."},
717
+ "pixels": {"type": "number", "description": "The amount of scrolling."},
718
+ "time": {"type": "number", "description": "The seconds to wait."},
719
+ "status": {
720
+ "type": "string",
721
+ "description": "The status of the task.",
722
+ "enum": ["success", "failure"]
723
+ }
724
+ }
725
+ },
726
+ "args_format": "Format the arguments as a JSON object."
727
+ }
728
+ }
729
+
730
+ # AgentNet → Qwen3-VL Action Mapping
731
+ This file documents how to convert AgentNet GUI actions (`traj[n].value.code`)
732
+ into Qwen3-VL `computer_use` tool calls.
733
+
734
+ Coordinates rule:
735
+ - AgentNet uses normalized floats `[0, 1]`
736
+ - Qwen3-VL uses integers `[0, 1000]`
737
+ - Convert with: `round(x * 1000), round(y * 1000)`
738
+
739
+ ---
740
+
741
+ ## (A) click → left_click
742
+ ```python
743
+ pyautogui.click(x=0.018, y=0.508)
744
+ ```
745
+ ```json
746
+ {
747
+ "tool_calls": [{
748
+ "type": "function",
749
+ "function": {
750
+ "name": "computer_use",
751
+ "arguments": {
752
+ "action": "left_click",
753
+ "coordinate": [18, 508]
754
+ }
755
+ }
756
+ }]
757
+ }
758
+ ```
759
+
760
+ ## (B) rightClick → right_click
761
+ ```python
762
+ pyautogui.rightClick(x=0.304, y=0.684)
763
+ ```
764
+ ```json
765
+ {
766
+ "tool_calls": [{
767
+ "type": "function",
768
+ "function": {
769
+ "name": "computer_use",
770
+ "arguments": {
771
+ "action": "right_click",
772
+ "coordinate": [304, 684]
773
+ }
774
+ }
775
+ }]
776
+ }
777
+ ```
778
+
779
+ ## (C) doubleClick → double_click
780
+ ```python
781
+ pyautogui.doubleClick(x=0.153, y=0.283)
782
+ ```
783
+ ```json
784
+ {
785
+ "tool_calls": [{
786
+ "type": "function",
787
+ "function": {
788
+ "name": "computer_use",
789
+ "arguments": {
790
+ "action": "double_click",
791
+ "coordinate": [153, 283]
792
+ }
793
+ }
794
+ }]
795
+ }
796
+ ```
797
+
798
+ ## (D) tripleClick → double_click (approx)
799
+ ```python
800
+ computer.tripleClick(x=0.226, y=0.311)
801
+ ```
802
+ ```json
803
+ {
804
+ "tool_calls": [{
805
+ "type": "function",
806
+ "function": {
807
+ "name": "computer_use",
808
+ "arguments": {
809
+ "action": "double_click",
810
+ "coordinate": [226, 311]
811
+ }
812
+ }
813
+ }]
814
+ }
815
+ ```
816
+
817
+ ## (E) moveTo → mouse_move
818
+ ```python
819
+ pyautogui.moveTo(x=0.394, y=0.604)
820
+ ```
821
+ ```json
822
+ {
823
+ "tool_calls": [{
824
+ "type": "function",
825
+ "function": {
826
+ "name": "computer_use",
827
+ "arguments": {
828
+ "action": "mouse_move",
829
+ "coordinate": [394, 604]
830
+ }
831
+ }
832
+ }]
833
+ }
834
+ ```
835
+
836
+ ## (F) moveTo + dragTo → mouse_move + left_click_drag
837
+ ```python
838
+ pyautogui.moveTo(x=0.078, y=0.381)
839
+ pyautogui.dragTo(x=0.085, y=0.361, button="left")
840
+ ```
841
+ ```json
842
+ {
843
+ "tool_calls": [
844
+ {
845
+ "type": "function",
846
+ "function": {
847
+ "name": "computer_use",
848
+ "arguments": {
849
+ "action": "mouse_move",
850
+ "coordinate": [78, 381]
851
+ }
852
+ }
853
+ },
854
+ {
855
+ "type": "function",
856
+ "function": {
857
+ "name": "computer_use",
858
+ "arguments": {
859
+ "action": "left_click_drag",
860
+ "coordinate": [85, 361]
861
+ }
862
+ }
863
+ }
864
+ ]
865
+ }
866
+ ```
867
+
868
+ ## (G) scroll → scroll
869
+ ```python
870
+ pyautogui.scroll(-8)
871
+ ```
872
+ ```json
873
+ {
874
+ "tool_calls": [{
875
+ "type": "function",
876
+ "function": {
877
+ "name": "computer_use",
878
+ "arguments": {
879
+ "action": "scroll",
880
+ "pixels": -8
881
+ }
882
+ }
883
+ }]
884
+ }
885
+ ```
886
+
887
+ ## (H) hotkey → key
888
+ ```python
889
+ pyautogui.hotkey(["ctrl", "o"])
890
+ ```
891
+ ```json
892
+ {
893
+ "tool_calls": [{
894
+ "type": "function",
895
+ "function": {
896
+ "name": "computer_use",
897
+ "arguments": {
898
+ "action": "key",
899
+ "keys": ["ctrl", "o"]
900
+ }
901
+ }
902
+ }]
903
+ }
904
+ ```
905
+
906
+ ## (I) press → key
907
+ ```python
908
+ pyautogui.press("enter")
909
+ ```
910
+ ```json
911
+ {
912
+ "tool_calls": [{
913
+ "type": "function",
914
+ "function": {
915
+ "name": "computer_use",
916
+ "arguments": {
917
+ "action": "key",
918
+ "keys": ["enter"]
919
+ }
920
+ }
921
+ }]
922
+ }
923
+ ```
924
+
925
+ ## (J) write → type
926
+ ```python
927
+ pyautogui.write(message="cd ./Pictures")
928
+ ```
929
+ ```json
930
+ {
931
+ "tool_calls": [{
932
+ "type": "function",
933
+ "function": {
934
+ "name": "computer_use",
935
+ "arguments": {
936
+ "action": "type",
937
+ "text": "cd ./Pictures"
938
+ }
939
+ }
940
+ }]
941
+ }
942
+ ```
943
+
944
+ ## (K) wait → wait
945
+ ```python
946
+ computer.wait()
947
+ ```
948
+ ```json
949
+ {
950
+ "tool_calls": [{
951
+ "type": "function",
952
+ "function": {
953
+ "name": "computer_use",
954
+ "arguments": {
955
+ "action": "wait",
956
+ "time": 1.0
957
+ }
958
+ }
959
+ }]
960
+ }
961
+ ```
962
+
963
+ ## (L) terminate → terminate
964
+ ```python
965
+ computer.terminate(status="success")
966
+ ```
967
+ ```json
968
+ {
969
+ "tool_calls": [{
970
+ "type": "function",
971
+ "function": {
972
+ "name": "computer_use",
973
+ "arguments": {
974
+ "action": "terminate",
975
+ "status": "success"
976
+ }
977
+ }
978
+ }]
979
+ }
980
+ ```
981
+
982
+ # Error Handling
983
+ The script must raise a breakpoint (or exception) if:
984
+ 1. The final action in the trajectory is not terminate.
985
+ 2. Image files missing
986
+ 3. Any other parsing errors or unexpected formats occur.
987
+ """
src/cua_train/sft.py ADDED
File without changes