Spaces:
Paused
Paused
Download python_files/prepare_dataset.py from Rachel7/hvac_fable: direct link, hf CLI and curl.
- Browser
- Download file 6.35 kB
-
https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/python_files/prepare_dataset.py
- Command line
-
hf download hf://spaces/Rachel7/hvac_fable/python_files/prepare_dataset.py
-
curl -L -o prepare_dataset.py https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/python_files/prepare_dataset.py
6.35 kB
| """ | |
| Prepare unified dataset from your annotated pages. | |
| INPUT directory layout: | |
| yolo_v2_data/pages/ | |
| page_001/ | |
| image.jpg <-- the page image | |
| labels.txt <-- YOLO format (one per box, normalized) | |
| page_002/ | |
| image.jpg | |
| labels.txt | |
| ... | |
| OUTPUT: | |
| yolo_v2_data/dataset_unified/ | |
| train/ | |
| images/ <- copied train images | |
| labels/ <- YOLO labels for train | |
| val/ | |
| images/ | |
| labels/ | |
| test/ | |
| images/ | |
| labels/ | |
| gold_train.json <- absolute-pixel gold for compare_models.py | |
| gold_val.json | |
| gold_test.json | |
| data.yaml <- YOLO dataset config | |
| split_info.json <- which pages went where | |
| Splits whole pages (not boxes) so test set is truly unseen. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import random | |
| import shutil | |
| from pathlib import Path | |
| from PIL import Image | |
| CLASS_NAMES = {0: "ceiling_ducted", 1: "wall_mounted"} | |
| def parse_yolo_label(label_path: Path, img_w: int, img_h: int) -> list[dict]: | |
| """Convert YOLO normalized labels to absolute-pixel boxes.""" | |
| boxes = [] | |
| if not label_path.exists(): | |
| return boxes | |
| for line in label_path.read_text().strip().splitlines(): | |
| parts = line.strip().split() | |
| if len(parts) != 5: | |
| continue | |
| cls, xc, yc, w, h = parts | |
| cls_id = int(cls) | |
| xc, yc, w, h = float(xc), float(yc), float(w), float(h) | |
| boxes.append({ | |
| "class": CLASS_NAMES.get(cls_id, f"class_{cls_id}"), | |
| "class_id": cls_id, | |
| "x1": int((xc - w/2) * img_w), | |
| "y1": int((yc - h/2) * img_h), | |
| "x2": int((xc + w/2) * img_w), | |
| "y2": int((yc + h/2) * img_h), | |
| "label": None, # text label not in YOLO format; can be added manually | |
| }) | |
| return boxes | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--source", default="yolo_v2_data/pages", | |
| help="Directory containing one folder per page") | |
| parser.add_argument("--output", default="yolo_v2_data/dataset_unified", | |
| help="Output directory") | |
| parser.add_argument("--train_ratio", type=float, default=0.6) | |
| parser.add_argument("--val_ratio", type=float, default=0.2) | |
| parser.add_argument("--seed", type=int, default=42) | |
| args = parser.parse_args() | |
| source = Path(args.source).resolve() | |
| output = Path(args.output).resolve() | |
| if not source.exists(): | |
| print(f"Source directory not found: {source}") | |
| print(f"\nExpected layout:") | |
| print(f" {source}/page_001/image.jpg + labels.txt") | |
| print(f" {source}/page_002/image.jpg + labels.txt") | |
| print(f" ...") | |
| return | |
| # Find pages | |
| pages = [] | |
| for page_dir in sorted(source.iterdir()): | |
| if not page_dir.is_dir(): | |
| continue | |
| img_candidates = list(page_dir.glob("*.jpg")) + list(page_dir.glob("*.png")) | |
| label_candidates = list(page_dir.glob("*.txt")) | |
| if not img_candidates or not label_candidates: | |
| print(f"Skipping {page_dir.name}: missing image or label") | |
| continue | |
| pages.append({ | |
| "page_id": page_dir.name, | |
| "image": img_candidates[0], | |
| "label": label_candidates[0], | |
| }) | |
| if not pages: | |
| print(f"No valid pages in {source}") | |
| return | |
| print(f"Found {len(pages)} pages") | |
| # Shuffle and split BY PAGE (so test set is truly unseen) | |
| random.seed(args.seed) | |
| random.shuffle(pages) | |
| n = len(pages) | |
| n_train = max(1, int(n * args.train_ratio)) | |
| n_val = max(1, int(n * args.val_ratio)) | |
| train_pages = pages[:n_train] | |
| val_pages = pages[n_train:n_train + n_val] | |
| test_pages = pages[n_train + n_val:] | |
| if not test_pages: | |
| # Move one from val to test if test is empty | |
| if len(val_pages) > 1: | |
| test_pages.append(val_pages.pop()) | |
| else: | |
| test_pages.append(train_pages.pop()) | |
| print(f"Split: {len(train_pages)} train / {len(val_pages)} val / {len(test_pages)} test") | |
| # Create output structure | |
| if output.exists(): | |
| shutil.rmtree(output) | |
| for split in ["train", "val", "test"]: | |
| (output / split / "images").mkdir(parents=True, exist_ok=True) | |
| (output / split / "labels").mkdir(parents=True, exist_ok=True) | |
| # Copy files + build gold JSON | |
| split_info = {} | |
| for split_name, split_pages in [("train", train_pages), ("val", val_pages), ("test", test_pages)]: | |
| gold_pages_list = [] | |
| page_ids = [] | |
| for p in split_pages: | |
| page_ids.append(p["page_id"]) | |
| # Copy image and label | |
| target_img = output / split_name / "images" / f"{p['page_id']}{p['image'].suffix}" | |
| target_lbl = output / split_name / "labels" / f"{p['page_id']}.txt" | |
| shutil.copy(p["image"], target_img) | |
| shutil.copy(p["label"], target_lbl) | |
| # Build gold entry | |
| img = Image.open(p["image"]) | |
| w, h = img.size | |
| gold_boxes = parse_yolo_label(p["label"], w, h) | |
| gold_pages_list.append({ | |
| "page_id": p["page_id"], | |
| "image_width": w, | |
| "image_height": h, | |
| "gold": gold_boxes, | |
| }) | |
| # Write gold JSON for this split | |
| (output / f"gold_{split_name}.json").write_text( | |
| json.dumps(gold_pages_list, indent=2) | |
| ) | |
| split_info[split_name] = page_ids | |
| print(f" {split_name}: {len(split_pages)} pages, " | |
| f"{sum(len(g['gold']) for g in gold_pages_list)} boxes") | |
| # data.yaml for YOLO | |
| data_yaml = { | |
| "path": str(output).replace("\\", "/"), | |
| "train": "train/images", | |
| "val": "val/images", | |
| "test": "test/images", | |
| "nc": 2, | |
| "names": list(CLASS_NAMES.values()), | |
| } | |
| import yaml | |
| (output / "data.yaml").write_text(yaml.dump(data_yaml, sort_keys=False)) | |
| # Split info | |
| (output / "split_info.json").write_text(json.dumps(split_info, indent=2)) | |
| print(f"\nDataset ready at: {output}") | |
| print(f" YOLO config: {output}/data.yaml") | |
| print(f" Gold (eval): {output}/gold_{{train,val,test}}.json") | |
| if __name__ == "__main__": | |
| main() | |