Datasets:
Download scripts/verify_dataset.py from ULM-DS-Lab/Sawit-Weight: direct link, hf CLI and curl.
- Browser
- Download file 9.45 kB
-
https://huggingface.co/datasets/ULM-DS-Lab/Sawit-Weight/resolve/main/scripts/verify_dataset.py
- Command line
-
hf download hf://datasets/ULM-DS-Lab/Sawit-Weight/scripts/verify_dataset.py
-
curl -L -o verify_dataset.py https://huggingface.co/datasets/ULM-DS-Lab/Sawit-Weight/resolve/main/scripts/verify_dataset.py
9.45 kB
| """Verify the Sawit-Weight dataset package. | |
| Two layers are checked. The as-captured layer under annotations/raw/ must still match | |
| every SHA-256 its manifests recorded. The corrected layer (annotations/labels/, | |
| annotations/trees.jsonl, data/train/metadata.jsonl) must be internally consistent and | |
| must differ from the raw layer only where a correction is declared below. | |
| python scripts/verify_dataset.py [dataset_root] | |
| """ | |
| import hashlib | |
| import json | |
| import os | |
| import sys | |
| TOL = 2e-3 # bbox_pixel and bbox_yolo agree to within this fraction of the image side | |
| # Corrections applied on top of the as-captured annotations, mirrored from the README. | |
| ADDED_BOXES = {("TANERA_303_BW_0004", 1)} # (tree, side_index) | |
| FRACTION_OVERRIDES = {"TANERA_303_BW_0003", "TANERA_303_BW_0004", "TANERA_303_BW_0005"} | |
| def sha256(path): | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for chunk in iter(lambda: f.read(1 << 20), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def read_json(path): | |
| with open(path, encoding="utf-8") as f: | |
| return json.load(f) | |
| def read_jsonl(path): | |
| with open(path, encoding="utf-8") as f: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def read_label(path): | |
| with open(path, encoding="utf-8") as f: | |
| return [line.split() for line in f.read().splitlines() if line.strip()] | |
| def main(root): | |
| images = os.path.join(root, "data", "train") | |
| ann = os.path.join(root, "annotations") | |
| raw = os.path.join(ann, "raw") | |
| fail = [] | |
| def check(ok, message): | |
| if not ok: | |
| fail.append(message) | |
| trees = sorted(f[:-5] for f in os.listdir(os.path.join(raw, "trees")) if f.endswith(".json")) | |
| check(len(trees) > 0, "no tree JSON found") | |
| seen_images, seen_labels, digests = set(), set(), {} | |
| for name in trees: | |
| tree = read_json(os.path.join(raw, "trees", f"{name}.json")) | |
| manifest = read_json(os.path.join(raw, "manifests", f"{name}.json")) | |
| device = os.path.join(raw, "device_metadata", f"{name}.json") | |
| check(tree["tree_name"] == name, f"{name}: tree_name does not match filename") | |
| # Layer 1: the as-captured artifacts still hash to what the device recorded. | |
| for side in manifest["sides"]: | |
| rgb = os.path.join(images, side["rgb"]["file"]) | |
| raw_label = os.path.join(raw, "labels", side["label"]["file"]) | |
| check(os.path.exists(rgb), f"{name}: missing image {side['rgb']['file']}") | |
| check(os.path.exists(raw_label), f"{name}: missing raw label {side['label']['file']}") | |
| if os.path.exists(rgb): | |
| digest = sha256(rgb) | |
| check(digest == side["rgb"]["sha256"], f"{name}: SHA-256 mismatch {side['rgb']['file']}") | |
| check(digest not in digests, f"{name}: duplicate image content, also in {digests.get(digest)}") | |
| digests[digest] = side["rgb"]["file"] | |
| seen_images.add(side["rgb"]["file"]) | |
| if os.path.exists(raw_label): | |
| check(sha256(raw_label) == side["label"]["sha256"], | |
| f"{name}: SHA-256 mismatch {side['label']['file']}") | |
| seen_labels.add(side["label"]["file"]) | |
| check(sha256(os.path.join(raw, "trees", f"{name}.json")) == manifest["outputJson"]["sha256"], | |
| f"{name}: SHA-256 mismatch on tree JSON") | |
| check(sha256(device) == manifest["metadata"]["sha256"], f"{name}: SHA-256 mismatch on device metadata") | |
| # Layer 2: the corrected labels are the raw ones plus only the declared additions. | |
| for key, side in tree["images"].items(): | |
| raw_rows = read_label(os.path.join(raw, "labels", side["label_file"])) | |
| fixed_rows = read_label(os.path.join(ann, "labels", side["label_file"])) | |
| expected = side["bbox_count"] + (1 if (name, side["side_index"]) in ADDED_BOXES else 0) | |
| check(len(raw_rows) == side["bbox_count"], | |
| f"{name}/{key}: raw label has {len(raw_rows)} rows, bbox_count is {side['bbox_count']}") | |
| check(len(fixed_rows) == expected, | |
| f"{name}/{key}: corrected label has {len(fixed_rows)} rows, expected {expected}") | |
| for parts in fixed_rows: | |
| check(parts[0] == "0", f"{name}/{key}: class id is not 0") | |
| check(all(0.0 <= float(v) <= 1.0 for v in parts[1:]), | |
| f"{name}/{key}: bbox outside [0, 1]") | |
| for i, parts in enumerate(raw_rows): | |
| check([round(float(v), 5) for v in parts[1:]] == [round(float(v), 5) for v in fixed_rows[i][1:]], | |
| f"{name}/{key}: corrected label altered the original box {i}") | |
| # Capture set coverage. | |
| capture_set = read_json(os.path.join(raw, "capture_set.json")) | |
| check({t["treeName"] for t in capture_set["trees"]} == set(trees), | |
| "capture_set.json does not list exactly the trees present") | |
| # No orphan files. | |
| on_disk_images = {f for f in os.listdir(images) if f.lower().endswith(".jpg")} | |
| on_disk_raw = {f for f in os.listdir(os.path.join(raw, "labels")) if f.endswith(".txt")} | |
| on_disk_fixed = {f for f in os.listdir(os.path.join(ann, "labels")) if f.endswith(".txt")} | |
| check(on_disk_images == seen_images, f"orphan images: {sorted(on_disk_images ^ seen_images)}") | |
| check(on_disk_raw == seen_labels, f"orphan raw labels: {sorted(on_disk_raw ^ seen_labels)}") | |
| check(on_disk_fixed == seen_labels, f"orphan corrected labels: {sorted(on_disk_fixed ^ seen_labels)}") | |
| # metadata.jsonl agrees with the corrected labels and with itself. | |
| rows = read_jsonl(os.path.join(images, "metadata.jsonl")) | |
| check({r["file_name"] for r in rows} == seen_images, "metadata.jsonl does not cover every image") | |
| check(len(rows) == len(seen_images), "metadata.jsonl has duplicate file_name rows") | |
| for row in rows: | |
| objects = row["objects"] | |
| lengths = {len(v) for v in objects.values()} | |
| check(lengths == {row["num_bunches"]}, f"{row['file_name']}: objects lists disagree with num_bunches") | |
| label_rows = read_label(os.path.join(ann, "labels", row["file_name"][:-4] + ".txt")) | |
| check(len(label_rows) == row["num_bunches"], | |
| f"{row['file_name']}: label row count disagrees with num_bunches") | |
| for i, parts in enumerate(label_rows): | |
| check([round(float(v), 6) for v in parts[1:]] == [round(v, 6) for v in objects["bbox_yolo"][i]], | |
| f"{row['file_name']}: label row {i} disagrees with bbox_yolo") | |
| w, h = row["width"], row["height"] | |
| for i, (cx, cy, bw, bh) in enumerate(objects["bbox_yolo"]): | |
| x1, y1, x2, y2 = objects["bbox_pixel"][i] | |
| check(x1 < x2 and y1 < y2, f"{row['file_name']}: box {i} has no positive area") | |
| check(abs((x1 + x2) / 2 / w - cx) < TOL and abs((y1 + y2) / 2 / h - cy) < TOL | |
| and abs((x2 - x1) / w - bw) < TOL and abs((y2 - y1) / h - bh) < TOL, | |
| f"{row['file_name']}: box {i} pixel and yolo forms disagree") | |
| for i, frac in enumerate(objects["ripeness_fraction"]): | |
| source = objects["ripeness_fraction_source"][i] | |
| check(frac in (1, 2, 3, 4, 5), f"{row['file_name']}: ripeness_fraction {frac} outside 1-5") | |
| check(source in ("field_note", "visual_estimate"), | |
| f"{row['file_name']}: unknown ripeness_fraction_source {source}") | |
| check(source == "field_note" or row["tree_name"] in FRACTION_OVERRIDES, | |
| f"{row['file_name']}: undeclared ripeness override") | |
| for i, source in enumerate(objects["bbox_source"]): | |
| check(source in ("field", "visual_estimate"), f"{row['file_name']}: unknown bbox_source {source}") | |
| check(source == "field" or (row["tree_name"], row["side_index"]) in ADDED_BOXES, | |
| f"{row['file_name']}: undeclared added box") | |
| for note in objects["notes"]: | |
| check(note is None or "FAKSI" not in note.upper().replace("FRAKSI", ""), | |
| f"{row['file_name']}: FAKSI left unnormalised in notes") | |
| tree_rows = read_jsonl(os.path.join(ann, "trees.jsonl")) | |
| check({r["tree_name"] for r in tree_rows} == set(trees), "trees.jsonl does not cover every tree") | |
| boxes_by_tree = {} | |
| for row in rows: | |
| boxes_by_tree[row["tree_name"]] = boxes_by_tree.get(row["tree_name"], 0) + row["num_bunches"] | |
| for row in tree_rows: | |
| check(row["total_detections"] == boxes_by_tree[row["tree_name"]], | |
| f"{row['tree_name']}: total_detections disagrees with metadata.jsonl") | |
| check(len(row["bunches"]) == row["total_unique_bunches"], | |
| f"{row['tree_name']}: bunch count disagrees with total_unique_bunches") | |
| for bunch in row["bunches"]: | |
| check(len(bunch["appearances"]) == bunch["appearance_count"], | |
| f"{row['tree_name']}: appearance_count disagrees with appearances") | |
| print(f"trees {len(trees)} | images {len(seen_images)} | labels {len(seen_labels)} | " | |
| f"boxes {sum(r['num_bunches'] for r in rows)}") | |
| if fail: | |
| print(f"FAIL: {len(fail)} problem(s)") | |
| for message in fail: | |
| print(f" - {message}") | |
| return 1 | |
| print("PASS: raw SHA-256 digests hold and the corrected layer is consistent") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else ".")) | |