4K-Aircraft-Detection / scripts /export_yolo.py
FelixKAI's picture
Add bilingual cards, provenance, labels, preview and export tools
ffa7c61 verified
Raw History Blame Contribute Delete
9.64 kB
#!/usr/bin/env python3
"""Export Hub Parquet rows to YOLO without resizing or re-encoding images.
pip install datasets pyarrow huggingface_hub
python export_yolo.py --repo-id OWNER/DATASET --output ./aircraft-yolo
python export_yolo.py --repo-id OWNER/DATASET --output ./plane-yolo --single-class
python export_yolo.py --local-dir ./downloaded-hub-repo --output ./aircraft-yolo
The default retains size classes 0/1/2. --single-class maps all three to plane=0.
The streaming Image column is explicitly decoded as bytes, so even large native
images are written without pixel decoding. Some individual native images exceed
1 GiB; sufficient memory and disk space for the encoded row are still required.
"""
import argparse
import collections
import hashlib
import json
import math
from pathlib import Path
NAMES = {0: 'small_plane', 1: 'middle_plane', 2: 'big_plane'}
def annotation_lists(row):
objects = row.get('objects')
if objects is None:
raise ValueError('Missing objects field; expected objects.yolo_bbox and category/category_id.')
if isinstance(objects, dict):
boxes = objects.get('yolo_bbox')
categories = objects.get('category', objects.get('category_id', objects.get('categories')))
elif isinstance(objects, list):
boxes = [obj['yolo_bbox'] for obj in objects]
categories = [obj.get('category', obj.get('category_id')) for obj in objects]
else:
raise ValueError('objects must be a dict of lists or a list of object dictionaries.')
if boxes is None or categories is None or len(boxes) != len(categories):
raise ValueError('Missing or inconsistent object categories and normalized YOLO boxes.')
return boxes, categories
def export_one_row(row, split, output, single_class=False):
image = row.get('image')
if isinstance(image, dict):
encoded = image.get('bytes')
encoded_path = image.get('path')
elif isinstance(image, (bytes, bytearray, memoryview)):
encoded = image
encoded_path = None
else:
encoded = row.get('image_bytes')
encoded_path = None
if encoded is None:
raise ValueError('No embedded image bytes. Ensure the Image column uses decode=False.')
if not isinstance(encoded, (bytes, bytearray, memoryview)):
raise ValueError('Image bytes have an unexpected type; pixel decoding is not supported.')
filename = row.get('file_name') or row.get('filename') or row.get('original_filename') or encoded_path
if not filename:
raise ValueError('Missing filename.')
# Keep only the basename from a parquet image.path while rejecting user-facing paths.
filename = str(filename)
if row.get('file_name') or row.get('filename') or row.get('original_filename'):
if Path(filename).name != filename or '\\' in filename:
raise ValueError('Unsafe filename: ' + filename)
else:
filename = Path(filename).name
if filename in ['', '.', '..']:
raise ValueError('Unsafe filename.')
image_path = output / 'images' / split / filename
label_path = output / 'labels' / split / (Path(filename).stem + '.txt')
if image_path.exists() or label_path.exists():
raise FileExistsError('Output filename already exists: ' + filename)
digest = hashlib.sha256(encoded).hexdigest()
expected = row.get('sha256') or row.get('image_sha256')
if expected and digest != expected:
raise ValueError('Image SHA256 mismatch: ' + filename)
boxes, categories = annotation_lists(row)
lines = []
counts = collections.Counter()
for box, category in zip(boxes, categories):
category = int(category)
if category not in NAMES or len(box) != 4:
raise ValueError('Invalid category or YOLO bbox: ' + filename)
cx, cy, width, height = map(float, box)
values = [cx, cy, width, height]
if not all(math.isfinite(value) for value in values) or width <= 0 or height <= 0:
raise ValueError('Invalid normalized YOLO bbox: ' + filename)
if min(cx-width/2, cy-height/2) < -1e-10 or max(cx+width/2, cy+height/2) > 1+1e-10:
raise ValueError('YOLO bbox extends beyond image bounds: ' + filename)
selected = 0 if single_class else category
counts[selected] += 1
lines.append(str(selected) + ' ' + ' '.join(format(value, '.17g') for value in values))
image_path.parent.mkdir(parents=True, exist_ok=True)
label_path.parent.mkdir(parents=True, exist_ok=True)
# Write the exact encoded bytes, with no Image.open, decode, resize, or save.
view = memoryview(encoded)
with image_path.open('xb') as handle:
for position in range(0, len(view), 8*1024*1024):
handle.write(view[position:position+8*1024*1024])
label_path.write_text('\n'.join(lines) + ('\n' if lines else ''))
return {'split': split, 'filename': filename, 'image_relative_path': str(image_path.relative_to(output)), 'label_relative_path': str(label_path.relative_to(output)), 'sha256': digest, 'sample_id': row.get('sample_id'), 'source_group_id': row.get('source_group_id'), 'source_dataset': row.get('source_dataset'), 'annotation_count': len(lines), 'class_counts': dict(counts)}
def discover_parquet(root, splits):
files = list(root.rglob('*.parquet'))
result = {}
for split in splits:
aliases = ['validation', 'val'] if split == 'val' else [split]
matched = sorted(str(path) for path in files if any(path.name.startswith(alias+'-') or alias in path.relative_to(root).parts[:-1] for alias in aliases))
if not matched:
raise FileNotFoundError('No parquet shards found for split ' + split + ' under ' + str(root))
result['validation' if split == 'val' else split] = matched
return result
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument('--repo-id', help='Hugging Face dataset ID, OWNER/DATASET.')
source.add_argument('--local-dir', type=Path, help='Downloaded repository containing train/val/test Parquet shards.')
parser.add_argument('--config', default='default', help='Hub dataset configuration; default is the full-resolution default config. The preview config is not a training source.')
parser.add_argument('--revision', help='Optional Hub commit SHA or revision.')
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--single-class', action='store_true', help='Map original size class IDs 0/1/2 to one plane=0 class.')
parser.add_argument('--splits', nargs='+', choices=['train', 'val', 'test'], default=['train', 'val', 'test'])
parser.add_argument('--max-samples', type=int, help='Optional smoke-test limit per split; omitted exports all images.')
args = parser.parse_args()
if args.max_samples is not None and args.max_samples <= 0:
parser.error('--max-samples must be positive.')
if args.config == 'preview':
parser.error('The preview configuration contains display images and cannot be exported as training data. Use --config default.')
if args.output.exists() and any(args.output.iterdir()):
parser.error('--output must be a new or empty directory; existing files are never overwritten.')
from datasets import Image, load_dataset
args.output.mkdir(parents=True, exist_ok=True)
if args.local_dir:
datasets = load_dataset('parquet', data_files=discover_parquet(args.local_dir, args.splits), streaming=True)
else:
kwargs = {'path': args.repo_id, 'streaming': True}
if args.config:
kwargs['name'] = args.config
if args.revision:
kwargs['revision'] = args.revision
datasets = load_dataset(**kwargs)
summary = {'mode': 'plane' if args.single_class else 'size3', 'splits': {}, 'image_bytes_reencoded': False}
with (args.output/'export_manifest.jsonl').open('w') as manifest:
for split in args.splits:
source_split = 'validation' if split == 'val' else split
if source_split not in datasets and split == 'val' and 'val' in datasets:
source_split = 'val'
data = datasets[source_split]
if 'image' in (data.features or {}):
data = data.cast_column('image', Image(decode=False))
images = 0
objects = 0
classes = collections.Counter()
for row in data:
result = export_one_row(row, split, args.output, args.single_class)
manifest.write(json.dumps(result, ensure_ascii=False)+'\n')
images += 1
objects += result['annotation_count']
classes.update(result['class_counts'])
if images % 100 == 0:
print(split+': '+str(images)+' images', flush=True)
if args.max_samples is not None and images >= args.max_samples:
break
summary['splits'][split] = {'images': images, 'objects': objects, 'class_counts': dict(classes)}
names = {0: 'plane'} if args.single_class else NAMES
(args.output/'data.yaml').write_text('train: images/train\nval: images/val\ntest: images/test\n\nnames:\n'+''.join(' '+str(key)+': '+name+'\n' for key, name in names.items()))
(args.output/'export_summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2)+'\n')
print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()