File size: 6,078 Bytes
4aade78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import datasets
import os
import numpy as np

# --- Các hàm phụ trợ để đọc file chú thích ---

def parse_bbox_file(filepath):
    """Đọc file bbox và chuyển đổi thành list các số thực."""
    if not os.path.exists(filepath):
        return []
    with open(filepath, 'r', encoding='utf-8') as f:
        line = f.read().strip()
        if not line:
            return []
        return [float(coord) for coord in line.split(',')]

def parse_points_file(filepath):
    """Đọc file points và chuyển đổi thành list của các list số nguyên."""
    if not os.path.exists(filepath):
        return []
    points = []
    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            coords = [int(p.strip()) for p in line.split(',')]
            points.append(coords)
    return points

# --- Lớp Builder chính ---

class ORiDaFactualCounterfactual(datasets.GeneratorBasedBuilder):
    """Dataset loader cho bộ dữ liệu ORiDa Factual/Counterfactual."""

    def _info(self):
        # Cập nhật lại cấu trúc (schema) để khớp với kiểu dữ liệu chính xác
        return datasets.DatasetInfo(
            description="Bộ dữ liệu ORiDa chứa các mẫu factual và counterfactual.",
            features=datasets.Features({
                'group_id': datasets.Value("string"),
                'sample_id': datasets.Value("string"),
                'type': datasets.ClassLabel(names=['factual_only', 'factual_counterfactual']),
                'image': datasets.Image(),
                'ground_truth': datasets.Image(),
                'annotations': {
                    'bbox': datasets.Sequence(datasets.Value("float32")), # Danh sách số thực
                    'points': datasets.Sequence(datasets.Sequence(datasets.Value("int32"))), # Danh sách của các danh sách số nguyên
                    'masks': datasets.Image(),
                    'results_vis': datasets.Image(), # Thêm results_vis là ảnh
                }
            }),
        )

    def _split_generators(self, dl_manager):
        # dl_manager sẽ tự động tìm và giải nén các file zip trong repo
        train_path = dl_manager.extract("train.zip")
        validation_path = dl_manager.extract("validation.zip")

        # Đường dẫn bây giờ sẽ trỏ vào bên trong các thư mục đã được giải nén
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={"filepath": os.path.join(train_path, "train")}
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={"filepath": os.path.join(validation_path, "validation")}
            ),
        ]

    def _generate_examples(self, filepath):
        """Hàm này sẽ duyệt qua thư mục và 'yield' từng mẫu dữ liệu."""
        key = 0
        for group_id in os.listdir(filepath):
            group_path = os.path.join(filepath, group_id)
            if not os.path.isdir(group_path): continue

            ground_truth_path = os.path.join(group_path, f"{group_id}.png")
            if not os.path.exists(ground_truth_path): continue

            for type_name in ["factual_only", "factual_counterfactual"]:
                type_path = os.path.join(group_path, type_name)
                if not os.path.isdir(type_path): continue
                
                for sample_id in os.listdir(type_path):
                    sample_path = os.path.join(type_path, sample_id)
                    if not os.path.isdir(sample_path): continue
                        
                    images_path = os.path.join(sample_path, "images")
                    annotations_path = os.path.join(sample_path, "annotations")
                    if not os.path.isdir(images_path): continue

                    for image_filename in os.listdir(images_path):
                        if not image_filename.lower().endswith(('.png', '.jpg', '.jpeg')): continue
                        
                        image_path = os.path.join(images_path, image_filename)
                        base_image_name = os.path.splitext(image_filename)[0]
                        
                        # Xây dựng đường dẫn đầy đủ tới các file chú thích
                        bbox_file = os.path.join(annotations_path, "bbox", f"{base_image_name}.txt")
                        points_file = os.path.join(annotations_path, "points", f"{base_image_name}.txt")
                        # Thay đổi đuôi file mask và results_vis thành .jpg
                        mask_file = os.path.join(annotations_path, "masks", f"{base_image_name}.jpg")
                        results_vis_file = os.path.join(annotations_path, "results_vis", f"{base_image_name}.jpg")

                        # Gọi các hàm phụ trợ để đọc và xử lý dữ liệu
                        bbox_data = parse_bbox_file(bbox_file)
                        points_data = parse_points_file(points_file)
                        
                        # Chỉ yield mẫu nếu các file ảnh cần thiết tồn tại
                        if not os.path.exists(mask_file) or not os.path.exists(results_vis_file):
                            continue

                        yield key, {
                            "group_id": group_id,
                            "sample_id": sample_id,
                            "type": type_name,
                            "image": image_path,
                            "ground_truth": ground_truth_path,
                            "annotations": {
                                "bbox": bbox_data,
                                "points": points_data,
                                "masks": mask_file,
                                "results_vis": results_vis_file,
                            }
                        }
                        key += 1