chanelcolgate commited on
Commit
d7fef5a
1 Parent(s): c77675b

new file: yenthienviet.py

Browse files
Files changed (1) hide show
  1. yenthienviet.py +212 -0
yenthienviet.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
4
+
5
+ import datasets
6
+ from datasets.data_files import DataFilesDict
7
+ from datasets.download.download_manager import ArchiveIterable, DownloadManager
8
+ from datasets.features import Features
9
+ from datasets.info import DatasetInfo
10
+
11
+ # Typing
12
+ _TYPING_BOX = Tuple[float, float, float, float]
13
+
14
+ _DESCRIPTION = """\
15
+ This dataset contains all THIENVIET products images and annotations split in training
16
+ and validation.
17
+ """
18
+
19
+ _URLS = {
20
+ "train": "https://huggingface.co/datasets/chanelcolgate/yenthienviet/resolve/main/data/coco/train.zip",
21
+ "val": "https://huggingface.co/datasets/chanelcolgate/yenthienviet/resolve/main/data/coco/val.zip",
22
+ "test": "https://huggingface.co/datasets/chanelcolgate/yenthienviet/resolve/main/data/coco/test.zip",
23
+ "annotations": "https://huggingface.co/datasets/chanelcolgate/yenthienviet/resolve/main/data/coco/annotations.zip",
24
+ }
25
+
26
+ _SPLITS = ["train", "val", "test"]
27
+
28
+ _PATHS = {
29
+ "annotations": {
30
+ "train": Path("_annotations.coco.train.json"),
31
+ "val": Path("_annotaions.coco.val.json"),
32
+ "test": Path("_annotations.coco.test.json"),
33
+ },
34
+ "images": {
35
+ "train": Path("train"),
36
+ "val": Path("val"),
37
+ "test": Path("test"),
38
+ },
39
+ }
40
+
41
+ _CLASSES = [
42
+ "hop_dln",
43
+ "hop_jn",
44
+ "hop_vtg",
45
+ "hop_ytv",
46
+ "lo_kids",
47
+ "lo_ytv",
48
+ "loc_ytv",
49
+ "loc_kids",
50
+ "loc_dln",
51
+ "bot_dln",
52
+ "loc_jn",
53
+ ]
54
+
55
+
56
+ def round_box_values(box, decimals=2):
57
+ return [round(val, decimals) for val in box]
58
+
59
+
60
+ class COCOHelper:
61
+ """Helper class to load COCO annotations"""
62
+
63
+ def __init__(self, annotation_path: Path, images_dir: Path) -> None:
64
+ with open(annotation_path, "r") as file:
65
+ data = json.load(file)
66
+ self.data = data
67
+
68
+ dict_id2annot: Dict[int, Any] = {}
69
+ for annot in self.annotations:
70
+ dict_id2annot.setdefault(annot["image_id"], []).append(annot)
71
+
72
+ # Sort by id
73
+ dict_id2annot = {
74
+ k: list(sorted(v, key=lambda a: a["id"]))
75
+ for k, v in dict_id2annot.items()
76
+ }
77
+
78
+ self.dict_path2annot: Dict[str, Any] = {}
79
+ self.dict_path2id: Dict[str, Any] = {}
80
+ for img in self.images:
81
+ path_img = images_dir / str(img["file_name"])
82
+ path_img_str = str(path_img)
83
+ idx = int(img["id"])
84
+ annot = dict_id2annot.get(idx, [])
85
+ self.dict_path2annot[path_img_str] = annot
86
+ self.dict_path2id[path_img_str] = img["id"]
87
+
88
+ def __len__(self) -> int:
89
+ return len(self.data["images"])
90
+
91
+ @property
92
+ def images(self) -> List[Dict[str, Union[str, int]]]:
93
+ return self.data["images"]
94
+
95
+ @property
96
+ def annotations(self) -> List[Any]:
97
+ return self.data["annotations"]
98
+
99
+ @property
100
+ def categories(self) -> List[Dict[str, Union[str, int]]]:
101
+ return self.data["categories"]
102
+
103
+ def get_annotations(self, image_path: str) -> List[Any]:
104
+ return self.dict_path2annot.get(image_path, [])
105
+
106
+ def get_image_id(self, image_path: str) -> int:
107
+ return self.dict_path2id.get(image_path, -1)
108
+
109
+
110
+ class COCOThienviet(datasets.GeneratorBasedBuilder):
111
+ """COCO Thienviet dataset."""
112
+
113
+ VERSION = datasets.Version("1.0.1")
114
+
115
+ def _info(self) -> datasets.DatasetInfo:
116
+ """
117
+ Return the dataset metadata and features.
118
+
119
+ Returns:
120
+ DatasetInfo: Metadata and features of the dataset.
121
+ """
122
+ return datasets.DatasetInfo(
123
+ description=_DESCRIPTION,
124
+ features=datasets.Features(
125
+ {
126
+ "image": datasets.Image(),
127
+ "image_id": datasets.Value("int64"),
128
+ "objects": datasets.Sequence(
129
+ {
130
+ "id": datasets.Value("int64"),
131
+ "area": datasets.Value("float64"),
132
+ "bbox": datasets.Sequence(
133
+ datasets.Value("float32"), length=4
134
+ ),
135
+ "label": datasets.ClassLabel(names=_CLASSES),
136
+ "iscrowd": datasets.Value("bool"),
137
+ }
138
+ ),
139
+ }
140
+ ),
141
+ )
142
+
143
+ def _split_generators(
144
+ self, dl_manager: DownloadManager
145
+ ) -> List[datasets.SplitGenerator]:
146
+ """
147
+ Provides the split information and downloads the data.
148
+
149
+ Args:
150
+ dl_manager (DownloadManager): The DownloadManager to use for downloading and
151
+ extracting data.
152
+
153
+ Returns:
154
+ List[SplitGenerator]: List of SplitGenerator objects representing the data splits.
155
+ """
156
+ archive_annots = dl_manager.download_and_extract(_URLS["annotations"])
157
+
158
+ splits = []
159
+ for split in _SPLITS:
160
+ archive_split = dl_manager.download(_URLS[split])
161
+ annotation_path = (
162
+ Path(archive_annots) / _PATHS["annotations"][split]
163
+ )
164
+ images = dl_manager.iter_archive(archive_split)
165
+ splits.append(
166
+ datasets.SplitGenerator(
167
+ name=datasets.Split(split),
168
+ gen_kwargs={
169
+ "anotation_path": annotation_path,
170
+ "images_dir": _PATHS["images"][split],
171
+ "images": images,
172
+ },
173
+ )
174
+ )
175
+ return splits
176
+
177
+ def _generate_examples(
178
+ self, annotation_path: Path, images_dir: Path, images: ArchiveIterable
179
+ ) -> Iterator:
180
+ """
181
+ Generates examples for the dataset.
182
+
183
+ Args:
184
+ annotation_path (Path): The path to the annotation file.
185
+ images_dir (Path): The path to the directory containing the images.
186
+ images: (ArchiveIterable): An iterable containing the images.
187
+
188
+ Yields:
189
+ Dict[str, Union[str, Image]]: A dictionary containing the generated examples.
190
+ """
191
+ coco_annotation = COCOHelper(annotation_path, images_dir)
192
+
193
+ for image_path, f in images:
194
+ annotations = coco_annotation.get_annotations(image_path)
195
+ ret = {
196
+ "image": {"path": image_path, "bytes": f.read()},
197
+ "image_id": coco_annotation.get_image_id(image_path),
198
+ "objects": [
199
+ {
200
+ "id": annot["id"],
201
+ "area": annot["area"],
202
+ "bbox": round_box_values(
203
+ annot["bbox"], 2
204
+ ), # [x, y, w, h]
205
+ "label": annot["category_id"],
206
+ "iscrowd": bool(annot["iscrowd"]),
207
+ }
208
+ for annot in annotations
209
+ ],
210
+ }
211
+
212
+ yield image_path, ret