File size: 2,823 Bytes
509147a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python3
"""
Generate HuggingFace-compatible metadata CSV files for the billiards dataset.
Creates train.csv, validation.csv, and test.csv with image paths and annotations.
"""

import csv
import os
from pathlib import Path


def read_yolo_labels(label_path):
    """Read YOLO format labels from a text file."""
    if not os.path.exists(label_path):
        return []

    with open(label_path, 'r') as f:
        lines = f.readlines()

    annotations = []
    for line in lines:
        parts = line.strip().split()
        if len(parts) == 5:
            class_id, x_center, y_center, width, height = parts
            annotations.append({
                'class_id': int(class_id),
                'x_center': float(x_center),
                'y_center': float(y_center),
                'width': float(width),
                'height': float(height)
            })
    return annotations


def create_metadata_csv(split_name, output_filename):
    """Create a metadata CSV file for a given split."""
    data_dir = Path('data')
    images_dir = data_dir / split_name / 'images'
    labels_dir = data_dir / split_name / 'labels'

    if not images_dir.exists():
        print(f"Warning: {images_dir} does not exist")
        return

    rows = []
    image_files = sorted(images_dir.glob('*.png'))

    for image_path in image_files:
        # Get corresponding label file
        label_filename = image_path.stem + '.txt'
        label_path = labels_dir / label_filename

        # Read annotations
        annotations = read_yolo_labels(label_path)

        # Create relative path from root
        relative_image_path = str(image_path)

        row = {
            'image': relative_image_path,
            'annotations': str(annotations)  # Store as string for CSV compatibility
        }
        rows.append(row)

    # Write CSV file
    if rows:
        with open(output_filename, 'w', newline='') as csvfile:
            fieldnames = ['image', 'annotations']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(rows)

        print(f"Created {output_filename} with {len(rows)} entries")
    else:
        print(f"No data found for {split_name}")


def main():
    """Generate metadata CSV files for all splits."""
    # Map split directory names to HuggingFace-compatible output filenames
    splits = {
        'train': 'train.csv',
        'val': 'validation.csv',  # 'validation' is a recognized split name
        'test': 'test.csv'
    }

    for split_dir, output_file in splits.items():
        create_metadata_csv(split_dir, output_file)

    print("\nMetadata CSV files created successfully!")
    print("These files are compatible with HuggingFace's dataset viewer.")


if __name__ == '__main__':
    main()