dariakern commited on
Commit
cd94748
·
verified ·
1 Parent(s): f321807

Update Chicks4FreeID.py

Browse files
Files changed (1) hide show
  1. Chicks4FreeID.py +487 -485
Chicks4FreeID.py CHANGED
@@ -1,485 +1,487 @@
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
-
 
 
 
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
+ ontologies["v1_240507_SMALL"] = ontologies["v1_240507"]
180
+
181
+
182
+ class Ontology:
183
+ ontology: dict = None
184
+ def __init__(self, version_name: str):
185
+ self.ontology: dict = ontologies[version_name]
186
+
187
+
188
+ def names(self, class_name, tool_name=None, drop_unkown=False):
189
+ """
190
+ Returns a list of all possible names for a given category (accross all tools)
191
+ """
192
+ if class_name == "animal_category":
193
+ return list({tool["name"] for tool in self.ontology["tools"]} - {"background"})
194
+
195
+ result = set()
196
+ for tool in self.ontology["tools"]:
197
+ if "classifications" in tool:
198
+ for classification in tool["classifications"]:
199
+ if classification["instructions"] == class_name and (tool_name is None or tool_name == tool["name"]):
200
+ result.update({option["label"] for option in classification["options"] if not (drop_unkown and option["label"] == "Unknown")})
201
+ return list(result)
202
+
203
+ def get_color_map(self):
204
+ """
205
+ Returns a dictionary mapping class names to their respective colors
206
+ """
207
+ return {tool["name"]: tool["color"] for tool in self.ontology["tools"]}
208
+
209
+
210
+
211
+
212
+
213
+
214
+
215
+ ontology = Ontology(VERSION)
216
+
217
+ # Feature Names
218
+ IMAGE = "image"
219
+ image_feature = {IMAGE: Image()}
220
+
221
+ SEGMENTATION_MAKS = "segmentation_mask"
222
+ segmentation_mask_feature = {SEGMENTATION_MAKS: Image()}
223
+
224
+ INSTANCE_MASK = "instance_mask"
225
+ instance_mask_feature = {INSTANCE_MASK: Image()}
226
+
227
+ CROP = "crop"
228
+ crop_feature = {CROP: Image()}
229
+
230
+ ID = "identity"
231
+ identity_feature = {ID: ClassLabel(names=ontology.names(ID))}
232
+ chicken_only_identitiy_feature = {ID: ClassLabel(names=ontology.names(ID, "chicken", drop_unkown=True))}
233
+
234
+ VISIBILITY = "visibility"
235
+ visibility_feature = {VISIBILITY: ClassLabel(names=ontology.names(VISIBILITY))}
236
+
237
+ COOP = "coop"
238
+ coop_feature = {COOP: ClassLabel(names=ontology.names(COOP))}
239
+
240
+ CATEGORY = "animal_category"
241
+ animal_category_feature = {CATEGORY: ClassLabel(names=ontology.names(CATEGORY))}
242
+
243
+ INSTANCES = "instances"
244
+ instance_features = {
245
+ **crop_feature,
246
+ **instance_mask_feature,
247
+ **identity_feature,
248
+ **visibility_feature,
249
+ **animal_category_feature,
250
+ }
251
+
252
+ all_features = {
253
+ **image_feature,
254
+ **segmentation_mask_feature,
255
+ **coop_feature,
256
+ INSTANCES: [instance_features],
257
+ }
258
+
259
+
260
+
261
+
262
+
263
+ def name_to_dict(filename: str):
264
+ """
265
+ 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.
266
+ """
267
+ return {filename.split('_')[i]: filename.split('_')[i + 1] for i in range(0, len(filename.split('_')) - 1, 2)}
268
+
269
+
270
+ class ChicksDataset(GeneratorBasedBuilder):
271
+ BUILDER_CONFIGS = [
272
+ 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."),
273
+ BuilderConfig(name=semantic_segmentation_name, version=Version(HF_VERSION), description="Includes images and color-coded segmentation masks."),
274
+ 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."),
275
+ 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."),
276
+ BuilderConfig(name=re_id_best_name, version=Version(HF_VERSION), description="Includes crops of chickens which have the best visibility rating for re-identification."),
277
+ #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."),
278
+ #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."),
279
+ 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."),
280
+ ]
281
+
282
+
283
+ def _info(self, *args, **kwargs):
284
+
285
+ if self.config.name == full_dataset_name:
286
+ return DatasetInfo(
287
+ features=Features(all_features),
288
+ )
289
+
290
+ elif self.config.name in [
291
+ re_id_full_name, re_id_best_name,
292
+ # re_id_good_name, re_id_bad_name
293
+ ]:
294
+ return DatasetInfo(
295
+ features=Features({
296
+ **crop_feature,
297
+ **chicken_only_identitiy_feature,
298
+ }),
299
+ supervised_keys=(
300
+ CROP,
301
+ ID,
302
+ ),
303
+ )
304
+
305
+
306
+ elif self.config.name == semantic_segmentation_name:
307
+ return DatasetInfo(
308
+ features=Features({
309
+ **image_feature,
310
+ **segmentation_mask_feature,
311
+ }),
312
+ supervised_keys=(
313
+ IMAGE,
314
+ SEGMENTATION_MAKS,
315
+ )
316
+ )
317
+
318
+ elif self.config.name == instance_segmentation_name:
319
+ return DatasetInfo(
320
+ features=Features({
321
+ **image_feature,
322
+ INSTANCES: [instance_mask_feature],
323
+ }),
324
+ supervised_keys=(
325
+ IMAGE,
326
+ INSTANCES, # TODO use nested reference to instance_mask_feature
327
+ )
328
+ )
329
+
330
+ elif self.config.name == animal_category_anomoalies_name:
331
+ return DatasetInfo(
332
+ features=Features({
333
+ **crop_feature,
334
+ **animal_category_feature,
335
+ }),
336
+ supervised_keys=(
337
+ CROP,
338
+ CATEGORY
339
+ )
340
+ )
341
+
342
+ def _split_generators(self, dl_manager: DownloadManager):
343
+ URL = f"https://huggingface.co/datasets/dariakern/Chicks4FreeID/resolve/main/{VERSION}.zip?download=true"
344
+ base_path = Path(dl_manager.download_and_extract(URL))
345
+
346
+ # Only offer train test split for chicken-re-id task
347
+ if self.config.name in [
348
+ re_id_full_name,
349
+ re_id_best_name
350
+ ]:
351
+ from sklearn.model_selection import train_test_split
352
+
353
+ # all crop files (only chicken, remove unknowns)
354
+ all_crops = sorted([
355
+ crop_file
356
+ for crop_file
357
+ in base_path.rglob(f"**/{VERSION}/reId/chicken/**/*crop_*.png")
358
+ if "Unknown" not in crop_file.parts
359
+ ])
360
+ # all identity targets (labels)
361
+ identities = [name_to_dict(crop.stem)[ID] for crop in all_crops]
362
+
363
+ # Splitting the dataset into train and test using stratified train_test_split
364
+ train_crops, test_crops, _, _ = train_test_split(
365
+ all_crops, identities, test_size=0.2, stratify=identities, shuffle=True, random_state=42
366
+ )
367
+
368
+ return [
369
+ SplitGenerator(
370
+ gen_kwargs={"base_path": base_path, "split": set(train_crops)},
371
+ name=datasets.Split.TRAIN,
372
+ ),
373
+ SplitGenerator(
374
+ gen_kwargs={"base_path": base_path, "split": set(test_crops)},
375
+ name=datasets.Split.TEST,
376
+ )
377
+ ]
378
+ else:
379
+ return [
380
+ SplitGenerator(
381
+ name=datasets.Split.TRAIN,
382
+ gen_kwargs={"base_path": base_path, "split": None})
383
+ ]
384
+
385
+
386
+ def _generate_all(self, base_path: Path, split: Set[Path]=None):
387
+ """
388
+ Generates all examples for the dataset, including all features.
389
+
390
+ Args:
391
+ base_path (Path): The base path to the dataset
392
+ split (Set[Path]): The paths to all instance crops to include in the current dataset
393
+ """
394
+ img_dir = base_path / f"{VERSION}/images"
395
+ mask_dir = base_path / f"{VERSION}/masks"
396
+ reid_dir = base_path / f"{VERSION}/reId"
397
+
398
+ # Collecting images, segmentation masks, and instance masks
399
+ for img_file in img_dir.iterdir():
400
+ image_id = img_file.stem
401
+ image_path = img_file
402
+ segmentation_mask_path = mask_dir / f"{image_id}_segmentationMask.png"
403
+ instance_masks = list(mask_dir.rglob(f"{image_id}_instanceMask_*.png"))
404
+ instance_crops = list(reid_dir.rglob(f"**/{image_id}_crop_*.png"))
405
+
406
+ # Check if all crops have a corresponding instance mask
407
+ assert len(instance_masks) == len(instance_crops) and len(instance_masks) > 0
408
+
409
+ # Remove any instance_crops that are not in crops_split
410
+ if split is not None:
411
+ instance_crops = [crop for crop in instance_crops if crop in split]
412
+
413
+ instance_data = []
414
+ infos = {}
415
+ for instance_mask_path, crop_path in zip(instance_masks, instance_crops):
416
+ infos = name_to_dict(crop_path.stem)
417
+ instance_data.append({
418
+ INSTANCE_MASK: str(instance_mask_path),
419
+ CROP: str(crop_path),
420
+ VISIBILITY: infos[VISIBILITY],
421
+ ID: infos[ID],
422
+ CATEGORY: crop_path.relative_to(reid_dir).parts[0],
423
+ })
424
+
425
+
426
+ if instance_data:
427
+ yield image_id, {
428
+ IMAGE: str(image_path),
429
+ SEGMENTATION_MAKS: str(segmentation_mask_path),
430
+ COOP: infos[COOP],
431
+ INSTANCES: instance_data,
432
+ }
433
+
434
+
435
+ def _generate_examples(self, **kwargs):
436
+ if self.config.name in [full_dataset_name]:
437
+ yield from self._generate_all(**kwargs)
438
+
439
+ elif self.config.name == semantic_segmentation_name:
440
+ for image_id, example in self._generate_all(**kwargs):
441
+ yield image_id, {
442
+ IMAGE: example[IMAGE],
443
+ SEGMENTATION_MAKS: example[SEGMENTATION_MAKS],
444
+ }
445
+
446
+ elif self.config.name == instance_segmentation_name:
447
+ for image_id, example in self._generate_all(**kwargs):
448
+ yield image_id, {
449
+ IMAGE: example[IMAGE],
450
+ INSTANCES: [
451
+ {
452
+ INSTANCE_MASK: instance[INSTANCE_MASK]
453
+ }
454
+ for instance in example[INSTANCES]
455
+ ]
456
+ }
457
+
458
+ elif self.config.name == animal_category_anomoalies_name:
459
+ for image_id, example in self._generate_all(**kwargs):
460
+ for instance in example[INSTANCES]:
461
+ instance_id = Path(instance[CROP]).stem
462
+ yield instance_id, {
463
+ CROP: instance[CROP],
464
+ CATEGORY: instance[CATEGORY],
465
+ }
466
+
467
+ elif self.config.name in [
468
+ re_id_best_name, re_id_full_name,
469
+ # re_id_good_name, re_id_bad_name
470
+ ]:
471
+ for image_id, example in self._generate_all(**kwargs):
472
+ for instance in example[INSTANCES]:
473
+
474
+ # Conditions for filtering
475
+ use_all = self.config.name == re_id_full_name
476
+ selected_visibility = instance[VISIBILITY] == self.config.name.split("-")[-2]
477
+
478
+ if use_all or selected_visibility:
479
+ instance_id = Path(instance[CROP]).stem
480
+ yield instance_id, {
481
+ CROP: instance[CROP],
482
+ ID: instance[ID],
483
+ }
484
+
485
+
486
+
487
+