ZHZisZZ commited on
Commit ·
1e86838
1
Parent(s): 1518c66
temp save
Browse files- src/cua_lite/data/interfaces/base.py +38 -108
- src/cua_lite/data/interfaces/qwen3_vl.py +246 -5
- src/cua_lite/data/preproc/README.md +82 -0
- src/cua_lite/data/preproc/opencua/README.md +43 -7
- src/cua_lite/data/preproc/opencua/opencua.py +125 -40
- src/cua_lite/data/unzip.py +38 -36
- src/cua_lite/data/utils.py +46 -11
src/cua_lite/data/interfaces/base.py
CHANGED
|
@@ -1,130 +1,60 @@
|
|
| 1 |
import dataclasses
|
| 2 |
-
import copy
|
| 3 |
from typing import Callable, Any
|
| 4 |
|
|
|
|
|
|
|
|
|
|
| 5 |
@dataclasses.dataclass
|
| 6 |
class BaseDataInterface:
|
| 7 |
|
| 8 |
-
|
| 9 |
-
def
|
| 10 |
-
|
| 11 |
-
batch: dict[str, list[Any]],
|
| 12 |
-
output_col: str = "messages"
|
| 13 |
-
) -> dict[str, list[Any]]:
|
| 14 |
-
"""
|
| 15 |
-
Core reusable logic:
|
| 16 |
-
Process 'list of dicts' (Batch) -> Reconstruct 'Row' -> func -> Aggregate Results.
|
| 17 |
-
|
| 18 |
-
Suitable for all 1-to-1 mapping operations.
|
| 19 |
-
"""
|
| 20 |
-
# Determine batch size (by checking the length of an arbitrary column)
|
| 21 |
-
# Assumes batch is not empty and columns are aligned.
|
| 22 |
-
first_key = next(iter(batch))
|
| 23 |
-
batch_size = len(batch[first_key])
|
| 24 |
-
|
| 25 |
-
results = []
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
# This replaces manually constructing `single_row` in every function.
|
| 30 |
-
row = {key: batch[key][i] for key in batch}
|
| 31 |
-
|
| 32 |
-
# 2. Call the processing function.
|
| 33 |
-
# The function receives a single row and MUST return a dict (e.g., {'messages': ...})
|
| 34 |
-
processed_output = func(row)
|
| 35 |
-
|
| 36 |
-
# 3. Extract result.
|
| 37 |
-
if output_col in processed_output:
|
| 38 |
-
results.append(processed_output[output_col])
|
| 39 |
-
else:
|
| 40 |
-
# Fallback or error handling if key is missing
|
| 41 |
-
raise KeyError(f"Function output missing expected key: {output_col}")
|
| 42 |
-
|
| 43 |
-
return {output_col: results}
|
| 44 |
|
| 45 |
-
|
| 46 |
-
def
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
# Modifying 'row' in-place can corrupt the dataset cache or cause issues if data is reused.
|
| 52 |
-
messages = copy.deepcopy(row.get("messages", []))
|
| 53 |
-
images = row.get("images", [])
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
continue
|
| 64 |
-
|
| 65 |
-
if 0 <= idx < len(images):
|
| 66 |
-
# Replace in-place (on the copied object)
|
| 67 |
-
item.pop("index", None)
|
| 68 |
-
item.pop("text", None)
|
| 69 |
-
item["image"] = images[idx]
|
| 70 |
-
else:
|
| 71 |
-
# Handle out-of-bounds error gracefully or log warning
|
| 72 |
-
pass
|
| 73 |
|
| 74 |
-
return {"messages": messages}
|
| 75 |
-
|
| 76 |
-
@staticmethod
|
| 77 |
-
def fill_images_batch(batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
|
| 78 |
-
return BaseDataInterface._process_batch_generic(
|
| 79 |
-
BaseDataInterface.fill_images,
|
| 80 |
-
batch
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
def planning_action_map(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 84 |
-
# FIX: The generic helper expects a dict return, not a list.
|
| 85 |
-
return {"messages": row["messages"]}
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
self.planning_action_map,
|
| 90 |
-
batch
|
| 91 |
-
)
|
| 92 |
|
| 93 |
-
|
| 94 |
-
# Placeholder for actual logic
|
| 95 |
-
return messages
|
| 96 |
|
| 97 |
-
def
|
|
|
|
|
|
|
| 98 |
"""
|
| 99 |
Handles 1-to-N data expansion (Unrolling conversation history).
|
| 100 |
Note: This changes the number of rows.
|
| 101 |
"""
|
| 102 |
messages_list = []
|
| 103 |
-
|
| 104 |
-
# Note: If there are other columns in 'batch' (like 'images'),
|
| 105 |
-
# they will be out of sync because we are expanding 'messages'.
|
| 106 |
-
# HF Datasets usually requires dropping other columns or expanding them manually here.
|
| 107 |
-
|
| 108 |
for messages in batch["messages"]:
|
| 109 |
-
assistant_indices = [
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
# Slicing includes the assistant message
|
| 112 |
-
context = messages[:assistant_index+1]
|
| 113 |
-
processed_context = self.
|
|
|
|
|
|
|
| 114 |
messages_list.append(processed_context)
|
| 115 |
-
|
| 116 |
-
return {"messages": messages_list}
|
| 117 |
|
| 118 |
-
|
| 119 |
-
if __name__ == "__main__":
|
| 120 |
-
from datasets import load_from_disk
|
| 121 |
-
dataset = load_from_disk(".data/scalecua/ubuntu/shard-00000-of-00256")
|
| 122 |
-
breakpoint()
|
| 123 |
-
# dataset = dataset.map(
|
| 124 |
-
# BaseDataInterface.fill_images_batch,
|
| 125 |
-
# batched=True,
|
| 126 |
-
# )
|
| 127 |
-
dataset = dataset.map(
|
| 128 |
-
BaseDataInterface.fill_images,
|
| 129 |
-
)
|
| 130 |
-
breakpoint()
|
|
|
|
| 1 |
import dataclasses
|
|
|
|
| 2 |
from typing import Callable, Any
|
| 3 |
|
| 4 |
+
from cua_lite.data.utils import batch_proc
|
| 5 |
+
|
| 6 |
+
|
| 7 |
@dataclasses.dataclass
|
| 8 |
class BaseDataInterface:
|
| 9 |
|
| 10 |
+
# --- Grounding ---
|
| 11 |
+
# def process_grounding(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 12 |
+
# return row
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# def process_grounding_batch(self, batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
|
| 15 |
+
# return batch_proc(self.process_grounding, batch)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# --- Planning ---
|
| 18 |
+
def process_action(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 19 |
+
return row
|
| 20 |
+
|
| 21 |
+
def process_action_batch(self, batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
|
| 22 |
+
return batch_proc(self.process_action, batch)
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# --- Context ---
|
| 25 |
+
def process_context(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 26 |
+
return row
|
| 27 |
+
|
| 28 |
+
def process_context_batch(
|
| 29 |
+
self, batch: dict[str, list[Any]]
|
| 30 |
+
) -> dict[str, list[Any]]:
|
| 31 |
+
return batch_proc(self.process_context, batch)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 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]]
|
| 41 |
+
) -> dict[str, list[Any]]:
|
| 42 |
"""
|
| 43 |
Handles 1-to-N data expansion (Unrolling conversation history).
|
| 44 |
Note: This changes the number of rows.
|
| 45 |
"""
|
| 46 |
messages_list = []
|
| 47 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
for messages in batch["messages"]:
|
| 49 |
+
assistant_indices = [
|
| 50 |
+
i for i, msg in enumerate(messages) if msg.get("role") == "assistant"
|
| 51 |
+
]
|
| 52 |
+
for assistant_index in assistant_indices:
|
| 53 |
# Slicing includes the assistant message
|
| 54 |
+
context = messages[: assistant_index + 1]
|
| 55 |
+
processed_context = self.process_context({"messages": context})[
|
| 56 |
+
"messages"
|
| 57 |
+
]
|
| 58 |
messages_list.append(processed_context)
|
|
|
|
|
|
|
| 59 |
|
| 60 |
+
return {"messages": messages_list}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/cua_lite/data/interfaces/qwen3_vl.py
CHANGED
|
@@ -1,9 +1,250 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
| 2 |
|
|
|
|
| 3 |
|
| 4 |
-
class Qwen3VLDataInterface(BaseDataInterface):
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_str}"""
|
| 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 |
+
processed_messages.append(anchor_step["assistant"])
|
| 215 |
+
|
| 216 |
+
# --- 追加剩余步骤 ---
|
| 217 |
+
for i in range(truncate_count + 1, total_steps):
|
| 218 |
+
# ======== FIX 2: 对齐 QwenAgent:非 anchor 的 user 只保留 image 部分 ========
|
| 219 |
+
u = copy.deepcopy(steps[i]["user"])
|
| 220 |
+
if isinstance(u.get("content"), list):
|
| 221 |
+
u["content"] = [it for it in u["content"] if it.get("type") != "text"]
|
| 222 |
+
processed_messages.append(u)
|
| 223 |
+
# ================================================================
|
| 224 |
+
if steps[i]["assistant"]:
|
| 225 |
+
processed_messages.append(steps[i]["assistant"])
|
| 226 |
+
|
| 227 |
+
return {"messages": processed_messages}
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
if __name__ == "__main__":
|
| 231 |
+
from datasets import load_from_disk
|
| 232 |
+
from transformers import AutoProcessor
|
| 233 |
+
from cua_lite.data.utils import clean_nones
|
| 234 |
+
|
| 235 |
+
processor = AutoProcessor.from_pretrained(
|
| 236 |
+
"/mnt/lustrenew/mllm_aligned/shared/models/huggingface/Qwen/Qwen3-VL-2B-Thinking"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
dataset = load_from_disk(".data/unzipped/scalecua/ubuntu/shard-00000-of-00256")
|
| 240 |
+
dataset.set_transform(clean_nones)
|
| 241 |
+
|
| 242 |
+
qwen3vl_interface = Qwen3VLDataInterface(history_n=4)
|
| 243 |
+
dataset_mapped = dataset.map(
|
| 244 |
+
qwen3vl_interface.process_context_batch, batched=True, batch_size=1000
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
inputs = processor.apply_chat_template(
|
| 248 |
+
dataset_mapped["messages"][0], return_dict=True
|
| 249 |
+
)
|
| 250 |
+
breakpoint()
|
src/cua_lite/data/preproc/README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Standardized dataset format
|
| 2 |
+
Please see [`ZHZisZZ/test`](https://huggingface.co/datasets/ZHZisZZ/test) for an example.
|
| 3 |
+
```
|
| 4 |
+
# Dataset row format
|
| 5 |
+
Each dataset row must contain exactly two keys: `images` and `messages`.
|
| 6 |
+
|
| 7 |
+
1) images
|
| 8 |
+
~~~~~~~~~
|
| 9 |
+
A list of PIL images loaded from the extracted image directory:
|
| 10 |
+
|
| 11 |
+
images = [
|
| 12 |
+
PIL(f"{image_0}"),
|
| 13 |
+
...
|
| 14 |
+
PIL(f"{image_n}")
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
2) messages
|
| 18 |
+
~~~~~~~~~~~
|
| 19 |
+
A multi-turn chat transcript that alternates user/assistant turns.
|
| 20 |
+
- The first user turn includes image index 0 AND the high-level instruction text.
|
| 21 |
+
- Each subsequent user turn includes ONLY the next image index.
|
| 22 |
+
- Each assistant turn includes:
|
| 23 |
+
- reasoning_content: reasoning that leads to the action.
|
| 24 |
+
- content: high-level description of the action.
|
| 25 |
+
- tool_calls: action taken in tool calling format.
|
| 26 |
+
|
| 27 |
+
messages = [
|
| 28 |
+
# Initial user instruction + first image
|
| 29 |
+
{
|
| 30 |
+
"role": "user",
|
| 31 |
+
"content": [
|
| 32 |
+
{"type": "image", "index": 0},
|
| 33 |
+
{"type": "text", "text": f"{instruction}"},
|
| 34 |
+
],
|
| 35 |
+
},
|
| 36 |
+
|
| 37 |
+
# Step 0 assistant response
|
| 38 |
+
{
|
| 39 |
+
"role": "assistant",
|
| 40 |
+
"reasoning_content": ..., # reasoning that leads to the action
|
| 41 |
+
"content": [{"type": "text", "text": ...}], # high-level description of the action
|
| 42 |
+
"tool_calls": [
|
| 43 |
+
{"type": "function", "function": {"name": "computer_use", "arguments": ...}}
|
| 44 |
+
], # action taken in tool calling format.
|
| 45 |
+
},
|
| 46 |
+
|
| 47 |
+
# Step 1 user image
|
| 48 |
+
{
|
| 49 |
+
"role": "user",
|
| 50 |
+
"content": [
|
| 51 |
+
{"type": "image", "index": 1},
|
| 52 |
+
],
|
| 53 |
+
},
|
| 54 |
+
|
| 55 |
+
# Step 1 assistant response
|
| 56 |
+
{
|
| 57 |
+
"role": "assistant",
|
| 58 |
+
"reasoning_content": ...,
|
| 59 |
+
"content": [{"type": "text", "text": ...}],
|
| 60 |
+
"tool_calls": [
|
| 61 |
+
{"type": "function", "function": {"name": "computer_use", "arguments": ...}}
|
| 62 |
+
],
|
| 63 |
+
},
|
| 64 |
+
|
| 65 |
+
# ...
|
| 66 |
+
# Final step n
|
| 67 |
+
{
|
| 68 |
+
"role": "user",
|
| 69 |
+
"content": [
|
| 70 |
+
{"type": "image", "index": n},
|
| 71 |
+
],
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"role": "assistant",
|
| 75 |
+
"reasoning_content": "...",
|
| 76 |
+
"content": [{"type": "text", "text": "..."}],
|
| 77 |
+
"tool_calls": [
|
| 78 |
+
{"type": "function", "function": {"name": "computer_use", "arguments": ...}}
|
| 79 |
+
],
|
| 80 |
+
},
|
| 81 |
+
]
|
| 82 |
+
```
|
src/cua_lite/data/preproc/opencua/README.md
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
## AgentNet Preprocessing
|
| 2 |
|
|
|
|
| 3 |
```shell
|
| 4 |
huggingface-cli download xlangai/AgentNet --repo-type dataset --local-dir .data/huggingface/xlangai/AgentNet
|
| 5 |
```
|
|
@@ -18,7 +19,8 @@ unzip images-full.zip -d ../extracted_ubuntu_images
|
|
| 18 |
cd ..
|
| 19 |
```
|
| 20 |
|
| 21 |
-
|
|
|
|
| 22 |
```shell
|
| 23 |
# process 1/256 of the dataset
|
| 24 |
python src/cua_lite/data/preproc/opencua/opencua.py \
|
|
@@ -31,20 +33,54 @@ python src/cua_lite/data/preproc/opencua/opencua.py \
|
|
| 31 |
## User Instruction
|
| 32 |
> `.data/tmp/scalecua/ubuntu/shard-00000-of-00256` should be replaced with a remote huggingface dataset path after we have finished AgentNet Preprocessing and pushed the dataset to huggingface.
|
| 33 |
|
|
|
|
|
|
|
| 34 |
```shell
|
| 35 |
-
# unzip
|
| 36 |
python src/cua_lite/data/unzip.py \
|
| 37 |
--input_path ".data/tmp/scalecua/ubuntu/shard-00000-of-00256" \
|
| 38 |
--output_path ".data/unzipped/scalecua/ubuntu/shard-00000-of-00256" \
|
| 39 |
--overwrite
|
| 40 |
```
|
| 41 |
|
| 42 |
-
```
|
| 43 |
-
# convert to
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
```shell
|
| 48 |
-
# convert to the format that qwen3 requires
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
```
|
|
|
|
| 1 |
## AgentNet Preprocessing
|
| 2 |
|
| 3 |
+
Download AgentNet.
|
| 4 |
```shell
|
| 5 |
huggingface-cli download xlangai/AgentNet --repo-type dataset --local-dir .data/huggingface/xlangai/AgentNet
|
| 6 |
```
|
|
|
|
| 19 |
cd ..
|
| 20 |
```
|
| 21 |
|
| 22 |
+
Standardize AgentNet preprocessing using the Qwen3-VL action spaces. By saving images and text together, we can ensure proper visualization on Hugging Face.
|
| 23 |
+
> TODO (zwc): Please scale it up and push the complete dataset to huggingface. The script is running slowly and needs to be sped up.
|
| 24 |
```shell
|
| 25 |
# process 1/256 of the dataset
|
| 26 |
python src/cua_lite/data/preproc/opencua/opencua.py \
|
|
|
|
| 33 |
## User Instruction
|
| 34 |
> `.data/tmp/scalecua/ubuntu/shard-00000-of-00256` should be replaced with a remote huggingface dataset path after we have finished AgentNet Preprocessing and pushed the dataset to huggingface.
|
| 35 |
|
| 36 |
+
Unzip the file to separate images and text. This prevents redundant image saving during the text preprocessing later on.
|
| 37 |
+
> TODO (zwc): The script is running slowly and needs to be sped up.
|
| 38 |
```shell
|
|
|
|
| 39 |
python src/cua_lite/data/unzip.py \
|
| 40 |
--input_path ".data/tmp/scalecua/ubuntu/shard-00000-of-00256" \
|
| 41 |
--output_path ".data/unzipped/scalecua/ubuntu/shard-00000-of-00256" \
|
| 42 |
--overwrite
|
| 43 |
```
|
| 44 |
|
| 45 |
+
<!-- ```python
|
| 46 |
+
# convert to default context unrolling messages format
|
| 47 |
+
from datasets import load_from_disk
|
| 48 |
+
from cua_lite.data.interfaces.base import UnrolledContextDataInterface
|
| 49 |
+
from cua_lite.data.utils import clean_nones
|
| 50 |
|
| 51 |
+
dataset = load_from_disk(".data/unzipped/scalecua/ubuntu/shard-00000-of-00256")
|
| 52 |
+
dataset.set_transform(clean_nones)
|
| 53 |
+
|
| 54 |
+
unrolled_interface = UnrolledContextDataInterface()
|
| 55 |
+
dataset_mapped = dataset.map(
|
| 56 |
+
unrolled_interface.process_context_batch,
|
| 57 |
+
batched=True,
|
| 58 |
+
)
|
| 59 |
+
``` -->
|
| 60 |
+
|
| 61 |
+
Convert to qwen3 messages format.
|
| 62 |
+
```python
|
| 63 |
+
from datasets import load_from_disk
|
| 64 |
+
from transformers import AutoProcessor
|
| 65 |
+
|
| 66 |
+
from cua_lite.data.utils import clean_nones
|
| 67 |
+
from cua_lite.data.interfaces.qwen3_vl import Qwen3VLDataInterface
|
| 68 |
+
|
| 69 |
+
dataset = load_from_disk(".data/unzipped/scalecua/ubuntu/shard-00000-of-00256")
|
| 70 |
+
dataset.set_transform(clean_nones)
|
| 71 |
+
|
| 72 |
+
qwen3vl_interface = Qwen3VLDataInterface(history_n=4)
|
| 73 |
+
dataset_mapped = dataset.map(
|
| 74 |
+
qwen3vl_interface.process_context_batch,
|
| 75 |
+
batched=True,
|
| 76 |
+
)
|
| 77 |
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
processor = AutoProcessor.from_pretrained(
|
| 80 |
+
"/mnt/lustrenew/mllm_aligned/shared/models/huggingface/Qwen/Qwen3-VL-2B-Thinking"
|
| 81 |
+
)
|
| 82 |
+
inputs = processor.apply_chat_template(
|
| 83 |
+
dataset_mapped["messages"][0], return_dict=True
|
| 84 |
+
)
|
| 85 |
+
print(inputs)
|
| 86 |
```
|
src/cua_lite/data/preproc/opencua/opencua.py
CHANGED
|
@@ -47,10 +47,13 @@ import tyro
|
|
| 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 =
|
|
|
|
|
|
|
| 54 |
output_path: str = ".data/scalecua/ubuntu"
|
| 55 |
rank: Optional[int] = None
|
| 56 |
world_size: Optional[int] = None
|
|
@@ -61,10 +64,13 @@ class ScriptArguments:
|
|
| 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(
|
|
|
|
|
|
|
| 68 |
return {
|
| 69 |
"type": "function",
|
| 70 |
"function": {
|
|
@@ -78,6 +84,7 @@ def _make_computer_use_tool_call(arguments: Dict[str, Any]) -> Dict[str, Any]:
|
|
| 78 |
# AgentNet code parsing
|
| 79 |
# -----------------------------
|
| 80 |
|
|
|
|
| 81 |
class AgentNetCodeParseError(RuntimeError):
|
| 82 |
pass
|
| 83 |
|
|
@@ -96,7 +103,9 @@ def _literal_eval(node: ast.AST) -> Any:
|
|
| 96 |
try:
|
| 97 |
return ast.literal_eval(node)
|
| 98 |
except Exception as e:
|
| 99 |
-
raise AgentNetCodeParseError(
|
|
|
|
|
|
|
| 100 |
|
| 101 |
|
| 102 |
def _get_kw(call: ast.Call, name: str) -> Optional[ast.AST]:
|
|
@@ -133,7 +142,9 @@ 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(
|
|
|
|
|
|
|
| 137 |
xi = int(round(x * 1000))
|
| 138 |
yi = int(round(y * 1000))
|
| 139 |
xi = max(0, min(1000, xi))
|
|
@@ -166,35 +177,45 @@ def agentnet_code_to_qwen_tool_calls(code: str) -> List[Dict[str, Any]]:
|
|
| 166 |
if fname == "pyautogui.click":
|
| 167 |
x, y = _extract_xy(call)
|
| 168 |
tool_calls.append(
|
| 169 |
-
_make_computer_use_tool_call(
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
| 198 |
)
|
| 199 |
continue
|
| 200 |
|
|
@@ -202,7 +223,9 @@ def agentnet_code_to_qwen_tool_calls(code: str) -> List[Dict[str, Any]]:
|
|
| 202 |
if fname == "pyautogui.moveTo":
|
| 203 |
x, y = _extract_xy(call)
|
| 204 |
tool_calls.append(
|
| 205 |
-
_make_computer_use_tool_call(
|
|
|
|
|
|
|
| 206 |
)
|
| 207 |
continue
|
| 208 |
|
|
@@ -215,38 +238,60 @@ def agentnet_code_to_qwen_tool_calls(code: str) -> List[Dict[str, Any]]:
|
|
| 215 |
)
|
| 216 |
x, y = _extract_xy(call)
|
| 217 |
tool_calls.append(
|
| 218 |
-
_make_computer_use_tool_call(
|
|
|
|
|
|
|
| 219 |
)
|
| 220 |
continue
|
| 221 |
|
| 222 |
# ---- Scroll ----
|
| 223 |
if fname in {"pyautogui.scroll", "pyautogui.hscroll"}:
|
| 224 |
if len(call.args) < 1:
|
| 225 |
-
raise AgentNetCodeParseError(
|
|
|
|
|
|
|
| 226 |
pixels = int(_literal_eval(call.args[0]))
|
| 227 |
-
tool_calls.append(
|
|
|
|
|
|
|
| 228 |
continue
|
| 229 |
|
| 230 |
# ---- Keyboard ----
|
| 231 |
if fname == "pyautogui.hotkey":
|
| 232 |
if len(call.args) != 1:
|
| 233 |
-
raise AgentNetCodeParseError(
|
|
|
|
|
|
|
| 234 |
keys_val = _literal_eval(call.args[0])
|
| 235 |
if not isinstance(keys_val, (list, tuple)) or not keys_val:
|
| 236 |
-
raise AgentNetCodeParseError(
|
|
|
|
|
|
|
| 237 |
keys = [str(k).lower() for k in keys_val]
|
| 238 |
-
tool_calls.append(
|
|
|
|
|
|
|
| 239 |
continue
|
| 240 |
|
| 241 |
if fname == "pyautogui.press":
|
| 242 |
if len(call.args) != 1:
|
| 243 |
-
raise AgentNetCodeParseError(
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
else:
|
| 249 |
-
tool_calls.append(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
continue
|
| 251 |
|
| 252 |
if fname in {"pyautogui.write", "pyautogui.typewrite"}:
|
|
@@ -254,9 +299,13 @@ def agentnet_code_to_qwen_tool_calls(code: str) -> List[Dict[str, Any]]:
|
|
| 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(
|
|
|
|
|
|
|
| 258 |
text = str(_literal_eval(msg_node))
|
| 259 |
-
tool_calls.append(
|
|
|
|
|
|
|
| 260 |
continue
|
| 261 |
|
| 262 |
# ---- Wait / Terminate ----
|
|
@@ -266,21 +315,33 @@ def agentnet_code_to_qwen_tool_calls(code: str) -> List[Dict[str, Any]]:
|
|
| 266 |
elif len(call.args) == 1 and len(call.keywords) == 0:
|
| 267 |
t = float(_literal_eval(call.args[0]))
|
| 268 |
else:
|
| 269 |
-
raise AgentNetCodeParseError(
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
continue
|
| 272 |
|
| 273 |
if fname == "computer.terminate":
|
| 274 |
status_node = _get_kw(call, "status")
|
| 275 |
if status_node is None:
|
| 276 |
-
raise AgentNetCodeParseError(
|
|
|
|
|
|
|
| 277 |
status = str(_literal_eval(status_node))
|
| 278 |
if status not in {"success", "failure"}:
|
| 279 |
-
raise AgentNetCodeParseError(
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
continue
|
| 282 |
|
| 283 |
-
raise AgentNetCodeParseError(
|
|
|
|
|
|
|
| 284 |
|
| 285 |
return tool_calls
|
| 286 |
|
|
@@ -289,6 +350,7 @@ def agentnet_code_to_qwen_tool_calls(code: str) -> List[Dict[str, Any]]:
|
|
| 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}")
|
|
@@ -299,15 +361,21 @@ def _load_image_or_raise(path: Path) -> PILImage.Image:
|
|
| 299 |
raise RuntimeError(f"Failed to open image: {path}") from e
|
| 300 |
|
| 301 |
|
| 302 |
-
def record_to_example(
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
| 307 |
|
| 308 |
traj = record.get("traj")
|
| 309 |
if not isinstance(traj, list) or len(traj) == 0:
|
| 310 |
-
raise ValueError(
|
|
|
|
|
|
|
| 311 |
|
| 312 |
images: List[PILImage.Image] = []
|
| 313 |
for i, step in enumerate(traj):
|
|
@@ -334,18 +402,26 @@ def record_to_example(record: Dict[str, Any], extracted_images_dir: Path) -> Dic
|
|
| 334 |
for i, step in enumerate(traj):
|
| 335 |
value = step.get("value")
|
| 336 |
if not isinstance(value, dict):
|
| 337 |
-
raise ValueError(
|
|
|
|
|
|
|
| 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(
|
|
|
|
|
|
|
| 345 |
if not isinstance(action_text, str):
|
| 346 |
-
raise ValueError(
|
|
|
|
|
|
|
| 347 |
if not isinstance(code, str):
|
| 348 |
-
raise ValueError(
|
|
|
|
|
|
|
| 349 |
|
| 350 |
tool_calls = agentnet_code_to_qwen_tool_calls(code)
|
| 351 |
|
|
@@ -370,7 +446,9 @@ def record_to_example(record: Dict[str, Any], extracted_images_dir: Path) -> Dic
|
|
| 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(
|
|
|
|
|
|
|
| 374 |
|
| 375 |
last_call = last_step_tool_calls[-1]
|
| 376 |
try:
|
|
@@ -388,7 +466,9 @@ def record_to_example(record: Dict[str, Any], extracted_images_dir: Path) -> Dic
|
|
| 388 |
return {"images": images, "messages": messages}
|
| 389 |
|
| 390 |
|
| 391 |
-
def compute_shard_range(
|
|
|
|
|
|
|
| 392 |
"""Contiguous shard ranges.
|
| 393 |
|
| 394 |
Ensures:
|
|
@@ -456,10 +536,14 @@ def iter_examples(
|
|
| 456 |
try:
|
| 457 |
record = json.loads(line)
|
| 458 |
except Exception as e:
|
| 459 |
-
raise ValueError(
|
|
|
|
|
|
|
| 460 |
|
| 461 |
if not isinstance(record, dict):
|
| 462 |
-
raise ValueError(
|
|
|
|
|
|
|
| 463 |
|
| 464 |
yield record_to_example(record, extracted_images_dir=extracted_images_dir)
|
| 465 |
record_idx += 1
|
|
@@ -516,7 +600,9 @@ def main() -> None:
|
|
| 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(
|
|
|
|
|
|
|
| 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:
|
|
@@ -534,7 +620,6 @@ def main() -> None:
|
|
| 534 |
features = build_features()
|
| 535 |
|
| 536 |
if hasattr(Dataset, "from_generator"):
|
| 537 |
-
breakpoint()
|
| 538 |
ds = Dataset.from_generator(
|
| 539 |
iter_examples,
|
| 540 |
gen_kwargs={
|
|
|
|
| 47 |
# Args
|
| 48 |
# -----------------------------
|
| 49 |
|
| 50 |
+
|
| 51 |
@dataclass
|
| 52 |
class ScriptArguments:
|
| 53 |
jsonl_path: str = ".data/huggingface/xlangai/AgentNet/agentnet_ubuntu_5k.jsonl"
|
| 54 |
+
extracted_images_dir: str = (
|
| 55 |
+
".data/huggingface/xlangai/AgentNet/extracted_ubuntu_images"
|
| 56 |
+
)
|
| 57 |
output_path: str = ".data/scalecua/ubuntu"
|
| 58 |
rank: Optional[int] = None
|
| 59 |
world_size: Optional[int] = None
|
|
|
|
| 64 |
# Qwen3-VL tool call formatting
|
| 65 |
# -----------------------------
|
| 66 |
|
| 67 |
+
|
| 68 |
def _make_computer_use_tool_call(arguments: Dict[str, Any]) -> Dict[str, Any]:
|
| 69 |
"""Wrap a computer_use tool call in Qwen3-VL tool_call structure."""
|
| 70 |
if "action" not in arguments:
|
| 71 |
+
raise ValueError(
|
| 72 |
+
f"computer_use arguments must include 'action'. Got: {arguments}"
|
| 73 |
+
)
|
| 74 |
return {
|
| 75 |
"type": "function",
|
| 76 |
"function": {
|
|
|
|
| 84 |
# AgentNet code parsing
|
| 85 |
# -----------------------------
|
| 86 |
|
| 87 |
+
|
| 88 |
class AgentNetCodeParseError(RuntimeError):
|
| 89 |
pass
|
| 90 |
|
|
|
|
| 103 |
try:
|
| 104 |
return ast.literal_eval(node)
|
| 105 |
except Exception as e:
|
| 106 |
+
raise AgentNetCodeParseError(
|
| 107 |
+
f"Failed literal_eval on node={ast.dump(node)}"
|
| 108 |
+
) from e
|
| 109 |
|
| 110 |
|
| 111 |
def _get_kw(call: ast.Call, name: str) -> Optional[ast.AST]:
|
|
|
|
| 142 |
"""Convert normalized [0,1] floats -> int [0,1000] with rounding."""
|
| 143 |
eps = 1e-6
|
| 144 |
if x < -eps or x > 1 + eps or y < -eps or y > 1 + eps:
|
| 145 |
+
raise AgentNetCodeParseError(
|
| 146 |
+
f"Coordinates out of normalized range [0,1]: x={x}, y={y}"
|
| 147 |
+
)
|
| 148 |
xi = int(round(x * 1000))
|
| 149 |
yi = int(round(y * 1000))
|
| 150 |
xi = max(0, min(1000, xi))
|
|
|
|
| 177 |
if fname == "pyautogui.click":
|
| 178 |
x, y = _extract_xy(call)
|
| 179 |
tool_calls.append(
|
| 180 |
+
_make_computer_use_tool_call(
|
| 181 |
+
{"action": "left_click", "coordinate": _norm01_to_0_1000(x, y)}
|
| 182 |
+
)
|
| 183 |
)
|
| 184 |
continue
|
| 185 |
|
| 186 |
if fname == "pyautogui.rightClick":
|
| 187 |
x, y = _extract_xy(call)
|
| 188 |
tool_calls.append(
|
| 189 |
+
_make_computer_use_tool_call(
|
| 190 |
+
{"action": "right_click", "coordinate": _norm01_to_0_1000(x, y)}
|
| 191 |
+
)
|
| 192 |
)
|
| 193 |
continue
|
| 194 |
|
| 195 |
if fname == "pyautogui.middleClick":
|
| 196 |
x, y = _extract_xy(call)
|
| 197 |
tool_calls.append(
|
| 198 |
+
_make_computer_use_tool_call(
|
| 199 |
+
{"action": "middle_click", "coordinate": _norm01_to_0_1000(x, y)}
|
| 200 |
+
)
|
| 201 |
)
|
| 202 |
continue
|
| 203 |
|
| 204 |
if fname == "pyautogui.doubleClick":
|
| 205 |
x, y = _extract_xy(call)
|
| 206 |
tool_calls.append(
|
| 207 |
+
_make_computer_use_tool_call(
|
| 208 |
+
{"action": "double_click", "coordinate": _norm01_to_0_1000(x, y)}
|
| 209 |
+
)
|
| 210 |
)
|
| 211 |
continue
|
| 212 |
|
| 213 |
if fname in {"pyautogui.tripleClick", "computer.tripleClick"}:
|
| 214 |
x, y = _extract_xy(call)
|
| 215 |
tool_calls.append(
|
| 216 |
+
_make_computer_use_tool_call(
|
| 217 |
+
{"action": "double_click", "coordinate": _norm01_to_0_1000(x, y)}
|
| 218 |
+
)
|
| 219 |
)
|
| 220 |
continue
|
| 221 |
|
|
|
|
| 223 |
if fname == "pyautogui.moveTo":
|
| 224 |
x, y = _extract_xy(call)
|
| 225 |
tool_calls.append(
|
| 226 |
+
_make_computer_use_tool_call(
|
| 227 |
+
{"action": "mouse_move", "coordinate": _norm01_to_0_1000(x, y)}
|
| 228 |
+
)
|
| 229 |
)
|
| 230 |
continue
|
| 231 |
|
|
|
|
| 238 |
)
|
| 239 |
x, y = _extract_xy(call)
|
| 240 |
tool_calls.append(
|
| 241 |
+
_make_computer_use_tool_call(
|
| 242 |
+
{"action": "left_click_drag", "coordinate": _norm01_to_0_1000(x, y)}
|
| 243 |
+
)
|
| 244 |
)
|
| 245 |
continue
|
| 246 |
|
| 247 |
# ---- Scroll ----
|
| 248 |
if fname in {"pyautogui.scroll", "pyautogui.hscroll"}:
|
| 249 |
if len(call.args) < 1:
|
| 250 |
+
raise AgentNetCodeParseError(
|
| 251 |
+
f"scroll/hscroll requires a pixels argument.\ncode=\n{code}"
|
| 252 |
+
)
|
| 253 |
pixels = int(_literal_eval(call.args[0]))
|
| 254 |
+
tool_calls.append(
|
| 255 |
+
_make_computer_use_tool_call({"action": "scroll", "pixels": pixels})
|
| 256 |
+
)
|
| 257 |
continue
|
| 258 |
|
| 259 |
# ---- Keyboard ----
|
| 260 |
if fname == "pyautogui.hotkey":
|
| 261 |
if len(call.args) != 1:
|
| 262 |
+
raise AgentNetCodeParseError(
|
| 263 |
+
f"hotkey expected a single list argument.\ncode=\n{code}"
|
| 264 |
+
)
|
| 265 |
keys_val = _literal_eval(call.args[0])
|
| 266 |
if not isinstance(keys_val, (list, tuple)) or not keys_val:
|
| 267 |
+
raise AgentNetCodeParseError(
|
| 268 |
+
f"hotkey arg must be a non-empty list/tuple. Got: {keys_val!r}"
|
| 269 |
+
)
|
| 270 |
keys = [str(k).lower() for k in keys_val]
|
| 271 |
+
tool_calls.append(
|
| 272 |
+
_make_computer_use_tool_call({"action": "key", "keys": keys})
|
| 273 |
+
)
|
| 274 |
continue
|
| 275 |
|
| 276 |
if fname == "pyautogui.press":
|
| 277 |
if len(call.args) != 1:
|
| 278 |
+
raise AgentNetCodeParseError(
|
| 279 |
+
f"press expected a single key argument.\ncode=\n{code}"
|
| 280 |
+
)
|
| 281 |
key_val = _literal_eval(call.args[0])
|
| 282 |
if isinstance(key_val, (list, tuple)):
|
| 283 |
for k in key_val:
|
| 284 |
+
tool_calls.append(
|
| 285 |
+
_make_computer_use_tool_call(
|
| 286 |
+
{"action": "key", "keys": [str(k).lower()]}
|
| 287 |
+
)
|
| 288 |
+
)
|
| 289 |
else:
|
| 290 |
+
tool_calls.append(
|
| 291 |
+
_make_computer_use_tool_call(
|
| 292 |
+
{"action": "key", "keys": [str(key_val).lower()]}
|
| 293 |
+
)
|
| 294 |
+
)
|
| 295 |
continue
|
| 296 |
|
| 297 |
if fname in {"pyautogui.write", "pyautogui.typewrite"}:
|
|
|
|
| 299 |
if msg_node is None and len(call.args) == 1:
|
| 300 |
msg_node = call.args[0]
|
| 301 |
if msg_node is None:
|
| 302 |
+
raise AgentNetCodeParseError(
|
| 303 |
+
f"write/typewrite requires message argument.\ncode=\n{code}"
|
| 304 |
+
)
|
| 305 |
text = str(_literal_eval(msg_node))
|
| 306 |
+
tool_calls.append(
|
| 307 |
+
_make_computer_use_tool_call({"action": "type", "text": text})
|
| 308 |
+
)
|
| 309 |
continue
|
| 310 |
|
| 311 |
# ---- Wait / Terminate ----
|
|
|
|
| 315 |
elif len(call.args) == 1 and len(call.keywords) == 0:
|
| 316 |
t = float(_literal_eval(call.args[0]))
|
| 317 |
else:
|
| 318 |
+
raise AgentNetCodeParseError(
|
| 319 |
+
f"Unsupported wait signature.\ncode=\n{code}"
|
| 320 |
+
)
|
| 321 |
+
tool_calls.append(
|
| 322 |
+
_make_computer_use_tool_call({"action": "wait", "time": t})
|
| 323 |
+
)
|
| 324 |
continue
|
| 325 |
|
| 326 |
if fname == "computer.terminate":
|
| 327 |
status_node = _get_kw(call, "status")
|
| 328 |
if status_node is None:
|
| 329 |
+
raise AgentNetCodeParseError(
|
| 330 |
+
f"terminate requires status='success'|'failure'.\ncode=\n{code}"
|
| 331 |
+
)
|
| 332 |
status = str(_literal_eval(status_node))
|
| 333 |
if status not in {"success", "failure"}:
|
| 334 |
+
raise AgentNetCodeParseError(
|
| 335 |
+
f"Unsupported terminate status={status!r}.\ncode=\n{code}"
|
| 336 |
+
)
|
| 337 |
+
tool_calls.append(
|
| 338 |
+
_make_computer_use_tool_call({"action": "terminate", "status": status})
|
| 339 |
+
)
|
| 340 |
continue
|
| 341 |
|
| 342 |
+
raise AgentNetCodeParseError(
|
| 343 |
+
f"Unsupported function call: {fname!r}.\ncode=\n{code}"
|
| 344 |
+
)
|
| 345 |
|
| 346 |
return tool_calls
|
| 347 |
|
|
|
|
| 350 |
# Trajectory -> dataset example
|
| 351 |
# -----------------------------
|
| 352 |
|
| 353 |
+
|
| 354 |
def _load_image_or_raise(path: Path) -> PILImage.Image:
|
| 355 |
if not path.exists():
|
| 356 |
raise FileNotFoundError(f"Missing image file: {path}")
|
|
|
|
| 361 |
raise RuntimeError(f"Failed to open image: {path}") from e
|
| 362 |
|
| 363 |
|
| 364 |
+
def record_to_example(
|
| 365 |
+
record: Dict[str, Any], extracted_images_dir: Path
|
| 366 |
+
) -> Dict[str, Any]:
|
| 367 |
"""Convert one JSONL record into one dataset row with keys: images, messages."""
|
| 368 |
instruction = record.get("instruction")
|
| 369 |
if not isinstance(instruction, str) or not instruction.strip():
|
| 370 |
+
raise ValueError(
|
| 371 |
+
f"Missing/invalid 'instruction' in record. Keys={list(record.keys())}"
|
| 372 |
+
)
|
| 373 |
|
| 374 |
traj = record.get("traj")
|
| 375 |
if not isinstance(traj, list) or len(traj) == 0:
|
| 376 |
+
raise ValueError(
|
| 377 |
+
f"Missing/invalid 'traj' in record. task_id={record.get('task_id')}"
|
| 378 |
+
)
|
| 379 |
|
| 380 |
images: List[PILImage.Image] = []
|
| 381 |
for i, step in enumerate(traj):
|
|
|
|
| 402 |
for i, step in enumerate(traj):
|
| 403 |
value = step.get("value")
|
| 404 |
if not isinstance(value, dict):
|
| 405 |
+
raise ValueError(
|
| 406 |
+
f"Missing/invalid step.value at traj[{i}] task_id={record.get('task_id')}"
|
| 407 |
+
)
|
| 408 |
|
| 409 |
thought = value.get("thought")
|
| 410 |
action_text = value.get("action")
|
| 411 |
code = value.get("code")
|
| 412 |
|
| 413 |
if not isinstance(thought, str):
|
| 414 |
+
raise ValueError(
|
| 415 |
+
f"Missing/invalid value.thought at traj[{i}] task_id={record.get('task_id')}"
|
| 416 |
+
)
|
| 417 |
if not isinstance(action_text, str):
|
| 418 |
+
raise ValueError(
|
| 419 |
+
f"Missing/invalid value.action at traj[{i}] task_id={record.get('task_id')}"
|
| 420 |
+
)
|
| 421 |
if not isinstance(code, str):
|
| 422 |
+
raise ValueError(
|
| 423 |
+
f"Missing/invalid value.code at traj[{i}] task_id={record.get('task_id')}"
|
| 424 |
+
)
|
| 425 |
|
| 426 |
tool_calls = agentnet_code_to_qwen_tool_calls(code)
|
| 427 |
|
|
|
|
| 446 |
|
| 447 |
last_step_tool_calls = messages[-1].get("tool_calls")
|
| 448 |
if not isinstance(last_step_tool_calls, list) or len(last_step_tool_calls) == 0:
|
| 449 |
+
raise ValueError(
|
| 450 |
+
f"Last assistant message has no tool_calls. task_id={record.get('task_id')}"
|
| 451 |
+
)
|
| 452 |
|
| 453 |
last_call = last_step_tool_calls[-1]
|
| 454 |
try:
|
|
|
|
| 466 |
return {"images": images, "messages": messages}
|
| 467 |
|
| 468 |
|
| 469 |
+
def compute_shard_range(
|
| 470 |
+
num_records: int, rank: int, world_size: int
|
| 471 |
+
) -> Tuple[int, int]:
|
| 472 |
"""Contiguous shard ranges.
|
| 473 |
|
| 474 |
Ensures:
|
|
|
|
| 536 |
try:
|
| 537 |
record = json.loads(line)
|
| 538 |
except Exception as e:
|
| 539 |
+
raise ValueError(
|
| 540 |
+
f"JSON parse error at line {line_no} (record_idx={record_idx}) in {jsonl_path}"
|
| 541 |
+
) from e
|
| 542 |
|
| 543 |
if not isinstance(record, dict):
|
| 544 |
+
raise ValueError(
|
| 545 |
+
f"Expected JSON object at line {line_no} (record_idx={record_idx})"
|
| 546 |
+
)
|
| 547 |
|
| 548 |
yield record_to_example(record, extracted_images_dir=extracted_images_dir)
|
| 549 |
record_idx += 1
|
|
|
|
| 600 |
if not jsonl_path.exists():
|
| 601 |
raise FileNotFoundError(f"jsonl_path not found: {jsonl_path}")
|
| 602 |
if not extracted_images_dir.exists():
|
| 603 |
+
raise FileNotFoundError(
|
| 604 |
+
f"extracted_images_dir not found: {extracted_images_dir}"
|
| 605 |
+
)
|
| 606 |
|
| 607 |
# If sharded, save into a deterministic shard subdir so ranks don't clobber each other.
|
| 608 |
if args.rank is not None and args.world_size is not None:
|
|
|
|
| 620 |
features = build_features()
|
| 621 |
|
| 622 |
if hasattr(Dataset, "from_generator"):
|
|
|
|
| 623 |
ds = Dataset.from_generator(
|
| 624 |
iter_examples,
|
| 625 |
gen_kwargs={
|
src/cua_lite/data/unzip.py
CHANGED
|
@@ -13,6 +13,7 @@ from PIL import Image as PILImage
|
|
| 13 |
# Args
|
| 14 |
# -----------------------------
|
| 15 |
|
|
|
|
| 16 |
@dataclass
|
| 17 |
class ScriptArguments:
|
| 18 |
input_path: str = ".data/tmp/scalecua/ubuntu/shard-00000-of-00256"
|
|
@@ -24,20 +25,19 @@ class ScriptArguments:
|
|
| 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:
|
|
@@ -49,53 +49,56 @@ def process_row(
|
|
| 49 |
"""
|
| 50 |
out_messages_batch = []
|
| 51 |
|
| 52 |
-
for batch_idx, (row_images, row_messages) in enumerate(
|
|
|
|
|
|
|
| 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 |
-
|
| 84 |
-
})
|
| 85 |
else:
|
| 86 |
-
raise ValueError(
|
|
|
|
|
|
|
| 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}
|
|
@@ -103,35 +106,39 @@ def process_row(
|
|
| 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(
|
|
|
|
|
|
|
| 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(
|
| 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 |
|
|
@@ -190,16 +197,11 @@ Write a Python script that loads the dataset from `input_path` and performs the
|
|
| 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 |
},
|
|
|
|
| 13 |
# Args
|
| 14 |
# -----------------------------
|
| 15 |
|
| 16 |
+
|
| 17 |
@dataclass
|
| 18 |
class ScriptArguments:
|
| 19 |
input_path: str = ".data/tmp/scalecua/ubuntu/shard-00000-of-00256"
|
|
|
|
| 25 |
# Dataset Transformation
|
| 26 |
# -----------------------------
|
| 27 |
|
| 28 |
+
|
| 29 |
def _save_image(image: PILImage.Image, row_dir: Path, img_idx: int) -> str:
|
| 30 |
"""Save PIL image to the specific row directory and return the absolute posix path."""
|
| 31 |
filename = f"{img_idx:03d}.png"
|
| 32 |
file_path = row_dir / filename
|
| 33 |
+
|
| 34 |
image.save(file_path)
|
| 35 |
+
|
| 36 |
return str(file_path.resolve())
|
| 37 |
|
| 38 |
|
| 39 |
def process_row(
|
| 40 |
+
batch: Dict[str, Any], indices: List[int], output_data_dir: Path
|
|
|
|
|
|
|
| 41 |
) -> Dict[str, Any]:
|
| 42 |
"""
|
| 43 |
Process a batch of rows to:
|
|
|
|
| 49 |
"""
|
| 50 |
out_messages_batch = []
|
| 51 |
|
| 52 |
+
for batch_idx, (row_images, row_messages) in enumerate(
|
| 53 |
+
zip(batch["images"], batch["messages"])
|
| 54 |
+
):
|
| 55 |
global_idx = indices[batch_idx]
|
| 56 |
+
|
| 57 |
# 1. Prepare row-specific directory: output/data/00000000/
|
| 58 |
row_dir = output_data_dir / f"{global_idx:08d}"
|
| 59 |
row_dir.mkdir(parents=True, exist_ok=True)
|
| 60 |
+
|
| 61 |
# Cache saved paths for this row: map image_index -> absolute_path
|
| 62 |
saved_path_map: Dict[int, str] = {}
|
| 63 |
+
|
| 64 |
for img_idx, image in enumerate(row_images):
|
| 65 |
# 2. Save image into the row directory
|
| 66 |
abs_path = _save_image(image, row_dir, img_idx)
|
| 67 |
saved_path_map[img_idx] = abs_path
|
| 68 |
+
|
| 69 |
# 3. Rebuild messages
|
| 70 |
new_row_messages = []
|
| 71 |
+
|
| 72 |
for msg in row_messages:
|
| 73 |
new_content = []
|
| 74 |
+
|
| 75 |
raw_content = msg.get("content", [])
|
| 76 |
for item in raw_content:
|
| 77 |
item_type = item.get("type")
|
| 78 |
+
|
| 79 |
if item_type == "image":
|
| 80 |
# Handle Image: Transform structure and remove index implicitly
|
| 81 |
idx_val = item.get("index")
|
| 82 |
if idx_val is not None and idx_val in saved_path_map:
|
| 83 |
+
new_content.append(
|
| 84 |
+
{"type": "image", "image": saved_path_map[idx_val]}
|
| 85 |
+
)
|
|
|
|
| 86 |
else:
|
| 87 |
+
raise ValueError(
|
| 88 |
+
f"Image index {idx_val} not found in saved images for row {global_idx}"
|
| 89 |
+
)
|
| 90 |
else:
|
| 91 |
# Handle Text/Other: Copy item and explicitly remove 'index'
|
| 92 |
clean_item = item.copy()
|
| 93 |
clean_item.pop("index", None)
|
| 94 |
new_content.append(clean_item)
|
| 95 |
+
|
| 96 |
# Dynamic Copy: Preserve ALL original keys and only overwrite 'content'
|
| 97 |
new_msg = msg.copy()
|
| 98 |
new_msg["content"] = new_content
|
| 99 |
+
|
| 100 |
new_row_messages.append(new_msg)
|
| 101 |
+
|
| 102 |
out_messages_batch.append(new_row_messages)
|
| 103 |
|
| 104 |
return {"messages": out_messages_batch}
|
|
|
|
| 106 |
|
| 107 |
def main() -> None:
|
| 108 |
args = tyro.cli(ScriptArguments)
|
| 109 |
+
|
| 110 |
input_path = Path(args.input_path)
|
| 111 |
output_path = Path(args.output_path)
|
| 112 |
output_data_dir = output_path / "data"
|
| 113 |
|
| 114 |
if not input_path.exists():
|
| 115 |
raise FileNotFoundError(f"input_path does not exist: {input_path}")
|
| 116 |
+
|
| 117 |
if output_path.exists():
|
| 118 |
if args.overwrite:
|
| 119 |
shutil.rmtree(output_path)
|
| 120 |
else:
|
| 121 |
+
raise FileExistsError(
|
| 122 |
+
f"output_path exists: {output_path}. Use --overwrite to replace."
|
| 123 |
+
)
|
| 124 |
|
| 125 |
output_data_dir.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
|
| 127 |
print(f"Loading dataset from: {input_path}")
|
| 128 |
ds = load_from_disk(str(input_path))
|
| 129 |
+
|
| 130 |
+
print(
|
| 131 |
+
f"Processing {len(ds)} rows. Images will be saved to subdirectories in: {output_data_dir}"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
updated_ds = ds.map(
|
| 135 |
process_row,
|
| 136 |
fn_kwargs={"output_data_dir": output_data_dir},
|
| 137 |
batched=True,
|
| 138 |
with_indices=True,
|
| 139 |
+
desc="Extracting images and rewriting messages",
|
| 140 |
)
|
| 141 |
+
|
| 142 |
if "images" in updated_ds.column_names:
|
| 143 |
updated_ds = updated_ds.remove_columns("images")
|
| 144 |
|
|
|
|
| 197 |
|
| 198 |
# Example of Dataset Row after converstion (`ds[0]`)
|
| 199 |
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
'messages': [
|
| 201 |
{
|
| 202 |
'role': 'user',
|
| 203 |
'content': [
|
| 204 |
+
{'image': '{image_path}', 'text': None, 'type': 'image'},
|
| 205 |
{'text': 'Open the Pikachu picture...', 'type': 'text'}
|
| 206 |
]
|
| 207 |
},
|
src/cua_lite/data/utils.py
CHANGED
|
@@ -1,21 +1,56 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
from typing import Callable, Any
|
| 3 |
+
|
| 4 |
+
|
| 5 |
def clean_nones(item):
|
| 6 |
"""
|
| 7 |
递归移除字典或列表中值为 None 的键。
|
| 8 |
"""
|
| 9 |
if isinstance(item, dict):
|
| 10 |
+
return {k: clean_nones(v) for k, v in item.items() if v is not None}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
elif isinstance(item, list):
|
| 12 |
return [clean_nones(i) for i in item]
|
| 13 |
else:
|
| 14 |
return item
|
| 15 |
|
| 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()}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def batch_proc(
|
| 25 |
+
func: Callable[[dict[str, Any]], dict[str, Any]], batch: dict[str, list[Any]]
|
| 26 |
+
) -> dict[str, list[Any]]:
|
| 27 |
+
"""
|
| 28 |
+
Core reusable logic:
|
| 29 |
+
Process 'list of dicts' (Batch) -> Reconstruct 'Row' -> func -> Aggregate All Results.
|
| 30 |
+
|
| 31 |
+
Transforms a Columnar Batch input into a Columnar Batch output, preserving
|
| 32 |
+
all keys returned by the processing function.
|
| 33 |
+
"""
|
| 34 |
+
# 1. Determine batch size
|
| 35 |
+
if not batch:
|
| 36 |
+
return {}
|
| 37 |
+
|
| 38 |
+
first_key = next(iter(batch))
|
| 39 |
+
batch_size = len(batch[first_key])
|
| 40 |
+
|
| 41 |
+
# Use defaultdict to automatically create lists for new keys
|
| 42 |
+
output_batch = defaultdict(list)
|
| 43 |
+
|
| 44 |
+
for i in range(batch_size):
|
| 45 |
+
# 2. Dynamically reconstruct a Single Row
|
| 46 |
+
row = {key: batch[key][i] for key in batch}
|
| 47 |
+
|
| 48 |
+
# 3. Call the processing function
|
| 49 |
+
# Expected to return a dict, e.g., {'messages': ..., 'status': ..., 'meta': ...}
|
| 50 |
+
processed_row = func(row)
|
| 51 |
+
|
| 52 |
+
# 4. Aggregate ALL keys from the result
|
| 53 |
+
for key, value in processed_row.items():
|
| 54 |
+
output_batch[key].append(value)
|
| 55 |
+
|
| 56 |
+
return dict(output_batch)
|