Download simulation/datasets_construct.sh from bfz111/STDP-Dataset: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/datasets/bfz111/STDP-Dataset/resolve/main/simulation/datasets_construct.sh
- Command line
-
hf download hf://datasets/bfz111/STDP-Dataset/simulation/datasets_construct.sh
-
curl -L -o datasets_construct.sh https://huggingface.co/datasets/bfz111/STDP-Dataset/resolve/main/simulation/datasets_construct.sh
13.3 kB
| # | |
| # Build and verify four-view images for dataset trajectories. | |
| # | |
| # For each trajectory CSV, this script runs run.sh in dataset playback mode. | |
| # The Gazebo plugin stops at every waypoint and captures front/down/left/right. | |
| # After every run, this script verifies that all images referenced by the CSV | |
| # exist and rejects near-uniform frames or low-texture gray render patches. | |
| # Failed trajectories are restored and retried. | |
| # | |
| # Usage: | |
| # ./datasets_construct.sh | |
| # ./datasets_construct.sh gui | |
| # ./datasets_construct.sh datasets/world_v3 | |
| # DATASET_ROOT=./datasets/world_v3 ./datasets_construct.sh | |
| set -euo pipefail | |
| PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | |
| MODE_ARGS=() | |
| if [[ "${1:-}" == "gui" ]]; then | |
| MODE_ARGS+=(gui) | |
| shift | |
| fi | |
| ROOTS=() | |
| if [[ $# -gt 0 ]]; then | |
| for root in "$@"; do | |
| ROOTS+=("${root}") | |
| done | |
| elif [[ -n "${DATASET_ROOT:-}" ]]; then | |
| ROOTS+=("${DATASET_ROOT}") | |
| else | |
| ROOTS+=("${PROJECT_DIR}/datasets/world_v3") | |
| fi | |
| MAX_ATTEMPTS="${DATASET_CAPTURE_MAX_ATTEMPTS:-5}" | |
| CAPTURE_LIMIT="${DATASET_CAPTURE_LIMIT:-}" | |
| VALIDATOR_PY="$(mktemp /tmp/simple_drone_validate.XXXXXX.py)" | |
| ORIGINAL_CSV="" | |
| CURRENT_TRAJ="" | |
| cleanup() { | |
| rm -f "${VALIDATOR_PY}" | |
| if [[ -n "${ORIGINAL_CSV}" && -f "${ORIGINAL_CSV}" && -n "${CURRENT_TRAJ}" ]]; then | |
| cp "${ORIGINAL_CSV}" "${CURRENT_TRAJ}" 2>/dev/null || true | |
| fi | |
| if [[ -n "${ORIGINAL_CSV}" && -f "${ORIGINAL_CSV}" ]]; then | |
| rm -f "${ORIGINAL_CSV}" | |
| fi | |
| } | |
| trap cleanup EXIT | |
| cat > "${VALIDATOR_PY}" <<'PY' | |
| import csv | |
| import os | |
| import shutil | |
| import sys | |
| from pathlib import Path | |
| try: | |
| import numpy as np | |
| from PIL import Image | |
| except Exception as exc: | |
| print(f"validator dependency error: {exc}", file=sys.stderr) | |
| raise SystemExit(2) | |
| VIEWS = ("front", "down", "left", "right") | |
| GRAY_DELTA = int(os.environ.get("DATASET_GRAY_DELTA", "3")) | |
| GRAY_MIN = int(os.environ.get("DATASET_GRAY_MIN", "120")) | |
| GRAY_MAX = int(os.environ.get("DATASET_GRAY_MAX", "136")) | |
| GRAY_MAX_RATIO = min(0.99, max(0.0, float(os.environ.get("DATASET_GRAY_MAX_RATIO", "0.12")))) | |
| GRAY_TILE_RATIO = min(0.99, max(0.0, float(os.environ.get("DATASET_GRAY_TILE_RATIO", "0.90")))) | |
| GRAY_SCANLINE_RATIO = min(0.99, max(0.0, float(os.environ.get("DATASET_GRAY_SCANLINE_RATIO", "0.95")))) | |
| MIN_LUMA_STD = float(os.environ.get("DATASET_MIN_LUMA_STD", "4.0")) | |
| MIN_RGB_RANGE = int(os.environ.get("DATASET_MIN_RGB_RANGE", "12")) | |
| def rows_and_required(csv_path: Path): | |
| with csv_path.open(newline="", encoding="utf-8") as f: | |
| reader = csv.DictReader(f) | |
| required = { | |
| "capture_frame", | |
| "captured_yaw_rad", | |
| "captured_yaw_deg", | |
| "front_image", | |
| "down_image", | |
| "left_image", | |
| "right_image", | |
| } | |
| if not reader.fieldnames or not required.issubset(reader.fieldnames): | |
| return None, "missing capture/image columns" | |
| rows = list(reader) | |
| if not rows: | |
| return None, "empty trajectory CSV" | |
| return rows, "" | |
| def validate_image(path: Path): | |
| try: | |
| with Image.open(path) as image: | |
| rgb = image.convert("RGB") | |
| arr = np.asarray(rgb, dtype=np.uint8) | |
| except Exception as exc: | |
| return False, f"cannot open image: {path} ({exc})" | |
| if arr.ndim != 3 or arr.shape[0] < 8 or arr.shape[1] < 8: | |
| return False, f"bad image dimensions: {path}" | |
| channel_min = arr.min(axis=2).astype(np.int16) | |
| channel_max = arr.max(axis=2).astype(np.int16) | |
| luma = arr.mean(axis=2) | |
| rgb_range = int(arr.max()) - int(arr.min()) | |
| luma_std = float(luma.std()) | |
| if rgb_range < MIN_RGB_RANGE: | |
| return False, f"all/near-gray image: {path} range={rgb_range} luma_std={luma_std:.3f}" | |
| neutral = (channel_max - channel_min) <= GRAY_DELTA | |
| medium_gray = (luma >= GRAY_MIN) & (luma <= GRAY_MAX) | |
| gray_mask = neutral & medium_gray | |
| gray_ratio = float(gray_mask.mean()) | |
| if gray_ratio > GRAY_MAX_RATIO: | |
| return False, f"global gray ratio too high: {path} ratio={gray_ratio:.4f}" | |
| buffer_mask = np.all(arr == 128, axis=2) | |
| row_ratios = buffer_mask.mean(axis=1) | |
| column_ratios = buffer_mask.mean(axis=0) | |
| if float(row_ratios.max()) > GRAY_SCANLINE_RATIO: | |
| row = int(row_ratios.argmax()) | |
| return False, ( | |
| f"gray render-buffer row: {path} row={row} " | |
| f"ratio={float(row_ratios[row]):.4f}" | |
| ) | |
| if float(column_ratios.max()) > GRAY_SCANLINE_RATIO: | |
| column = int(column_ratios.argmax()) | |
| return False, ( | |
| f"gray render-buffer column: {path} column={column} " | |
| f"ratio={float(column_ratios[column]):.4f}" | |
| ) | |
| height, width = gray_mask.shape | |
| tile_h = max(1, height // 8) | |
| tile_w = max(1, width // 8) | |
| for y0 in range(0, height, tile_h): | |
| for x0 in range(0, width, tile_w): | |
| tile = gray_mask[y0:min(y0 + tile_h, height), x0:min(x0 + tile_w, width)] | |
| tile_ratio = float(tile.mean()) if tile.size else 0.0 | |
| tile_luma = luma[y0:min(y0 + tile_h, height), x0:min(x0 + tile_w, width)] | |
| tile_rgb = arr[y0:min(y0 + tile_h, height), x0:min(x0 + tile_w, width), :] | |
| tile_std = float(tile_luma.std()) if tile_luma.size else 0.0 | |
| tile_range = int(tile_rgb.max()) - int(tile_rgb.min()) if tile_rgb.size else 0 | |
| if tile_ratio > GRAY_TILE_RATIO and tile_std < MIN_LUMA_STD and tile_range < MIN_RGB_RANGE: | |
| return False, ( | |
| f"large low-texture gray tile: {path} " | |
| f"tile_ratio={tile_ratio:.4f} range={tile_range} luma_std={tile_std:.3f}" | |
| ) | |
| return True, "" | |
| def validate(dataset_root: Path, csv_path: Path): | |
| rows, reason = rows_and_required(csv_path) | |
| if rows is None: | |
| return False, reason | |
| image_root = dataset_root / "images" / csv_path.stem | |
| for index, row in enumerate(rows): | |
| if not row.get("capture_frame") or not row.get("captured_yaw_rad") or not row.get("captured_yaw_deg"): | |
| return False, f"row {index} missing capture metadata" | |
| for view in VIEWS: | |
| image_name = row.get(f"{view}_image", "") | |
| if not image_name: | |
| return False, f"row {index} missing {view}_image" | |
| image_path = image_root / f"images_{view}" / image_name | |
| if not image_path.is_file(): | |
| return False, f"missing image: {image_path}" | |
| ok, detail = validate_image(image_path) | |
| if not ok: | |
| return False, detail | |
| return True, "ok" | |
| def quick_complete(dataset_root: Path, csv_path: Path): | |
| rows, reason = rows_and_required(csv_path) | |
| if rows is None: | |
| return False, reason | |
| image_root = dataset_root / "images" / csv_path.stem | |
| for index, row in enumerate(rows): | |
| if not row.get("capture_frame") or not row.get("captured_yaw_rad") or not row.get("captured_yaw_deg"): | |
| return False, f"row {index} missing capture metadata" | |
| for view in VIEWS: | |
| image_name = row.get(f"{view}_image", "") | |
| if not image_name: | |
| return False, f"row {index} missing {view}_image" | |
| image_path = image_root / f"images_{view}" / image_name | |
| if not image_path.is_file(): | |
| return False, f"missing image: {image_path}" | |
| return True, "ok" | |
| def clean(dataset_root: Path, csv_path: Path): | |
| image_root = dataset_root / "images" / csv_path.stem | |
| if image_root.exists(): | |
| shutil.rmtree(image_root) | |
| def main(): | |
| if len(sys.argv) != 4: | |
| raise SystemExit("usage: validator.py validate|clean DATASET_ROOT CSV") | |
| command = sys.argv[1] | |
| dataset_root = Path(sys.argv[2]) | |
| csv_path = Path(sys.argv[3]) | |
| if command == "validate": | |
| ok, message = validate(dataset_root, csv_path) | |
| print(message) | |
| raise SystemExit(0 if ok else 1) | |
| if command == "quick": | |
| ok, message = quick_complete(dataset_root, csv_path) | |
| print(message) | |
| raise SystemExit(0 if ok else 1) | |
| if command == "clean": | |
| clean(dataset_root, csv_path) | |
| raise SystemExit(0) | |
| raise SystemExit(f"unknown command: {command}") | |
| if __name__ == "__main__": | |
| main() | |
| PY | |
| trajectory_complete() { | |
| local dataset_root="$1" | |
| local csv_path="$2" | |
| if [[ "${DATASET_REVALIDATE_EXISTING:-0}" != "0" ]]; then | |
| python3 "${VALIDATOR_PY}" validate "${dataset_root}" "${csv_path}" >/dev/null 2>&1 | |
| else | |
| python3 "${VALIDATOR_PY}" quick "${dataset_root}" "${csv_path}" >/dev/null 2>&1 | |
| fi | |
| } | |
| validate_or_explain() { | |
| local dataset_root="$1" | |
| local csv_path="$2" | |
| python3 "${VALIDATOR_PY}" validate "${dataset_root}" "${csv_path}" | |
| } | |
| clean_outputs() { | |
| local dataset_root="$1" | |
| local csv_path="$2" | |
| python3 "${VALIDATOR_PY}" clean "${dataset_root}" "${csv_path}" | |
| } | |
| for root in "${ROOTS[@]}"; do | |
| DATASET_ROOT_ABS="$(cd "${root}" && pwd)" | |
| TRAJECTORY_DIR="${DATASET_ROOT_ABS}/trajectory" | |
| if [[ ! -d "${TRAJECTORY_DIR}" ]]; then | |
| echo "[datasets_construct] trajectory directory not found: ${TRAJECTORY_DIR}" >&2 | |
| exit 1 | |
| fi | |
| mapfile -t ALL_TRAJECTORIES < <(find "${TRAJECTORY_DIR}" -maxdepth 1 -type f -name '*.csv' | sort) | |
| if [[ -n "${DATASET_CAPTURE_TRAJECTORY:-}" ]]; then | |
| REQUESTED_TRAJECTORY="${DATASET_CAPTURE_TRAJECTORY}" | |
| if [[ "${REQUESTED_TRAJECTORY}" != /* ]]; then | |
| REQUESTED_TRAJECTORY="${TRAJECTORY_DIR}/${REQUESTED_TRAJECTORY}" | |
| fi | |
| if [[ ! -f "${REQUESTED_TRAJECTORY}" ]]; then | |
| echo "[datasets_construct] requested trajectory not found: ${REQUESTED_TRAJECTORY}" >&2 | |
| exit 1 | |
| fi | |
| ALL_TRAJECTORIES=("$(cd "$(dirname "${REQUESTED_TRAJECTORY}")" && pwd)/$(basename "${REQUESTED_TRAJECTORY}")") | |
| fi | |
| if [[ "${#ALL_TRAJECTORIES[@]}" -eq 0 ]]; then | |
| echo "[datasets_construct] no trajectory CSV files found in ${TRAJECTORY_DIR}" >&2 | |
| exit 1 | |
| fi | |
| echo "[datasets_construct] dataset -> ${DATASET_ROOT_ABS}" | |
| echo "[datasets_construct] total trajectories -> ${#ALL_TRAJECTORIES[@]}" | |
| echo "[datasets_construct] scanning existing captures..." | |
| TRAJECTORIES=() | |
| scanned=0 | |
| for traj in "${ALL_TRAJECTORIES[@]}"; do | |
| scanned=$((scanned + 1)) | |
| if (( scanned % 100 == 0 )); then | |
| echo "[datasets_construct] scanned ${scanned}/${#ALL_TRAJECTORIES[@]}" | |
| fi | |
| if trajectory_complete "${DATASET_ROOT_ABS}" "${traj}"; then | |
| echo "[datasets_construct] skip verified $(basename "${traj}")" | |
| else | |
| TRAJECTORIES+=("${traj}") | |
| if [[ -n "${CAPTURE_LIMIT}" && "${#TRAJECTORIES[@]}" -ge "${CAPTURE_LIMIT}" ]]; then | |
| echo "[datasets_construct] reached DATASET_CAPTURE_LIMIT=${CAPTURE_LIMIT}; stopping scan early" | |
| break | |
| fi | |
| fi | |
| done | |
| echo "[datasets_construct] remaining trajectories -> ${#TRAJECTORIES[@]}" | |
| echo "[datasets_construct] max attempts -> ${MAX_ATTEMPTS}" | |
| if [[ "${#TRAJECTORIES[@]}" -eq 0 ]]; then | |
| echo "[datasets_construct] complete: all trajectories are already verified" | |
| continue | |
| fi | |
| skipped_timeouts=0 | |
| for i in "${!TRAJECTORIES[@]}"; do | |
| traj="${TRAJECTORIES[$i]}" | |
| CURRENT_TRAJ="${traj}" | |
| idx=$((i + 1)) | |
| echo "[datasets_construct] ${idx}/${#TRAJECTORIES[@]} running $(basename "${traj}")" | |
| ORIGINAL_CSV="$(mktemp /tmp/simple_drone_csv.XXXXXX)" | |
| cp "${traj}" "${ORIGINAL_CSV}" | |
| attempt=1 | |
| timed_out=0 | |
| while [[ "${attempt}" -le "${MAX_ATTEMPTS}" ]]; do | |
| echo "[datasets_construct] attempt ${attempt}/${MAX_ATTEMPTS} $(basename "${traj}")" | |
| cp "${ORIGINAL_CSV}" "${traj}" | |
| clean_outputs "${DATASET_ROOT_ABS}" "${traj}" | |
| if DATASET_ROOT="${DATASET_ROOT_ABS}" SIMPLE_DRONE_QUIT_ON_FINISH=1 \ | |
| SIMPLE_DRONE_RENDER_BACKEND="${SIMPLE_DRONE_RENDER_BACKEND:-system}" \ | |
| SIMPLE_DRONE_SINGLE_CAMERA_SWEEP="${SIMPLE_DRONE_SINGLE_CAMERA_SWEEP:-0}" \ | |
| "${PROJECT_DIR}/run.sh" "${MODE_ARGS[@]}" "${traj}"; then | |
| if validate_or_explain "${DATASET_ROOT_ABS}" "${traj}"; then | |
| echo "[datasets_construct] verified $(basename "${traj}")" | |
| rm -f "${ORIGINAL_CSV}" | |
| ORIGINAL_CSV="" | |
| CURRENT_TRAJ="" | |
| break | |
| fi | |
| else | |
| run_status=$? | |
| if [[ "${run_status}" -eq 124 ]]; then | |
| timed_out=1 | |
| echo "[datasets_construct] timeout after ${SIMPLE_DRONE_RUN_TIMEOUT:-900}s; skipping $(basename "${traj}")" >&2 | |
| break | |
| fi | |
| echo "[datasets_construct] run.sh failed for $(basename "${traj}") status=${run_status}" >&2 | |
| fi | |
| attempt=$((attempt + 1)) | |
| if [[ "${attempt}" -le "${MAX_ATTEMPTS}" ]]; then | |
| echo "[datasets_construct] retrying $(basename "${traj}")" | |
| sleep 1 | |
| fi | |
| done | |
| if [[ -n "${ORIGINAL_CSV}" ]]; then | |
| cp "${ORIGINAL_CSV}" "${traj}" | |
| rm -f "${ORIGINAL_CSV}" | |
| ORIGINAL_CSV="" | |
| CURRENT_TRAJ="" | |
| if [[ "${timed_out}" -ne 0 ]]; then | |
| clean_outputs "${DATASET_ROOT_ABS}" "${traj}" | |
| skipped_timeouts=$((skipped_timeouts + 1)) | |
| continue | |
| fi | |
| echo "[datasets_construct] failed after ${MAX_ATTEMPTS} attempts: ${traj}" >&2 | |
| exit 1 | |
| fi | |
| done | |
| if [[ "${skipped_timeouts}" -gt 0 ]]; then | |
| echo "[datasets_construct] skipped timed-out trajectories -> ${skipped_timeouts}" >&2 | |
| exit 1 | |
| fi | |
| done | |
| echo "[datasets_construct] complete" | |