Datasets:
Download scripts/prepare_dataset.py from DONKEY13479/ForestFireFIghting: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/datasets/DONKEY13479/ForestFireFIghting/resolve/main/scripts/prepare_dataset.py
- Command line
-
hf download hf://datasets/DONKEY13479/ForestFireFIghting/scripts/prepare_dataset.py
-
curl -L -o prepare_dataset.py https://huggingface.co/datasets/DONKEY13479/ForestFireFIghting/resolve/main/scripts/prepare_dataset.py
17.3 kB
| """Build the local, reviewable dataset package. This script never uploads files.""" | |
| import argparse | |
| import ast | |
| from collections import Counter, defaultdict, deque | |
| from datetime import datetime | |
| import hashlib | |
| import io | |
| import json | |
| from pathlib import Path | |
| import random | |
| import re | |
| import shutil | |
| from zoneinfo import ZoneInfo | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from PIL import Image | |
| SEED = 20261115 | |
| SPLITS = ("train", "validation", "test") | |
| def compact(value): | |
| return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) | |
| def digest(value): | |
| return hashlib.sha256(value).hexdigest() | |
| def json_hash(value): | |
| return digest(compact(value).encode("utf-8")) | |
| def read_json(path): | |
| return json.loads(path.read_text(encoding="utf-8-sig")) | |
| def write_json(path, value): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") | |
| def planning_zones(zones): | |
| return [{k: zone[k] for k in ("id", "risk_level", "coordinates", "fire_points")} for zone in zones] | |
| def record_key(fleet, zones, output): | |
| return (json_hash(sorted(fleet, key=lambda u: u["id"])), | |
| json_hash(planning_zones(zones)), digest(output.replace("\r\n", "\n").encode("utf-8"))) | |
| def parse_prompt(instruction): | |
| resource_block = instruction.split("UAV RESOURCES:", 1)[1].split("ZONES (JSON):", 1)[0] | |
| fleet = [json.loads(match.group(1)) for match in | |
| re.finditer(r"^UAV_\w+\s*=\s*(\{[^\n]+\})\s*$", resource_block, re.MULTILINE)] | |
| assert fleet, "No UAV resources found in prompt" | |
| zone_block = instruction.split("ZONES (JSON):", 1)[1].lstrip() | |
| zones, _ = json.JSONDecoder().raw_decode(zone_block) | |
| return fleet, zones | |
| def schema_with_features(fields, image=False): | |
| features = {} | |
| for name, dtype in fields: | |
| if name == "image" and image: | |
| features[name] = {"_type": "Image"} | |
| else: | |
| features[name] = {"dtype": "int32" if pa.types.is_int32(dtype) else "string", "_type": "Value"} | |
| return pa.schema(fields).with_metadata({b"huggingface": json.dumps({"info": {"features": features}}).encode()}) | |
| VISION_SCHEMA = schema_with_features([ | |
| ("scene_id", pa.string()), | |
| ("image", pa.struct([("bytes", pa.binary()), ("path", pa.string())])), | |
| ("width", pa.int32()), ("height", pa.int32()), ("mode", pa.string()), | |
| ("num_zones", pa.int32()), ("num_fire_points", pa.int32()), | |
| ("zones_json", pa.string()), ("image_sha256", pa.string()), | |
| ("zones_sha256", pa.string()), ("visualization_file", pa.string()), | |
| ], image=True) | |
| PLANNING_SCHEMA = schema_with_features([ | |
| ("sample_id", pa.string()), ("scene_id", pa.string()), ("fleet_id", pa.string()), | |
| ("instruction", pa.string()), ("input", pa.string()), ("output", pa.string()), | |
| ("fleet_json", pa.string()), ("zones_json", pa.string()), | |
| ("num_uavs", pa.int32()), ("num_extinguishing_uavs", pa.int32()), | |
| ("num_surveillance_uavs", pa.int32()), ("num_zones", pa.int32()), | |
| ("num_fire_points", pa.int32()), ("origin", pa.string()), | |
| ("prompt_version", pa.string()), ("validation_scope", pa.string()), | |
| ("plan_sha256", pa.string()), | |
| ]) | |
| def write_shards(output, config, split, rows, schema, size): | |
| total = (len(rows) + size - 1) // size | |
| for i in range(total): | |
| batch = rows[i * size:(i + 1) * size] | |
| if config == "vision": | |
| batch = [dict(row, image={"bytes": Path(row["_image_path"]).read_bytes(), | |
| "path": row["scene_id"] + ".png"}) for row in batch] | |
| path = output / "data" / config / f"{split}-{i:05d}-of-{total:05d}.parquet" | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| pq.write_table(pa.Table.from_pylist(batch, schema=schema), path, | |
| compression="zstd", row_group_size=25 if config == "vision" else 250) | |
| print(f"Wrote {config}/{path.name}: {len(batch)} rows", flush=True) | |
| def assign_splits(scenes): | |
| # Keep identical images or identical planning geometries in one split. | |
| parent = {row["scene_id"]: row["scene_id"] for row in scenes} | |
| def find(key): | |
| while parent[key] != key: | |
| parent[key] = parent[parent[key]] | |
| key = parent[key] | |
| return key | |
| seen = {} | |
| for row in scenes: | |
| for field in ("image_sha256", "_planning_zones_sha256"): | |
| key = (field, row[field]) | |
| if key in seen: | |
| parent[find(row["scene_id"])] = find(seen[key]) | |
| else: | |
| seen[key] = row["scene_id"] | |
| groups = defaultdict(list) | |
| for row in scenes: | |
| groups[find(row["scene_id"])].append(row["scene_id"]) | |
| groups = list(groups.values()) | |
| random.Random(SEED).shuffle(groups) | |
| groups.sort(key=len, reverse=True) | |
| target = {"train": round(len(scenes) * 0.8), "validation": round(len(scenes) * 0.1)} | |
| target["test"] = len(scenes) - sum(target.values()) | |
| counts = Counter() | |
| assignments = {} | |
| for group in groups: | |
| split = max(SPLITS, key=lambda s: target[s] - counts[s]) | |
| for scene_id in group: | |
| assignments[scene_id] = split | |
| counts[split] += len(group) | |
| return assignments, [sorted(g) for g in groups if len(g) > 1] | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--source", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, required=True) | |
| args = parser.parse_args() | |
| source, output = args.source.resolve(), args.output.resolve() | |
| assert source != output and source not in output.parents, "Use a sibling output directory" | |
| assert not (output / "data").exists(), "Output data already exists; use a fresh output directory" | |
| output.mkdir(parents=True, exist_ok=True) | |
| print("Indexing 25,000 instruction records...", flush=True) | |
| export_path = source / "exports" / "firefighting_train.json" | |
| export_bytes = export_path.read_bytes() | |
| export_sha = digest(export_bytes) | |
| exported = json.loads(export_bytes) | |
| del export_bytes | |
| assert len(exported) == 25000 | |
| index = defaultdict(deque) | |
| for record in exported: | |
| fleet, zones = parse_prompt(record["instruction"]) | |
| index[record_key(fleet, zones, record["output"])].append(record) | |
| print(f"Indexed {len(exported)} records ({len(index)} distinct content keys).", flush=True) | |
| fleet_catalog = read_json(source / "fleet.json") | |
| assert len(fleet_catalog) == 25 | |
| fleet_by_id = {f["fleet_id"]: f for f in fleet_catalog} | |
| public_fleets = [{k: f[k] for k in ("fleet_id", "drone_count", "types", "resources")} | |
| for f in fleet_catalog] | |
| reference_ids = set() | |
| for manifest in source.glob("_logs/*/manifest.jsonl"): | |
| for line in manifest.read_text(encoding="utf-8").splitlines(): | |
| item = json.loads(line) | |
| if item.get("origin") == "original_reference": | |
| reference_ids.add((item["image_id"], item["fleet_id"])) | |
| assert len(reference_ids) == 932 | |
| scenes, plans = [], [] | |
| scene_dirs = sorted(p for p in source.iterdir() if p.is_dir() and p.name.isdigit()) | |
| assert len(scene_dirs) == 1000 | |
| risk_counts, origin_counts, prompt_counts = Counter(), Counter(), Counter() | |
| for i, scene_dir in enumerate(scene_dirs, 1): | |
| scene_id = scene_dir.name | |
| configs = sorted(p for p in scene_dir.iterdir() if p.is_dir() and p.name.startswith("config_")) | |
| assert len(configs) == 25, scene_id | |
| zones = read_json(configs[0] / f"{scene_id}.json") | |
| zone_payload = compact(zones) | |
| num_fire = sum(len(z["fire_points"]) for z in zones) | |
| risk_counts.update(z["risk_level"] for z in zones) | |
| image_path = scene_dir / f"{scene_id}.png" | |
| image_bytes = image_path.read_bytes() | |
| with Image.open(io.BytesIO(image_bytes)) as image: | |
| width, height, mode = image.width, image.height, image.mode | |
| image.verify() | |
| visualization = scene_dir / f"{scene_id}_visualized.png" | |
| visualization_rel = f"visualizations/{scene_id}_visualized.png" | |
| (output / "visualizations").mkdir(exist_ok=True) | |
| shutil.copyfile(visualization, output / visualization_rel) | |
| assert digest((output / visualization_rel).read_bytes()) == digest(visualization.read_bytes()) | |
| scenes.append({ | |
| "scene_id": scene_id, "width": width, "height": height, "mode": mode, | |
| "num_zones": len(zones), "num_fire_points": num_fire, "zones_json": zone_payload, | |
| "image_sha256": digest(image_bytes), "zones_sha256": digest(zone_payload.encode("utf-8")), | |
| "visualization_file": visualization_rel, "_image_path": str(image_path), | |
| "_planning_zones_sha256": json_hash(planning_zones(zones)), | |
| }) | |
| for config in configs: | |
| fleet_id = "fleet_" + config.name.split("_")[1] | |
| fleet = read_json(config / "fleet.json") | |
| assert fleet == fleet_by_id[fleet_id]["resources"], str(config) | |
| assert read_json(config / f"{scene_id}.json") == zones, str(config) | |
| plan_bytes = (config / "plan.txt").read_bytes() | |
| plan = plan_bytes.decode("utf-8-sig").replace("\r\n", "\n") | |
| key = record_key(fleet, zones, plan) | |
| assert index[key], f"No matching exported record: {scene_id}/{fleet_id}" | |
| record = index[key].popleft() | |
| assert record["output"].replace("\r\n", "\n") == plan | |
| ast.parse(plan) # Parse only; never execute mission code. | |
| reference = (scene_id, fleet_id) in reference_ids | |
| origin = "reference" if reference else "rule_generated" | |
| prompt_type = "payload_contract" if "PAYLOAD SAFETY CONTRACT" in record["instruction"] else "core_rules" | |
| origin_counts[origin] += 1 | |
| prompt_counts[prompt_type] += 1 | |
| types = Counter(u["type"] for u in fleet) | |
| plans.append({ | |
| "sample_id": f"{scene_id}_{fleet_id}", "scene_id": scene_id, "fleet_id": fleet_id, | |
| **record, "fleet_json": compact(fleet), "zones_json": zone_payload, | |
| "num_uavs": len(fleet), "num_extinguishing_uavs": types["extinguishing_drone"], | |
| "num_surveillance_uavs": types["surveillance_drone"], "num_zones": len(zones), | |
| "num_fire_points": num_fire, "origin": origin, "prompt_version": prompt_type, | |
| "validation_scope": "packaging_integrity_and_python_syntax", | |
| "plan_sha256": digest(record["output"].encode("utf-8")), | |
| }) | |
| if i % 100 == 0: | |
| print(f"Checked {i}/1000 scenes; matched {len(plans)}/25000 plans.", flush=True) | |
| assert sum(len(v) for v in index.values()) == 0, "Unmatched export records" | |
| assert len({p["sample_id"] for p in plans}) == 25000 | |
| assignments, duplicate_groups = assign_splits(scenes) | |
| split_ids = {split: sorted(s for s in assignments if assignments[s] == split) for split in SPLITS} | |
| split_counts = {} | |
| for split in SPLITS: | |
| vs = [row for row in scenes if assignments[row["scene_id"]] == split] | |
| ps = [row for row in plans if assignments[row["scene_id"]] == split] | |
| split_counts[split] = {"vision": len(vs), "planning": len(ps)} | |
| write_shards(output, "vision", split, vs, VISION_SCHEMA, 50) | |
| write_shards(output, "planning", split, ps, PLANNING_SCHEMA, 2500) | |
| print("Reading back Parquet files and checking payload hashes...", flush=True) | |
| checks = Counter() | |
| content_split = {} | |
| for split in SPLITS: | |
| for config in ("vision", "planning"): | |
| for path in sorted((output / "data" / config).glob(f"{split}-*.parquet")): | |
| table = pq.read_table(path) | |
| assert table.schema.metadata[b"huggingface"] | |
| for row in table.to_pylist(): | |
| assert assignments[row["scene_id"]] == split | |
| if config == "vision": | |
| assert digest(row["image"]["bytes"]) == row["image_sha256"] | |
| assert digest(row["zones_json"].encode("utf-8")) == row["zones_sha256"] | |
| for key in ("image_sha256",): | |
| value = (key, row[key]) | |
| assert content_split.setdefault(value, split) == split | |
| else: | |
| assert digest(row["output"].encode("utf-8")) == row["plan_sha256"] | |
| value = ("scenario", json_hash(planning_zones(json.loads(row["zones_json"])))) | |
| assert content_split.setdefault(value, split) == split | |
| checks[config] += 1 | |
| assert dict(checks) == {"vision": 1000, "planning": 25000} | |
| created_at = datetime.now(ZoneInfo("Asia/Shanghai")).isoformat(timespec="seconds") | |
| write_json(output / "metadata" / "fleets.json", public_fleets) | |
| write_json(output / "metadata" / "scene_splits.json", { | |
| "seed": SEED, "method": "seeded_group_assignment", | |
| "group_keys": ["original_image_sha256", "planning_zone_geometry_sha256"], | |
| "target_ratios": {"train": 0.8, "validation": 0.1, "test": 0.1}, "splits": split_ids, | |
| }) | |
| write_json(output / "metadata" / "duplicate_groups.json", { | |
| "method": "exact image bytes or identical normalized planning zones", | |
| "groups": duplicate_groups, "near_duplicate_image_detection": "not_performed", | |
| }) | |
| write_json(output / "metadata" / "provenance.json", { | |
| "dataset_name": "ForestFireFIghting", "package_version": "1.0.0", "created_at": created_at, | |
| "scenes": 1000, "fleets": 25, "planning_samples": 25000, | |
| "instruction_input_output_preserved": True, "original_image_bytes_preserved": True, | |
| "mission_code_comparison": "CRLF is normalized to LF for matching saved plan files only. Exported output strings are preserved exactly.", | |
| "origin_counts": dict(origin_counts), "prompt_version_counts": dict(prompt_counts), | |
| "origin_definitions": {"reference": "Reference mission code recorded by the generation pipeline; expert verification is not asserted.", | |
| "rule_generated": "Mission code produced by a deterministic rule planner."}, | |
| "prompt_version_definitions": {"core_rules": "Prompt without the PAYLOAD SAFETY CONTRACT section.", | |
| "payload_contract": "Prompt containing the PAYLOAD SAFETY CONTRACT section. This is a prompt-family label, not a software version."}, | |
| "validation_scope": "Packaging verifies sample correspondence, schemas, file integrity, prompt resources/geometry, and Python syntax. Mission code is not executed.", | |
| "source_export_sha256": export_sha, | |
| "license": "Apache-2.0", "license_review_status": "pending_owner_review", | |
| "visual_provenance": "Image generation and annotation provenance require owner confirmation before publication.", | |
| }) | |
| files = [p for p in output.rglob("*") if p.is_file() and p.suffix == ".parquet"] | |
| report = { | |
| "status": "passed", "checked_at": created_at, "split_counts": split_counts, | |
| "checks": { | |
| "all_25000_export_rows_matched_once": True, | |
| "all_25000_outputs_match_saved_plans_after_newline_normalization": True, | |
| "all_25000_prompts_match_fleet_and_planning_zones": True, | |
| "all_25000_plans_parse_as_python": True, | |
| "all_25_fleets_match_catalog": True, | |
| "all_25_annotation_copies_per_scene_identical": True, | |
| "all_1000_original_image_payloads_preserved": True, | |
| "all_1000_visualization_files_preserved": True, | |
| "all_26000_parquet_rows_read_back": True, | |
| "scene_and_exact_content_groups_disjoint_across_splits": True, | |
| }, | |
| "parquet_files": len(files), "parquet_bytes": sum(p.stat().st_size for p in files), | |
| "risk_zone_counts": dict(risk_counts), "origin_counts": dict(origin_counts), | |
| "prompt_version_counts": dict(prompt_counts), "duplicate_group_count": len(duplicate_groups), | |
| "limitations": ["Near-duplicate visual similarity was not evaluated.", | |
| "Packaging does not certify mission feasibility, optimality, simulator execution, or expert annotation quality.", | |
| "License and visual-data provenance need owner review before publication."], | |
| "upload_performed": False, | |
| } | |
| write_json(output / "metadata" / "validation_report.json", report) | |
| example_scene = scenes[0] | |
| write_json(output / "examples" / "vision_sample.json", { | |
| k: v for k, v in example_scene.items() if not k.startswith("_")}) | |
| write_json(output / "examples" / "planning_sample.json", plans[0]) | |
| checksum_path = output / "metadata" / "checksums.sha256" | |
| checksum_lines = [] | |
| for path in sorted(output.rglob("*")): | |
| if path.is_file() and path != checksum_path: | |
| with path.open("rb") as stream: | |
| checksum_lines.append(f"{hashlib.file_digest(stream, 'sha256').hexdigest()} {path.relative_to(output).as_posix()}") | |
| checksum_path.write_text("\n".join(checksum_lines) + "\n", encoding="utf-8") | |
| print(json.dumps(report, ensure_ascii=False, indent=2), flush=True) | |
| if __name__ == "__main__": | |
| main() | |