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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from typing import Set
3
+
4
+ from datasets import DatasetBuilder, GeneratorBasedBuilder, DatasetInfo, Features, Image, ClassLabel, Array3D, DownloadManager, SplitGenerator, BuilderConfig, Version
5
+ import numpy as np
6
+ import datasets
7
+
8
+ VERSION = "v1_240507_SMALL"
9
+ HF_VERSION = "1.0.0"
10
+
11
+ # Available Dataset View Names
12
+ full_dataset_name = "full-dataset"
13
+ semantic_segmentation_name = "semantic-segmentation"
14
+ instance_segmentation_name = "instance-segmentation"
15
+ animal_category_anomoalies_name = "animal-category-anomalies"
16
+ re_id_best_name = "chicken-re-id-best-visibility"
17
+ #re_id_good_name = "chicken-re-id-good-visibility"
18
+ #re_id_bad_name = "chicken-re-id-bad-visibility"
19
+ re_id_full_name = "chicken-re-id-all-visibility"
20
+
21
+
22
+ # Example usage
23
+ # from datasets import load_dataset
24
+ # dataset = datasets.load_dataset(
25
+ # "dariakern/Chicks4FreeID",
26
+ # "chicken-re-id-best-visibility",
27
+ # as_supervised=True,
28
+ # trust_remote_code=True
29
+ # )
30
+
31
+ ##### ONTOLOTGY ######
32
+
33
+
34
+ ontologies = {
35
+ "v1_240507":
36
+ {'tools': [{'classifications': [{'instructions': 'coop',
37
+ 'options': [{'label': '10'},
38
+ {'label': '1'},
39
+ {'label': '2'},
40
+ {'label': '3'},
41
+ {'label': '4'},
42
+ {'label': '5'},
43
+ {'label': '6'},
44
+ {'label': '7'},
45
+ {'label': '8'},
46
+ {'label': '9'},
47
+ {'label': '11'}],
48
+ 'required': True,
49
+ 'type': 'radio'},
50
+ {'instructions': 'identity',
51
+ 'options': [{'label': 'Beate'},
52
+ {'label': 'Borghild'},
53
+ {'label': 'Eleonore'},
54
+ {'label': 'Mona'},
55
+ {'label': 'Henriette'},
56
+ {'label': 'Margit'},
57
+ {'label': 'Millie'},
58
+ {'label': 'Sigrun'},
59
+ {'label': 'Kristina'},
60
+ {'label': 'Unknown'},
61
+ {'label': 'Tina'},
62
+ {'label': 'Gretel'},
63
+ {'label': 'Lena'},
64
+ {'label': 'Yolkoono'},
65
+ {'label': 'Skimmy'},
66
+ {'label': 'Mavi'},
67
+ {'label': 'Mirmir'},
68
+ {'label': 'Nugget'},
69
+ {'label': 'Fernanda'},
70
+ {'label': 'Isolde'},
71
+ {'label': 'Mechthild'},
72
+ {'label': 'Brunhilde'},
73
+ {'label': 'Spiderman'},
74
+ {'label': 'Brownie'},
75
+ {'label': 'Camy'},
76
+ {'label': 'Samy'},
77
+ {'label': 'Yin'},
78
+ {'label': 'Yuriko'},
79
+ {'label': 'Renate'},
80
+ {'label': 'Regina'},
81
+ {'label': 'Monika'},
82
+ {'label': 'Heidi'},
83
+ {'label': 'Erna'},
84
+ {'label': 'Marina'},
85
+ {'label': 'Kathrin'},
86
+ {'label': 'Isabella'},
87
+ {'label': 'Amalia'},
88
+ {'label': 'Edeltraut'},
89
+ {'label': 'Erdmute'},
90
+ {'label': 'Oktavia'},
91
+ {'label': 'Siglinde'},
92
+ {'label': 'Ulrike'},
93
+ {'label': 'Hermine'},
94
+ {'label': 'Matilda'},
95
+ {'label': 'Chantal'},
96
+ {'label': 'Chayenne'},
97
+ {'label': 'Jaqueline'},
98
+ {'label': 'Mandy'},
99
+ {'label': 'Henny'},
100
+ {'label': 'Shady'},
101
+ {'label': 'Shorty'}],
102
+ 'required': True,
103
+ 'type': 'radio'},
104
+ {'instructions': 'visibility',
105
+ 'options': [{'label': 'best'},
106
+ {'label': 'good'},
107
+ {'label': 'bad'}],
108
+ 'required': True,
109
+ 'type': 'radio'}],
110
+ 'color': '#1e1cff',
111
+ 'name': 'chicken',
112
+ 'required': False,
113
+ 'tool': 'superpixel'},
114
+ {'color': '#FF34FF',
115
+ 'name': 'background',
116
+ 'required': False,
117
+ 'tool': 'superpixel'},
118
+ {'classifications': [{'instructions': 'coop',
119
+ 'options': [{'label': '1'},
120
+ {'label': '2'},
121
+ {'label': '3'},
122
+ {'label': '4'},
123
+ {'label': '5'},
124
+ {'label': '6'},
125
+ {'label': '7'},
126
+ {'label': '8'},
127
+ {'label': '9'},
128
+ {'label': '10'},
129
+ {'label': '11'}],
130
+ 'required': True,
131
+ 'type': 'radio'},
132
+ {'instructions': 'identity',
133
+ 'options': [{'label': 'Evelyn'},
134
+ {'label': 'Marley'}],
135
+ 'required': True,
136
+ 'type': 'radio'},
137
+ {'instructions': 'visibility',
138
+ 'options': [{'label': 'best'},
139
+ {'label': 'good'},
140
+ {'label': 'bad'}],
141
+ 'required': True,
142
+ 'type': 'radio'}],
143
+ 'color': '#FF4A46',
144
+ 'name': 'duck',
145
+ 'required': False,
146
+ 'tool': 'superpixel'},
147
+ {'classifications': [{'instructions': 'coop',
148
+ 'options': [{'label': '1'},
149
+ {'label': '2'},
150
+ {'label': '3'},
151
+ {'label': '4'},
152
+ {'label': '5'},
153
+ {'label': '6'},
154
+ {'label': '7'},
155
+ {'label': '8'},
156
+ {'label': '9'},
157
+ {'label': '10'},
158
+ {'label': '11'}],
159
+ 'required': True,
160
+ 'type': 'radio'},
161
+ {'instructions': 'identity',
162
+ 'options': [{'label': 'Elvis'},
163
+ {'label': 'Jackson'}],
164
+ 'required': True,
165
+ 'type': 'radio'},
166
+ {'instructions': 'visibility',
167
+ 'options': [{'label': 'best'},
168
+ {'label': 'good'},
169
+ {'label': 'bad'}],
170
+ 'required': True,
171
+ 'type': 'radio'}],
172
+ 'color': '#ff0000',
173
+ 'name': 'rooster',
174
+ 'required': False,
175
+ 'tool': 'superpixel'}]}
176
+ }
177
+
178
+
179
+
180
+ class Ontology:
181
+ ontology: dict = None
182
+ def __init__(self, version_name: str):
183
+ self.ontology: dict = ontologies[version_name]
184
+
185
+
186
+ def names(self, class_name, tool_name=None, drop_unkown=False):
187
+ """
188
+ Returns a list of all possible names for a given category (accross all tools)
189
+ """
190
+ if class_name == "animal_category":
191
+ return list({tool["name"] for tool in self.ontology["tools"]} - {"background"})
192
+
193
+ result = set()
194
+ for tool in self.ontology["tools"]:
195
+ if "classifications" in tool:
196
+ for classification in tool["classifications"]:
197
+ if classification["instructions"] == class_name and (tool_name is None or tool_name == tool["name"]):
198
+ result.update({option["label"] for option in classification["options"] if not (drop_unkown and option["label"] == "Unknown")})
199
+ return list(result)
200
+
201
+ def get_color_map(self):
202
+ """
203
+ Returns a dictionary mapping class names to their respective colors
204
+ """
205
+ return {tool["name"]: tool["color"] for tool in self.ontology["tools"]}
206
+
207
+
208
+
209
+
210
+
211
+
212
+
213
+ ontology = Ontology(VERSION)
214
+
215
+ # Feature Names
216
+ IMAGE = "image"
217
+ image_feature = {IMAGE: Image()}
218
+
219
+ SEGMENTATION_MAKS = "segmentation_mask"
220
+ segmentation_mask_feature = {SEGMENTATION_MAKS: Image()}
221
+
222
+ INSTANCE_MASK = "instance_mask"
223
+ instance_mask_feature = {INSTANCE_MASK: Image()}
224
+
225
+ CROP = "crop"
226
+ crop_feature = {CROP: Image()}
227
+
228
+ ID = "identity"
229
+ identity_feature = {ID: ClassLabel(names=ontology.names(ID))}
230
+ chicken_only_identitiy_feature = {ID: ClassLabel(names=ontology.names(ID, "chicken", drop_unkown=True))}
231
+
232
+ VISIBILITY = "visibility"
233
+ visibility_feature = {VISIBILITY: ClassLabel(names=ontology.names(VISIBILITY))}
234
+
235
+ COOP = "coop"
236
+ coop_feature = {COOP: ClassLabel(names=ontology.names(COOP))}
237
+
238
+ CATEGORY = "animal_category"
239
+ animal_category_feature = {CATEGORY: ClassLabel(names=ontology.names(CATEGORY))}
240
+
241
+ INSTANCES = "instances"
242
+ instance_features = {
243
+ **crop_feature,
244
+ **instance_mask_feature,
245
+ **identity_feature,
246
+ **visibility_feature,
247
+ **animal_category_feature,
248
+ }
249
+
250
+ all_features = {
251
+ **image_feature,
252
+ **segmentation_mask_feature,
253
+ **coop_feature,
254
+ INSTANCES: [instance_features],
255
+ }
256
+
257
+
258
+
259
+
260
+
261
+ def name_to_dict(filename: str):
262
+ """
263
+ Converts a filename to a dictionary object by splitting the filename by underscores and using the even indices as keys and the odd indices as values.
264
+ """
265
+ return {filename.split('_')[i]: filename.split('_')[i + 1] for i in range(0, len(filename.split('_')) - 1, 2)}
266
+
267
+
268
+ class ChicksDataset(GeneratorBasedBuilder):
269
+ BUILDER_CONFIGS = [
270
+ BuilderConfig(name=full_dataset_name, version=Version(HF_VERSION), description="The complete dataset including all features and image types. Includes all coops, visibility ratings, identities, and animal categories, as well as segmentation masks and instance masks."),
271
+ BuilderConfig(name=semantic_segmentation_name, version=Version(HF_VERSION), description="Includes images and color-coded segmentation masks."),
272
+ BuilderConfig(name=instance_segmentation_name, version=Version(HF_VERSION), description="Includes images and a corresponding sequence of binary instance segmentation masks for each instance on the image."),
273
+ BuilderConfig(name=animal_category_anomoalies_name, version=Version(HF_VERSION), description="Includes images of mostly chicken, but also some roosters and ducks, which make up the anomalies in the dataset."),
274
+ BuilderConfig(name=re_id_best_name, version=Version(HF_VERSION), description="Includes crops of chickens which have the best visibility rating for re-identification."),
275
+ #BuilderConfig(name=re_id_good_name, version=Version(HF_VERSION), description="Includes crops of chickens which have neither the best nor the worst visibility rating for re-identification."),
276
+ #BuilderConfig(name=re_id_bad_name, version=Version(HF_VERSION), description="Includes crops of chickens which have the worst (bad) visibility rating for re-identification."),
277
+ BuilderConfig(name=re_id_full_name, version=Version(HF_VERSION), description="Includes crops of chickens with all visibilities for re-identification without any filtering on visibility rating."),
278
+ ]
279
+
280
+
281
+ def _info(self, *args, **kwargs):
282
+
283
+ if self.config.name == full_dataset_name:
284
+ return DatasetInfo(
285
+ features=Features(all_features),
286
+ )
287
+
288
+ elif self.config.name in [
289
+ re_id_full_name, re_id_best_name,
290
+ # re_id_good_name, re_id_bad_name
291
+ ]:
292
+ return DatasetInfo(
293
+ features=Features({
294
+ **crop_feature,
295
+ **chicken_only_identitiy_feature,
296
+ }),
297
+ supervised_keys=(
298
+ CROP,
299
+ ID,
300
+ ),
301
+ )
302
+
303
+
304
+ elif self.config.name == semantic_segmentation_name:
305
+ return DatasetInfo(
306
+ features=Features({
307
+ **image_feature,
308
+ **segmentation_mask_feature,
309
+ }),
310
+ supervised_keys=(
311
+ IMAGE,
312
+ SEGMENTATION_MAKS,
313
+ )
314
+ )
315
+
316
+ elif self.config.name == instance_segmentation_name:
317
+ return DatasetInfo(
318
+ features=Features({
319
+ **image_feature,
320
+ INSTANCES: [instance_mask_feature],
321
+ }),
322
+ supervised_keys=(
323
+ IMAGE,
324
+ INSTANCES, # TODO use nested reference to instance_mask_feature
325
+ )
326
+ )
327
+
328
+ elif self.config.name == animal_category_anomoalies_name:
329
+ return DatasetInfo(
330
+ features=Features({
331
+ **crop_feature,
332
+ **animal_category_feature,
333
+ }),
334
+ supervised_keys=(
335
+ CROP,
336
+ CATEGORY
337
+ )
338
+ )
339
+
340
+ def _split_generators(self, dl_manager: DownloadManager):
341
+ URL = f"https://huggingface.co/datasets/dariakern/Chicks4FreeID/resolve/main/{VERSION}.zip?download=true"
342
+ base_path = Path(dl_manager.download_and_extract(URL))
343
+
344
+ # Only offer train test split for chicken-re-id task
345
+ if self.config.name in [
346
+ re_id_full_name,
347
+ re_id_best_name
348
+ ]:
349
+ from sklearn.model_selection import train_test_split
350
+
351
+ # all crop files (only chicken, remove unknowns)
352
+ all_crops = sorted([
353
+ crop_file
354
+ for crop_file
355
+ in base_path.rglob(f"**/{VERSION}/reId/chicken/**/*crop_*.png")
356
+ if "Unknown" not in crop_file.parts
357
+ ])
358
+ # all identity targets (labels)
359
+ identities = [name_to_dict(crop.stem)[ID] for crop in all_crops]
360
+
361
+ # Splitting the dataset into train and test using stratified train_test_split
362
+ train_crops, test_crops, _, _ = train_test_split(
363
+ all_crops, identities, test_size=0.2, stratify=identities, shuffle=True, random_state=42
364
+ )
365
+
366
+ return [
367
+ SplitGenerator(
368
+ gen_kwargs={"base_path": base_path, "split": set(train_crops)},
369
+ name=datasets.Split.TRAIN,
370
+ ),
371
+ SplitGenerator(
372
+ gen_kwargs={"base_path": base_path, "split": set(test_crops)},
373
+ name=datasets.Split.TEST,
374
+ )
375
+ ]
376
+ else:
377
+ return [
378
+ SplitGenerator(
379
+ name=datasets.Split.TRAIN,
380
+ gen_kwargs={"base_path": base_path, "split": None})
381
+ ]
382
+
383
+
384
+ def _generate_all(self, base_path: Path, split: Set[Path]=None):
385
+ """
386
+ Generates all examples for the dataset, including all features.
387
+
388
+ Args:
389
+ base_path (Path): The base path to the dataset
390
+ split (Set[Path]): The paths to all instance crops to include in the current dataset
391
+ """
392
+ img_dir = base_path / f"{VERSION}/images"
393
+ mask_dir = base_path / f"{VERSION}/masks"
394
+ reid_dir = base_path / f"{VERSION}/reId"
395
+
396
+ # Collecting images, segmentation masks, and instance masks
397
+ for img_file in img_dir.iterdir():
398
+ image_id = img_file.stem
399
+ image_path = img_file
400
+ segmentation_mask_path = mask_dir / f"{image_id}_segmentationMask.png"
401
+ instance_masks = list(mask_dir.rglob(f"{image_id}_instanceMask_*.png"))
402
+ instance_crops = list(reid_dir.rglob(f"**/{image_id}_crop_*.png"))
403
+
404
+ # Check if all crops have a corresponding instance mask
405
+ assert len(instance_masks) == len(instance_crops) and len(instance_masks) > 0
406
+
407
+ # Remove any instance_crops that are not in crops_split
408
+ if split is not None:
409
+ instance_crops = [crop for crop in instance_crops if crop in split]
410
+
411
+ instance_data = []
412
+ infos = {}
413
+ for instance_mask_path, crop_path in zip(instance_masks, instance_crops):
414
+ infos = name_to_dict(crop_path.stem)
415
+ instance_data.append({
416
+ INSTANCE_MASK: str(instance_mask_path),
417
+ CROP: str(crop_path),
418
+ VISIBILITY: infos[VISIBILITY],
419
+ ID: infos[ID],
420
+ CATEGORY: crop_path.relative_to(reid_dir).parts[0],
421
+ })
422
+
423
+
424
+ if instance_data:
425
+ yield image_id, {
426
+ IMAGE: str(image_path),
427
+ SEGMENTATION_MAKS: str(segmentation_mask_path),
428
+ COOP: infos[COOP],
429
+ INSTANCES: instance_data,
430
+ }
431
+
432
+
433
+ def _generate_examples(self, **kwargs):
434
+ if self.config.name in [full_dataset_name]:
435
+ yield from self._generate_all(**kwargs)
436
+
437
+ elif self.config.name == semantic_segmentation_name:
438
+ for image_id, example in self._generate_all(**kwargs):
439
+ yield image_id, {
440
+ IMAGE: example[IMAGE],
441
+ SEGMENTATION_MAKS: example[SEGMENTATION_MAKS],
442
+ }
443
+
444
+ elif self.config.name == instance_segmentation_name:
445
+ for image_id, example in self._generate_all(**kwargs):
446
+ yield image_id, {
447
+ IMAGE: example[IMAGE],
448
+ INSTANCES: [
449
+ {
450
+ INSTANCE_MASK: instance[INSTANCE_MASK]
451
+ }
452
+ for instance in example[INSTANCES]
453
+ ]
454
+ }
455
+
456
+ elif self.config.name == animal_category_anomoalies_name:
457
+ for image_id, example in self._generate_all(**kwargs):
458
+ for instance in example[INSTANCES]:
459
+ instance_id = Path(instance[CROP]).stem
460
+ yield instance_id, {
461
+ CROP: instance[CROP],
462
+ CATEGORY: instance[CATEGORY],
463
+ }
464
+
465
+ elif self.config.name in [
466
+ re_id_best_name, re_id_full_name,
467
+ # re_id_good_name, re_id_bad_name
468
+ ]:
469
+ for image_id, example in self._generate_all(**kwargs):
470
+ for instance in example[INSTANCES]:
471
+
472
+ # Conditions for filtering
473
+ use_all = self.config.name == re_id_full_name
474
+ selected_visibility = instance[VISIBILITY] == self.config.name.split("-")[-2]
475
+
476
+ if use_all or selected_visibility:
477
+ instance_id = Path(instance[CROP]).stem
478
+ yield instance_id, {
479
+ CROP: instance[CROP],
480
+ ID: instance[ID],
481
+ }
482
+
483
+
484
+
485
+