jometeorie commited on
Commit
38f4f31
·
verified ·
1 Parent(s): 9c9421e

Simplify dataset builder

Browse files
Files changed (1) hide show
  1. scripts/build_dataset.py +33 -156
scripts/build_dataset.py CHANGED
@@ -5,10 +5,8 @@ from __future__ import annotations
5
 
6
  import argparse
7
  import copy
8
- import hashlib
9
  import json
10
  import re
11
- import zipfile
12
  from collections import Counter
13
  from pathlib import Path
14
  from typing import Any
@@ -77,7 +75,11 @@ EXPECTED_BASE_COUNTS = {
77
  5: 60,
78
  13: 60,
79
  }
80
- EXPECTED_DERIVED_COUNTS = {14: 30, 15: 80}
 
 
 
 
81
 
82
 
83
  def snake_case(name: str) -> str:
@@ -106,15 +108,7 @@ def read_task_file(path: Path) -> dict[str, Any]:
106
  return task
107
 
108
 
109
- def make_record(
110
- task: dict[str, Any],
111
- *,
112
- source_file: str,
113
- release_role: str,
114
- is_derived: bool,
115
- derivation: str = "",
116
- variant_prefix: str = "",
117
- ) -> dict[str, Any]:
118
  task_type_id = int(task["type"])
119
  if task_type_id not in TYPE_INFO:
120
  raise ValueError(f"{task['id']}: unsupported task type {task_type_id}")
@@ -123,7 +117,7 @@ def make_record(
123
  payload = snake_case_keys(copy.deepcopy(task))
124
  task_id = str(payload.pop("id"))
125
  payload.pop("type")
126
- source_task_id = str(payload.pop("source_task_id", "") or "")
127
 
128
  qa_answer_text = ""
129
  qa_options = payload.get("qa_options", [])
@@ -143,12 +137,6 @@ def make_record(
143
  "task_abbreviation": abbreviation,
144
  "capability_level": level,
145
  "capability_name": capability,
146
- "release_role": release_role,
147
- "is_derived": is_derived,
148
- "derivation": derivation,
149
- "source_task_id": source_task_id,
150
- "source_file": source_file,
151
- "variant_prefix": variant_prefix,
152
  "qa_answer_text": qa_answer_text,
153
  "poi_category_name": poi_category_name,
154
  }
@@ -156,18 +144,21 @@ def make_record(
156
  return record
157
 
158
 
159
- def derive_level_five(source: dict[str, Any], target_type: int) -> dict[str, Any]:
160
  if target_type == 14 and source["type"] != 11:
161
- raise ValueError("DCR must be derived from a constrained-navigation task")
162
  if target_type == 15 and source["type"] != 2:
163
- raise ValueError("NP must be derived from a long-range navigation task")
164
 
165
- derived = copy.deepcopy(source)
166
  abbreviation = TYPE_INFO[target_type][1]
167
- derived["id"] = f"{abbreviation}::{source['id']}"
168
- derived["type"] = target_type
169
- derived["sourceTaskId"] = source["id"]
170
- return derived
 
 
 
171
 
172
 
173
  def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None:
@@ -177,40 +168,6 @@ def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None:
177
  handle.write("\n")
178
 
179
 
180
- def write_raw_archive(
181
- archive_path: Path,
182
- task_paths: list[Path],
183
- manifest: dict[str, Any],
184
- ) -> list[str]:
185
- checksums: list[str] = []
186
- with zipfile.ZipFile(
187
- archive_path,
188
- "w",
189
- compression=zipfile.ZIP_DEFLATED,
190
- compresslevel=9,
191
- ) as archive:
192
- for path in task_paths:
193
- raw = path.read_bytes()
194
- digest = hashlib.sha256(raw).hexdigest()
195
- checksums.append(f"{digest} task/{path.name}")
196
-
197
- info = zipfile.ZipInfo(f"task/{path.name}", date_time=(1980, 1, 1, 0, 0, 0))
198
- info.compress_type = zipfile.ZIP_DEFLATED
199
- info.external_attr = 0o644 << 16
200
- archive.writestr(info, raw, compresslevel=9)
201
-
202
- manifest_info = zipfile.ZipInfo("manifest.json", date_time=(1980, 1, 1, 0, 0, 0))
203
- manifest_info.compress_type = zipfile.ZIP_DEFLATED
204
- manifest_info.external_attr = 0o644 << 16
205
- archive.writestr(
206
- manifest_info,
207
- json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
208
- + b"\n",
209
- compresslevel=9,
210
- )
211
- return checksums
212
-
213
-
214
  def build(source_dir: Path, output_dir: Path) -> None:
215
  task_paths = sorted(source_dir.glob("*.json"), key=lambda path: path.name)
216
  if not task_paths:
@@ -221,64 +178,33 @@ def build(source_dir: Path, output_dir: Path) -> None:
221
  if len(ids) != len(set(ids)):
222
  raise ValueError("duplicate task ids found")
223
 
224
- base_tasks: list[tuple[Path, dict[str, Any]]] = []
225
- auxiliary_tasks: list[tuple[Path, dict[str, Any]]] = []
226
  for path, task in stored_tasks:
227
  prefix = task["id"].split("-", 1)[0]
228
  expected_type = BASE_PREFIX_TO_TYPE.get(prefix)
229
  if expected_type is None:
230
- auxiliary_tasks.append((path, task))
231
  continue
232
  if task["type"] != expected_type:
233
  raise ValueError(
234
  f"{task['id']}: prefix expects type {expected_type}, got {task['type']}"
235
  )
236
- base_tasks.append((path, task))
237
 
238
- base_counts = Counter(task["type"] for _, task in base_tasks)
239
  if dict(base_counts) != EXPECTED_BASE_COUNTS:
240
  raise ValueError(
241
  f"base task counts changed: expected {EXPECTED_BASE_COUNTS}, got {dict(base_counts)}"
242
  )
243
 
244
- base_ids = {task["id"] for _, task in base_tasks}
245
- for _, task in auxiliary_tasks:
246
- source_id = str(task.get("sourceTaskId", "") or "")
247
- if source_id and source_id not in base_ids:
248
- raise ValueError(f"{task['id']}: missing source task {source_id}")
249
-
250
  benchmark_records: list[dict[str, Any]] = []
251
- for path, task in base_tasks:
252
- benchmark_records.append(
253
- make_record(
254
- task,
255
- source_file=f"task/{path.name}",
256
- release_role="stored_base",
257
- is_derived=False,
258
- )
259
- )
260
 
261
- for path, task in base_tasks:
262
  if task["type"] == 11:
263
- benchmark_records.append(
264
- make_record(
265
- derive_level_five(task, 14),
266
- source_file=f"task/{path.name}",
267
- release_role="derived_level_5",
268
- is_derived=True,
269
- derivation="dynamic_road_closure_from_constrained_navigation",
270
- )
271
- )
272
  elif task["type"] == 2:
273
- benchmark_records.append(
274
- make_record(
275
- derive_level_five(task, 15),
276
- source_file=f"task/{path.name}",
277
- release_role="derived_level_5",
278
- is_derived=True,
279
- derivation="pedestrian_navigation_from_long_range_navigation",
280
- )
281
- )
282
 
283
  benchmark_records.sort(
284
  key=lambda record: (
@@ -290,54 +216,29 @@ def build(source_dir: Path, output_dir: Path) -> None:
290
  for index, record in enumerate(benchmark_records):
291
  record["instance_index"] = index
292
 
293
- derived_counts = Counter(
294
- record["task_type_id"] for record in benchmark_records if record["is_derived"]
295
- )
296
- if dict(derived_counts) != EXPECTED_DERIVED_COUNTS:
297
  raise ValueError(
298
- f"derived task counts changed: expected {EXPECTED_DERIVED_COUNTS}, got {dict(derived_counts)}"
 
299
  )
300
  if len(benchmark_records) != 810:
301
  raise ValueError(f"expected 810 benchmark instances, got {len(benchmark_records)}")
302
 
303
- auxiliary_records: list[dict[str, Any]] = []
304
- for path, task in auxiliary_tasks:
305
- prefix = task["id"].split("-", 1)[0]
306
- auxiliary_records.append(
307
- make_record(
308
- task,
309
- source_file=f"task/{path.name}",
310
- release_role="auxiliary_variant",
311
- is_derived=False,
312
- variant_prefix=prefix,
313
- )
314
- )
315
- auxiliary_records.sort(key=lambda record: record["id"])
316
- for index, record in enumerate(auxiliary_records):
317
- record["instance_index"] = index
318
- if len(auxiliary_records) != 28:
319
- raise ValueError(f"expected 28 auxiliary variants, got {len(auxiliary_records)}")
320
-
321
  data_dir = output_dir / "data"
322
- raw_dir = output_dir / "raw"
323
  metadata_dir = output_dir / "metadata"
324
  data_dir.mkdir(parents=True, exist_ok=True)
325
- raw_dir.mkdir(parents=True, exist_ok=True)
326
  metadata_dir.mkdir(parents=True, exist_ok=True)
327
 
328
  write_jsonl(data_dir / "benchmark.jsonl", benchmark_records)
329
- write_jsonl(data_dir / "auxiliary_variants.jsonl", auxiliary_records)
330
 
331
  benchmark_counts = Counter(
332
  (record["capability_level"], record["task_abbreviation"])
333
  for record in benchmark_records
334
  )
335
  statistics = {
336
- "stored_task_files": len(stored_tasks),
337
- "stored_benchmark_source_files": len(base_tasks),
338
- "stored_auxiliary_variant_files": len(auxiliary_tasks),
339
- "materialized_level_5_instances": sum(EXPECTED_DERIVED_COUNTS.values()),
340
- "paper_benchmark_instances": len(benchmark_records),
341
  "benchmark_counts": [
342
  {
343
  "capability_level": level,
@@ -352,31 +253,7 @@ def build(source_dir: Path, output_dir: Path) -> None:
352
  encoding="utf-8",
353
  )
354
 
355
- manifest = {
356
- "dataset": "UrbanGround Tasks",
357
- "dataset_url": "https://huggingface.co/datasets/jometeorie/urbanground-tasks",
358
- "format_version": 1,
359
- "license": "MIT",
360
- "paper": "arXiv:2608.27456",
361
- "paper_url": "https://arxiv.org/abs/2608.27456",
362
- "project_url": "https://github.com/UrbanGround/UrbanGround",
363
- "source_application_release": "v1.0.0",
364
- **statistics,
365
- }
366
- checksums = write_raw_archive(
367
- raw_dir / "urbanground-app-task-files-v1.0.0.zip",
368
- task_paths,
369
- manifest,
370
- )
371
- (raw_dir / "task-files.sha256").write_text("\n".join(checksums) + "\n", encoding="utf-8")
372
- (raw_dir / "manifest.json").write_text(
373
- json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
374
- encoding="utf-8",
375
- )
376
-
377
- print(f"Built {len(benchmark_records)} benchmark records")
378
- print(f"Built {len(auxiliary_records)} auxiliary records")
379
- print(f"Archived {len(task_paths)} App-compatible task files")
380
 
381
 
382
  def parse_args() -> argparse.Namespace:
 
5
 
6
  import argparse
7
  import copy
 
8
  import json
9
  import re
 
10
  from collections import Counter
11
  from pathlib import Path
12
  from typing import Any
 
75
  5: 60,
76
  13: 60,
77
  }
78
+ EXPECTED_BENCHMARK_COUNTS = {
79
+ **EXPECTED_BASE_COUNTS,
80
+ 14: 30,
81
+ 15: 80,
82
+ }
83
 
84
 
85
  def snake_case(name: str) -> str:
 
108
  return task
109
 
110
 
111
+ def make_record(task: dict[str, Any]) -> dict[str, Any]:
 
 
 
 
 
 
 
 
112
  task_type_id = int(task["type"])
113
  if task_type_id not in TYPE_INFO:
114
  raise ValueError(f"{task['id']}: unsupported task type {task_type_id}")
 
117
  payload = snake_case_keys(copy.deepcopy(task))
118
  task_id = str(payload.pop("id"))
119
  payload.pop("type")
120
+ payload.pop("source_task_id", None)
121
 
122
  qa_answer_text = ""
123
  qa_options = payload.get("qa_options", [])
 
137
  "task_abbreviation": abbreviation,
138
  "capability_level": level,
139
  "capability_name": capability,
 
 
 
 
 
 
140
  "qa_answer_text": qa_answer_text,
141
  "poi_category_name": poi_category_name,
142
  }
 
144
  return record
145
 
146
 
147
+ def make_level_five_task(source: dict[str, Any], target_type: int) -> dict[str, Any]:
148
  if target_type == 14 and source["type"] != 11:
149
+ raise ValueError("DCR requires constrained-navigation task geometry")
150
  if target_type == 15 and source["type"] != 2:
151
+ raise ValueError("NP requires long-range navigation task geometry")
152
 
153
+ task = copy.deepcopy(source)
154
  abbreviation = TYPE_INFO[target_type][1]
155
+ _, separator, suffix = str(source["id"]).partition("-")
156
+ if not separator:
157
+ raise ValueError(f"{source['id']}: expected a prefixed task id")
158
+ task["id"] = f"{abbreviation}-{suffix}"
159
+ task["type"] = target_type
160
+ task["sourceTaskId"] = ""
161
+ return task
162
 
163
 
164
  def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None:
 
168
  handle.write("\n")
169
 
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  def build(source_dir: Path, output_dir: Path) -> None:
172
  task_paths = sorted(source_dir.glob("*.json"), key=lambda path: path.name)
173
  if not task_paths:
 
178
  if len(ids) != len(set(ids)):
179
  raise ValueError("duplicate task ids found")
180
 
181
+ benchmark_source_tasks: list[dict[str, Any]] = []
 
182
  for path, task in stored_tasks:
183
  prefix = task["id"].split("-", 1)[0]
184
  expected_type = BASE_PREFIX_TO_TYPE.get(prefix)
185
  if expected_type is None:
 
186
  continue
187
  if task["type"] != expected_type:
188
  raise ValueError(
189
  f"{task['id']}: prefix expects type {expected_type}, got {task['type']}"
190
  )
191
+ benchmark_source_tasks.append(task)
192
 
193
+ base_counts = Counter(task["type"] for task in benchmark_source_tasks)
194
  if dict(base_counts) != EXPECTED_BASE_COUNTS:
195
  raise ValueError(
196
  f"base task counts changed: expected {EXPECTED_BASE_COUNTS}, got {dict(base_counts)}"
197
  )
198
 
 
 
 
 
 
 
199
  benchmark_records: list[dict[str, Any]] = []
200
+ for task in benchmark_source_tasks:
201
+ benchmark_records.append(make_record(task))
 
 
 
 
 
 
 
202
 
203
+ for task in benchmark_source_tasks:
204
  if task["type"] == 11:
205
+ benchmark_records.append(make_record(make_level_five_task(task, 14)))
 
 
 
 
 
 
 
 
206
  elif task["type"] == 2:
207
+ benchmark_records.append(make_record(make_level_five_task(task, 15)))
 
 
 
 
 
 
 
 
208
 
209
  benchmark_records.sort(
210
  key=lambda record: (
 
216
  for index, record in enumerate(benchmark_records):
217
  record["instance_index"] = index
218
 
219
+ benchmark_type_counts = Counter(record["task_type_id"] for record in benchmark_records)
220
+ if dict(benchmark_type_counts) != EXPECTED_BENCHMARK_COUNTS:
 
 
221
  raise ValueError(
222
+ "benchmark task counts changed: "
223
+ f"expected {EXPECTED_BENCHMARK_COUNTS}, got {dict(benchmark_type_counts)}"
224
  )
225
  if len(benchmark_records) != 810:
226
  raise ValueError(f"expected 810 benchmark instances, got {len(benchmark_records)}")
227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  data_dir = output_dir / "data"
 
229
  metadata_dir = output_dir / "metadata"
230
  data_dir.mkdir(parents=True, exist_ok=True)
 
231
  metadata_dir.mkdir(parents=True, exist_ok=True)
232
 
233
  write_jsonl(data_dir / "benchmark.jsonl", benchmark_records)
 
234
 
235
  benchmark_counts = Counter(
236
  (record["capability_level"], record["task_abbreviation"])
237
  for record in benchmark_records
238
  )
239
  statistics = {
240
+ "total_instances": len(benchmark_records),
241
+ "splits": {"test": len(benchmark_records)},
 
 
 
242
  "benchmark_counts": [
243
  {
244
  "capability_level": level,
 
253
  encoding="utf-8",
254
  )
255
 
256
+ print(f"Built {len(benchmark_records)} UrbanGround task records")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
 
259
  def parse_args() -> argparse.Namespace: