Upload 6 files
Browse filesFiles changed (6)
- README.md+244-3
- convert-hf-dataset.pyAdded+375
- diff-hf-datasets.pyAdded+428
- sample-hf-dataset.pyAdded+341
- stats-hf-dataset.pyAdded+402
- validate-hf-dataset.pyAdded+455
123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244---viewer: falsetags: [uv-script, object-detection]---# Object Detection Dataset Scripts5 scripts to convert, validate, inspect, diff, and sample object detection datasets on the Hub. Supports 6 bbox formats — no setup required.This repository is inspired by [panlabel](https://github.com/strickvl/panlabel)## Quick StartConvert bounding box formats without cloning anything:```bash# Convert COCO-style bboxes to YOLO normalized formatuv run convert-hf-dataset.py merve/coco-dataset merve/coco-yolo \--from coco_xywh --to yolo --max-samples 100```That's it! The script will:- Load the dataset from the Hub- Convert all bounding boxes in-place- Push the result to a new dataset repo- View results at: `https://huggingface.co/datasets/merve/coco-yolo`## Scripts| Script | Description ||--------|-------------|| `convert-hf-dataset.py` | Convert between 6 bbox formats and push to Hub || `validate-hf-dataset.py` | Check annotations for errors (invalid bboxes, duplicates, bounds) || `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) || `diff-hf-datasets.py` | Compare two datasets semantically (IoU-based annotation matching) || `sample-hf-dataset.py` | Create subsets (random or stratified) and push to Hub |## Supported Bbox FormatsAll scripts support these 6 bounding box formats, matching the [panlabel](https://github.com/strickvl/panlabel) Rust CLI:| Format | Encoding | Coordinate Space ||--------|----------|------------------|| `coco_xywh` | `[x, y, width, height]` | Pixels || `xyxy` | `[xmin, ymin, xmax, ymax]` | Pixels || `voc` | `[xmin, ymin, xmax, ymax]` | Pixels (alias for `xyxy`) || `yolo` | `[center_x, center_y, width, height]` | Normalized 0–1 || `tfod` | `[xmin, ymin, xmax, ymax]` | Normalized 0–1 || `label_studio` | `[x, y, width, height]` | Percentage 0–100 |Conversions go through XYXY pixel-space as the intermediate representation, so any format can be converted to any other format.## Common OptionsAll scripts accept flexible column mapping. Datasets can store annotations as flat columns or nested under an `objects` dict — both layouts are handled automatically.| Option | Description ||--------|-------------|| `--bbox-column` | Column containing bboxes (default: `bbox`) || `--category-column` | Column containing category labels (default: `category`) || `--width-column` | Column for image width (default: `width`) || `--height-column` | Column for image height (default: `height`) || `--split` | Dataset split (default: `train`) || `--max-samples` | Limit number of samples (useful for testing) || `--hf-token` | HF API token (or set `HF_TOKEN` env var) || `--private` | Make output dataset private |Every script supports `--help` to see all available options:```bashuv run convert-hf-dataset.py --help```## Convert (`convert-hf-dataset.py`)Convert bounding boxes between any of the 6 supported formats:```bash# COCO -> XYXYuv run convert-hf-dataset.py merve/license-plates merve/license-plates-voc \--from coco_xywh --to voc# YOLO -> COCOuv run convert-hf-dataset.py merve/license-plates merve/license-plates-yolo \--from coco_xywh --to yolo# TFOD (normalized xyxy) -> COCOuv run convert-hf-dataset.py merve/license-plates-tfod merve/license-plates-coco \--from tfod --to coco_xywh# Label Studio (percentage xywh) -> XYXYuv run convert-hf-dataset.py merve/ls-dataset merve/ls-xyxy \--from label_studio --to xyxy# Test on 10 samples firstuv run convert-hf-dataset.py merve/dataset merve/converted \--from xyxy --to yolo --max-samples 10# Shuffle before converting a subsetuv run convert-hf-dataset.py merve/dataset merve/converted \--from coco_xywh --to tfod --max-samples 500 --shuffle```| Option | Description ||--------|-------------|| `--from` | Source bbox format (required) || `--to` | Target bbox format (required) || `--batch-size` | Batch size for map (default: 1000) || `--create-pr` | Push as PR instead of direct commit || `--shuffle` | Shuffle dataset before processing || `--seed` | Random seed for shuffling (default: 42) |## Validate (`validate-hf-dataset.py`)Check annotations for common issues:```bash# Basic validationuv run validate-hf-dataset.py merve/coco-dataset# Validate YOLO-format datasetuv run validate-hf-dataset.py merve/yolo-dataset --bbox-format yolo# Validate TFOD-format datasetuv run validate-hf-dataset.py merve/tfod-dataset --bbox-format tfod# Strict mode (warnings become errors)uv run validate-hf-dataset.py merve/dataset --strict# JSON reportuv run validate-hf-dataset.py merve/dataset --report json# Stream large datasets without full downloaduv run validate-hf-dataset.py merve/huge-dataset --streaming --max-samples 5000# Push validation report to Hubuv run validate-hf-dataset.py merve/dataset --output-dataset merve/validation-report```**Issue Codes:**| Code | Level | Description ||------|-------|-------------|| E001 | Error | Bbox/category count mismatch || E002 | Error | Invalid bbox (missing values) || E003 | Error | Non-finite coordinates (NaN/Inf) || E004 | Error | xmin > xmax || E005 | Error | ymin > ymax || W001 | Warning | No annotations in example || W002 | Warning | Zero or negative area || W003 | Warning | Bbox before image origin || W004 | Warning | Bbox beyond image bounds || W005 | Warning | Empty category label || W006 | Warning | Duplicate file name |## Stats (`stats-hf-dataset.py`)Compute rich statistics for a dataset:```bash# Basic statsuv run stats-hf-dataset.py merve/coco-dataset# Top 20 label histogram, JSON outputuv run stats-hf-dataset.py merve/dataset --top 20 --report json# Stats for TFOD-format datasetuv run stats-hf-dataset.py merve/dataset --bbox-format tfod# Stream large datasetsuv run stats-hf-dataset.py merve/huge-dataset --streaming --max-samples 10000# Push stats report to Hubuv run stats-hf-dataset.py merve/dataset --output-dataset merve/stats-report```Reports include: summary counts, label distribution, annotation density, bbox area/aspect ratio distributions, per-category area stats, category co-occurrence pairs, and image resolution distribution.## Diff (`diff-hf-datasets.py`)Compare two datasets semantically using IoU-based annotation matching:```bash# Basic diffuv run diff-hf-datasets.py merve/dataset-v1 merve/dataset-v2# Stricter matchinguv run diff-hf-datasets.py merve/old merve/new --iou-threshold 0.7# Per-annotation change detailsuv run diff-hf-datasets.py merve/old merve/new --detail# JSON reportuv run diff-hf-datasets.py merve/old merve/new --report json```Reports include: shared/unique images, shared/unique categories, matched/added/removed/modified annotations.## Sample (`sample-hf-dataset.py`)Create random or stratified subsets:```bash# Random 500 samplesuv run sample-hf-dataset.py merve/dataset merve/subset -n 500# 10% fractionuv run sample-hf-dataset.py merve/dataset merve/subset --fraction 0.1# Stratified sampling (preserves class distribution)uv run sample-hf-dataset.py merve/dataset merve/subset \-n 200 --strategy stratified# Filter by categoriesuv run sample-hf-dataset.py merve/dataset merve/subset \-n 100 --categories "cat,dog,bird"# Reproducible samplinguv run sample-hf-dataset.py merve/dataset merve/subset \-n 500 --seed 42```| Option | Description ||--------|-------------|| `-n` | Number of samples to select || `--fraction` | Fraction of dataset (0.0–1.0) || `--strategy` | `random` (default) or `stratified` || `--categories` | Comma-separated list of categories to filter by || `--category-mode` | `images` (default) or `annotations` |## Run Locally```bash# Clone and rungit clone https://huggingface.co/datasets/uv-scripts/panlabelcd panlabeluv run convert-hf-dataset.py input-dataset output-dataset --from coco_xywh --to yolo# Or run directly from URLuv run https://huggingface.co/datasets/uv-scripts/panlabel/raw/main/convert-hf-dataset.py \input-dataset output-dataset --from coco_xywh --to yolo```Works with any Hugging Face dataset containing object detection annotations — COCO, YOLO, VOC, TFOD, or Label Studio format.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375# /// script# requires-python = ">=3.11"# dependencies = [# "datasets>=3.1.0",# "huggingface-hub",# "tqdm",# "toolz",# "Pillow", # ]# ///
"""Convert bounding box formats in a Hugging Face object detection dataset.
Mirrors panlabel's convert command. Converts between: - COCO xywh: [x, y, width, height] in pixels - XYXY: [xmin, ymin, xmax, ymax] in pixels - VOC: [xmin, ymin, xmax, ymax] in pixels (alias for xyxy) - YOLO: [center_x, center_y, width, height] normalized 0-1 - TFOD: [xmin, ymin, xmax, ymax] normalized 0-1 - Label Studio: [x, y, width, height] percentage 0-100
Reads from HF Hub, converts bboxes in-place, and pushes the result to a new(or the same) dataset repo on HF Hub.
Examples: uv run convert-hf-dataset.py merve/coco-dataset merve/coco-xyxy --from coco_xywh --to xyxy uv run convert-hf-dataset.py merve/yolo-dataset merve/yolo-coco --from yolo --to coco_xywh uv run convert-hf-dataset.py merve/dataset merve/converted --from xyxy --to yolo --max-samples 100 uv run convert-hf-dataset.py merve/dataset merve/converted --from tfod --to coco_xywh uv run convert-hf-dataset.py merve/dataset merve/converted --from label_studio --to xyxy"""
import argparseimport jsonimport loggingimport osimport sysimport timefrom datetime import datetimefrom typing import Any
from datasets import load_datasetfrom huggingface_hub import DatasetCard, loginfrom toolz import partition_allfrom tqdm.auto import tqdm
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
BBOX_FORMATS = ["coco_xywh", "xyxy", "voc", "yolo", "tfod", "label_studio"]
def convert_bbox( bbox: list[float], from_fmt: str, to_fmt: str, img_w: float = 1.0, img_h: float = 1.0,) -> list[float]: """Convert a single bbox between formats via XYXY pixel-space intermediate.""" # Step 1: to XYXY pixel space if from_fmt == "coco_xywh": x, y, w, h = bbox[:4] xmin, ymin, xmax, ymax = x, y, x + w, y + h elif from_fmt in ("xyxy", "voc"): xmin, ymin, xmax, ymax = bbox[:4] elif from_fmt == "yolo": cx, cy, w, h = bbox[:4] xmin = (cx - w / 2) * img_w ymin = (cy - h / 2) * img_h xmax = (cx + w / 2) * img_w ymax = (cy + h / 2) * img_h elif from_fmt == "tfod": xmin_n, ymin_n, xmax_n, ymax_n = bbox[:4] xmin = xmin_n * img_w ymin = ymin_n * img_h xmax = xmax_n * img_w ymax = ymax_n * img_h elif from_fmt == "label_studio": x_pct, y_pct, w_pct, h_pct = bbox[:4] xmin = x_pct / 100.0 * img_w ymin = y_pct / 100.0 * img_h xmax = (x_pct + w_pct) / 100.0 * img_w ymax = (y_pct + h_pct) / 100.0 * img_h else: raise ValueError(f"Unknown source format: {from_fmt}")
# Step 2: from XYXY pixel space to target if to_fmt in ("xyxy", "voc"): return [xmin, ymin, xmax, ymax] elif to_fmt == "coco_xywh": return [xmin, ymin, xmax - xmin, ymax - ymin] elif to_fmt == "yolo": if img_w <= 0 or img_h <= 0: raise ValueError("YOLO format requires positive image dimensions") w = xmax - xmin h = ymax - ymin cx = (xmin + w / 2) / img_w cy = (ymin + h / 2) / img_h return [cx, cy, w / img_w, h / img_h] elif to_fmt == "tfod": if img_w <= 0 or img_h <= 0: raise ValueError("TFOD format requires positive image dimensions") return [xmin / img_w, ymin / img_h, xmax / img_w, ymax / img_h] elif to_fmt == "label_studio": if img_w <= 0 or img_h <= 0: raise ValueError("Label Studio format requires positive image dimensions") x_pct = xmin / img_w * 100.0 y_pct = ymin / img_h * 100.0 w_pct = (xmax - xmin) / img_w * 100.0 h_pct = (ymax - ymin) / img_h * 100.0 return [x_pct, y_pct, w_pct, h_pct] else: raise ValueError(f"Unknown target format: {to_fmt}")
def convert_example( example: dict[str, Any], bbox_column: str, from_fmt: str, to_fmt: str, width_column: str | None, height_column: str | None,) -> dict[str, Any]: """Convert bboxes in a single example.""" objects = example.get("objects") is_nested = objects is not None and isinstance(objects, dict)
if is_nested: bboxes = objects.get(bbox_column, []) or [] else: bboxes = example.get(bbox_column, []) or []
img_w = 1.0 img_h = 1.0 if width_column: img_w = float(example.get(width_column, 1.0) or 1.0) if height_column: img_h = float(example.get(height_column, 1.0) or 1.0)
converted = [] for bbox in bboxes: if bbox is None or len(bbox) < 4: converted.append(bbox) continue converted.append(convert_bbox(bbox, from_fmt, to_fmt, img_w, img_h))
if is_nested: new_objects = dict(objects) new_objects[bbox_column] = converted return {"objects": new_objects} else: return {bbox_column: converted}
def create_dataset_card( source_dataset: str, output_dataset: str, from_fmt: str, to_fmt: str, num_samples: int, processing_time: str, split: str,) -> str: return f"""---tags:- object-detection- bbox-conversion- panlabel- uv-script- generated---
# Bbox Format Conversion: {from_fmt} -> {to_fmt}
Bounding boxes converted from `{from_fmt}` to `{to_fmt}` format.
## Processing Details
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})- **Conversion**: `{from_fmt}` -> `{to_fmt}`- **Number of Samples**: {num_samples:,}- **Processing Time**: {processing_time}- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}- **Split**: `{split}`
## Bbox Formats
| Format | Description ||--------|-------------|| `coco_xywh` | `[x, y, width, height]` in pixels || `xyxy` | `[xmin, ymin, xmax, ymax]` in pixels || `voc` | `[xmin, ymin, xmax, ymax]` in pixels (alias for xyxy) || `yolo` | `[center_x, center_y, width, height]` normalized 0-1 || `tfod` | `[xmin, ymin, xmax, ymax]` normalized 0-1 || `label_studio` | `[x, y, width, height]` percentage 0-100 |
## Reproduction
```bashuv run convert-hf-dataset.py {source_dataset} {output_dataset} --from {from_fmt} --to {to_fmt}```
Generated with panlabel-hf (convert-hf-dataset.py)"""
def main( input_dataset: str, output_dataset: str, from_fmt: str, to_fmt: str, bbox_column: str = "bbox", width_column: str | None = "width", height_column: str | None = "height", split: str = "train", max_samples: int | None = None, batch_size: int = 1000, hf_token: str | None = None, private: bool = False, create_pr: bool = False, shuffle: bool = False, seed: int = 42,): """Convert bbox format in a HF dataset and push to Hub."""
if from_fmt == to_fmt: logger.error(f"Source and target formats are the same: {from_fmt}") sys.exit(1)
start_time = datetime.now()
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN)
logger.info(f"Loading dataset: {input_dataset} (split={split})") dataset = load_dataset(input_dataset, split=split)
if shuffle: logger.info(f"Shuffling dataset with seed {seed}") dataset = dataset.shuffle(seed=seed)
if max_samples: dataset = dataset.select(range(min(max_samples, len(dataset)))) logger.info(f"Limited to {len(dataset)} samples")
total_samples = len(dataset) logger.info(f"Converting {total_samples:,} samples: {from_fmt} -> {to_fmt}")
# Convert using map dataset = dataset.map( lambda example: convert_example( example, bbox_column, from_fmt, to_fmt, width_column, height_column ), desc=f"Converting {from_fmt} -> {to_fmt}", )
processing_duration = datetime.now() - start_time processing_time_str = f"{processing_duration.total_seconds():.1f}s"
# Add conversion metadata conversion_info = json.dumps({ "source_format": from_fmt, "target_format": to_fmt, "source_dataset": input_dataset, "timestamp": datetime.now().isoformat(), "script": "convert-hf-dataset.py", })
if "conversion_info" not in dataset.column_names: dataset = dataset.add_column( "conversion_info", [conversion_info] * len(dataset) )
# Push to Hub logger.info(f"Pushing to {output_dataset}") max_retries = 3 for attempt in range(1, max_retries + 1): try: if attempt > 1: logger.warning("Disabling XET (fallback to HTTP upload)") os.environ["HF_HUB_DISABLE_XET"] = "1" dataset.push_to_hub( output_dataset, private=private, token=HF_TOKEN, max_shard_size="500MB", create_pr=create_pr, ) break except Exception as e: logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}") if attempt < max_retries: delay = 30 * (2 ** (attempt - 1)) logger.info(f"Retrying in {delay}s...") time.sleep(delay) else: logger.error("All upload attempts failed.") sys.exit(1)
# Push dataset card card_content = create_dataset_card( source_dataset=input_dataset, output_dataset=output_dataset, from_fmt=from_fmt, to_fmt=to_fmt, num_samples=total_samples, processing_time=processing_time_str, split=split, ) card = DatasetCard(card_content) card.push_to_hub(output_dataset, token=HF_TOKEN)
logger.info("Done!") logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}") logger.info(f"Converted {total_samples:,} samples in {processing_time_str}")
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Convert bbox formats in a HF object detection dataset", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Bbox formats: coco_xywh [x, y, width, height] in pixels xyxy [xmin, ymin, xmax, ymax] in pixels voc [xmin, ymin, xmax, ymax] in pixels (alias for xyxy) yolo [cx, cy, w, h] normalized 0-1 tfod [xmin, ymin, xmax, ymax] normalized 0-1 label_studio [x, y, w, h] percentage 0-100
Examples: uv run convert-hf-dataset.py merve/coco merve/coco-xyxy --from coco_xywh --to xyxy uv run convert-hf-dataset.py merve/yolo merve/yolo-coco --from yolo --to coco_xywh uv run convert-hf-dataset.py merve/tfod merve/tfod-coco --from tfod --to coco_xywh """, )
parser.add_argument("input_dataset", help="Input dataset ID on HF Hub") parser.add_argument("output_dataset", help="Output dataset ID on HF Hub") parser.add_argument("--from", dest="from_fmt", required=True, choices=BBOX_FORMATS, help="Source bbox format") parser.add_argument("--to", dest="to_fmt", required=True, choices=BBOX_FORMATS, help="Target bbox format") parser.add_argument("--bbox-column", default="bbox", help="Column containing bboxes (default: bbox)") parser.add_argument("--width-column", default="width", help="Column for image width (default: width)") parser.add_argument("--height-column", default="height", help="Column for image height (default: height)") parser.add_argument("--split", default="train", help="Dataset split (default: train)") parser.add_argument("--max-samples", type=int, help="Max samples to process") parser.add_argument("--batch-size", type=int, default=1000, help="Batch size for map (default: 1000)") parser.add_argument("--hf-token", help="HF API token") parser.add_argument("--private", action="store_true", help="Make output dataset private") parser.add_argument("--create-pr", action="store_true", help="Create PR instead of direct push") parser.add_argument("--shuffle", action="store_true", help="Shuffle dataset before processing") parser.add_argument("--seed", type=int, default=42, help="Random seed (default: 42)")
args = parser.parse_args()
main( input_dataset=args.input_dataset, output_dataset=args.output_dataset, from_fmt=args.from_fmt, to_fmt=args.to_fmt, bbox_column=args.bbox_column, width_column=args.width_column, height_column=args.height_column, split=args.split, max_samples=args.max_samples, batch_size=args.batch_size, hf_token=args.hf_token, private=args.private, create_pr=args.create_pr, shuffle=args.shuffle, seed=args.seed, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428# /// script# requires-python = ">=3.11"# dependencies = [# "datasets>=3.1.0",# "huggingface-hub",# "tqdm",# "Pillow", # ]# ///
"""Semantic diff between two object detection datasets on Hugging Face Hub.
Mirrors panlabel's diff command. Compares two dataset versions and reports:
- Images shared / only-in-A / only-in-B- Categories shared / only-in-A / only-in-B- Annotations added / removed / modified- Bbox geometry changes (IoU-based matching)
Matching strategies: - ID-based: Match images by file_name or image_id column - For annotations within shared images, match by IoU threshold
Examples: uv run diff-hf-datasets.py merve/dataset-v1 merve/dataset-v2 uv run diff-hf-datasets.py merve/old merve/new --iou-threshold 0.7 --detail uv run diff-hf-datasets.py merve/old merve/new --report json"""
import argparseimport jsonimport loggingimport mathimport osimport sysfrom collections import Counter, defaultdictfrom datetime import datetimefrom typing import Any
from datasets import load_datasetfrom huggingface_hub import loginfrom tqdm.auto import tqdm
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
BBOX_FORMATS = ["coco_xywh", "xyxy", "voc", "yolo", "tfod", "label_studio"]
def to_xyxy(bbox: list[float], fmt: str, img_w: float = 1.0, img_h: float = 1.0) -> tuple[float, float, float, float]: if fmt == "coco_xywh": x, y, w, h = bbox return (x, y, x + w, y + h) elif fmt in ("xyxy", "voc"): return tuple(bbox[:4]) elif fmt == "yolo": cx, cy, w, h = bbox return (cx - w / 2) * img_w, (cy - h / 2) * img_h, (cx + w / 2) * img_w, (cy + h / 2) * img_h elif fmt == "tfod": xmin_n, ymin_n, xmax_n, ymax_n = bbox return (xmin_n * img_w, ymin_n * img_h, xmax_n * img_w, ymax_n * img_h) elif fmt == "label_studio": x_pct, y_pct, w_pct, h_pct = bbox return ( x_pct / 100.0 * img_w, y_pct / 100.0 * img_h, (x_pct + w_pct) / 100.0 * img_w, (y_pct + h_pct) / 100.0 * img_h, ) else: raise ValueError(f"Unknown bbox format: {fmt}")
def compute_iou(box_a: tuple, box_b: tuple) -> float: """Compute IoU between two XYXY boxes.""" xa = max(box_a[0], box_b[0]) ya = max(box_a[1], box_b[1]) xb = min(box_a[2], box_b[2]) yb = min(box_a[3], box_b[3])
inter = max(0, xb - xa) * max(0, yb - ya) area_a = (box_a[2] - box_a[0]) * (box_a[3] - box_a[1]) area_b = (box_b[2] - box_b[0]) * (box_b[3] - box_b[1]) union = area_a + area_b - inter
if union <= 0: return 0.0 return inter / union
def extract_annotations( example: dict[str, Any], bbox_column: str, category_column: str, bbox_format: str, width_column: str | None, height_column: str | None,) -> list[dict]: """Extract annotations from example as list of {bbox_xyxy, category}.""" objects = example.get("objects", example) bboxes = objects.get(bbox_column, []) or [] categories = objects.get(category_column, []) or []
img_w = 1.0 img_h = 1.0 if width_column: img_w = float(example.get(width_column, 1.0) or 1.0) if height_column: img_h = float(example.get(height_column, 1.0) or 1.0)
anns = [] for i, bbox in enumerate(bboxes): if bbox is None or len(bbox) < 4: continue if not all(math.isfinite(v) for v in bbox[:4]): continue xyxy = to_xyxy(bbox[:4], bbox_format, img_w, img_h) cat = str(categories[i]) if i < len(categories) else "<unknown>" anns.append({"bbox_xyxy": xyxy, "category": cat})
return anns
def match_annotations_iou( anns_a: list[dict], anns_b: list[dict], iou_threshold: float,) -> tuple[list[tuple[int, int, float]], list[int], list[int]]: """Greedy IoU matching. Returns (matched_pairs, unmatched_a, unmatched_b).""" if not anns_a or not anns_b: return [], list(range(len(anns_a))), list(range(len(anns_b)))
# Compute all pairwise IoUs pairs = [] for i, a in enumerate(anns_a): for j, b in enumerate(anns_b): iou = compute_iou(a["bbox_xyxy"], b["bbox_xyxy"]) if iou >= iou_threshold: pairs.append((iou, i, j))
pairs.sort(reverse=True)
matched_a = set() matched_b = set() matches = []
for iou, i, j in pairs: if i not in matched_a and j not in matched_b: matches.append((i, j, iou)) matched_a.add(i) matched_b.add(j)
unmatched_a = [i for i in range(len(anns_a)) if i not in matched_a] unmatched_b = [j for j in range(len(anns_b)) if j not in matched_b]
return matches, unmatched_a, unmatched_b
def get_image_key(example: dict, id_column: str) -> str: """Get a unique key for an image example.""" val = example.get(id_column) if val is not None: return str(val) return str(example.get("file_name", ""))
def main( dataset_a: str, dataset_b: str, bbox_column: str = "bbox", category_column: str = "category", bbox_format: str = "coco_xywh", id_column: str = "image_id", width_column: str | None = "width", height_column: str | None = "height", split: str = "train", max_samples: int | None = None, iou_threshold: float = 0.5, detail: bool = False, report_format: str = "text", hf_token: str | None = None,): """Compare two object detection datasets semantically."""
start_time = datetime.now()
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN)
logger.info(f"Loading dataset A: {dataset_a}") ds_a = load_dataset(dataset_a, split=split) logger.info(f"Loading dataset B: {dataset_b}") ds_b = load_dataset(dataset_b, split=split)
if max_samples: ds_a = ds_a.select(range(min(max_samples, len(ds_a)))) ds_b = ds_b.select(range(min(max_samples, len(ds_b))))
# Index by image key logger.info("Indexing images...") index_a = {} for i in tqdm(range(len(ds_a)), desc="Indexing A"): ex = ds_a[i] key = get_image_key(ex, id_column) index_a[key] = ex
index_b = {} for i in tqdm(range(len(ds_b)), desc="Indexing B"): ex = ds_b[i] key = get_image_key(ex, id_column) index_b[key] = ex
keys_a = set(index_a.keys()) keys_b = set(index_b.keys())
shared_keys = keys_a & keys_b only_a_keys = keys_a - keys_b only_b_keys = keys_b - keys_a
# Collect all categories cats_a = set() cats_b = set() total_added = 0 total_removed = 0 total_modified = 0 total_matched = 0 detail_records = []
logger.info(f"Comparing {len(shared_keys)} shared images...") for key in tqdm(sorted(shared_keys), desc="Diffing"): ex_a = index_a[key] ex_b = index_b[key]
anns_a = extract_annotations(ex_a, bbox_column, category_column, bbox_format, width_column, height_column) anns_b = extract_annotations(ex_b, bbox_column, category_column, bbox_format, width_column, height_column)
for a in anns_a: cats_a.add(a["category"]) for b in anns_b: cats_b.add(b["category"])
matches, unmatched_a, unmatched_b = match_annotations_iou(anns_a, anns_b, iou_threshold)
total_matched += len(matches) total_removed += len(unmatched_a) total_added += len(unmatched_b)
# Check for category changes in matched pairs for i, j, iou in matches: if anns_a[i]["category"] != anns_b[j]["category"]: total_modified += 1 if detail: detail_records.append({ "image": key, "type": "modified", "from_category": anns_a[i]["category"], "to_category": anns_b[j]["category"], "iou": round(iou, 3), })
if detail: for idx in unmatched_a: detail_records.append({ "image": key, "type": "removed", "category": anns_a[idx]["category"], "bbox": list(anns_a[idx]["bbox_xyxy"]), }) for idx in unmatched_b: detail_records.append({ "image": key, "type": "added", "category": anns_b[idx]["category"], "bbox": list(anns_b[idx]["bbox_xyxy"]), })
# Count annotations in only-A and only-B images anns_only_a = 0 for key in only_a_keys: anns = extract_annotations(index_a[key], bbox_column, category_column, bbox_format, width_column, height_column) anns_only_a += len(anns) for a in anns: cats_a.add(a["category"])
anns_only_b = 0 for key in only_b_keys: anns = extract_annotations(index_b[key], bbox_column, category_column, bbox_format, width_column, height_column) anns_only_b += len(anns) for b in anns: cats_b.add(b["category"])
shared_cats = cats_a & cats_b only_a_cats = cats_a - cats_b only_b_cats = cats_b - cats_a
processing_time = datetime.now() - start_time
report = { "dataset_a": dataset_a, "dataset_b": dataset_b, "split": split, "iou_threshold": iou_threshold, "images": { "in_a": len(keys_a), "in_b": len(keys_b), "shared": len(shared_keys), "only_in_a": len(only_a_keys), "only_in_b": len(only_b_keys), }, "categories": { "in_a": len(cats_a), "in_b": len(cats_b), "shared": len(shared_cats), "only_in_a": sorted(only_a_cats), "only_in_b": sorted(only_b_cats), }, "annotations": { "matched": total_matched, "modified": total_modified, "added_in_shared_images": total_added, "removed_in_shared_images": total_removed, "in_only_a_images": anns_only_a, "in_only_b_images": anns_only_b, }, "processing_time_seconds": processing_time.total_seconds(), }
if detail: report["details"] = detail_records
if report_format == "json": print(json.dumps(report, indent=2)) else: print("\n" + "=" * 60) print(f"Dataset Diff") print(f" A: {dataset_a}") print(f" B: {dataset_b}") print("=" * 60)
img = report["images"] print(f"\n Images:") print(f" A: {img['in_a']:,} | B: {img['in_b']:,}") print(f" Shared: {img['shared']:,}") print(f" Only in A: {img['only_in_a']:,}") print(f" Only in B: {img['only_in_b']:,}")
cat = report["categories"] print(f"\n Categories:") print(f" A: {cat['in_a']} | B: {cat['in_b']} | Shared: {cat['shared']}") if cat["only_in_a"]: print(f" Only in A: {', '.join(cat['only_in_a'][:10])}") if cat["only_in_b"]: print(f" Only in B: {', '.join(cat['only_in_b'][:10])}")
ann = report["annotations"] print(f"\n Annotations (IoU >= {iou_threshold}):") print(f" Matched: {ann['matched']:,}") print(f" Modified: {ann['modified']:,} (category changed)") print(f" Added: {ann['added_in_shared_images']:,} (in shared images)") print(f" Removed: {ann['removed_in_shared_images']:,} (in shared images)") if ann["in_only_a_images"]: print(f" In A-only images: {ann['in_only_a_images']:,}") if ann["in_only_b_images"]: print(f" In B-only images: {ann['in_only_b_images']:,}")
if detail and detail_records: print(f"\n Detail ({len(detail_records)} changes):") for rec in detail_records[:20]: if rec["type"] == "modified": print(f" [{rec['image']}] {rec['from_category']} -> {rec['to_category']} (IoU={rec['iou']})") elif rec["type"] == "added": print(f" [{rec['image']}] + {rec['category']}") elif rec["type"] == "removed": print(f" [{rec['image']}] - {rec['category']}") if len(detail_records) > 20: print(f" ... and {len(detail_records) - 20} more")
print(f"\n Processing time: {processing_time.total_seconds():.1f}s") print("=" * 60)
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Semantic diff between two object detection datasets on HF Hub", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Examples: uv run diff-hf-datasets.py merve/dataset-v1 merve/dataset-v2 uv run diff-hf-datasets.py merve/old merve/new --iou-threshold 0.7 --detail uv run diff-hf-datasets.py merve/old merve/new --report json """, )
parser.add_argument("dataset_a", help="First dataset ID (A)") parser.add_argument("dataset_b", help="Second dataset ID (B)") parser.add_argument("--bbox-column", default="bbox", help="Column containing bboxes (default: bbox)") parser.add_argument("--category-column", default="category", help="Column containing categories (default: category)") parser.add_argument("--bbox-format", choices=BBOX_FORMATS, default="coco_xywh", help="Bbox format (default: coco_xywh)") parser.add_argument("--id-column", default="image_id", help="Column to match images by (default: image_id)") parser.add_argument("--width-column", default="width", help="Column for image width (default: width)") parser.add_argument("--height-column", default="height", help="Column for image height (default: height)") parser.add_argument("--split", default="train", help="Dataset split (default: train)") parser.add_argument("--max-samples", type=int, help="Max samples per dataset") parser.add_argument("--iou-threshold", type=float, default=0.5, help="IoU threshold for matching (default: 0.5)") parser.add_argument("--detail", action="store_true", help="Show per-annotation changes") parser.add_argument("--report", choices=["text", "json"], default="text", help="Report format (default: text)") parser.add_argument("--hf-token", help="HF API token")
args = parser.parse_args()
main( dataset_a=args.dataset_a, dataset_b=args.dataset_b, bbox_column=args.bbox_column, category_column=args.category_column, bbox_format=args.bbox_format, id_column=args.id_column, width_column=args.width_column, height_column=args.height_column, split=args.split, max_samples=args.max_samples, iou_threshold=args.iou_threshold, detail=args.detail, report_format=args.report, hf_token=args.hf_token, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341# /// script# requires-python = ">=3.11"# dependencies = [# "datasets>=3.1.0",# "huggingface-hub",# "tqdm",# "Pillow", # ]# ///
"""Create random or stratified subsets of object detection datasets on HF Hub.
Mirrors panlabel's sample command. Supports:
- Random sampling: Uniform random selection of N images or a fraction- Stratified sampling: Category-aware weighted sampling to preserve class distribution- Category filtering: Select only images containing specific categories- Category mode: Filter by image-level or annotation-level membership
Pushes the resulting subset to a new dataset repo on HF Hub.
Examples: uv run sample-hf-dataset.py merve/dataset merve/subset -n 500 uv run sample-hf-dataset.py merve/dataset merve/subset --fraction 0.1 uv run sample-hf-dataset.py merve/dataset merve/subset -n 200 --strategy stratified uv run sample-hf-dataset.py merve/dataset merve/subset -n 100 --categories "cat,dog,bird""""
import argparseimport jsonimport loggingimport osimport randomimport sysimport timefrom collections import Counter, defaultdictfrom datetime import datetimefrom typing import Any
from datasets import load_datasetfrom huggingface_hub import DatasetCard, loginfrom tqdm.auto import tqdm
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
def get_image_categories( example: dict[str, Any], category_column: str,) -> list[str]: """Get list of category labels from an example.""" objects = example.get("objects", example) categories = objects.get(category_column, []) or [] return [str(c) for c in categories if c is not None]
def create_dataset_card( source_dataset: str, output_dataset: str, strategy: str, num_samples: int, original_size: int, categories_filter: list[str] | None, category_mode: str, seed: int, split: str,) -> str: fraction = num_samples / original_size if original_size > 0 else 0 filter_str = f"\n- **Category Filter**: {', '.join(categories_filter)}" if categories_filter else "" return f"""---tags:- object-detection- dataset-subset- panlabel- uv-script- generated---
# Dataset Subset: {strategy} sampling
A {strategy} subset of [{source_dataset}](https://huggingface.co/datasets/{source_dataset}).
## Details
- **Source**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})- **Strategy**: {strategy}- **Samples**: {num_samples:,} / {original_size:,} ({fraction:.1%})- **Seed**: {seed}- **Split**: `{split}`- **Category Mode**: {category_mode}{filter_str}- **Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
## Reproduction
```bashuv run sample-hf-dataset.py {source_dataset} {output_dataset} \\ -n {num_samples} --strategy {strategy} --seed {seed}```
Generated with panlabel-hf (sample-hf-dataset.py)"""
def main( input_dataset: str, output_dataset: str, n: int | None = None, fraction: float | None = None, strategy: str = "random", category_column: str = "category", categories: list[str] | None = None, category_mode: str = "images", split: str = "train", seed: int = 42, hf_token: str | None = None, private: bool = False, create_pr: bool = False,): """Create a subset of an object detection dataset and push to Hub."""
start_time = datetime.now()
if n is None and fraction is None: logger.error("Must specify either -n (count) or --fraction") sys.exit(1)
if n is not None and fraction is not None: logger.error("Specify only one of -n or --fraction, not both") sys.exit(1)
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN)
logger.info(f"Loading dataset: {input_dataset} (split={split})") dataset = load_dataset(input_dataset, split=split) original_size = len(dataset) logger.info(f"Loaded {original_size:,} examples")
# Determine target count if fraction is not None: target_n = max(1, int(original_size * fraction)) logger.info(f"Fraction {fraction} -> {target_n:,} samples") else: target_n = min(n, original_size)
rng = random.Random(seed)
# Category filtering if categories: logger.info(f"Filtering by categories: {categories} (mode={category_mode})") keep_indices = [] for idx in tqdm(range(original_size), desc="Filtering"): ex = dataset[idx] img_cats = get_image_categories(ex, category_column) if category_mode == "images": # Keep image if ANY of its annotations match if any(c in categories for c in img_cats): keep_indices.append(idx) else: # annotations mode — just check presence, filtering happens below if any(c in categories for c in img_cats): keep_indices.append(idx)
dataset = dataset.select(keep_indices) logger.info(f"After category filter: {len(dataset):,} examples") target_n = min(target_n, len(dataset))
if strategy == "random": logger.info(f"Random sampling {target_n:,} from {len(dataset):,}") indices = list(range(len(dataset))) rng.shuffle(indices) selected = sorted(indices[:target_n]) dataset = dataset.select(selected)
elif strategy == "stratified": logger.info(f"Stratified sampling {target_n:,} from {len(dataset):,}")
# Count categories per image and build index cat_to_images = defaultdict(list) for idx in tqdm(range(len(dataset)), desc="Indexing categories"): ex = dataset[idx] img_cats = set(get_image_categories(ex, category_column)) for cat in img_cats: cat_to_images[cat].append(idx)
# Compute per-category allocation proportional to frequency total_cat_count = sum(len(imgs) for imgs in cat_to_images.values()) cat_allocations = {} for cat, imgs in cat_to_images.items(): cat_allocations[cat] = max(1, round(target_n * len(imgs) / total_cat_count))
# Greedy selection: pick from underrepresented categories first selected = set() cat_fulfilled = Counter()
# Sort categories by allocation (smallest first for better representation) sorted_cats = sorted(cat_allocations.keys(), key=lambda c: cat_allocations[c])
for cat in sorted_cats: needed = cat_allocations[cat] - cat_fulfilled[cat] if needed <= 0: continue
available = [i for i in cat_to_images[cat] if i not in selected] rng.shuffle(available) pick = available[:needed] selected.update(pick)
# Update fulfilled counts for all categories of picked images for idx in pick: ex = dataset[idx] for c in set(get_image_categories(ex, category_column)): cat_fulfilled[c] += 1
# If we still need more, fill randomly if len(selected) < target_n: remaining = [i for i in range(len(dataset)) if i not in selected] rng.shuffle(remaining) selected.update(remaining[: target_n - len(selected)])
# If we have too many, trim selected_list = sorted(selected) if len(selected_list) > target_n: rng.shuffle(selected_list) selected_list = sorted(selected_list[:target_n])
dataset = dataset.select(selected_list) logger.info(f"Selected {len(dataset):,} samples via stratified sampling")
else: logger.error(f"Unknown strategy: {strategy}") sys.exit(1)
num_samples = len(dataset) processing_duration = datetime.now() - start_time processing_time_str = f"{processing_duration.total_seconds():.1f}s"
# Push to Hub logger.info(f"Pushing {num_samples:,} samples to {output_dataset}") max_retries = 3 for attempt in range(1, max_retries + 1): try: if attempt > 1: logger.warning("Disabling XET (fallback to HTTP upload)") os.environ["HF_HUB_DISABLE_XET"] = "1" dataset.push_to_hub( output_dataset, private=private, token=HF_TOKEN, max_shard_size="500MB", create_pr=create_pr, ) break except Exception as e: logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}") if attempt < max_retries: delay = 30 * (2 ** (attempt - 1)) logger.info(f"Retrying in {delay}s...") time.sleep(delay) else: logger.error("All upload attempts failed.") sys.exit(1)
# Push dataset card card_content = create_dataset_card( source_dataset=input_dataset, output_dataset=output_dataset, strategy=strategy, num_samples=num_samples, original_size=original_size, categories_filter=categories, category_mode=category_mode, seed=seed, split=split, ) card = DatasetCard(card_content) card.push_to_hub(output_dataset, token=HF_TOKEN)
logger.info("Done!") logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}") logger.info(f"Sampled {num_samples:,} / {original_size:,} in {processing_time_str}")
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Create random or stratified subsets of HF object detection datasets", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Strategies: random Uniform random selection (default) stratified Category-aware weighted sampling
Category modes (with --categories): images Keep images containing any matching annotation (default) annotations Keep images containing any matching annotation
Examples: uv run sample-hf-dataset.py merve/dataset merve/subset -n 500 uv run sample-hf-dataset.py merve/dataset merve/subset --fraction 0.1 uv run sample-hf-dataset.py merve/dataset merve/subset -n 200 --strategy stratified uv run sample-hf-dataset.py merve/dataset merve/subset -n 100 --categories "cat,dog" """, )
parser.add_argument("input_dataset", help="Input dataset ID on HF Hub") parser.add_argument("output_dataset", help="Output dataset ID on HF Hub") parser.add_argument("-n", type=int, help="Number of samples to select") parser.add_argument("--fraction", type=float, help="Fraction of dataset to select (0.0-1.0)") parser.add_argument("--strategy", choices=["random", "stratified"], default="random", help="Sampling strategy (default: random)") parser.add_argument("--category-column", default="category", help="Column containing categories (default: category)") parser.add_argument("--categories", help="Comma-separated list of categories to filter by") parser.add_argument("--category-mode", choices=["images", "annotations"], default="images", help="How to apply category filter (default: images)") parser.add_argument("--split", default="train", help="Dataset split (default: train)") parser.add_argument("--seed", type=int, default=42, help="Random seed (default: 42)") parser.add_argument("--hf-token", help="HF API token") parser.add_argument("--private", action="store_true", help="Make output dataset private") parser.add_argument("--create-pr", action="store_true", help="Create PR instead of direct push")
args = parser.parse_args()
cats = None if args.categories: cats = [c.strip() for c in args.categories.split(",")]
main( input_dataset=args.input_dataset, output_dataset=args.output_dataset, n=args.n, fraction=args.fraction, strategy=args.strategy, category_column=args.category_column, categories=cats, category_mode=args.category_mode, split=args.split, seed=args.seed, hf_token=args.hf_token, private=args.private, create_pr=args.create_pr, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402# /// script# requires-python = ">=3.11"# dependencies = [# "datasets>=3.1.0",# "huggingface-hub",# "tqdm",# "Pillow", # ]# ///
"""Generate rich statistics for object detection datasets on Hugging Face Hub.
Mirrors panlabel's stats command. Computes:
- Summary counts (images, annotations, categories)- Label distribution histogram (top-N)- Bounding box statistics (area, aspect ratio, out-of-bounds)- Annotation density per image- Per-category bbox statistics- Category co-occurrence pairs- Image resolution distribution
Supports COCO-style (xywh), XYXY/VOC, YOLO (normalized center xywh),TFOD (normalized xyxy), and Label Studio (percentage xywh) bbox formats.Supports streaming for large datasets. Outputs text or JSON.
Examples: uv run stats-hf-dataset.py merve/test-coco-dataset uv run stats-hf-dataset.py merve/test-coco-dataset --top 20 --report json uv run stats-hf-dataset.py merve/test-coco-dataset --bbox-format tfod uv run stats-hf-dataset.py merve/test-coco-dataset --streaming --max-samples 5000"""
import argparseimport jsonimport loggingimport mathimport osimport sysimport timefrom collections import Counter, defaultdictfrom datetime import datetimefrom typing import Any
from datasets import load_datasetfrom huggingface_hub import DatasetCard, loginfrom tqdm.auto import tqdm
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
BBOX_FORMATS = ["coco_xywh", "xyxy", "voc", "yolo", "tfod", "label_studio"]
def to_xyxy(bbox: list[float], fmt: str, img_w: float = 1.0, img_h: float = 1.0) -> tuple[float, float, float, float]: """Convert any bbox format to (xmin, ymin, xmax, ymax) in pixel space.""" if fmt == "coco_xywh": x, y, w, h = bbox return (x, y, x + w, y + h) elif fmt in ("xyxy", "voc"): return tuple(bbox[:4]) elif fmt == "yolo": cx, cy, w, h = bbox return (cx - w / 2) * img_w, (cy - h / 2) * img_h, (cx + w / 2) * img_w, (cy + h / 2) * img_h elif fmt == "tfod": xmin_n, ymin_n, xmax_n, ymax_n = bbox return (xmin_n * img_w, ymin_n * img_h, xmax_n * img_w, ymax_n * img_h) elif fmt == "label_studio": x_pct, y_pct, w_pct, h_pct = bbox return ( x_pct / 100.0 * img_w, y_pct / 100.0 * img_h, (x_pct + w_pct) / 100.0 * img_w, (y_pct + h_pct) / 100.0 * img_h, ) else: raise ValueError(f"Unknown bbox format: {fmt}")
def percentile(sorted_vals: list[float], p: float) -> float: """Compute percentile from sorted values.""" if not sorted_vals: return 0.0 k = (len(sorted_vals) - 1) * p / 100.0 f = int(k) c = f + 1 if c >= len(sorted_vals): return sorted_vals[-1] return sorted_vals[f] + (k - f) * (sorted_vals[c] - sorted_vals[f])
def main( input_dataset: str, bbox_column: str = "bbox", category_column: str = "category", bbox_format: str = "coco_xywh", width_column: str | None = "width", height_column: str | None = "height", split: str = "train", max_samples: int | None = None, streaming: bool = False, top: int = 10, report_format: str = "text", tolerance: float = 0.5, hf_token: str | None = None, output_dataset: str | None = None, private: bool = False,): """Compute statistics for an object detection dataset."""
start_time = datetime.now()
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN)
logger.info(f"Loading dataset: {input_dataset} (split={split}, streaming={streaming})") dataset = load_dataset(input_dataset, split=split, streaming=streaming)
# Accumulators total_images = 0 total_annotations = 0 category_counts = Counter() annotations_per_image = [] areas = [] aspect_ratios = [] widths = [] heights = [] out_of_bounds_count = 0 zero_area_count = 0 per_category_areas = defaultdict(list) co_occurrence_pairs = Counter() images_without_annotations = 0
iterable = dataset if max_samples: if streaming: iterable = dataset.take(max_samples) else: iterable = dataset.select(range(min(max_samples, len(dataset))))
for idx, example in enumerate(tqdm(iterable, desc="Computing stats", total=max_samples)): total_images += 1
objects = example.get("objects", example) bboxes = objects.get(bbox_column, []) or [] categories = objects.get(category_column, []) or []
# Image dimensions img_w = None img_h = None if width_column: img_w = example.get(width_column) or (objects.get(width_column) if isinstance(objects, dict) else None) if height_column: img_h = example.get(height_column) or (objects.get(height_column) if isinstance(objects, dict) else None)
if img_w is not None and img_h is not None: widths.append(img_w) heights.append(img_h)
num_anns = len(bboxes) annotations_per_image.append(num_anns) total_annotations += num_anns
if num_anns == 0: images_without_annotations += 1 continue
# Track categories and co-occurrences image_cats = set() for ann_idx, bbox in enumerate(bboxes): cat = categories[ann_idx] if ann_idx < len(categories) else None cat_str = str(cat) if cat is not None else "<unknown>" category_counts[cat_str] += 1 image_cats.add(cat_str)
if bbox is None or len(bbox) < 4: continue if not all(math.isfinite(v) for v in bbox[:4]): continue
w_for_conv = img_w if img_w else 1.0 h_for_conv = img_h if img_h else 1.0 xmin, ymin, xmax, ymax = to_xyxy(bbox[:4], bbox_format, w_for_conv, h_for_conv)
bw = xmax - xmin bh = ymax - ymin area = bw * bh
if area <= 0: zero_area_count += 1 else: areas.append(area) per_category_areas[cat_str].append(area)
if bh > 0: aspect_ratios.append(bw / bh)
# Out of bounds check if img_w is not None and img_h is not None: if xmin < -tolerance or ymin < -tolerance or xmax > img_w + tolerance or ymax > img_h + tolerance: out_of_bounds_count += 1
# Co-occurrence pairs sorted_cats = sorted(image_cats) for i in range(len(sorted_cats)): for j in range(i + 1, len(sorted_cats)): co_occurrence_pairs[(sorted_cats[i], sorted_cats[j])] += 1
processing_time = datetime.now() - start_time
# Compute distribution stats areas.sort() aspect_ratios.sort() annotations_per_image.sort()
def dist_stats(vals: list[float]) -> dict: if not vals: return {"count": 0, "min": 0, "max": 0, "mean": 0, "median": 0, "p25": 0, "p75": 0} return { "count": len(vals), "min": round(vals[0], 2), "max": round(vals[-1], 2), "mean": round(sum(vals) / len(vals), 2), "median": round(percentile(vals, 50), 2), "p25": round(percentile(vals, 25), 2), "p75": round(percentile(vals, 75), 2), }
# Top-N categories top_categories = category_counts.most_common(top)
# Top co-occurrence pairs top_cooccurrences = co_occurrence_pairs.most_common(top)
# Per-category bbox area stats per_cat_stats = {} for cat, cat_areas in sorted(per_category_areas.items(), key=lambda x: -len(x[1])): cat_areas.sort() per_cat_stats[cat] = dist_stats(cat_areas)
report = { "dataset": input_dataset, "split": split, "summary": { "total_images": total_images, "total_annotations": total_annotations, "unique_categories": len(category_counts), "images_without_annotations": images_without_annotations, "out_of_bounds_bboxes": out_of_bounds_count, "zero_area_bboxes": zero_area_count, }, "label_distribution": {cat: count for cat, count in top_categories}, "annotation_density": dist_stats([float(x) for x in annotations_per_image]), "bbox_area": dist_stats(areas), "bbox_aspect_ratio": dist_stats(aspect_ratios), "image_resolution": { "width": dist_stats([float(w) for w in sorted(widths)]) if widths else {}, "height": dist_stats([float(h) for h in sorted(heights)]) if heights else {}, }, "per_category_area": {cat: per_cat_stats[cat] for cat in list(per_cat_stats)[:top]}, "co_occurrence_pairs": [ {"pair": list(pair), "count": count} for pair, count in top_cooccurrences ], "processing_time_seconds": processing_time.total_seconds(), "timestamp": datetime.now().isoformat(), }
if report_format == "json": print(json.dumps(report, indent=2)) else: print("\n" + "=" * 60) print(f"Dataset Statistics: {input_dataset}") print("=" * 60)
s = report["summary"] print(f"\n Images: {s['total_images']:,}") print(f" Annotations: {s['total_annotations']:,}") print(f" Categories: {s['unique_categories']:,}") print(f" Empty images: {s['images_without_annotations']:,}") print(f" Out-of-bounds: {s['out_of_bounds_bboxes']:,}") print(f" Zero-area bboxes: {s['zero_area_bboxes']:,}")
if total_images > 0: print(f"\n Annotations/image: {total_annotations / total_images:.1f} avg")
d = report["annotation_density"] if d["count"]: print(f" min={d['min']}, median={d['median']}, max={d['max']}")
print(f"\n Label Distribution (top {top}):") for cat, count in top_categories: pct = 100.0 * count / total_annotations if total_annotations else 0 bar = "#" * int(pct / 2) print(f" {cat:30s} {count:>8,} ({pct:5.1f}%) {bar}")
a = report["bbox_area"] if a["count"]: print(f"\n Bbox Area:") print(f" min={a['min']}, median={a['median']}, mean={a['mean']}, max={a['max']}")
ar = report["bbox_aspect_ratio"] if ar["count"]: print(f"\n Bbox Aspect Ratio (w/h):") print(f" min={ar['min']}, median={ar['median']}, mean={ar['mean']}, max={ar['max']}")
if top_cooccurrences: print(f"\n Category Co-occurrence (top {top}):") for pair, count in top_cooccurrences: print(f" {pair[0]} + {pair[1]}: {count:,}")
print(f"\n Processing time: {processing_time.total_seconds():.1f}s") print("=" * 60)
# Optionally push stats report as a dataset if output_dataset: from datasets import Dataset as HFDataset
report_ds = HFDataset.from_dict({ "report_json": [json.dumps(report)], "dataset": [input_dataset], "total_images": [total_images], "total_annotations": [total_annotations], "unique_categories": [len(category_counts)], "timestamp": [datetime.now().isoformat()], })
logger.info(f"Pushing stats report to {output_dataset}") max_retries = 3 for attempt in range(1, max_retries + 1): try: if attempt > 1: os.environ["HF_HUB_DISABLE_XET"] = "1" report_ds.push_to_hub(output_dataset, private=private, token=HF_TOKEN) break except Exception as e: logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}") if attempt < max_retries: time.sleep(30 * (2 ** (attempt - 1))) else: logger.error("All upload attempts failed.") sys.exit(1)
logger.info(f"Stats pushed to: https://huggingface.co/datasets/{output_dataset}")
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Generate statistics for object detection datasets on HF Hub", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Bbox formats: coco_xywh [x, y, width, height] in pixels (default) xyxy [xmin, ymin, xmax, ymax] in pixels voc [xmin, ymin, xmax, ymax] in pixels (alias for xyxy) yolo [cx, cy, w, h] normalized 0-1 tfod [xmin, ymin, xmax, ymax] normalized 0-1 label_studio [x, y, w, h] percentage 0-100
Examples: uv run stats-hf-dataset.py merve/coco-dataset uv run stats-hf-dataset.py merve/coco-dataset --top 20 --report json uv run stats-hf-dataset.py merve/coco-dataset --streaming --max-samples 5000 """, )
parser.add_argument("input_dataset", help="Input dataset ID on HF Hub") parser.add_argument("--bbox-column", default="bbox", help="Column containing bboxes (default: bbox)") parser.add_argument("--category-column", default="category", help="Column containing categories (default: category)") parser.add_argument("--bbox-format", choices=BBOX_FORMATS, default="coco_xywh", help="Bbox format (default: coco_xywh)") parser.add_argument("--width-column", default="width", help="Column for image width (default: width)") parser.add_argument("--height-column", default="height", help="Column for image height (default: height)") parser.add_argument("--split", default="train", help="Dataset split (default: train)") parser.add_argument("--max-samples", type=int, help="Max samples to process") parser.add_argument("--streaming", action="store_true", help="Use streaming mode") parser.add_argument("--top", type=int, default=10, help="Top-N items for histograms (default: 10)") parser.add_argument("--report", choices=["text", "json"], default="text", help="Report format (default: text)") parser.add_argument("--tolerance", type=float, default=0.5, help="Out-of-bounds tolerance in pixels (default: 0.5)") parser.add_argument("--hf-token", help="HF API token") parser.add_argument("--output-dataset", help="Push stats report to this HF dataset") parser.add_argument("--private", action="store_true", help="Make output dataset private")
args = parser.parse_args()
main( input_dataset=args.input_dataset, bbox_column=args.bbox_column, category_column=args.category_column, bbox_format=args.bbox_format, width_column=args.width_column, height_column=args.height_column, split=args.split, max_samples=args.max_samples, streaming=args.streaming, top=args.top, report_format=args.report, tolerance=args.tolerance, hf_token=args.hf_token, output_dataset=args.output_dataset, private=args.private, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455# /// script# requires-python = ">=3.11"# dependencies = [# "datasets>=3.1.0",# "huggingface-hub",# "tqdm",# "Pillow", # ]# ///
"""Validate object detection annotations in a Hugging Face dataset.
Streams a HF dataset and checks for common annotation issues, mirroringpanlabel's validate command. Checks include:
- Duplicate image file names- Missing or empty bounding boxes- Bounding box ordering (xmin <= xmax, ymin <= ymax)- Bounding boxes out of image bounds- Non-finite coordinates (NaN/Inf)- Zero-area bounding boxes- Empty or missing category labels- Category ID consistency
Supports COCO-style (xywh), XYXY/VOC, YOLO (normalized center xywh),TFOD (normalized xyxy), and Label Studio (percentage xywh) bbox formats.Outputs a validation report as text or JSON.
Examples: uv run validate-hf-dataset.py merve/test-coco-dataset uv run validate-hf-dataset.py merve/test-coco-dataset --bbox-format xyxy --strict uv run validate-hf-dataset.py merve/test-coco-dataset --bbox-format tfod --report json uv run validate-hf-dataset.py merve/test-coco-dataset --report json --max-samples 1000"""
import argparseimport jsonimport loggingimport mathimport osimport sysimport timefrom collections import Counter, defaultdictfrom datetime import datetimefrom typing import Any
from datasets import load_datasetfrom huggingface_hub import DatasetCard, loginfrom tqdm.auto import tqdm
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
BBOX_FORMATS = ["coco_xywh", "xyxy", "voc", "yolo", "tfod", "label_studio"]
def to_xyxy(bbox: list[float], fmt: str, img_w: float = 1.0, img_h: float = 1.0) -> tuple[float, float, float, float]: """Convert any bbox format to (xmin, ymin, xmax, ymax) in pixel space.""" if fmt == "coco_xywh": x, y, w, h = bbox return (x, y, x + w, y + h) elif fmt in ("xyxy", "voc"): return tuple(bbox[:4]) elif fmt == "yolo": cx, cy, w, h = bbox xmin = (cx - w / 2) * img_w ymin = (cy - h / 2) * img_h xmax = (cx + w / 2) * img_w ymax = (cy + h / 2) * img_h return (xmin, ymin, xmax, ymax) elif fmt == "tfod": xmin_n, ymin_n, xmax_n, ymax_n = bbox return (xmin_n * img_w, ymin_n * img_h, xmax_n * img_w, ymax_n * img_h) elif fmt == "label_studio": x_pct, y_pct, w_pct, h_pct = bbox return ( x_pct / 100.0 * img_w, y_pct / 100.0 * img_h, (x_pct + w_pct) / 100.0 * img_w, (y_pct + h_pct) / 100.0 * img_h, ) else: raise ValueError(f"Unknown bbox format: {fmt}")
def is_finite(val: float) -> bool: return not (math.isnan(val) or math.isinf(val))
def validate_example( example: dict[str, Any], idx: int, bbox_column: str, category_column: str, bbox_format: str, image_column: str, width_column: str | None, height_column: str | None, tolerance: float = 0.5,) -> list[dict]: """Validate a single example. Returns a list of issue dicts.""" issues = []
def add_issue(level: str, code: str, message: str, ann_idx: int | None = None): issue = {"level": level, "code": code, "message": message, "example_idx": idx} if ann_idx is not None: issue["annotation_idx"] = ann_idx issues.append(issue)
# Get objects container — handle nested dict (objects column) or flat lists objects = example.get("objects", example) bboxes = objects.get(bbox_column, []) categories = objects.get(category_column, [])
if bboxes is None: bboxes = [] if categories is None: categories = []
# Image dimensions (if available) img_w = None img_h = None if width_column and width_column in example: img_w = example[width_column] elif width_column and objects and width_column in objects: img_w = objects[width_column] if height_column and height_column in example: img_h = example[height_column] elif height_column and objects and height_column in objects: img_h = objects[height_column]
if not bboxes and not categories: add_issue("warning", "W001", "No annotations found in this example") return issues
if len(bboxes) != len(categories): add_issue( "error", "E001", f"Bbox count ({len(bboxes)}) != category count ({len(categories)})", )
for ann_idx, bbox in enumerate(bboxes): if bbox is None or len(bbox) < 4: add_issue("error", "E002", f"Invalid bbox (need 4 values, got {bbox})", ann_idx) continue
# Check finite if not all(is_finite(v) for v in bbox[:4]): add_issue("error", "E003", f"Non-finite bbox coordinates: {bbox}", ann_idx) continue
# Convert to xyxy w_for_conv = img_w if img_w else 1.0 h_for_conv = img_h if img_h else 1.0 xmin, ymin, xmax, ymax = to_xyxy(bbox[:4], bbox_format, w_for_conv, h_for_conv)
# Check ordering if xmin > xmax: add_issue("error", "E004", f"xmin ({xmin}) > xmax ({xmax})", ann_idx) if ymin > ymax: add_issue("error", "E005", f"ymin ({ymin}) > ymax ({ymax})", ann_idx)
# Check zero area area = (xmax - xmin) * (ymax - ymin) if area <= 0: add_issue("warning", "W002", f"Zero or negative area bbox: {bbox}", ann_idx)
# Check bounds (only if image dimensions available) if img_w is not None and img_h is not None: if xmin < -tolerance or ymin < -tolerance: add_issue( "warning", "W003", f"Bbox extends before image origin: ({xmin}, {ymin})", ann_idx, ) if xmax > img_w + tolerance or ymax > img_h + tolerance: add_issue( "warning", "W004", f"Bbox extends beyond image bounds: ({xmax}, {ymax}) > ({img_w}, {img_h})", ann_idx, )
# Check categories for ann_idx, cat in enumerate(categories): if cat is None or (isinstance(cat, str) and cat.strip() == ""): add_issue("warning", "W005", "Empty category label", ann_idx)
return issues
def main( input_dataset: str, bbox_column: str = "bbox", category_column: str = "category", bbox_format: str = "coco_xywh", image_column: str = "image", width_column: str | None = "width", height_column: str | None = "height", split: str = "train", max_samples: int | None = None, streaming: bool = False, strict: bool = False, report_format: str = "text", tolerance: float = 0.5, hf_token: str | None = None, output_dataset: str | None = None, private: bool = False,): """Validate an object detection dataset from HF Hub."""
start_time = datetime.now()
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN)
logger.info(f"Loading dataset: {input_dataset} (split={split}, streaming={streaming})") dataset = load_dataset(input_dataset, split=split, streaming=streaming)
all_issues = [] file_names = [] total_annotations = 0 total_examples = 0 category_counts = Counter() error_count = 0 warning_count = 0
iterable = dataset if max_samples: if streaming: iterable = dataset.take(max_samples) else: iterable = dataset.select(range(min(max_samples, len(dataset))))
for idx, example in enumerate(tqdm(iterable, desc="Validating", total=max_samples)): total_examples += 1
issues = validate_example( example=example, idx=idx, bbox_column=bbox_column, category_column=category_column, bbox_format=bbox_format, image_column=image_column, width_column=width_column, height_column=height_column, tolerance=tolerance, ) all_issues.extend(issues)
# Count stats objects = example.get("objects", example) bboxes = objects.get(bbox_column, []) or [] categories = objects.get(category_column, []) or [] total_annotations += len(bboxes) for cat in categories: if cat is not None: category_counts[str(cat)] += 1
# Track file names for duplicate check fname = example.get("file_name") or example.get("image_id") or str(idx) file_names.append(fname)
# Check duplicate file names fname_counts = Counter(file_names) duplicates = {k: v for k, v in fname_counts.items() if v > 1} for fname, count in duplicates.items(): all_issues.append({ "level": "warning", "code": "W006", "message": f"Duplicate file name '{fname}' appears {count} times", "example_idx": None, })
for issue in all_issues: if issue["level"] == "error": error_count += 1 else: warning_count += 1
processing_time = datetime.now() - start_time
# Build report report = { "dataset": input_dataset, "split": split, "total_examples": total_examples, "total_annotations": total_annotations, "unique_categories": len(category_counts), "errors": error_count, "warnings": warning_count, "duplicate_filenames": len(duplicates), "issues": all_issues, "processing_time_seconds": processing_time.total_seconds(), "timestamp": datetime.now().isoformat(), "valid": error_count == 0 and (not strict or warning_count == 0), }
if report_format == "json": print(json.dumps(report, indent=2)) else: print("\n" + "=" * 60) print(f"Validation Report: {input_dataset}") print("=" * 60) print(f" Examples: {total_examples:,}") print(f" Annotations: {total_annotations:,}") print(f" Categories: {len(category_counts):,}") print(f" Errors: {error_count}") print(f" Warnings: {warning_count}") if duplicates: print(f" Duplicate IDs: {len(duplicates)}") print(f" Processing: {processing_time.total_seconds():.1f}s") print()
if all_issues: print("Issues:") # Group by code by_code = defaultdict(list) for issue in all_issues: by_code[issue["code"]].append(issue)
for code in sorted(by_code.keys()): code_issues = by_code[code] level = code_issues[0]["level"].upper() sample = code_issues[0]["message"] print(f" [{level}] {code}: {sample}") if len(code_issues) > 1: print(f" ... and {len(code_issues) - 1} more") print()
status = "VALID" if report["valid"] else "INVALID" mode = " (strict)" if strict else "" print(f"Result: {status}{mode}") print("=" * 60)
# Optionally push validation report as a dataset if output_dataset: from datasets import Dataset as HFDataset
report_ds = HFDataset.from_dict({ "report": [json.dumps(report)], "dataset": [input_dataset], "valid": [report["valid"]], "errors": [error_count], "warnings": [warning_count], "total_examples": [total_examples], "total_annotations": [total_annotations], "timestamp": [datetime.now().isoformat()], })
logger.info(f"Pushing validation report to {output_dataset}") max_retries = 3 for attempt in range(1, max_retries + 1): try: if attempt > 1: os.environ["HF_HUB_DISABLE_XET"] = "1" report_ds.push_to_hub( output_dataset, private=private, token=HF_TOKEN, ) break except Exception as e: logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}") if attempt < max_retries: time.sleep(30 * (2 ** (attempt - 1))) else: logger.error("All upload attempts failed.") sys.exit(1)
logger.info(f"Report pushed to: https://huggingface.co/datasets/{output_dataset}")
if not report["valid"]: sys.exit(1 if strict else 0)
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Validate object detection annotations in a HF dataset", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Bbox formats: coco_xywh [x, y, width, height] in pixels (default) xyxy [xmin, ymin, xmax, ymax] in pixels voc [xmin, ymin, xmax, ymax] in pixels (alias for xyxy) yolo [cx, cy, w, h] normalized 0-1 tfod [xmin, ymin, xmax, ymax] normalized 0-1 label_studio [x, y, w, h] percentage 0-100
Issue codes: E001 Bbox/category count mismatch E002 Invalid bbox (missing values) E003 Non-finite coordinates (NaN/Inf) E004 xmin > xmax E005 ymin > ymax W001 No annotations in example W002 Zero or negative area W003 Bbox before image origin W004 Bbox beyond image bounds W005 Empty category label W006 Duplicate file name
Examples: uv run validate-hf-dataset.py merve/coco-dataset uv run validate-hf-dataset.py merve/coco-dataset --bbox-format xyxy --strict uv run validate-hf-dataset.py merve/coco-dataset --streaming --max-samples 500 """, )
parser.add_argument("input_dataset", help="Input dataset ID on HF Hub") parser.add_argument("--bbox-column", default="bbox", help="Column containing bboxes (default: bbox)") parser.add_argument("--category-column", default="category", help="Column containing categories (default: category)") parser.add_argument( "--bbox-format", choices=BBOX_FORMATS, default="coco_xywh", help="Bounding box format (default: coco_xywh)", ) parser.add_argument("--image-column", default="image", help="Column containing images (default: image)") parser.add_argument("--width-column", default="width", help="Column for image width (default: width)") parser.add_argument("--height-column", default="height", help="Column for image height (default: height)") parser.add_argument("--split", default="train", help="Dataset split (default: train)") parser.add_argument("--max-samples", type=int, help="Max samples to validate") parser.add_argument("--streaming", action="store_true", help="Use streaming mode (no full download)") parser.add_argument("--strict", action="store_true", help="Treat warnings as errors") parser.add_argument("--report", choices=["text", "json"], default="text", help="Report format (default: text)") parser.add_argument("--tolerance", type=float, default=0.5, help="Out-of-bounds tolerance in pixels (default: 0.5)") parser.add_argument("--hf-token", help="HF API token") parser.add_argument("--output-dataset", help="Push validation report to this HF dataset") parser.add_argument("--private", action="store_true", help="Make output dataset private")
args = parser.parse_args()
main( input_dataset=args.input_dataset, bbox_column=args.bbox_column, category_column=args.category_column, bbox_format=args.bbox_format, image_column=args.image_column, width_column=args.width_column, height_column=args.height_column, split=args.split, max_samples=args.max_samples, streaming=args.streaming, strict=args.strict, report_format=args.report, tolerance=args.tolerance, hf_token=args.hf_token, output_dataset=args.output_dataset, private=args.private, )README.md+244-3
convert-hf-dataset.pyAdded+375
diff-hf-datasets.pyAdded+428
sample-hf-dataset.pyAdded+341
stats-hf-dataset.pyAdded+402
validate-hf-dataset.pyAdded+455