#!/usr/bin/env python3 """Build the public UrbanGround Hugging Face dataset from App task JSON files.""" from __future__ import annotations import argparse import copy import json import re from collections import Counter from pathlib import Path from typing import Any TYPE_INFO = { 0: ("Short-Range Goal Navigation", "SGN", 2, "Navigation under Explicit Instructions"), 2: ("Long-Range Goal Navigation", "LGN", 2, "Navigation under Explicit Instructions"), 3: ("Place-Type Search", "PTS", 3, "Exploration under Implicit Instructions"), 5: ("Time-Window Scheduling", "TWS", 4, "Multi-Task Planning"), 7: ("Visual Recognition", "VR", 1, "Local Environment Understanding"), 8: ("Orientation Understanding", "OU", 1, "Local Environment Understanding"), 9: ("Active Exploration Questions", "AEQ", 1, "Local Environment Understanding"), 10: ("Instructional Navigation", "IN", 2, "Navigation under Explicit Instructions"), 11: ("Constrained Navigation", "CN", 2, "Navigation under Explicit Instructions"), 12: ("Implicit Intent Inference", "III", 3, "Exploration under Implicit Instructions"), 13: ("Multi-Stop Route Planning", "MSP", 4, "Multi-Task Planning"), 14: ("Dynamic Road-Closure Replanning", "DCR", 5, "Dynamic Environment Interaction"), 15: ("Navigation among Pedestrians", "NP", 5, "Dynamic Environment Interaction"), } BASE_PREFIX_TO_TYPE = { "LQ": 7, "OQ": 8, "SQ": 9, "SN": 0, "LN": 2, "IN": 10, "CN": 11, "PS": 3, "II": 12, "SF": 5, "MP": 13, } POI_CATEGORIES = { 0: "Education", 1: "Medical & Health", 2: "Social Welfare", 3: "Recreation & Sports", 4: "Open Space", 5: "Culture & Entertainment", 6: "Religious & Burial Facilities", 7: "Municipal & Public Utilities", 8: "Government Offices", 9: "Transport", 10: "Commercial & Retail", 11: "Food & Beverage", 12: "Accommodation", 13: "Residential", } TYPE_ORDER = [7, 8, 9, 0, 2, 10, 11, 3, 12, 5, 13, 14, 15] TYPE_ORDER_INDEX = {task_type: index for index, task_type in enumerate(TYPE_ORDER)} EXPECTED_BASE_COUNTS = { 7: 80, 8: 60, 9: 80, 0: 80, 2: 80, 10: 50, 11: 30, 3: 60, 12: 60, 5: 60, 13: 60, } EXPECTED_BENCHMARK_COUNTS = { **EXPECTED_BASE_COUNTS, 14: 30, 15: 80, } def snake_case(name: str) -> str: first = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", first).lower() def snake_case_keys(value: Any) -> Any: if isinstance(value, dict): return {snake_case(str(key)): snake_case_keys(item) for key, item in value.items()} if isinstance(value, list): return [snake_case_keys(item) for item in value] return value def read_task_file(path: Path) -> dict[str, Any]: with path.open("r", encoding="utf-8") as handle: document = json.load(handle) if set(document) != {"task"} or not isinstance(document["task"], dict): raise ValueError(f"{path}: expected one top-level 'task' object") task = document["task"] if task.get("id") != path.stem: raise ValueError(f"{path}: filename does not match task id {task.get('id')!r}") if not isinstance(task.get("type"), int): raise ValueError(f"{path}: task type must be an integer") return task def make_record(task: dict[str, Any]) -> dict[str, Any]: task_type_id = int(task["type"]) if task_type_id not in TYPE_INFO: raise ValueError(f"{task['id']}: unsupported task type {task_type_id}") task_type, abbreviation, level, capability = TYPE_INFO[task_type_id] payload = snake_case_keys(copy.deepcopy(task)) task_id = str(payload.pop("id")) payload.pop("type") payload.pop("source_task_id", None) qa_answer_text = "" qa_options = payload.get("qa_options", []) qa_answer_index = payload.get("qa_answer_index") if isinstance(qa_answer_index, int) and 0 <= qa_answer_index < len(qa_options): qa_answer_text = str(qa_options[qa_answer_index].get("text", "")) poi_category = payload.get("poi_category") poi_category_name = ( POI_CATEGORIES.get(poi_category, "") if task_type_id == 3 else "" ) record: dict[str, Any] = { "id": task_id, "task_type_id": task_type_id, "task_type": task_type, "task_abbreviation": abbreviation, "capability_level": level, "capability_name": capability, "qa_answer_text": qa_answer_text, "poi_category_name": poi_category_name, } record.update(payload) return record def make_level_five_task(source: dict[str, Any], target_type: int) -> dict[str, Any]: if target_type == 14 and source["type"] != 11: raise ValueError("DCR requires constrained-navigation task geometry") if target_type == 15 and source["type"] != 2: raise ValueError("NP requires long-range navigation task geometry") task = copy.deepcopy(source) abbreviation = TYPE_INFO[target_type][1] _, separator, suffix = str(source["id"]).partition("-") if not separator: raise ValueError(f"{source['id']}: expected a prefixed task id") task["id"] = f"{abbreviation}-{suffix}" task["type"] = target_type task["sourceTaskId"] = "" return task def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None: with path.open("w", encoding="utf-8", newline="\n") as handle: for record in records: handle.write(json.dumps(record, ensure_ascii=False, separators=(",", ":"))) handle.write("\n") def build(source_dir: Path, output_dir: Path) -> None: task_paths = sorted(source_dir.glob("*.json"), key=lambda path: path.name) if not task_paths: raise ValueError(f"no task JSON files found in {source_dir}") stored_tasks = [(path, read_task_file(path)) for path in task_paths] ids = [task["id"] for _, task in stored_tasks] if len(ids) != len(set(ids)): raise ValueError("duplicate task ids found") benchmark_source_tasks: list[dict[str, Any]] = [] for path, task in stored_tasks: prefix = task["id"].split("-", 1)[0] expected_type = BASE_PREFIX_TO_TYPE.get(prefix) if expected_type is None: continue if task["type"] != expected_type: raise ValueError( f"{task['id']}: prefix expects type {expected_type}, got {task['type']}" ) benchmark_source_tasks.append(task) base_counts = Counter(task["type"] for task in benchmark_source_tasks) if dict(base_counts) != EXPECTED_BASE_COUNTS: raise ValueError( f"base task counts changed: expected {EXPECTED_BASE_COUNTS}, got {dict(base_counts)}" ) benchmark_records: list[dict[str, Any]] = [] for task in benchmark_source_tasks: benchmark_records.append(make_record(task)) for task in benchmark_source_tasks: if task["type"] == 11: benchmark_records.append(make_record(make_level_five_task(task, 14))) elif task["type"] == 2: benchmark_records.append(make_record(make_level_five_task(task, 15))) benchmark_records.sort( key=lambda record: ( record["capability_level"], TYPE_ORDER_INDEX[record["task_type_id"]], record["id"], ) ) for index, record in enumerate(benchmark_records): record["instance_index"] = index benchmark_type_counts = Counter(record["task_type_id"] for record in benchmark_records) if dict(benchmark_type_counts) != EXPECTED_BENCHMARK_COUNTS: raise ValueError( "benchmark task counts changed: " f"expected {EXPECTED_BENCHMARK_COUNTS}, got {dict(benchmark_type_counts)}" ) if len(benchmark_records) != 810: raise ValueError(f"expected 810 benchmark instances, got {len(benchmark_records)}") data_dir = output_dir / "data" metadata_dir = output_dir / "metadata" data_dir.mkdir(parents=True, exist_ok=True) metadata_dir.mkdir(parents=True, exist_ok=True) write_jsonl(data_dir / "benchmark.jsonl", benchmark_records) benchmark_counts = Counter( (record["capability_level"], record["task_abbreviation"]) for record in benchmark_records ) statistics = { "total_instances": len(benchmark_records), "splits": {"test": len(benchmark_records)}, "benchmark_counts": [ { "capability_level": level, "task_abbreviation": abbreviation, "number": count, } for (level, abbreviation), count in sorted(benchmark_counts.items()) ], } (metadata_dir / "statistics.json").write_text( json.dumps(statistics, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) print(f"Built {len(benchmark_records)} UrbanGround task records") def parse_args() -> argparse.Namespace: script_dir = Path(__file__).resolve().parent default_output = script_dir.parent default_source = default_output.parents[1] / "task" parser = argparse.ArgumentParser() parser.add_argument("--source", type=Path, default=default_source) parser.add_argument("--output", type=Path, default=default_output) return parser.parse_args() if __name__ == "__main__": arguments = parse_args() build(arguments.source.resolve(), arguments.output.resolve())