sileod commited on
Commit
90e03a9
·
verified ·
1 Parent(s): fd6920e

Upload repackage.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. repackage.py +163 -0
repackage.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Text-only Mind2Web preparation: native actions and DOM candidates, no screenshots."""
2
+ from collections import Counter
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import random
7
+ import re
8
+
9
+ from datasets import Dataset, DatasetDict, Features, Sequence, Value
10
+ from huggingface_hub import snapshot_download
11
+
12
+ SOURCE = 'osunlp/Mind2Web'
13
+ REVISION = '17ece8eb89862368edc0cc806acee6fca5163474'
14
+
15
+
16
+ def page_html(action):
17
+ # Remove indentation between tags; retain all native DOM content and node IDs.
18
+ return re.sub(r'>\s+<', '><', action['cleaned_html']).strip()
19
+
20
+
21
+ def page_key(action):
22
+ return hashlib.sha256(page_html(action).encode()).hexdigest()
23
+
24
+
25
+ def trajectory_splits(trajectories, seed=42):
26
+ """80/10/10 hash partitions of trajectories connected by identical DOM snapshots."""
27
+ parents, pages = {}, {}
28
+ def root(key):
29
+ parents.setdefault(key, key)
30
+ if parents[key] != key:
31
+ parents[key] = root(parents[key])
32
+ return parents[key]
33
+ for trajectory in trajectories:
34
+ identity = trajectory['annotation_id']
35
+ root(identity)
36
+ for action in trajectory['actions']:
37
+ key = page_key(action)
38
+ if key in pages:
39
+ a, b = root(identity), root(pages[key])
40
+ parents[max(a, b)] = min(a, b)
41
+ pages[key] = identity
42
+ groups = {identity: root(identity) for identity in parents}
43
+ splits = {}
44
+ for identity, group in groups.items():
45
+ value = int(hashlib.sha256(f'{seed}:{group}'.encode()).hexdigest(), 16) % 100
46
+ splits[identity] = 'train' if value < 80 else 'validation' if value < 90 else 'test'
47
+ return splits, groups
48
+
49
+
50
+ def mind2web_record(trajectory, index, elements=False, seed=42):
51
+ """Gold flags/arguments stay out of inputs; alternative positives are never negatives."""
52
+ action = trajectory['actions'][index]
53
+ operation = action['operation']['op']
54
+ if operation not in ('CLICK', 'TYPE', 'SELECT'):
55
+ return None, 'unsupported_operation'
56
+ html = page_html(action)
57
+ if not html or not trajectory['confirmed_task'].strip():
58
+ return None, 'missing_context'
59
+ history = trajectory['action_reprs'][:index]
60
+ inputs = (f"Task: {trajectory['confirmed_task']}\nPrevious actions:\n" + '\n'.join(history)
61
+ + '\nDOM:\n' + html)
62
+ identity = f"{trajectory['annotation_id']}:{action['action_uid']}"
63
+ metadata = dict(id=identity, source_row=identity, trajectory_id=trajectory['annotation_id'],
64
+ action_uid=action['action_uid'], action_index=index, website=trajectory['website'],
65
+ domain=trajectory['domain'], source_dataset=SOURCE, source_revision=REVISION,
66
+ source_split='train', input_view='dom', page_group_id=page_key(action))
67
+ if not elements:
68
+ return dict(inputs=inputs, labels=operation, metadata=json.dumps(metadata, sort_keys=True)), None
69
+ positives = action['pos_candidates']
70
+ original = [candidate for candidate in positives if candidate.get('is_original_target') is True]
71
+ if len(original) != 1:
72
+ return None, 'ambiguous_or_missing_original_target'
73
+ positive_ids = {str(candidate['backend_node_id']) for candidate in positives}
74
+ nodes = set(re.findall(r'backend_node_id=["\']([^"\']+)["\']', html))
75
+ def describe(candidate):
76
+ node = str(candidate['backend_node_id'])
77
+ if node not in nodes:
78
+ return None
79
+ attributes = candidate['attributes']
80
+ attributes = json.loads(attributes) if isinstance(attributes, str) else attributes
81
+ visible = {key: attributes[key] for key in
82
+ ('aria_label', 'aria-label', 'placeholder', 'title', 'role', 'type', 'id', 'text')
83
+ if attributes.get(key)}
84
+ return node, json.dumps(dict(node=node, tag=candidate['tag'], attributes=visible),
85
+ ensure_ascii=False, sort_keys=True)
86
+ gold = describe(original[0])
87
+ if gold is None:
88
+ return None, 'target_missing_from_dom'
89
+ negatives = {}
90
+ for candidate in action['neg_candidates']:
91
+ if str(candidate['backend_node_id']) not in positive_ids:
92
+ option = describe(candidate)
93
+ if option:
94
+ negatives[option[0]] = option
95
+ # Four native candidates match the normal text MC template; never invent negatives.
96
+ if len(negatives) < 3:
97
+ return None, 'fewer_than_three_native_negatives'
98
+ rng = random.Random(f'{seed}:{identity}')
99
+ choices = [gold] + rng.sample(sorted(negatives.values()), 3)
100
+ rng.shuffle(choices)
101
+ metadata.update(candidate_ids=[node for node, _ in choices], target_id=gold[0],
102
+ candidate_sampling_seed=seed, native_negative_count=len(negatives))
103
+ return dict(inputs=inputs + f'\nOperation: {operation}', choices_list=[text for _, text in choices],
104
+ labels=choices.index(gold), metadata=json.dumps(metadata, sort_keys=True)), None
105
+
106
+
107
+ def mind2web_dom(seed=42):
108
+ """Mind2Web public training trajectories as compact HTML-only actions and native MCQs.
109
+
110
+ Dataset annotations are CC BY 4.0: https://huggingface.co/datasets/osunlp/Mind2Web
111
+ No official benchmark test files are downloaded or republished. Derived 80/10/10
112
+ train/validation/test partitions group whole trajectories and identical cleaned DOM
113
+ snapshots. They are internal holdouts, not the official Mind2Web benchmark splits.
114
+ Only past actions enter context. Four-way MC uses the original target and three
115
+ deterministically sampled native negatives, excluding all alternative positives.
116
+ """
117
+ root = Path(snapshot_download(SOURCE, repo_type='dataset', revision=REVISION,
118
+ allow_patterns=['data/train/*.json']))
119
+ paths = sorted(root.glob('data/train/*.json'))
120
+ def trajectories():
121
+ for path in paths:
122
+ yield from json.loads(path.read_text())
123
+ splits, groups = trajectory_splits(trajectories(), seed)
124
+ output = Path('build/mind2web-dom-release')
125
+ output.mkdir(parents=True, exist_ok=True)
126
+ features = Features(dict(inputs=Value('string'), labels=Value('string'), metadata=Value('string')))
127
+ result, counts, exclusions = {}, Counter(), []
128
+ for view in ('action', 'dom-element'):
129
+ schema = features.copy()
130
+ if view == 'dom-element':
131
+ schema.update(labels=Value('int64'), choices_list=Sequence(Value('string')))
132
+ def rows():
133
+ for trajectory in trajectories():
134
+ for index in range(len(trajectory['actions'])):
135
+ record, reason = mind2web_record(trajectory, index, view == 'dom-element', seed)
136
+ split = splits[trajectory['annotation_id']]
137
+ if reason:
138
+ counts[f'{view}/{split}/excluded/{reason}'] += 1
139
+ exclusions.append(dict(view=view, trajectory_id=trajectory['annotation_id'],
140
+ action_uid=trajectory['actions'][index]['action_uid'], reason=reason))
141
+ continue
142
+ metadata = json.loads(record['metadata'])
143
+ metadata.update(split_group_id=groups[trajectory['annotation_id']],
144
+ split_policy='public-train-connected-trajectories-80/10/10-v1', split_seed=seed)
145
+ record['metadata'] = json.dumps(metadata, sort_keys=True)
146
+ record['_split'] = split
147
+ counts[f'{view}/{split}/included'] += 1
148
+ yield record
149
+ full_schema = Features({**schema, '_split': Value('string')})
150
+ data = Dataset.from_generator(rows, features=full_schema, cache_dir=str(output / 'cache'))
151
+ result[view] = DatasetDict({split: data.filter(lambda row: row['_split'] == split).remove_columns('_split')
152
+ for split in ('train', 'validation', 'test')})
153
+ for split, dataset in result[view].items():
154
+ dataset.to_parquet(str(output / f'{view}-{split}.parquet'))
155
+ report = dict(source=SOURCE, revision=REVISION, seed=seed, counts=dict(counts),
156
+ split_policy='public-train-connected-trajectories-80/10/10-v1',
157
+ trajectory_splits=splits, trajectory_groups=groups,
158
+ source_sha256={p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths},
159
+ conversion_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
160
+ license='cc-by-4.0', official_benchmark_tests_consumed=False)
161
+ (output / 'provenance.json').write_text(json.dumps(report, indent=2) + '\n')
162
+ (output / 'excluded-questions.jsonl').write_text(''.join(json.dumps(row) + '\n' for row in exclusions))
163
+ return result