File size: 32,299 Bytes
232313d
 
 
 
 
 
 
 
 
 
 
 
d25cd8a
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
"""Browser skill of Jev Skills (evaluation only): which page element should the agent act on next, and how.

Each item is one step of a web task in the Mind2Web style: a user goal, a short action history and a simplified page (an
accessibility-tree style list of 5-30 candidate elements with tag, text and attributes). Gold comes from code: the page
is built from a task template that contains the correct element, then distractors are added (same-role elements,
near-synonym labels, elements that belong to other steps, ads, navigation and footer links).

Questions: `element` (choice over the candidate elements), `operation` (choice click / type / select) and, for type /
select steps, `value` (choice over candidate values: the right one and near ones).

Eight domains (food delivery, event tickets, ride hailing, fitness classes, insurance claims, pet adoption, utility
billing, conference registration); step kinds search / pick / fill / select / submit; three difficulty tiers (number of
candidates 5-10 / 11-19 / 20-30 and how many near-synonym distractors). A standalone generator: gold is computed by code from the task template.
"""

import gzip
import hashlib
import json
import random

import bench_common as X
from bench_common import choice, onehot

VERSION = "v1"
BENCH = "BrowserBench"
LICENSE = "CC0-1.0"
SIZE = 600
TIERS = {"easy": (5, 10, 0), "medium": (11, 19, 3), "hard": (20, 30, 7)}  # candidates lo, hi, max near distractors
OPERATIONS = {"click": "Click (or press) the element.", "type": "Type text into an input field.",
              "select": "Choose an option from a dropdown (select) element."}
Q_ELEMENT = ("Which element should the agent act on next to make progress on the goal?",
             "Pick the page element the next action should target.",
             "Given the goal and the steps so far, which element is the right one to act on now?")
Q_OP = ("What kind of action is the next step?", "Which operation should the agent perform next?")
Q_VALUE = ("What value should the agent enter or choose?", "Which value does the goal call for in this step?")

GENERIC_NAV = ["Home", "Help", "Sign in", "My account", "Notifications", "Language: English", "Contact us"]
GENERIC_FOOT = ["Privacy policy", "Terms of service", "Careers", "About us", "Accessibility", "Cookie settings",
                "Press", "Site map", "Investors", "Gift cards"]
GENERIC_ADS = ["Sponsored: upgrade to Premium and save 30%", "Ad: win a free weekend getaway, enter now",
               "Sponsored: download our mobile app", "Ad: refer a friend and earn rewards"]


def D(site, noun, cart, ents, search_ph, pick, texts, selects, submit, nav, ads, goals_pick, goals_search):
    return dict(site=site, noun=noun, cart=cart, ents=ents, search_ph=search_ph, pick=pick, texts=texts,
                selects=selects, submit=submit, nav=nav, ads=ads, goals_pick=goals_pick, goals_search=goals_search)


DOMAINS = {
    "food_delivery": D(
        "Forkly", "dish", "basket",
        [("Margherita pizza", "Napoli Corner"), ("Margherita pizza", "Slice House"), ("Pad thai", "Bangkok Bowl"),
         ("Pad thai", "Noodle Lane"), ("Chicken burrito", "Casa Verde"), ("Chicken burrito bowl", "Casa Verde"),
         ("Veggie ramen", "Tokyo Steam"), ("Spicy ramen", "Tokyo Steam"), ("Caesar salad", "Green Fork"),
         ("Greek salad", "Green Fork"), ("Falafel wrap", "Beirut Bites"), ("Falafel plate", "Beirut Bites"),
         ("Beef pho", "Saigon Kitchen"), ("Chicken pho", "Saigon Kitchen"), ("Tiramisu", "Napoli Corner")],
        "Search dishes or restaurants", "Add {n} from {g} to basket",
        {"Delivery address": ["14 Elm Street", "220 Harbor Road", "7 Birch Court", "81 Mill Lane"],
         "Billing address": ["14 Elm Street", "9 Station Square", "52 Oak Avenue"],
         "Delivery instructions": ["leave at the door", "ring twice", "call on arrival"],
         "Promo code": ["WELCOME10", "SPRING5", "FREESHIP"], "Contact phone": ["555-0142", "555-0178", "555-0199"],
         "Gift message": ["happy birthday", "thank you", "enjoy the dinner"]},
        {"Delivery time": ["As soon as possible", "In 30 minutes", "In 1 hour", "Tomorrow noon"],
         "Delivery speed": ["Standard", "Priority", "Saver"], "Tip": ["No tip", "10%", "15%", "20%"],
         "Utensils": ["None", "Include cutlery", "Include chopsticks"], "Payment method": ["Card", "Cash", "Wallet"]},
        ("Place order", "place the order", ["Place scheduled order", "Save basket for later", "Place order for a friend",
                                           "Cancel order", "Place group order"]),
        ["Restaurants", "Grocery", "Offers", "Order history", "Basket"], GENERIC_ADS,
        ["Order the {n} from {g}", "Add the {n} from {g} to your basket", "Get a {n} from {g}"],
        ["Look up {n}", "Find {n} to order", "Search for {n}"]),
    "event_tickets": D(
        "Showpass", "event", "cart",
        [("Jazz Night", "Blue Hall"), ("Jazz Night", "River Stage"), ("Comedy Slam", "Blue Hall"),
         ("Comedy Slam Late Show", "Blue Hall"), ("Indie Rock Festival", "Dockside Arena"),
         ("Indie Rock Festival Day 2", "Dockside Arena"), ("Symphony Under Stars", "Park Amphitheatre"),
         ("Ballet Gala", "Grand Opera"), ("Ballet Gala Matinee", "Grand Opera"), ("Stand-up Special", "River Stage"),
         ("Film Score Live", "Grand Opera"), ("Folk Evening", "Park Amphitheatre"), ("Opera Classics", "Grand Opera")],
        "Search events, artists or venues", "Buy tickets for {n} at {g}",
        {"Attendee name": ["Maria Lopez", "Tom Becker", "Aiko Sato", "Liam Byrne"],
         "Attendee email": ["maria@example.org", "tom.b@example.org", "aiko@example.org"],
         "Billing name": ["Maria Lopez", "Tom Becker", "Dana Wolfe"],
         "Billing email": ["billing@example.org", "accounts@example.org"],
         "Discount code": ["EARLYBIRD", "STUDENT15", "MEMBER20"], "Seat note": ["near the aisle", "wheelchair access", "front half"]},
        {"Ticket type": ["General admission", "VIP", "Student", "Senior"], "Ticket quantity": ["1", "2", "3", "4"],
         "Delivery method": ["E-ticket", "Mobile wallet", "Will call"], "Seating section": ["Floor", "Balcony", "Mezzanine"],
         "Event date": ["Fri 14 Mar", "Sat 15 Mar", "Sun 16 Mar", "Fri 21 Mar"]},
        ("Complete purchase", "complete the purchase", ["Complete purchase later", "Hold tickets for 10 minutes",
                                                       "Complete purchase as gift", "Cancel purchase", "Join waitlist"]),
        ["Concerts", "Theatre", "Sports", "My tickets", "Cart"], GENERIC_ADS,
        ["Buy tickets for {n} at {g}", "Get tickets to {n} at {g}", "Add {n} at {g} to your cart"],
        ["Look for {n}", "Find the event {n}", "Search for {n}"]),
    "ride_hailing": D(
        "Hopr", "ride", "trip",
        [("Airport transfer", "Terminal 1"), ("Airport transfer", "Terminal 2"), ("Economy ride", "City Centre"),
         ("Economy shared ride", "City Centre"), ("Comfort ride", "City Centre"), ("Comfort XL ride", "City Centre"),
         ("Scheduled pickup", "Central Station"), ("Scheduled pickup", "North Station"), ("Bike hire", "Riverside Dock"),
         ("Scooter hire", "Riverside Dock"), ("Wheelchair accessible ride", "City Centre"), ("Night ride", "Old Town")],
        "Where to?", "Book {n} from {g}",
        {"Pickup location": ["12 Market Street", "Central Station", "88 Lake Road", "Terminal 1"],
         "Drop-off location": ["Airport Terminal 2", "40 Pine Street", "Riverside Dock", "North Station"],
         "Pickup note": ["wait by the main entrance", "blue door", "call when outside"],
         "Rider name": ["Sam Ortiz", "Ines Costa", "Yuki Tanaka"], "Rider phone": ["555-0111", "555-0122", "555-0133"],
         "Promo code": ["FIRSTRIDE", "WEEKEND10", "COMMUTE5"]},
        {"Pickup time": ["Now", "In 15 minutes", "In 1 hour", "Tomorrow 8:00"], "Pickup date": ["Today", "Tomorrow", "Next Monday"],
         "Ride type": ["Economy", "Comfort", "XL", "Accessible"], "Passengers": ["1", "2", "3", "4"],
         "Payment method": ["Card", "Wallet", "Cash", "Company account"]},
        ("Confirm ride", "confirm the ride", ["Confirm ride for later", "Share ride details", "Confirm ride for a friend",
                                             "Cancel ride", "Confirm shared ride"]),
        ["Ride", "Rent a bike", "Trips", "Wallet", "Safety"], GENERIC_ADS,
        ["Book a {n} from {g}", "Book the {n} starting at {g}", "Order a {n} at {g}"],
        ["Enter {n} as the destination", "Search for {n}", "Look up {n}"]),
    "fitness_classes": D(
        "Pulse Studio", "class", "schedule",
        [("Morning Yoga", "Studio A"), ("Morning Yoga", "Studio B"), ("Power Yoga", "Studio A"), ("Spin 45", "Cycle Room"),
         ("Spin 60", "Cycle Room"), ("HIIT Express", "Main Floor"), ("HIIT Strength", "Main Floor"),
         ("Pilates Core", "Studio B"), ("Pilates Reformer", "Studio B"), ("Boxing Basics", "Main Floor"),
         ("Aqua Fit", "Pool"), ("Meditation Hour", "Studio A")],
        "Search classes or instructors", "Reserve {n} in {g}",
        {"Member name": ["Anna Kowal", "Ben Hughes", "Carla Reyes", "Dev Patel"],
         "Member email": ["anna@example.org", "ben@example.org", "carla@example.org"],
         "Guest name": ["Chris Doyle", "Elif Demir", "Noor Haddad"], "Guest email": ["chris@example.org", "elif@example.org"],
         "Emergency contact": ["555-0188", "555-0166", "555-0155"], "Injury notes": ["bad left knee", "none", "lower back pain"]},
        {"Class time": ["06:30", "08:00", "12:15", "18:00", "19:30"], "Class date": ["Mon 3 Mar", "Tue 4 Mar", "Wed 5 Mar", "Thu 6 Mar"],
         "Instructor": ["Priya", "Marcus", "Lena", "Jon"], "Membership plan": ["Monthly", "Annual", "Ten-class pack"],
         "Mat rental": ["No mat", "Rent a mat", "Mat and towel"]},
        ("Confirm booking", "confirm the booking", ["Confirm booking for a guest", "Join the waitlist", "Save for later",
                                                   "Cancel booking", "Confirm recurring booking"]),
        ["Schedule", "Memberships", "Instructors", "My bookings", "Shop"], GENERIC_ADS,
        ["Reserve a spot in {n} in {g}", "Book {n} in {g}", "Sign up for {n} in {g}"],
        ["Look for {n}", "Search for the class {n}", "Find {n}"]),
    "insurance_claims": D(
        "Safeharbor", "claim", "claim draft",
        [("Water damage claim", "Home policy"), ("Water damage claim", "Renters policy"), ("Theft claim", "Home policy"),
         ("Theft claim", "Auto policy"), ("Windscreen claim", "Auto policy"), ("Collision claim", "Auto policy"),
         ("Lost luggage claim", "Travel policy"), ("Trip cancellation claim", "Travel policy"),
         ("Dental claim", "Health policy"), ("Vision claim", "Health policy"), ("Pet vet claim", "Pet policy")],
        "Search policies or claims", "Start a {n} under {g}",
        {"Policy number": ["HP-440912", "AU-118203", "TR-771045", "RN-300871"],
         "Claim reference": ["CL-90314", "CL-77120", "CL-65099"], "Incident location": ["Maple Street garage", "Gate B14", "kitchen", "Route 9 junction"],
         "Contact phone": ["555-0120", "555-0137", "555-0149"], "Contact email": ["claims@example.org", "me@example.org"],
         "Damage description": ["burst pipe under sink", "cracked screen", "bag never arrived", "rear bumper dented"]},
        {"Incident date": ["Yesterday", "Last week", "Last month", "Choose a date"], "Report date": ["Today", "Yesterday"],
         "Claim type": ["Damage", "Theft", "Liability", "Medical"], "Preferred contact": ["Email", "Phone", "Post"],
         "Payout method": ["Bank transfer", "Cheque", "Repair voucher"]},
        ("Submit claim", "submit the claim", ["Submit claim later", "Save claim draft", "Submit claim on behalf of someone",
                                              "Withdraw claim", "Submit supplementary claim"]),
        ["Policies", "Claims", "Documents", "Payments", "Support"], GENERIC_ADS,
        ["Start the {n} under the {g}", "File a {n} for your {g}", "Open a {n} under the {g}"],
        ["Look up {n}", "Search for {n}", "Find the {n} form"]),
    "pet_adoption": D(
        "Pawfinder", "pet", "shortlist",
        [("Beagle puppy Milo", "Hillside Shelter"), ("Beagle puppy Milo", "Harbor Rescue"), ("Tabby cat Luna", "Hillside Shelter"),
         ("Tabby kitten Luna", "Harbor Rescue"), ("Labrador Rex", "Valley Rescue"), ("Labrador pup Rex", "Valley Rescue"),
         ("Rabbit Clover", "Hillside Shelter"), ("Parrot Kiwi", "Harbor Rescue"), ("Husky Nova", "Valley Rescue"),
         ("Husky mix Nova", "Valley Rescue"), ("Senior cat Oscar", "Hillside Shelter"), ("Guinea pig Peanut", "Harbor Rescue")],
        "Search pets by name or breed", "Add {n} at {g} to shortlist",
        {"Applicant name": ["Hana Novak", "Marcus Webb", "Rosa Vidal", "Omar Khalil"],
         "Applicant email": ["hana@example.org", "marcus@example.org", "rosa@example.org"],
         "Home address": ["5 Cedar Way", "310 Lake View", "18 Orchard Close"],
         "Vet name": ["Dr. Moreau", "Dr. Okafor", "Dr. Lindqvist"], "Vet phone": ["555-0101", "555-0102", "555-0103"],
         "Reason for adopting": ["lifelong companion", "company for our child", "active family"]},
        {"Visit date": ["Sat 8 Mar", "Sun 9 Mar", "Sat 15 Mar"], "Visit time": ["10:00", "11:30", "14:00", "16:00"],
         "Housing type": ["House with garden", "Apartment", "Farm"], "Other pets": ["None", "One dog", "One cat", "Several"],
         "Species filter": ["Dogs", "Cats", "Small animals", "Birds"]},
        ("Send application", "send the application", ["Send application later", "Save application draft",
                                                      "Send application for a friend", "Withdraw application", "Send enquiry only"]),
        ["Dogs", "Cats", "Small animals", "Shelters", "Success stories"], GENERIC_ADS,
        ["Add {n} at {g} to your shortlist", "Shortlist {n} at {g}", "Save {n} at {g} to your list"],
        ["Look for {n}", "Search for {n}", "Find {n}"]),
    "utility_billing": D(
        "Gridwell", "bill", "payment list",
        [("Electricity bill March", "Account 1204"), ("Electricity bill March", "Account 3388"), ("Gas bill March", "Account 1204"),
         ("Water bill Q1", "Account 1204"), ("Water bill Q2", "Account 1204"), ("Internet bill March", "Account 3388"),
         ("Electricity bill April", "Account 1204"), ("Waste collection fee", "Account 3388"), ("Gas bill April", "Account 3388"),
         ("Solar credit statement", "Account 1204")],
        "Search bills or accounts", "Pay {n} on {g}",
        {"Meter reading": ["48213", "10987", "73450", "20076"], "Account number": ["1204", "3388", "5521"],
         "Billing email": ["bills@example.org", "home@example.org", "me@example.org"],
         "Card number": ["4111 1111 1111 1111", "5500 0000 0000 0004"], "Payment note": ["March bill", "paid by landlord", "split with flatmate"],
         "Mobile number": ["555-0112", "555-0113", "555-0114"]},
        {"Payment date": ["Today", "On the due date", "Next Friday"], "Payment amount": ["Full balance", "Minimum due", "Other amount"],
         "Payment method": ["Bank account", "Credit card", "Direct debit"], "Bill delivery": ["Email", "Post", "Paperless app"],
         "Billing period": ["Last month", "Last 3 months", "Last year"]},
        ("Pay now", "pay it now", ["Pay later", "Schedule payment", "Pay on behalf of another account", "Cancel payment",
                                  "Pay partial amount"]),
        ["Bills", "Usage", "Payments", "Moving home", "Outages"], GENERIC_ADS,
        ["Pay the {n} on {g}", "Settle the {n} on {g}", "Open the {n} on {g} for payment"],
        ["Look up {n}", "Search for {n}", "Find the {n}"]),
    "conference_registration": D(
        "Summitly", "session", "agenda",
        [("Keynote: Future of Data", "Main Hall"), ("Keynote: Future of Data", "Overflow Room"), ("Workshop: Intro to Rust", "Room 12"),
         ("Workshop: Intro to Rust", "Room 14"), ("Workshop: Advanced Rust", "Room 12"), ("Panel: Open Source Funding", "Main Hall"),
         ("Panel: Open Source Funding Q&A", "Main Hall"), ("Talk: Scaling Queues", "Room 3"), ("Talk: Scaling Caches", "Room 3"),
         ("Lightning Talks", "Room 5"), ("Poster Session", "Atrium"), ("Mentor Lunch", "Atrium")],
        "Search sessions or speakers", "Add {n} in {g} to agenda",
        {"Full name": ["Elena Petrova", "Jonas Berg", "Mina Park", "Tariq Aziz"], "Work email": ["elena@example.org", "jonas@example.org", "mina@example.org"],
         "Company": ["Northwind", "Contoso Labs", "Initech", "Globex"], "Job title": ["Staff engineer", "Product manager", "Researcher"],
         "Dietary requirements": ["vegetarian", "vegan", "gluten free", "no restrictions"], "Badge name": ["Elena", "Jonas", "Mina"]},
        {"Ticket type": ["Full conference", "Day pass", "Workshop only", "Student"], "Day": ["Monday", "Tuesday", "Wednesday"],
         "T-shirt size": ["S", "M", "L", "XL"], "Hotel block": ["No hotel", "Hotel Aurora", "Hotel Meridian"],
         "Track": ["Data", "Systems", "Security", "Product"]},
        ("Complete registration", "complete the registration", ["Complete registration later", "Save registration draft",
                                                               "Complete registration for a colleague", "Cancel registration", "Join the waitlist"]),
        ["Schedule", "Speakers", "Venue", "Sponsors", "My agenda"], GENERIC_ADS,
        ["Add {n} in {g} to your agenda", "Save {n} in {g} to your agenda", "Register for {n} in {g}"],
        ["Look for {n}", "Search for {n}", "Find {n}"]),
}
KINDS = ["search", "pick", "fill", "select", "submit"]
# per domain: (attribute of an item card, its values); two sections a form field can sit in (the same label appears in both)
VARIANTS = {
    "food_delivery": ("size", ["small", "medium", "large", "family"]),
    "event_tickets": ("date", ["Fri 14 Mar", "Sat 15 Mar", "Sun 16 Mar", "Fri 21 Mar"]),
    "ride_hailing": ("departure", ["06:30", "09:00", "13:15", "18:45"]),
    "fitness_classes": ("slot", ["07:00", "12:15", "18:00", "19:30"]),
    "insurance_claims": ("excess", ["100", "250", "500", "1000"]),
    "pet_adoption": ("age", ["under 1 year", "1-3 years", "4-7 years", "8+ years"]),
    "utility_billing": ("period", ["January", "February", "March", "April"]),
    "conference_registration": ("time", ["09:00", "11:30", "14:00", "16:30"]),
}
SECTIONS = {
    "food_delivery": ("Delivery details", "Gift recipient"), "event_tickets": ("Attendee", "Gift recipient"),
    "ride_hailing": ("Rider", "Passenger"), "fitness_classes": ("Member", "Guest"),
    "insurance_claims": ("Policyholder", "Third party"), "pet_adoption": ("Applicant", "Reference"),
    "utility_billing": ("Account holder", "Authorised person"), "conference_registration": ("Attendee", "Colleague"),
}
NEUTRAL = ["{label}: {value}", "{value} for {label_l}", "Make the {label_l} {value}"]


def _words(s):
    return set(s.lower().replace(":", "").split())


def _near(label, pool, k, rng):
    """Labels of `pool` closest to `label` by shared words, then random."""
    others = [p for p in pool if p != label]
    rng.shuffle(others)
    others.sort(key=lambda p: -len(_words(p) & _words(label)))
    return others[:k]


class El:
    """An interactive element. `ctx` is the text of a non-interactive label / heading printed on the line above it in the
    page outline (the element itself then carries no readable name)."""

    def __init__(self, tag, text, ctx=None, **attrs):
        self.tag, self.text, self.ctx, self.attrs = tag, text, ctx, attrs

    def line(self, i=None):
        a = "".join(f' {k.replace("_", "-")}="{v}"' for k, v in self.attrs.items())
        t = f' "{self.text}"' if self.text else ""
        return (f"[{i}] " if i is not None else "") + f"{self.tag}{t}{a}"


def make_step(dom: dict, kind: str, tier: str, rng: random.Random, domain: str) -> dict:
    """One step: goal, history, elements (shuffled into page order), the correct element index, operation, value pool."""
    lo, hi, max_near = TIERS[tier]
    total = rng.randint(lo, hi)
    n_near = rng.randint(max_near // 2 if max_near else 0, max_near) if max_near else 0
    site, noun, hist, near, filler = dom["site"], dom["noun"], [], [], []
    sec_a, sec_b = SECTIONS[domain]
    vattr, vvals = VARIANTS[domain]
    op, value, values, gold = "click", None, [], None
    texts, selects = dom["texts"], dom["selects"]
    if kind == "search":
        name = rng.choice(dom["ents"])[0]
        goal = rng.choice(dom["goals_search"]).format(n=name)
        scoped = tier != "easy" and rng.random() < 0.7
        gold = El("input", None, type="search", placeholder=dom["search_ph"], **({"scope": noun + "s"} if scoped else {}))
        op, value, values = "type", name, sorted({e[0] for e in dom["ents"]})
        pool_labels = [dom["search_ph"], "Search help articles", "Search by location", "Search past orders", "Search the site map",
                       "Search for a store", "Search saved items"]
        near = [El("input", None, type="search", placeholder=p) for p in _near(dom["search_ph"], pool_labels, n_near, rng)]
        near += [El("input", None, type="text", placeholder="Your email for offers")][: 1 if n_near else 0]
        if scoped:
            near.append(El("input", None, type="search", placeholder=dom["search_ph"], scope="help centre"))
            near.append(El("input", None, type="search", placeholder=dom["search_ph"], scope="whole site"))
            goal = f"In the {noun}s search, " + goal[0].lower() + goal[1:]
        hist = ["Opened the " + site + " home page"] if rng.random() < 0.7 else []
    elif kind == "pick":
        ent = rng.choice(dom["ents"])
        goal = rng.choice(dom["goals_pick"]).format(n=ent[0], g=ent[1])

        vv = rng.choice(vvals)
        cheapest = tier != "easy" and rng.random() < 0.5
        goal += ", choosing the cheapest option" if cheapest else f", with the {vattr} {vv}"
        prices = rng.sample(range(500, 6000, 25), 12)

        obf = tier == "hard" or (tier == "medium" and rng.random() < 0.75)

        def card(e, v=None):
            t = dom["pick"].format(n=e[0], g=e[1])
            attrs = {vattr.replace(" ", "_"): v or rng.choice(vvals), "price": f"{prices.pop() / 100:.2f}"}
            if obf:  # generic button; the item's title is a text line above it
                return El("button", "Add to " + dom["cart"], ctx=f"{e[0]} - {e[1]}", **attrs)
            return El("button", t, **attrs)

        gold = card(ent, vv)
        others = [e for e in dom["ents"] if e != ent]
        rng.shuffle(others)
        others.sort(key=lambda e: -((e[0] == ent[0]) * 2 + (e[1] == ent[1]) + len(_words(e[0]) & _words(ent[0]))))
        pick_n = others[:max(n_near, 0) if n_near else 2]
        near = [card(e) for e in pick_n]
        if tier != "easy":  # the same item with other variants
            twins = [card(ent, v) for v in rng.sample([v for v in vvals if v != vv], 2 if tier == "medium" else 3)]
            if cheapest:  # gold = the cheapest card of the item
                grp = [gold] + twins
                new_gold = min(grp, key=lambda el: float(el.attrs["price"]))
                near += [x for x in grp if x is not new_gold]
                gold = new_gold
            else:
                near += twins
        near += [El("a", f"View details: {e[0]} ({e[1]})", href="/item") for e in [ent] + pick_n[:2]][: 1 + (n_near > 2)]
        hist = rng.choice([[f"Searched for {ent[0].split()[0]}"], [f"Opened {ent[1]}"], ["Opened the " + site + " home page"]])
    else:  # fill / select / submit: a multi-part goal, the history says which parts are done; act on the next one
        n_sub = {"easy": 1, "medium": rng.randint(2, 3), "hard": rng.randint(3, 4)}[tier]
        want_text = {"fill": True, "select": False}.get(kind)
        subs = []  # (label, is_text, value)
        labels_t, labels_s = list(texts), list(selects)
        rng.shuffle(labels_t), rng.shuffle(labels_s)
        for j in range(n_sub):
            is_text = rng.random() < 0.5 if j else (want_text if want_text is not None else rng.random() < 0.5)
            pool = labels_t if is_text else labels_s
            if not pool:
                pool = labels_s if is_text else labels_t
                is_text = not is_text
            lab = pool.pop()
            subs.append((lab, is_text, rng.choice((texts if is_text else selects)[lab])))
        if kind == "submit":
            k_done = n_sub
        else:
            # the next part must be of the requested kind: put such a part at the position k_done
            k_done = rng.randrange(n_sub)
            lab, is_text, v = subs[k_done]
            if is_text != (kind == "fill"):
                pool = labels_t if kind == "fill" else labels_s
                if pool:
                    lab = pool.pop()
                    subs[k_done] = (lab, kind == "fill", rng.choice((texts if kind == "fill" else selects)[lab]))
                else:
                    kind = "fill" if subs[k_done][1] else "select"
        correct, phrase, same = dom["submit"]

        def part(sub):
            lab, is_text, v = sub
            return (f"enter {v} as the {lab.lower()}" if is_text else f"set the {lab.lower()} to {v}")

        words = [part(x) for x in subs]
        goal = ("First " + ", then ".join(words) + f", and finally {phrase}") if n_sub > 1 else \
            rng.choice([words[0].capitalize(), f"{words[0].capitalize()} and {phrase}", f"You need to {words[0]}"])
        if n_sub == 1 and kind == "submit":
            goal = f"The {noun} form is complete. Now {phrase}"
        for lab, is_text, v in subs[:k_done]:
            hist.append(("TYPE" if is_text else "SELECT") + f" [{lab}] -> {v}")
        if not hist and rng.random() < 0.5:
            hist = [f"Opened the {noun} form"]

        obf_p = {"easy": 0.0, "medium": 0.75, "hard": 1.0}[tier]

        def elem(lab, is_text):
            if rng.random() < obf_p:  # no readable name on the element: the label is a text line above it
                nm = f"f{rng.randint(100, 999)}"
                return El("input", None, ctx=lab, type="text", name=nm) if is_text else \
                    El("select", None, ctx=lab, name=nm, options="|".join(selects[lab]))
            nm = lab.lower().replace(" ", "_")
            return El("input", None, type="text", name=nm, aria_label=lab) if is_text else \
                El("select", None, name=nm, aria_label=lab, options="|".join(selects[lab]))

        if kind == "submit":
            gold = El("button", correct, type="submit")
            op = "click"
            near = [El("button", x, type="submit" if rng.random() < 0.5 else "button") for x in same[:max(n_near, 2)]]
        else:
            lab, is_text, value = subs[k_done]
            gold = elem(lab, is_text)
            op = "type" if is_text else "select"
            values = list((texts if is_text else selects)[lab])
            others = [x for j, x in enumerate(subs) if j != k_done]
            near = [elem(x[0], x[1]) for x in others]  # the elements of the other parts of the goal
            pool = list(texts) if is_text else list(selects)
            near += [elem(p, is_text) for p in _near(lab, pool, n_near or 1, rng) if p not in [x[0] for x in subs]]
            near.append(El("button", correct, type="submit"))
    # filler: navigation, footer, ads, cookie banner, other-step elements
    navs = [El("a", t, href="/" + t.lower().replace(" ", "-")) for t in dom["nav"] + GENERIC_NAV]
    foots = [El("a", t, href="/" + t.lower().replace(" ", "-"), region="footer") for t in GENERIC_FOOT]
    ads = [El("a", t, region="advertisement") for t in dom["ads"]]
    other = []
    if kind != "search":
        other.append(El("input", None, type="search", placeholder="Search"))
    if kind not in ("pick",):
        other += [El("button", dom["pick"].format(n=e[0], g=e[1])) for e in rng.sample(dom["ents"], 2)]
    cookie = [El("button", "Accept all cookies"), El("button", "Reject non-essential cookies")]
    rng.shuffle(navs), rng.shuffle(foots), rng.shuffle(ads), rng.shuffle(other)
    bank = navs[:4] + foots[:3] + ads[:1] + other + cookie[:1]  # priority order, extended below
    rest = navs[4:] + foots[3:] + ads[1:] + cookie[1:]
    rng.shuffle(rest)
    need = max(0, total - 1 - len(near))
    fill = (bank + rest)[:need]
    # trim near distractors if the budget is too small
    if len(near) + 1 > total:
        near = near[: total - 1]
    els = [gold] + near + fill
    order = list(range(len(els)))
    # page order: nav first, main content, footer last
    def rank(i):
        e = els[i]
        if e.attrs.get("region") == "footer":
            return 3
        if e.attrs.get("region") == "advertisement":
            return rng.choice((0, 1, 2))
        if e in fill and e.tag == "a" and not e.attrs.get("region"):
            return 0
        return 1 + rng.random()
    rng.shuffle(order)
    order.sort(key=rank)
    return {"goal": goal, "history": hist, "els": [els[i] for i in order], "gold": order.index(0), "op": op,
            "value": value, "values": values, "kind": kind}


def render(step: dict, dom: dict, rng: random.Random, idx: int, domain: str, tier: str) -> dict:
    ids = rng.sample(range(10, 10 + 4 * len(step["els"])), len(step["els"]))
    ids.sort()
    lines = [(f'    text "{e.ctx}"\n' if e.ctx else "") + e.line(i) for e, i in zip(step["els"], ids)]
    hist = "\n".join(f"{j}. {h}" for j, h in enumerate(step["history"], 1)) or "(none yet)"
    state = (f"Website: {dom['site']}\nGoal: {step['goal']}\n\nSteps taken so far:\n{hist}\n\n"
             f"Current page ({len(step['els'])} interactive elements, [id] tag \"text\" attributes):\n" + "\n".join(lines))
    crit = {str(i): e.line() for e, i in zip(step["els"], ids)}
    gid = str(ids[step["gold"]])
    qs = {"element": choice(rng.choice(Q_ELEMENT), crit), "operation": choice(rng.choice(Q_OP), OPERATIONS)}
    ts = {"element": onehot(crit, gid), "operation": onehot(OPERATIONS, step["op"])}
    if step["value"] is not None:
        vs = [v for v in dict.fromkeys(step["values"]) if v != step["value"]]
        rng.shuffle(vs)
        opts = [step["value"]] + vs[:3]
        rng.shuffle(opts)
        vcrit = {f"v{j}": v for j, v in enumerate(opts)}
        gold_v = next(k for k, v in vcrit.items() if v == step["value"])
        qs["value"] = choice(rng.choice(Q_VALUE), vcrit)
        ts["value"] = onehot(vcrit, gold_v)
    it = X._item(f"browser-{domain}-{tier}-{idx:04d}", "browser", f"browser:{domain}:{tier}", state, qs, ts, LICENSE,
                 f"{step['goal']} {' '.join(step['history'])}")
    it.update(bench=BENCH, split="generated", kind=step["kind"], n_elements=len(lines))
    return it


def build(seed: int = 0, size: int = SIZE) -> tuple[list, dict]:
    doms = sorted(DOMAINS)
    per = size // (len(doms) * len(TIERS))
    items, seen = [], set()
    for d in doms:
        for t in TIERS:
            rng = random.Random(f"{seed}:{d}:{t}")
            k = 0
            tries = 0
            while k < per and tries < per * 50:
                tries += 1
                kind = KINDS[k % len(KINDS)]
                step = make_step(DOMAINS[d], kind, t, rng, d)
                it = render(step, DOMAINS[d], rng, k, d, t)
                h = hashlib.sha1(it["state"].encode()).hexdigest()
                if h in seen:
                    continue
                seen.add(h)
                items.append(it)
                k += 1
    info = {"version": VERSION, "seed": seed, "counts": {"browser": len(items)}}
    return items, info


def write(items: list, info: dict, outdir: str = ".") -> list:
    import os

    p = os.path.join(outdir, f"browser_{VERSION}_items.json.gz")
    with gzip.open(p, "wt") as fh:
        json.dump(items, fh, ensure_ascii=False)
    return [p]


if __name__ == "__main__":
    import argparse

    ap = argparse.ArgumentParser(description="build the Jev Skills browser items")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--out", default=".")
    a = ap.parse_args()
    its, inf = build(a.seed)
    print(json.dumps(inf))
    print(write(its, inf, a.out))