ZHZisZZ commited on
Commit
dcdbd34
·
1 Parent(s): c32c04e

temp save

Browse files
pyproject.toml ADDED
File without changes
src/cua_lite/data/{raw_ds_preproc → preproc}/opencua/README.md RENAMED
@@ -5,13 +5,13 @@ huggingface-cli download xlangai/AgentNet --repo-type dataset --local-dir .data/
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 ..
@@ -19,15 +19,27 @@ cd ..
19
 
20
  ```shell
21
  # process 1/256 of the dataset
22
- python src/cua_lite/data/raw_ds_preproc/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
 
28
- python src/cua_lite/data/raw_ds_preproc/opencua/opencua_v2.py \
29
- --jsonl_path ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl" \
30
- --extracted_images_dir ".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images" \
31
- --output_path ".data/scalecua/ubuntu_v2" \
32
- --rank 0 --world_size 256 --overwrite
33
  ```
 
 
 
 
 
 
5
 
6
  ```shell
7
  # 1. Navigate to the directory
8
+ cd .data/huggingface/xlangai/AgentNet/ubuntu_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
15
 
16
  # 4. (Optional) Return to the parent directory
17
  cd ..
 
19
 
20
  ```shell
21
  # process 1/256 of the dataset
22
+ python src/cua_lite/data/preproc/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/tmp/scalecua/ubuntu" \
26
  --rank 0 --world_size 256 --overwrite
27
+ ```
28
+
29
+ ```shell
30
+ # unzip
31
+ python src/cua_lite/data/unzip.py \
32
+ --input_path ".data/tmp/scalecua/ubuntu/shard-00000-of-00256" \
33
+ --output_path ".data/unzipped/scalecua/ubuntu/shard-00000-of-00256" \
34
+ --overwrite
35
+ ```
36
+
37
+ ```shell
38
+ # convert to the format for infinite history
39
 
 
 
 
 
 
40
  ```
41
+
42
+ ```shell
43
+ # convert to the format that qwen3 requires
44
+
45
+ ```
src/cua_lite/data/{raw_ds_preproc → preproc}/opencua/opencua.py RENAMED
@@ -534,6 +534,7 @@ def main() -> None:
534
  features = build_features()
535
 
536
  if hasattr(Dataset, "from_generator"):
 
537
  ds = Dataset.from_generator(
538
  iter_examples,
539
  gen_kwargs={
@@ -562,8 +563,6 @@ 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`)
 
534
  features = build_features()
535
 
536
  if hasattr(Dataset, "from_generator"):
537
+ breakpoint()
538
  ds = Dataset.from_generator(
539
  iter_examples,
540
  gen_kwargs={
 
563
  main()
564
 
565
 
 
 
566
  """
567
  Attached file for GPT Pro
568
  - `agentnet_ubuntu.jsonl` (first 100 lines from `agentnet_ubuntu_5k.jsonl`)
src/cua_lite/data/raw_ds_preproc/opencua/opencua_v2.py DELETED
@@ -1,560 +0,0 @@
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
- - messages: list[dict] in a multi-turn user/assistant format with interleaved images.
14
-
15
- Error handling (strict):
16
- 1) Raises if final action is not terminate.
17
- 2) Raises if any referenced image file is missing/unreadable.
18
- 3) Raises on any JSON/parsing/unexpected code formats.
19
-
20
- Requires:
21
- pip install datasets pillow tyro
22
-
23
- Sharding (contiguous):
24
- - If rank and world_size are specified (both not None), rank=0 processes the
25
- first 1/world_size chunk of the dataset (by JSONL order), rank=1 the next
26
- chunk, etc.
27
- - Shards are saved to:
28
- {output_path}/shard_{rank}of{world_size}
29
- """
30
-
31
- from __future__ import annotations
32
-
33
- import ast
34
- import json
35
- import shutil
36
- from dataclasses import dataclass
37
- from pathlib import Path
38
- from typing import Any, Dict, Iterable, List, Optional, Tuple
39
-
40
- from PIL import Image as PILImage
41
- import tqdm
42
- import tyro
43
-
44
-
45
- # -----------------------------
46
- # Args
47
- # -----------------------------
48
-
49
- @dataclass
50
- class ScriptArguments:
51
- jsonl_path: str = ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl"
52
- extracted_images_dir: str = ".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images"
53
- output_path: str = ".data/scalecua/ubuntu"
54
- rank: Optional[int] = None
55
- world_size: Optional[int] = None
56
- overwrite: bool = False
57
-
58
-
59
- # -----------------------------
60
- # Qwen3-VL tool call formatting
61
- # -----------------------------
62
-
63
- def _make_computer_use_tool_call(arguments: Dict[str, Any]) -> Dict[str, Any]:
64
- """Wrap a computer_use tool call in Qwen3-VL tool_call structure."""
65
- if "action" not in arguments:
66
- raise ValueError(f"computer_use arguments must include 'action'. Got: {arguments}")
67
- return {
68
- "type": "function",
69
- "function": {
70
- "name": "computer_use",
71
- "arguments": arguments,
72
- },
73
- }
74
-
75
-
76
- # -----------------------------
77
- # AgentNet code parsing
78
- # -----------------------------
79
-
80
- class AgentNetCodeParseError(RuntimeError):
81
- pass
82
-
83
-
84
- def _dotted_name(expr: ast.AST) -> str:
85
- """Return dotted name for ast.Name / ast.Attribute chains, else empty string."""
86
- if isinstance(expr, ast.Name):
87
- return expr.id
88
- if isinstance(expr, ast.Attribute):
89
- base = _dotted_name(expr.value)
90
- return f"{base}.{expr.attr}" if base else expr.attr
91
- return ""
92
-
93
-
94
- def _literal_eval(node: ast.AST) -> Any:
95
- try:
96
- return ast.literal_eval(node)
97
- except Exception as e:
98
- raise AgentNetCodeParseError(f"Failed literal_eval on node={ast.dump(node)}") from e
99
-
100
-
101
- def _get_kw(call: ast.Call, name: str) -> Optional[ast.AST]:
102
- for kw in call.keywords:
103
- if kw.arg == name:
104
- return kw.value
105
- return None
106
-
107
-
108
- def _extract_xy(call: ast.Call) -> Tuple[float, float]:
109
- """Extract x,y from a pyautogui-like call.
110
-
111
- Supports keyword x=, y= (preferred), or positional (x, y).
112
- """
113
- x_node = _get_kw(call, "x")
114
- y_node = _get_kw(call, "y")
115
-
116
- if x_node is None and len(call.args) >= 1:
117
- x_node = call.args[0]
118
- if y_node is None and len(call.args) >= 2:
119
- y_node = call.args[1]
120
-
121
- if x_node is None or y_node is None:
122
- raise AgentNetCodeParseError(
123
- f"Expected x and y arguments, got args={len(call.args)} keywords={[kw.arg for kw in call.keywords]}"
124
- )
125
-
126
- x = float(_literal_eval(x_node))
127
- y = float(_literal_eval(y_node))
128
- return x, y
129
-
130
-
131
- def _norm01_to_0_1000(x: float, y: float) -> List[int]:
132
- """Convert normalized [0,1] floats -> int [0,1000] with rounding."""
133
- eps = 1e-6
134
- if x < -eps or x > 1 + eps or y < -eps or y > 1 + eps:
135
- raise AgentNetCodeParseError(f"Coordinates out of normalized range [0,1]: x={x}, y={y}")
136
- xi = int(round(x * 1000))
137
- yi = int(round(y * 1000))
138
- xi = max(0, min(1000, xi))
139
- yi = max(0, min(1000, yi))
140
- return [xi, yi]
141
-
142
-
143
- def agentnet_code_to_qwen_tool_calls(code: str) -> List[Dict[str, Any]]:
144
- """Convert AgentNet pyautogui/computer code string into Qwen3-VL computer_use tool calls."""
145
- if not isinstance(code, str) or not code.strip():
146
- raise AgentNetCodeParseError(f"Expected non-empty code string. Got: {code!r}")
147
-
148
- try:
149
- module = ast.parse(code)
150
- except Exception as e:
151
- raise AgentNetCodeParseError(f"ast.parse failed for code:\n{code}") from e
152
-
153
- tool_calls: List[Dict[str, Any]] = []
154
-
155
- for stmt in module.body:
156
- if not isinstance(stmt, ast.Expr) or not isinstance(stmt.value, ast.Call):
157
- raise AgentNetCodeParseError(
158
- f"Unsupported statement type: {type(stmt).__name__}. Only expression calls are supported.\ncode=\n{code}"
159
- )
160
-
161
- call: ast.Call = stmt.value
162
- fname = _dotted_name(call.func)
163
-
164
- # ---- Mouse clicks ----
165
- if fname == "pyautogui.click":
166
- x, y = _extract_xy(call)
167
- tool_calls.append(
168
- _make_computer_use_tool_call({"action": "left_click", "coordinate": _norm01_to_0_1000(x, y)})
169
- )
170
- continue
171
-
172
- if fname == "pyautogui.rightClick":
173
- x, y = _extract_xy(call)
174
- tool_calls.append(
175
- _make_computer_use_tool_call({"action": "right_click", "coordinate": _norm01_to_0_1000(x, y)})
176
- )
177
- continue
178
-
179
- if fname == "pyautogui.middleClick":
180
- x, y = _extract_xy(call)
181
- tool_calls.append(
182
- _make_computer_use_tool_call({"action": "middle_click", "coordinate": _norm01_to_0_1000(x, y)})
183
- )
184
- continue
185
-
186
- if fname == "pyautogui.doubleClick":
187
- x, y = _extract_xy(call)
188
- tool_calls.append(
189
- _make_computer_use_tool_call({"action": "double_click", "coordinate": _norm01_to_0_1000(x, y)})
190
- )
191
- continue
192
-
193
- if fname in {"pyautogui.tripleClick", "computer.tripleClick"}:
194
- x, y = _extract_xy(call)
195
- tool_calls.append(
196
- _make_computer_use_tool_call({"action": "double_click", "coordinate": _norm01_to_0_1000(x, y)})
197
- )
198
- continue
199
-
200
- # ---- Mouse movement / drag ----
201
- if fname == "pyautogui.moveTo":
202
- x, y = _extract_xy(call)
203
- tool_calls.append(
204
- _make_computer_use_tool_call({"action": "mouse_move", "coordinate": _norm01_to_0_1000(x, y)})
205
- )
206
- continue
207
-
208
- if fname == "pyautogui.dragTo":
209
- btn_node = _get_kw(call, "button")
210
- btn = "left" if btn_node is None else str(_literal_eval(btn_node))
211
- if btn != "left":
212
- raise AgentNetCodeParseError(
213
- f"Only button='left' dragTo is supported. Got button={btn!r}.\ncode=\n{code}"
214
- )
215
- x, y = _extract_xy(call)
216
- tool_calls.append(
217
- _make_computer_use_tool_call({"action": "left_click_drag", "coordinate": _norm01_to_0_1000(x, y)})
218
- )
219
- continue
220
-
221
- # ---- Scroll ----
222
- if fname in {"pyautogui.scroll", "pyautogui.hscroll"}:
223
- if len(call.args) < 1:
224
- raise AgentNetCodeParseError(f"scroll/hscroll requires a pixels argument.\ncode=\n{code}")
225
- pixels = int(_literal_eval(call.args[0]))
226
- tool_calls.append(_make_computer_use_tool_call({"action": "scroll", "pixels": pixels}))
227
- continue
228
-
229
- # ---- Keyboard ----
230
- if fname == "pyautogui.hotkey":
231
- if len(call.args) != 1:
232
- raise AgentNetCodeParseError(f"hotkey expected a single list argument.\ncode=\n{code}")
233
- keys_val = _literal_eval(call.args[0])
234
- if not isinstance(keys_val, (list, tuple)) or not keys_val:
235
- raise AgentNetCodeParseError(f"hotkey arg must be a non-empty list/tuple. Got: {keys_val!r}")
236
- keys = [str(k).lower() for k in keys_val]
237
- tool_calls.append(_make_computer_use_tool_call({"action": "key", "keys": keys}))
238
- continue
239
-
240
- if fname == "pyautogui.press":
241
- if len(call.args) != 1:
242
- raise AgentNetCodeParseError(f"press expected a single key argument.\ncode=\n{code}")
243
- key_val = _literal_eval(call.args[0])
244
- if isinstance(key_val, (list, tuple)):
245
- for k in key_val:
246
- tool_calls.append(_make_computer_use_tool_call({"action": "key", "keys": [str(k).lower()]}))
247
- else:
248
- tool_calls.append(_make_computer_use_tool_call({"action": "key", "keys": [str(key_val).lower()]}))
249
- continue
250
-
251
- if fname in {"pyautogui.write", "pyautogui.typewrite"}:
252
- msg_node = _get_kw(call, "message")
253
- if msg_node is None and len(call.args) == 1:
254
- msg_node = call.args[0]
255
- if msg_node is None:
256
- raise AgentNetCodeParseError(f"write/typewrite requires message argument.\ncode=\n{code}")
257
- text = str(_literal_eval(msg_node))
258
- tool_calls.append(_make_computer_use_tool_call({"action": "type", "text": text}))
259
- continue
260
-
261
- # ---- Wait / Terminate ----
262
- if fname == "computer.wait":
263
- if len(call.args) == 0 and len(call.keywords) == 0:
264
- t = 1.0
265
- elif len(call.args) == 1 and len(call.keywords) == 0:
266
- t = float(_literal_eval(call.args[0]))
267
- else:
268
- raise AgentNetCodeParseError(f"Unsupported wait signature.\ncode=\n{code}")
269
- tool_calls.append(_make_computer_use_tool_call({"action": "wait", "time": t}))
270
- continue
271
-
272
- if fname == "computer.terminate":
273
- status_node = _get_kw(call, "status")
274
- if status_node is None:
275
- raise AgentNetCodeParseError(f"terminate requires status='success'|'failure'.\ncode=\n{code}")
276
- status = str(_literal_eval(status_node))
277
- if status not in {"success", "failure"}:
278
- raise AgentNetCodeParseError(f"Unsupported terminate status={status!r}.\ncode=\n{code}")
279
- tool_calls.append(_make_computer_use_tool_call({"action": "terminate", "status": status}))
280
- continue
281
-
282
- raise AgentNetCodeParseError(f"Unsupported function call: {fname!r}.\ncode=\n{code}")
283
-
284
- return tool_calls
285
-
286
-
287
- # -----------------------------
288
- # Trajectory -> dataset example
289
- # -----------------------------
290
-
291
- def _load_image_or_raise(path: Path) -> PILImage.Image:
292
- if not path.exists():
293
- raise FileNotFoundError(f"Missing image file: {path}")
294
- try:
295
- with PILImage.open(path) as im:
296
- return im.convert("RGB").copy()
297
- except Exception as e:
298
- raise RuntimeError(f"Failed to open image: {path}") from e
299
-
300
-
301
- def record_to_example(record: Dict[str, Any], extracted_images_dir: Path) -> Dict[str, Any]:
302
- """Convert one JSONL record into one dataset row with key: messages."""
303
- instruction = record.get("instruction")
304
- if not isinstance(instruction, str) or not instruction.strip():
305
- raise ValueError(f"Missing/invalid 'instruction' in record. Keys={list(record.keys())}")
306
-
307
- traj = record.get("traj")
308
- if not isinstance(traj, list) or len(traj) == 0:
309
- raise ValueError(f"Missing/invalid 'traj' in record. task_id={record.get('task_id')}")
310
-
311
- images: List[PILImage.Image] = []
312
- for i, step in enumerate(traj):
313
- img_name = step.get("image")
314
- if not isinstance(img_name, str) or not img_name:
315
- raise ValueError(
316
- f"Missing/invalid step.image at traj[{i}]. task_id={record.get('task_id')} step={step}"
317
- )
318
- img_path = extracted_images_dir / img_name
319
- images.append(_load_image_or_raise(img_path))
320
-
321
- messages: List[Dict[str, Any]] = []
322
-
323
- messages.append(
324
- {
325
- "role": "user",
326
- "content": [
327
- {"type": "image", "image": images[0]},
328
- {"type": "text", "text": instruction},
329
- ],
330
- }
331
- )
332
-
333
- for i, step in enumerate(traj):
334
- value = step.get("value")
335
- if not isinstance(value, dict):
336
- raise ValueError(f"Missing/invalid step.value at traj[{i}] task_id={record.get('task_id')}")
337
-
338
- thought = value.get("thought")
339
- action_text = value.get("action")
340
- code = value.get("code")
341
-
342
- if not isinstance(thought, str):
343
- raise ValueError(f"Missing/invalid value.thought at traj[{i}] task_id={record.get('task_id')}")
344
- if not isinstance(action_text, str):
345
- raise ValueError(f"Missing/invalid value.action at traj[{i}] task_id={record.get('task_id')}")
346
- if not isinstance(code, str):
347
- raise ValueError(f"Missing/invalid value.code at traj[{i}] task_id={record.get('task_id')}")
348
-
349
- tool_calls = agentnet_code_to_qwen_tool_calls(code)
350
-
351
- messages.append(
352
- {
353
- "role": "assistant",
354
- "reasoning_content": thought,
355
- "content": [{"type": "text", "text": action_text}],
356
- "tool_calls": tool_calls,
357
- }
358
- )
359
-
360
- if i != len(traj) - 1:
361
- messages.append(
362
- {
363
- "role": "user",
364
- "content": [
365
- {"type": "image", "image": images[i + 1]},
366
- ],
367
- }
368
- )
369
-
370
- last_step_tool_calls = messages[-1].get("tool_calls")
371
- if not isinstance(last_step_tool_calls, list) or len(last_step_tool_calls) == 0:
372
- raise ValueError(f"Last assistant message has no tool_calls. task_id={record.get('task_id')}")
373
-
374
- last_call = last_step_tool_calls[-1]
375
- try:
376
- last_action = last_call["function"]["arguments"]["action"]
377
- except Exception:
378
- raise ValueError(
379
- f"Malformed tool_call structure in last step. task_id={record.get('task_id')} tool_call={last_call}"
380
- )
381
-
382
- if last_action != "terminate":
383
- raise ValueError(
384
- f"Final action is not terminate. task_id={record.get('task_id')} final_action={last_action!r}"
385
- )
386
-
387
- return {"messages": messages}
388
-
389
-
390
- def compute_shard_range(num_records: int, rank: int, world_size: int) -> Tuple[int, int]:
391
- """Contiguous shard ranges.
392
-
393
- Ensures:
394
- - rank=0 gets the first chunk
395
- - total coverage is exact (some ranks may get +1 if num_records % world_size != 0)
396
- """
397
- if world_size <= 0:
398
- raise ValueError(f"Invalid world_size={world_size}")
399
- if rank < 0 or rank >= world_size:
400
- raise ValueError(f"Invalid rank={rank} for world_size={world_size}")
401
-
402
- shard_size = num_records // world_size
403
- remainder = num_records % world_size
404
-
405
- start = rank * shard_size + min(rank, remainder)
406
- end = start + shard_size + (1 if rank < remainder else 0)
407
- return start, end
408
-
409
-
410
- def _count_nonempty_lines(jsonl_path: Path) -> int:
411
- n = 0
412
- with jsonl_path.open("r", encoding="utf-8") as f:
413
- for line in f:
414
- if line.strip():
415
- n += 1
416
- return n
417
-
418
-
419
- def iter_examples(
420
- jsonl_path: Path,
421
- extracted_images_dir: Path,
422
- rank: Optional[int] = None,
423
- world_size: Optional[int] = None,
424
- ) -> Iterable[Dict[str, Any]]:
425
- """Yield dataset rows from a JSONL file, optionally sharded contiguously by (rank, world_size)."""
426
- if (rank is None) ^ (world_size is None):
427
- raise ValueError("rank and world_size must be both specified or both None.")
428
- if rank is not None:
429
- if world_size is None:
430
- raise ValueError("world_size must be provided if rank is provided.")
431
- if world_size <= 0:
432
- raise ValueError(f"Invalid world_size={world_size}")
433
- if rank < 0 or rank >= world_size:
434
- raise ValueError(f"Invalid rank={rank} for world_size={world_size}")
435
-
436
- num_records = _count_nonempty_lines(jsonl_path)
437
- if rank is not None:
438
- start, end = compute_shard_range(num_records, rank, world_size) # [start, end)
439
- else:
440
- start, end = 0, num_records
441
-
442
- record_idx = 0 # counts non-empty JSONL lines
443
- with jsonl_path.open("r", encoding="utf-8") as f:
444
- for line_no, line in tqdm.tqdm(enumerate(f, start=1)):
445
- line = line.strip()
446
- if not line:
447
- continue
448
-
449
- if record_idx < start:
450
- record_idx += 1
451
- continue
452
- if record_idx >= end:
453
- break
454
-
455
- try:
456
- record = json.loads(line)
457
- except Exception as e:
458
- raise ValueError(f"JSON parse error at line {line_no} (record_idx={record_idx}) in {jsonl_path}") from e
459
-
460
- if not isinstance(record, dict):
461
- raise ValueError(f"Expected JSON object at line {line_no} (record_idx={record_idx})")
462
-
463
- yield record_to_example(record, extracted_images_dir=extracted_images_dir)
464
- record_idx += 1
465
-
466
-
467
- def build_features() -> Any:
468
- """Define HuggingFace datasets Features for stable serialization."""
469
- from datasets import Features, Image, Sequence, Value
470
-
471
- return Features(
472
- {
473
- "messages": Sequence(
474
- {
475
- "role": Value("string"),
476
- "content": Sequence(
477
- {
478
- "type": Value("string"),
479
- "text": Value("string"),
480
- "image": Image(),
481
- }
482
- ),
483
- "reasoning_content": Value("string"),
484
- "tool_calls": Sequence(
485
- {
486
- "type": Value("string"),
487
- "function": {
488
- "name": Value("string"),
489
- "arguments": {
490
- "action": Value("string"),
491
- "keys": Sequence(Value("string")),
492
- "text": Value("string"),
493
- "coordinate": Sequence(Value("int64")),
494
- "pixels": Value("int64"),
495
- "time": Value("float32"),
496
- "status": Value("string"),
497
- },
498
- },
499
- }
500
- ),
501
- }
502
- ),
503
- }
504
- )
505
-
506
-
507
- def main() -> None:
508
- args = tyro.cli(ScriptArguments)
509
-
510
- jsonl_path = Path(args.jsonl_path)
511
- extracted_images_dir = Path(args.extracted_images_dir)
512
- output_path = Path(args.output_path)
513
-
514
- if not jsonl_path.exists():
515
- raise FileNotFoundError(f"jsonl_path not found: {jsonl_path}")
516
- if not extracted_images_dir.exists():
517
- raise FileNotFoundError(f"extracted_images_dir not found: {extracted_images_dir}")
518
-
519
- # If sharded, save into a deterministic shard subdir so ranks don't clobber each other.
520
- if args.rank is not None and args.world_size is not None:
521
- output_path = output_path / f"shard-{args.rank:05d}-of-{args.world_size:05d}"
522
-
523
- if output_path.exists():
524
- if not args.overwrite:
525
- raise FileExistsError(
526
- f"output_path already exists: {output_path}. Use --overwrite to replace it."
527
- )
528
- shutil.rmtree(output_path)
529
-
530
- from datasets import Dataset
531
-
532
- features = build_features()
533
-
534
- if hasattr(Dataset, "from_generator"):
535
- ds = Dataset.from_generator(
536
- iter_examples,
537
- gen_kwargs={
538
- "jsonl_path": jsonl_path,
539
- "extracted_images_dir": extracted_images_dir,
540
- "rank": args.rank,
541
- "world_size": args.world_size,
542
- },
543
- )
544
- else:
545
- rows = list(
546
- iter_examples(
547
- jsonl_path=jsonl_path,
548
- extracted_images_dir=extracted_images_dir,
549
- rank=args.rank,
550
- world_size=args.world_size,
551
- )
552
- )
553
- ds = Dataset.from_list(rows)
554
-
555
- ds.save_to_disk(str(output_path))
556
- print(f"Saved dataset with {len(ds)} rows to: {output_path}")
557
-
558
-
559
- if __name__ == "__main__":
560
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/cua_lite/data/unzip.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ import tyro
9
+ from datasets import load_from_disk
10
+ from PIL import Image as PILImage
11
+
12
+ # -----------------------------
13
+ # Args
14
+ # -----------------------------
15
+
16
+ @dataclass
17
+ class ScriptArguments:
18
+ input_path: str = ".data/tmp/scalecua/ubuntu/shard-00000-of-00256"
19
+ output_path: str = ".data/unzipped/scalecua/ubuntu/shard-00000-of-00256"
20
+ overwrite: bool = False
21
+
22
+
23
+ # -----------------------------
24
+ # Dataset Transformation
25
+ # -----------------------------
26
+
27
+ def _save_image(image: PILImage.Image, row_dir: Path, img_idx: int) -> str:
28
+ """Save PIL image to the specific row directory and return the absolute posix path."""
29
+ filename = f"{img_idx:03d}.png"
30
+ file_path = row_dir / filename
31
+
32
+ image.save(file_path)
33
+
34
+ return str(file_path.resolve())
35
+
36
+
37
+ def process_row(
38
+ batch: Dict[str, Any],
39
+ indices: List[int],
40
+ output_data_dir: Path
41
+ ) -> Dict[str, Any]:
42
+ """
43
+ Process a batch of rows to:
44
+ 1. Create a subdirectory for the row (e.g., data/00000000/).
45
+ 2. Save images into that subdirectory.
46
+ 3. Update message content:
47
+ - Images: point to saved path, remove 'index'.
48
+ - Text: remove 'index' (e.g. {'index': None, ...} -> { ... }).
49
+ """
50
+ out_messages_batch = []
51
+
52
+ for batch_idx, (row_images, row_messages) in enumerate(zip(batch["images"], batch["messages"])):
53
+ global_idx = indices[batch_idx]
54
+
55
+ # 1. Prepare row-specific directory: output/data/00000000/
56
+ row_dir = output_data_dir / f"{global_idx:08d}"
57
+ row_dir.mkdir(parents=True, exist_ok=True)
58
+
59
+ # Cache saved paths for this row: map image_index -> absolute_path
60
+ saved_path_map: Dict[int, str] = {}
61
+
62
+ for img_idx, image in enumerate(row_images):
63
+ # 2. Save image into the row directory
64
+ abs_path = _save_image(image, row_dir, img_idx)
65
+ saved_path_map[img_idx] = abs_path
66
+
67
+ # 3. Rebuild messages
68
+ new_row_messages = []
69
+
70
+ for msg in row_messages:
71
+ new_content = []
72
+
73
+ raw_content = msg.get("content", [])
74
+ for item in raw_content:
75
+ item_type = item.get("type")
76
+
77
+ if item_type == "image":
78
+ # Handle Image: Transform structure and remove index implicitly
79
+ idx_val = item.get("index")
80
+ if idx_val is not None and idx_val in saved_path_map:
81
+ new_content.append({
82
+ "type": "image",
83
+ "image": saved_path_map[idx_val]
84
+ })
85
+ else:
86
+ raise ValueError(f"Image index {idx_val} not found in saved images for row {global_idx}")
87
+ else:
88
+ # Handle Text/Other: Copy item and explicitly remove 'index'
89
+ clean_item = item.copy()
90
+ clean_item.pop("index", None)
91
+ new_content.append(clean_item)
92
+
93
+ # Dynamic Copy: Preserve ALL original keys and only overwrite 'content'
94
+ new_msg = msg.copy()
95
+ new_msg["content"] = new_content
96
+
97
+ new_row_messages.append(new_msg)
98
+
99
+ out_messages_batch.append(new_row_messages)
100
+
101
+ return {"messages": out_messages_batch}
102
+
103
+
104
+ def main() -> None:
105
+ args = tyro.cli(ScriptArguments)
106
+
107
+ input_path = Path(args.input_path)
108
+ output_path = Path(args.output_path)
109
+ output_data_dir = output_path / "data"
110
+
111
+ if not input_path.exists():
112
+ raise FileNotFoundError(f"input_path does not exist: {input_path}")
113
+
114
+ if output_path.exists():
115
+ if args.overwrite:
116
+ shutil.rmtree(output_path)
117
+ else:
118
+ raise FileExistsError(f"output_path exists: {output_path}. Use --overwrite to replace.")
119
+
120
+ output_data_dir.mkdir(parents=True, exist_ok=True)
121
+
122
+ print(f"Loading dataset from: {input_path}")
123
+ ds = load_from_disk(str(input_path))
124
+
125
+ print(f"Processing {len(ds)} rows. Images will be saved to subdirectories in: {output_data_dir}")
126
+
127
+ updated_ds = ds.map(
128
+ process_row,
129
+ fn_kwargs={"output_data_dir": output_data_dir},
130
+ batched=True,
131
+ with_indices=True,
132
+ desc="Extracting images and rewriting messages"
133
+ )
134
+
135
+ if "images" in updated_ds.column_names:
136
+ updated_ds = updated_ds.remove_columns("images")
137
+
138
+ print(f"Saving modified dataset to: {output_path}")
139
+ updated_ds.save_to_disk(str(output_path))
140
+ print("Done.")
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()
145
+
146
+
147
+ """
148
+ # Args
149
+ - `input_path` (str, default=".data/tmp/scalecua/ubuntu/shard-00000-of-00256")
150
+ - `output_path` (str, default=".data/unzipped/scalecua/ubuntu/shard-00000-of-00256")
151
+
152
+ # Task
153
+ Write a Python script that loads the dataset from `input_path` and performs the following operations:
154
+
155
+ 1. **Save Images**: Extract images from the dataset and save them to `{output_path}/data`.
156
+ 2. **Transform Messages**: In the `messages` list, update the image entries to point to the saved files.
157
+ - **Change from**:
158
+ `{'index': 0, 'text': None, 'type': 'image'}`
159
+ - **To**:
160
+ `{'image': '/absolute/path/to/saved_image.png', 'type': 'image'}`
161
+ 3. **Cleanup**: Remove the `images` column from the dataset.
162
+ 4. **Save Dataset**: Save the modified dataset to `{output_path}`.
163
+
164
+ # Example of Dataset Row before converstion (`ds[0]`)
165
+ {
166
+ 'images': [
167
+ <PIL.PngImagePlugin.PngImageFile image mode=RGB size=1920x1080>,
168
+ <PIL.PngImagePlugin.PngImageFile image mode=RGB size=1920x1080>,
169
+ # ... more images
170
+ ],
171
+ 'messages': [
172
+ {
173
+ 'role': 'user',
174
+ 'content': [
175
+ {'index': 0, 'text': None, 'type': 'image'},
176
+ {'index': None, 'text': 'Open the Pikachu picture...', 'type': 'text'}
177
+ ]
178
+ },
179
+ {
180
+ 'role': 'assistant',
181
+ 'content': [{'index': None, 'text': 'Click on the GIMP...', 'type': 'text'}],
182
+ 'reasoning_content': 'I need to start working...',
183
+ 'tool_calls': [
184
+ {'function': {'name': 'computer_use', 'arguments': {'action': 'left_click', ...}}}
185
+ ]
186
+ },
187
+ # ... subsequent turns
188
+ ]
189
+ }
190
+
191
+ # Example of Dataset Row after converstion (`ds[0]`)
192
+ {
193
+ 'images': [
194
+ <PIL.PngImagePlugin.PngImageFile image mode=RGB size=1920x1080>,
195
+ <PIL.PngImagePlugin.PngImageFile image mode=RGB size=1920x1080>,
196
+ # ... more images
197
+ ],
198
+ 'messages': [
199
+ {
200
+ 'role': 'user',
201
+ 'content': [
202
+ {'text': None, 'type': 'image'},
203
+ {'text': 'Open the Pikachu picture...', 'type': 'text'}
204
+ ]
205
+ },
206
+ {
207
+ 'role': 'assistant',
208
+ 'content': [{'index': None, 'text': 'Click on the GIMP...', 'type': 'text'}],
209
+ 'reasoning_content': 'I need to start working...',
210
+ 'tool_calls': [
211
+ {'function': {'name': 'computer_use', 'arguments': {'action': 'left_click', ...}}}
212
+ ]
213
+ },
214
+ # ... subsequent turns
215
+ ]
216
+ }
217
+ """
src/cua_lite/data/utils.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 1. 定义清洗函数(递归移除 None)
2
+ def clean_nones(item):
3
+ """
4
+ 递归移除字典或列表中值为 None 的键。
5
+ """
6
+ if isinstance(item, dict):
7
+ return {
8
+ k: clean_nones(v)
9
+ for k, v in item.items()
10
+ if v is not None
11
+ }
12
+ elif isinstance(item, list):
13
+ return [clean_nones(i) for i in item]
14
+ else:
15
+ return item
16
+
17
+ # 2. 定义 Transform 函数(适配 Dataset 的 batch 格式)
18
+ def transform_batch(batch):
19
+ # batch 是一个字典,例如 {'messages': [ [...], [...] ]}
20
+ # 我们需要对里面的每一个样本进行清洗
21
+ return {k: [clean_nones(item) for item in v] for k, v in batch.items()}
src/cua_lite/utils/utils.py CHANGED
@@ -1,24 +0,0 @@
1
- def fill_images_into_messages(example: dict) -> dict:
2
- """
3
- Convert content items like:
4
- {'type':'image','index':k,'text':None}
5
- into:
6
- {'type':'image','image': example['images'][k]}
7
- (keeps other fields untouched)
8
- """
9
- images = example.get("images", [])
10
- messages = example.get("messages", [])
11
-
12
- for msg in messages:
13
- content = msg.get("content", [])
14
- for item in content:
15
- if item.get("type") == "image":
16
- idx = item.get("index", None)
17
- if idx is None:
18
- continue
19
- # replace in-place
20
- item.pop("index", None)
21
- item.pop("text", None)
22
- item["image"] = images[idx]
23
-
24
- return example["messages"]