File size: 18,867 Bytes
87fb54d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python3
"""Generate browser training data from MiniWoB++ task specs + BrowserGym action space."""
import json, random, os
from datasets import Dataset
from huggingface_hub import login

TOKEN = os.environ.get("HF_TOKEN", "")
if TOKEN:
    login(token=TOKEN)

TOOLS = [
    {"type": "function", "function": {"name": "navigate", "description": "Go to a URL", "parameters": {"type": "object", "properties": {"url": {"type": "string"}}, "required": ["url"]}}},
    {"type": "function", "function": {"name": "click", "description": "Click an element by selector or text", "parameters": {"type": "object", "properties": {"target": {"type": "string", "description": "CSS selector, text label, or coordinate"}}, "required": ["target"]}}},
    {"type": "function", "function": {"name": "type", "description": "Type text into a field", "parameters": {"type": "object", "properties": {"selector": {"type": "string"}, "text": {"type": "string"}, "clear_first": {"type": "boolean"}}, "required": ["selector", "text"]}}},
    {"type": "function", "function": {"name": "select", "description": "Select from dropdown", "parameters": {"type": "object", "properties": {"selector": {"type": "string"}, "value": {"type": "string"}}, "required": ["selector", "value"]}}},
    {"type": "function", "function": {"name": "extract", "description": "Extract text content", "parameters": {"type": "object", "properties": {"selector": {"type": "string"}}}}},
    {"type": "function", "function": {"name": "scroll", "description": "Scroll the page", "parameters": {"type": "object", "properties": {"direction": {"type": "string", "enum": ["up", "down", "top", "bottom"]}}, "required": ["direction"]}}},
    {"type": "function", "function": {"name": "wait", "description": "Wait for milliseconds", "parameters": {"type": "object", "properties": {"ms": {"type": "integer"}}, "required": ["ms"]}}},
    {"type": "function", "function": {"name": "press_key", "description": "Press a keyboard key", "parameters": {"type": "object", "properties": {"key": {"type": "string"}}, "required": ["key"]}}},
    {"type": "function", "function": {"name": "screenshot", "description": "Take screenshot", "parameters": {"type": "object", "properties": {}}}},
    {"type": "function", "function": {"name": "go_back", "description": "Go back", "parameters": {"type": "object", "properties": {}}}},
    {"type": "function", "function": {"name": "done", "description": "Mark task as complete", "parameters": {"type": "object", "properties": {"answer": {"type": "string"}}}}},
]

# MiniWoB++ task templates — each generates multiple randomized examples
TASKS = [
    # ── CLICK TASKS ──
    {"type": "click-single", "goal": "Click the button {label}", "steps": [("click", "{label}"), ("done", {"answer": "clicked"})], "variants": [("Submit",), ("OK",), ("Cancel",), ("Next",), ("Yes",), ("No",), ("Save",), ("Delete",), ("Search",), ("Continue",)]},
    {"type": "click-target", "goal": "Click the button with id {id}", "steps": [("click", "#{id}"), ("done", {"answer": "done"})], "variants": [("btn-1",), ("target",), ("submit-btn",), ("main-cta",), ("action",)]},
    {"type": "click-color", "goal": "Click the {color} button", "steps": [("click", ".{color}-btn"), ("done", {"answer": "clicked"})], "variants": [("red",), ("blue",), ("green",), ("yellow",), ("orange",), ("purple",)]},
    {"type": "click-shape", "goal": "Click the {shape} shape", "steps": [("click", ".shape-{shape}"), ("done", {"answer": "clicked"})], "variants": [("circle",), ("square",), ("triangle",), ("star",), ("hexagon",)]},
    {"type": "click-position", "goal": "Click the {pos} button", "steps": [("click", ".btn-{pos}"), ("done", {"answer": "clicked"})], "variants": [("first",), ("second",), ("third",), ("last",), ("middle",)]},
    {"type": "click-popup", "goal": "Click {btn} in the dialog", "steps": [("wait", {"ms": 1000}), ("click", ".dialog .{btn}"), ("done", {"answer": "dismissed"})], "variants": [("confirm",), ("cancel",), ("close",), ("accept",), ("dismiss",)]},

    # ── CHECKBOX TASKS ──
    {"type": "checkbox-single", "goal": "Select the checkbox labeled {label}", "steps": [("click", "input[type=checkbox][aria-label=\"{label}\"]"), ("done", {"answer": "selected"})], "variants": [("Option A",), ("Option B",), ("Subscribe",), ("Agree",), ("Remember me",)]},
    {"type": "checkbox-multiple", "goal": "Select {labels}", "steps": [("click", "#{id1}"), ("click", "#{id2}"), ("done", {"answer": "selected"})], "variants": [("opt1", "opt2"), ("a", "b"), ("x", "y"), ("foo", "bar"), ("yes", "no")]},

    # ── TEXT ENTRY ──
    {"type": "enter-text", "goal": "Type {text} into the text field", "steps": [("type", {"selector": "input[type=text]", "text": "{text}"}), ("press_key", {"key": "Enter"}), ("done", {"answer": "{text}"})], "variants": [("Hello World",), ("test@example.com",), ("John Doe",), ("123 Main St",), ("password123",), ("admin",), ("search query",)]},
    {"type": "enter-number", "goal": "Enter the number {num}", "steps": [("type", {"selector": "input[type=number]", "text": "{num}"}), ("done", {"answer": "{num}"})], "variants": [(42,), (100,), (3.14,), (0,), (-5,), (1000,)]},
    {"type": "enter-date", "goal": "Enter the date {date}", "steps": [("type", {"selector": "input[type=date]", "text": "{date}"}), ("done", {"answer": "{date}"})], "variants": [("2026-01-15",), ("2026-07-30",), ("2025-12-25",), ("2026-03-20",), ("2027-01-01",)]},
    {"type": "enter-email", "goal": "Fill in the email field with {email}", "steps": [("type", {"selector": "input[type=email]", "text": "{email}"}), ("done", {"answer": "{email}"})], "variants": [("user@gmail.com",), ("john@company.com",), ("test@example.org",), ("admin@site.net",), ("info@business.io",)]},
    {"type": "enter-password", "goal": "Type the password into the password field", "steps": [("type", {"selector": "input[type=password]", "text": "mypassword"}), ("done", {"answer": "entered"})], "variants": [(), ()]},

    # ── FORM FILLING ──
    {"type": "login-form", "goal": "Log in with username {user} and password {pass}", "steps": [("type", {"selector": "#username", "text": "{user}"}), ("type", {"selector": "#password", "text": "{pass}"}), ("click", "#login-btn"), ("done", {"answer": "logged in"})], "variants": [("admin", "admin123"), ("user1", "pass1"), ("john", "secret!"), ("test", "letmein"), ("demo", "demo123")]},
    {"type": "signup-form", "goal": "Sign up with name {name}, email {email}", "steps": [("type", {"selector": "#name", "text": "{name}"}), ("type", {"selector": "#email", "text": "{email}"}), ("click", "#signup-btn"), ("done", {"answer": "signed up"})], "variants": [("Alice", "alice@test.com"), ("Bob", "bob@test.com"), ("Carol", "carol@test.com"), ("Dave", "dave@test.com"), ("Eve", "eve@test.com")]},
    {"type": "search-form", "goal": "Search for {query}", "steps": [("type", {"selector": "input[type=search]", "text": "{query}"}), ("click", "button[type=submit]"), ("done", {"answer": "{query}"})], "variants": [("machine learning",), ("React tutorial",), ("best restaurants",), ("weather today",), ("Python jobs",), ("used cars",), ("flight deals",), ("movie times",)]},

    # ── SELECT/DROPDOWN ──
    {"type": "select-option", "goal": "Select {option} from the dropdown", "steps": [("select", {"selector": "select", "value": "{option}"}), ("done", {"answer": "{option}"})], "variants": [("option1",), ("option2",), ("A",), ("B",), ("C",), ("high",), ("medium",), ("low",), ("1",), ("2",)]},
    {"type": "select-country", "goal": "Select country {country}", "steps": [("select", {"selector": "#country", "value": "{country}"}), ("done", {"answer": "{country}"})], "variants": [("US",), ("UK",), ("CA",), ("DE",), ("FR",), ("JP",), ("AU",), ("BR",), ("IN",), ("TH",)]},
    {"type": "select-category", "goal": "Choose category {cat}", "steps": [("select", {"selector": "#category", "value": "{cat}"}), ("done", {"answer": "{cat}"})], "variants": [("electronics",), ("clothing",), ("books",), ("sports",), ("music",), ("software",), ("services",), ("automotive",)]},

    # ── NAVIGATION ──
    {"type": "navigate-tabs", "goal": "Switch to the {tab} tab", "steps": [("click", ".tab-{tab}"), ("done", {"answer": "{tab}"})], "variants": [("home",), ("profile",), ("settings",), ("billing",), ("notifications",), ("security",), ("help",)]},
    {"type": "pagination", "goal": "Go to page {num}", "steps": [("click", ".page-{num}"), ("done", {"answer": "{num}"})], "variants": [(2,), (3,), (4,), (5,), ("next",), ("prev",), ("last",)]},
    {"type": "breadcrumb", "goal": "Navigate to {section} via breadcrumb", "steps": [("click", ".breadcrumb .{section}"), ("done", {"answer": "{section}"})], "variants": [("home",), ("products",), ("category",), ("account",), ("dashboard",)]},

    # ── MULTI-STEP ──
    {"type": "multi-search-select", "goal": "Search for {query} and select result {num}", "steps": [("type", {"selector": "input[type=search]", "text": "{query}"}), ("click", "button[type=submit]"), ("click", ".result:nth-child({num}) a"), ("done", {"answer": "{query}"})], "variants": [("laptops", 1), ("phones", 2), ("books", 3), ("shoes", 1), ("headphones", 2)]},
    {"type": "multi-login-dashboard", "goal": "Login and navigate to dashboard", "steps": [("type", {"selector": "#username", "text": "{user}"}), ("type", {"selector": "#password", "text": "{pass}"}), ("click", "#login-btn"), ("wait", {"ms": 2000}), ("click", ".nav-dashboard"), ("done", {"answer": "dashboard"})], "variants": [("admin", "admin123"), ("user", "pass123")]},
    {"type": "multi-filter-sort", "goal": "Filter by {filter} and sort by {sort}", "steps": [("select", {"selector": "#filter", "value": "{filter}"}), ("select", {"selector": "#sort", "value": "{sort}"}), ("click", "#apply"), ("done", {"answer": "filtered"})], "variants": [("category", "price"), ("brand", "rating"), ("size", "name"), ("color", "newest"), ("price", "popular")]},

    # ── EXTRACT/VERIFY ──
    {"type": "read-text", "goal": "Read the text from the {element}", "steps": [("extract", {"selector": ".{element}"}), ("done", {"answer": "extracted"})], "variants": [("title",), ("description",), ("price",), ("status",), ("message",)]},
    {"type": "read-table", "goal": "Get the value from row {row} column {col}", "steps": [("extract", {"selector": "table tr:nth-child({row}) td:nth-child({col})"}), ("done", {"answer": "read"})], "variants": [(1, 1), (1, 2), (2, 1), (2, 3), (3, 2)]},

    # ── EMAIL TASKS ──
    {"type": "email-inbox", "goal": "Open the email from {sender}", "steps": [("click", ".email-from-{sender}"), ("done", {"answer": "opened"})], "variants": [("alice@c.com",), ("bob@c.com",), ("admin@site.com",), ("support@co.com",), ("newsletter@co.com",)]},
    {"type": "email-reply", "goal": "Reply to the email saying {message}", "steps": [("click", "#reply-btn"), ("type", {"selector": "#reply-body", "text": "{message}"}), ("click", "#send-reply"), ("done", {"answer": "replied"})], "variants": [("Thanks!",), ("Got it!",), ("Will do.",), ("Sounds good.",), ("On it.")]},
    {"type": "email-star", "goal": "Star the email about {topic}", "steps": [("click", ".email-star-{topic}"), ("done", {"answer": "starred"})], "variants": [("meeting",), ("invoice",), ("report",), ("update",), ("alert",)]},

    # ── SOCIAL MEDIA ──
    {"type": "social-like", "goal": "Like the post by {author}", "steps": [("click", ".like-{author}"), ("done", {"answer": "liked"})], "variants": [("user1",), ("user2",), ("author",), ("friend",), ("colleague",)]},
    {"type": "social-comment", "goal": "Comment {text} on the post", "steps": [("click", ".comment-btn"), ("type", {"selector": ".comment-input", "text": "{text}"}), ("click", ".submit-comment"), ("done", {"answer": "commented"})], "variants": [("Great post!",), ("Interesting!",), ("Thanks for sharing!",), ("I agree!",), ("Nice work!")]},
    {"type": "social-follow", "goal": "Follow the user {user}", "steps": [("click", ".follow-{user}"), ("done", {"answer": "followed"})], "variants": [("user1",), ("influencer",), ("brand",), ("friend",), ("expert",)]},

    # ── SORTING/FILTERING ──
    {"type": "sort-asc", "goal": "Sort results in ascending order", "steps": [("click", "#sort-asc"), ("done", {"answer": "sorted"})], "variants": [(), ()]},
    {"type": "sort-desc", "goal": "Sort results in descending order", "steps": [("click", "#sort-desc"), ("done", {"answer": "sorted"})], "variants": [(), ()]},
    {"type": "filter-active", "goal": "Show only active items", "steps": [("click", "#filter-active"), ("done", {"answer": "filtered"})], "variants": [(), ()]},

    # ── TIMING ──
    {"type": "wait-load", "goal": "Wait for the page to load", "steps": [("wait", {"ms": 3000}), ("extract", {"selector": ".loaded"}), ("done", {"answer": "loaded"})], "variants": [(), ()]},
    {"type": "wait-element", "goal": "Wait for element {el} to appear", "steps": [("wait", {"ms": 2000}), ("click", ".{el}"), ("done", {"answer": "seen"})], "variants": [("dynamic-content",), ("result",), ("popup",), ("confirmation",), ("status",)]},

    # ── DYNAMIC CONTENT ──
    {"type": "autocomplete", "goal": "Search {query} and select the autocomplete suggestion", "steps": [("type", {"selector": "input[type=search]", "text": "{query}"}), ("wait", {"ms": 1000}), ("click", ".autocomplete-item:first-child"), ("done", {"answer": "{query}"})], "variants": [("ja",), ("py",), ("rea",), ("doc",), ("hel",)]},
    {"type": "typeahead", "goal": "Type {text} and pick suggestion {suggestion}", "steps": [("type", {"selector": ".typeahead", "text": "{text}"}), ("wait", {"ms": 500}), ("click", ".suggestion-{suggestion}"), ("done", {"answer": "{suggestion}"})], "variants": [("New", "New York"), ("San", "San Francisco"), ("Los", "Los Angeles"), ("Chi", "Chicago"), ("Hou", "Houston")]},

    # ── DRAG & DROP ──
    {"type": "drag-item", "goal": "Drag item {id} to position {pos}", "steps": [("click", "#item-{id}"), ("click", ".drop-zone-{pos}"), ("done", {"answer": "dragged"})], "variants": [(1, 2), (2, 3), (3, 1), (4, 2), (5, 1)]},

    # ── SCROLL ──
    {"type": "scroll-down", "goal": "Scroll down to see more content", "steps": [("scroll", {"direction": "down"}), ("wait", {"ms": 500}), ("extract", {"selector": ".new-content"}), ("done", {"answer": "scrolled"})], "variants": [(), ()]},
    {"type": "scroll-find", "goal": "Scroll to find element {el}", "steps": [("scroll", {"direction": "down"}), ("scroll", {"direction": "down"}), ("click", ".{el}"), ("done", {"answer": "found"})], "variants": [("target",), ("result",), ("item",), ("link",), ("image",)]},
]

def tc(name, args):
    return {"type": "function", "function": {"name": name, "arguments": json.dumps(args)}}

def tr(name, content):
    return {"role": "tool", "content": content, "name": name}

random.seed(42)
examples = []

for task in TASKS:
    for variant in task["variants"]:
        goal = task["goal"]
        # Fill template
        for i, v in enumerate(variant):
            key = ["label", "id", "color", "shape", "pos", "btn", "text", "num", "date", "email", "name", "user", "pass", "query", "option", "country", "cat", "tab", "section", "filter", "sort", "row", "col", "sender", "message", "topic", "author", "el", "suggestion", "pos_num"][i % 30]
            goal = goal.replace("{" + key + "}", str(v))

        msgs = [
            {"role": "system", "content": "You are a browser automation agent. Complete web tasks using the provided browser tools."},
            {"role": "user", "content": goal},
        ]

        steps = []
        for action_name, action_args in task["steps"]:
            filled_args = {}
            if isinstance(action_args, dict):
                for k, v in action_args.items():
                    if isinstance(v, str) and "{" in v:
                        for i, vv in enumerate(variant):
                            key = ["label", "id", "color", "shape", "pos", "btn", "text", "num", "date", "email", "name", "user", "pass", "query", "option", "country", "cat", "tab", "section", "filter", "sort", "row", "col", "sender", "message", "topic", "author", "el", "suggestion", "pos_num"][i % 30]
                            v = v.replace("{" + key + "}", str(vv))
                    filled_args[k] = v
            elif isinstance(action_args, str):
                filled = action_args
                for i, vv in enumerate(variant):
                    key = ["label", "id", "color", "shape", "pos", "btn", "text", "num", "date", "email", "name", "user", "pass", "query", "option", "country", "cat", "tab", "section", "filter", "sort", "row", "col", "sender", "message", "topic", "author", "el", "suggestion", "pos_num"][i % 30]
                    filled = filled.replace("{" + key + "}", str(vv))
                filled_args = {"target": filled} if action_name == "click" else {"text": filled}

            steps.append((action_name, filled_args))

        for action_name, filled_args in steps:
            msgs.append({"role": "assistant", "content": None, "tool_calls": [tc(action_name, filled_args)]})
            resp_data = filled_args
            msgs.append(tr(action_name, json.dumps(resp_data)))

        examples.append({"messages": msgs, "tools": TOOLS})

# Add irrelevance examples
irrelevance_questions = [
    "What is the capital of France?", "Write a poem about AI.",
    "Explain quantum computing.", "What's the meaning of life?",
    "Tell me a joke.", "How do I bake a cake?",
    "What is 2+2?", "Translate 'hello' to Thai.",
    "Who invented the telephone?", "What's your favorite color?",
    "How does photosynthesis work?", "Define recursion.",
    "What is the speed of light?", "Who painted the Mona Lisa?",
    "What is the largest ocean?", "How tall is Mount Everest?",
    "When was the first iPhone released?", "What causes rainbows?",
    "What is machine learning?", "Tell me about the solar system.",
    "What is blockchain?", "How do vaccines work?",
    "What are black holes?", "What is the stock market?",
]

for q in irrelevance_questions:
    examples.append({"messages": [
        {"role": "system", "content": "You are a browser automation agent. Only perform web browsing tasks using browser tools."},
        {"role": "user", "content": q},
        {"role": "assistant", "content": "I'm a browser agent. I can navigate pages, click buttons, fill forms, extract content, and handle browser interactions. Please give me a web task to do using my browser tools."}],
    })

random.shuffle(examples)
ds = Dataset.from_list(examples)
ds.push_to_hub("Nanthasit/sakthai-coder-browser", split="train")
print(f"Pushed {len(examples)} examples ({len(examples)-len(irrelevance_questions)} browser + {len(irrelevance_questions)} irrelevance)")
print(f"Dataset: Nanthasit/sakthai-coder-browser")