-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path__init__.py
More file actions
2952 lines (2513 loc) · 131 KB
/
__init__.py
File metadata and controls
2952 lines (2513 loc) · 131 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
from collections import defaultdict
from itertools import combinations
import traceback
import random
import logging
from copy import deepcopy
from contextlib import contextmanager, redirect_stdout, redirect_stderr
from typing import List, Union
import numpy as np
from tqdm import tqdm
from shapely.geometry import Polygon, MultiPolygon
from shapely.validation import make_valid
import fiftyone as fo
import fiftyone.operators as foo
from fiftyone.operators import types
from fiftyone import ViewField as F
import fiftyone.utils.iou as foui
import fiftyone.core.labels as fol
from pymongo.errors import DocumentTooLarge, WriteError
from pycocotools import mask as coco_mask
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from kalphacv import reliability_data, krippendorff_alpha
_NO_MATCH_ID = ""
_NO_MATCH_IOU = None
AnnotationList = List[fol.Label]
class LoadMultiAnnotatedData(foo.Operator):
"""
An operator to load multi-annotated data into a FiftyOne `COCODetectionDataset` and split annotations by `rater_id`.
This operator addresses the challenge of loading datasets with multiple annotations per image (from different raters)
into FiftyOne, which does not natively support multi-annotations in a single `COCODetectionDataset`. It provides
a workaround by processing the dataset to include the necessary fields and splitting the annotations accordingly.
**Requirements:**
1. **Annotations**:
- Each annotation in your dataset must include a `rater_id` field indicating the annotator who provided the annotation.
- Example annotation with `rater_id`:
```json
{
"id": 1,
"image_id": 1,
"category_id": 3,
"bbox": [x, y, width, height],
"area": area,
"iscrowd": 0,
"rater_id": "r1"
}
```
2. **Images**:
- Each image in your dataset should have a `rater_list` field, which is a list of all `rater_id`s associated with that image.
- Example image with `rater_list`:
```json
{
"id": 1,
"file_name": "image1.jpg",
"height": height,
"width": width,
"rater_list": ["r1", "r2"]
}
```
3. **Enable `extra_attrs`**:
- When importing your dataset using `COCODetectionDataset`, you must set `extra_attrs=True` to ensure that
extra fields like `rater_id` and `rater_list` are loaded into the dataset.
**Usage:**
**1. Load Your Dataset with Extra Attributes:**
```python
import fiftyone as fo
labels_path = "/path/to/your/annotations.json"
dataset = fo.Dataset.from_dir(
dataset_type=fo.types.COCODetectionDataset,
data_path="/path/to/your/images/",
labels_path=labels_path,
name="your_dataset_name",
extra_attrs=True, # Important to include extra fields like 'rater_id' and 'rater_list'
use_polylines = True/False, # select True or False depending on what you want to use, polylines are usually better
label_types=["detections", "segmentations"], # in case you use an object detection dataset use only "detections"
)
```
**2. Use the Operator via the SDK (jupyter-notebook example):**
```python
import fiftyone.operators as foo
load_multi_annotated_data = foo.get_operator("@madave94/multi_annotator_toolkit/load_multi_annotated_data")
await load_multi_annotated_data(dataset, labels_path)
```
**3. Or Use the Operator via the FiftyOne App UI:**
- Open the FiftyOne App.
- Navigate to the Operators panel.
- Select "Load Multi Annotated Data" from the list of available operators.
- Provide the path to your annotation file when prompted. (same path as before used for labels_path)
**Note:** When using the UI function, the progress bar may not be displayed.
**What the Operator Does:**
- **Loads `rater_list` into each sample**: Associates each image with its list of raters based on the provided `rater_list` field in the annotations.
- **Splits annotations by `rater_id`**: For each annotation field (e.g., `detections`, `segmentations`), the operator splits the annotations into separate fields for each rater. For example, annotations from `rater_id` "r1" will be moved to a new field `detections_r1`.
- **Handles Missing Annotations Gracefully**: If some annotations do not have a `rater_id`, they will remain in the original annotation field.
**Example Annotation Format:**
Your annotation JSON file should follow the COCO format with the additional `rater_id` and `rater_list` fields:
```json
{
"images": [
{
"id": 1,
"file_name": "image1.jpg",
"height": 1024,
"width": 768,
"rater_list": ["r1", "r2"]
},
// ... more images ...
],
"annotations": [
{
"id": 1,
"image_id": 1,
"category_id": 3,
"bbox": [100, 200, 50, 80],
"area": 4000,
"iscrowd": 0,
"rater_id": "r1"
},
{
"id": 2,
"image_id": 1,
"category_id": 5,
"bbox": [150, 250, 60, 90],
"area": 5400,
"iscrowd": 0,
"rater_id": "r2"
},
// ... more annotations ...
],
"categories": [
{
"id": 3,
"name": "category_name_1",
"supercategory": "supercategory_name"
},
// ... more categories ...
]
}
```
**Important Notes:**
- **Workaround Implementation**: This operator provides a workaround for handling multi-annotated data in FiftyOne, which does not natively support multiple annotations per sample in the same field.
- **Data Integrity**: Ensure that your annotations and images include the `rater_id` and `rater_list` fields to allow the operator to process them correctly.
- **Field Naming**: The operator creates new fields in your dataset, such as `detections_r1`, `detections_r2`, etc., for each rater. These fields will contain the annotations specific to each rater.
- **Processing Limitations**: The operator currently supports splitting annotations in the `detections` and `segmentations` fields. If your dataset uses different fields, you may need to adjust the operator accordingly.
- **Backup Recommendation**: Since the operator modifies your dataset by reorganizing annotations, it is recommended to backup your dataset before applying the operator, especially if you plan to make further modifications.
"""
@property
def config(self):
return foo.OperatorConfig(
name="load_multi_annotated_data",
label="Load Multi Annotated Data",
description="This loads the multi-annotated meta-data like the rater-list into the samples and splits up the annotations by rater_id.",
icon="/assets/icon.svg",
light_icon="/assets/icon-light.svg",
dark_icon="/assets/icon-dark.svg",
)
def __call__(self, sample_collection, annos_path, overwrite=False, num_workers=False, delegate=False):
ctx = dict(view=sample_collection.view())
params = dict(annos_path=annos_path, overwrite=overwrite, num_workers=num_workers, delegate=delegate, api_call=True)
return foo.execute_operator(self.uri, ctx, params=params)
def resolve_input(self, ctx):
# --- for SDK call ---
api_call = ctx.params.get("api_call", False)
if api_call:
# Parameters are already provided; no need to resolve input
return None
# --- for SDK call ---
inputs = types.Object()
inputs.str("annotation_path_instructions",
default="Provide the path to the annotation file (same as the one used for loading the dataset previously.",
view=types.MarkdownView(read_only=True))
# Create an explorer that allows the user to choose a JSON file
file_explorer = types.FileExplorerView(
button_label="Choose a JSON file...",
choose_button_label="Select",
choose_dir=False
)
# Define a types.File property with the file explorer
inputs.file(
"annos_path",
required=True,
label="Annotation file",
description="Choose an annotation file",
view=file_explorer
)
annos_path = ctx.params.get("annos_path", None)
if annos_path is None:
return types.Property(inputs) # Wait for user input
# Extract the file path from the annos_path dictionary
if isinstance(annos_path, dict):
file_path = annos_path.get('absolute_path') or annos_path.get('path')
else:
file_path = annos_path
# check first if the file path is json and than check if it exists
if not file_path.lower().endswith('.json'):
prop = inputs.get_property('annos_path')
prop.invalid = True
prop.error_message = "Please select a file with a .json extension."
return types.Property(inputs)
if not os.path.isfile(file_path):
prop = inputs.get_property('annos_path')
prop.invalid = True
prop.error_message = f"The file '{file_path}' does not exist."
return types.Property(inputs)
return types.Property(inputs)
def execute(self, ctx):
try:
annos_path = ctx.params.get("annos_path")
if isinstance(annos_path, dict):
file_path = annos_path.get('absolute_path') or annos_path.get('path')
else:
file_path = annos_path
# Proceed with your logic using file_path
with open(file_path, 'r') as f:
data = json.load(f)
# Create a mapping from base file names to rater_list
file_name_to_rater_list = {
os.path.basename(image["file_name"]): image["rater_list"] for image in data["images"]
}
# Access the dataset
dataset = ctx.dataset
# Ensure 'rater_list' field is defined as ListField of StringField
if 'rater_list' not in dataset.get_field_schema():
dataset.add_sample_field('rater_list', fo.ListField, subfield=fo.StringField)
# Create a mapping from sample IDs to rater_list
id_to_rater_list = {}
# Iterate over the samples
for sample in dataset:
# Extract the base file name from the sample's filepath
sample_file_name = os.path.basename(sample.filepath)
# Get the rater_list for this sample, if it exists
try:
rater_list = file_name_to_rater_list[sample_file_name]
id_to_rater_list[sample.id] = rater_list
except KeyError:
raise ValueError(
f"Data Inconsistency: The image file '{sample_file_name}' "
f"does not contain the required 'rater_list' attribute."
f"Ensure that the annotation file is correctly formatted."
)
# Bulk update the rater_list field
if id_to_rater_list:
# Specify key_field="_id" to match sample IDs
dataset.set_values("rater_list", id_to_rater_list, key_field="_id")
num_updated = len(id_to_rater_list)
else:
num_updated = 0
# Create an index on 'rater_list' for faster queries
if "rater_list" not in dataset.list_indexes():
dataset.create_index("rater_list")
# Check which annotation fields exist
field_schema = dataset.get_field_schema()
messages = []
loading_success = False
#
# This should include 3 cases
# 1) detections and segmentations are available
# 2) only detections are loaded
# 3) only segmentations are loaded
#
# -> for the segmentations there is a difference between loading polylines or masks
#
# The approach is to check if case 2 or 3 exist which means the field is stored into ground_truth instead of
# segmentations or detections. We find out the type and map it to the correct type. At this point the regular
# process is followed.
# check for ground_truth type and rename it
if "ground_truth" in field_schema:
for sample in dataset:
gt = sample["ground_truth"]
if gt == None:
continue
else:
if hasattr(gt, "detections"):
if "mask" in gt.detections[0]:
dataset.rename_sample_field("ground_truth", "segmentations")
print("Rename ground_truth to segmentations..")
else:
dataset.rename_sample_field("ground_truth", "detections")
print("Rename ground_truth to detections..")
elif hasattr(gt, "polylines"):
dataset.rename_sample_field("ground_truth", "segmentations")
print("Rename ground_truth to segmentations..")
else:
raise Exception("Could not identify annotation type.")
field_schema = dataset.get_field_schema()
break
ann_types = []
if 'detections' in field_schema:
ann_types.append("bounding box")
detection_counts = split_annotations_by_rater(dataset, 'detections', ctx=ctx)
messages.append(
f"Detections - Total: {detection_counts['total_annotations']}, \n"
f"Moved: {detection_counts['annotations_moved']}, \n"
f"Unassigned: {detection_counts['annotations_unassigned']}. \n"
)
loading_success = True
if 'segmentations' in field_schema:
ann_types.append(return_segmentation_type(dataset))
segmentation_counts = split_annotations_by_rater(dataset, 'segmentations')
messages.append(
f"Segmentations - Total: {segmentation_counts['total_annotations']}, \n"
f"Moved: {segmentation_counts['annotations_moved']}, \n"
f"Unassigned: {segmentation_counts['annotations_unassigned']}. \n"
)
loading_success = True
dataset.info["ann_types"] = ann_types
dataset.save()
# **Join the messages into a single string**
if loading_success:
messages = [f"Successfully loaded multi-annotations for {num_updated} out of {len(dataset)} samples.\n "] + messages
else:
messages = ["Loading unsuccessful.\n "]
message_str = "\n".join(messages)
print(message_str)
return {
"message": message_str,
"num_updated": num_updated,
"num_samples": len(dataset),
}
except Exception as e:
error_details = traceback.format_exc()
error_message = (
f"❌ Operator failed!\n\n"
f"Error Type: {type(e).__name__}\n"
f"Error Details: {e}\n\n"
f"Full Traceback:\n-----------------\n{error_details}"
)
print(error_message)
return {"message": error_message}
def resolve_output(self, ctx):
outputs = types.Object()
# Display the message as a notice
outputs.view(
"message",
types.Notice(label=ctx.results.get("message", "")),
)
print(ctx.results.get("message", ""))
return types.Property(outputs)
# utility function to process annotations
def split_annotations_by_rater(dataset, source_field: str, field_prefix: str =None, ctx=None) -> dict:
"""
Splits annotations in the source_field into per-rater fields based on 'rater_id'.
Parameters:
- dataset: the FiftyOne dataset
- source_field: the name of the source field to process ('detections' or 'segmentations')
- field_prefix: prefix for the per-rater fields (default: source_field + '_')
"""
if field_prefix is None:
field_prefix = source_field + '_'
# Counters for reporting
total_annotations = 0
annotations_moved = 0
annotations_unassigned = 0
samples_processed = 0
# Get the source field's type from the dataset schema once
source_field_doc_type = dataset.get_field(source_field).document_type
all_raters = set()
for rater_list in dataset.values("rater_list"):
all_raters.update(rater_list)
# Ensure field exists in dataset schema -> executed only once for the entire dataset per field
# this needs to be done so that empty images are still added
for rater_id in all_raters:
sanitized_rater_id = _sanitize_for_field_name(rater_id).replace('.', '_')
field_name = f"{field_prefix}{sanitized_rater_id.replace('.', '_')}"
if not dataset.has_sample_field(field_name):
dataset.add_sample_field(
field_name,
fo.EmbeddedDocumentField,
embedded_doc_type=source_field_doc_type
)
# Process each sample
for sample in tqdm(dataset, desc=f"Processing {source_field}"):
original_rater_list = sample.get_field("rater_list")
if not original_rater_list:
raise Exception(f"Missing 'rater_list' for {sample.filepath}.")
sanitized_rater_list = [_sanitize_for_field_name(r) for r in original_rater_list]
sample.rater_list = sanitized_rater_list
# Initialize per-rater annotations dict
annotations_by_rater = {sanitized_id: [] for sanitized_id in sanitized_rater_list}
unassigned_annotations = []
annotations: fol.Label = sample.get_field(source_field)
# Determine the attribute to access based on field type
if annotations is not None:
if isinstance(annotations, fo.Detections):
annotations_list: AnnotationList = annotations.detections
elif isinstance(annotations, fo.Polylines):
annotations_list: AnnotationList = annotations.polylines
else:
raise TypeError(f"Unsupported label type {type(annotations)}.")
# Process annotations
for annotation in annotations_list:
original_rater_id = annotation.get_field('rater_id')
if not original_rater_id:
raise ValueError(f"Missing 'rater_id' for annotation in {sample.filepath}")
sanitized_rater_id = _sanitize_for_field_name(original_rater_id)
annotation.rater_id = sanitized_rater_id
total_annotations += 1
if sanitized_rater_id in annotations_by_rater:
annotations_by_rater[sanitized_rater_id].append(annotation)
annotations_moved += 1
else:
unassigned_annotations.append(annotation)
annotations_unassigned += 1
# Assign per-rater annotations to new fields
for rater_id in sanitized_rater_list:
ann_list = annotations_by_rater.get(rater_id, [])
field_name = f"{field_prefix}{rater_id}"
if ann_list:
if isinstance(annotations, fo.Detections):
sample[field_name] = fo.Detections(detections=ann_list)
elif isinstance(annotations, fo.Polylines):
sample[field_name] = fo.Polylines(polylines=ann_list)
else:
raise Exception("Invalid annotations type processed. Should be detections or polylines.")
else:
sample[field_name] = source_field_doc_type()
# Handle unassigned annotations
if unassigned_annotations:
# Keep them in the source field
if isinstance(annotations, fo.Detections):
sample[source_field] = fo.Detections(detections=unassigned_annotations)
elif isinstance(annotations, fo.Polylines):
sample[source_field] = fo.Polylines(polylines=unassigned_annotations)
else:
raise Exception("Invalid annotations type processed. Should be detections or polylines.")
else:
# No unassigned annotations; clear the source field
sample.clear_field(source_field)
# Save the sample
sample.save()
samples_processed += 1
# Optionally, remove the source field from the dataset schema if empty
if dataset.match(F(source_field).exp()).count() == 0:
dataset.delete_sample_field(source_field)
# Return counts for reporting
return {
'total_annotations': total_annotations,
'annotations_moved': annotations_moved,
'annotations_unassigned': annotations_unassigned,
'samples_processed': samples_processed
}
def return_segmentation_type(dataset):
for sample in dataset:
annotations = sample.get_field("segmentations")
if annotations is None:
continue
# Determine the attribute to access based on field type
if isinstance(annotations, fo.Detections):
return "mask"
elif isinstance(annotations, fo.Polylines):
return "polygon"
else:
raise Exception("Invalid annotations type processed. Should be detections or polylines.")
class CalculateIaa(foo.Operator):
@property
def config(self):
return foo.OperatorConfig(
name="calculate_iaa",
label="Calculate IAA",
description="Calculates the Inter-Annotator-Agreement",
allow_immediate_execution=True,
allow_delegated_execution=True,
icon="/assets/icon.svg",
light_icon="/assets/icon-light.svg",
dark_icon="/assets/icon-dark.svg",
dynamic=True,
)
def __call__(self, sample_collection, annotation_type, iou_thresholds, run_sampling=False, subset_n=None,
sampling_k=None, random_seed_s=None, delegate=False):
ctx = dict(view=sample_collection.view())
# set default parameters for sampling procedure if sampling is activated
if run_sampling:
subset_n = subset_n if subset_n else int(len(sample_collection) * 0.1)
sampling_k = sampling_k if sampling_k else 1000
random_seed_s = random_seed_s if random_seed_s else 42
params = dict(annotation_type=annotation_type, iou_thresholds=iou_thresholds, run_sampling=run_sampling,
subset_n=subset_n, sampling_k=sampling_k, random_seed_s=random_seed_s, delegate=delegate, api_call=True)
return foo.execute_operator(self.uri, ctx, params=params)
def resolve_input(self, ctx):
# Check available annotation types (bbox, polygon, mask)
available_types = check_available_annotation_types(ctx)
# --- for SDK call ---
api_call = ctx.params.get("api_call", False)
if api_call:
# Parameters are already provided; no need to resolve input
assert ctx.params.get("annotation_type") in available_types, \
"Annotation type {} not in {}.".format(ctx.params.get("annotation_type"), available_types)
return None
# --- for SDK call ---
inputs = types.Object()
inputs.md("###### Options for calculating inter annotator agreement", name="mk1")
# Create checkboxes for available annotation types
annotation_types_radio_group = types.RadioGroup()
for annotation_type in available_types:
annotation_types_radio_group.add_choice(annotation_type, label=annotation_type)
inputs.enum(
"annotation_type",
annotation_types_radio_group.values(),
label="Annotation Type",
description="Select the annotation type to include in the analysis:",
types=types.RadioView(),
default=list(available_types)[0],
)
inputs.list(
"iou_thresholds",
types.Number(min=0.01, max=0.99, float=True),
label="IoU Thresholds",
description="Enter IoU thresholds. Values should range between 0.01 and 0.99.",
)
inputs.bool(
"run_sampling",
default=False,
label="Run sampling",
description="Run sampling procedure to produce confidence interval when determining convergence threshold."
)
run_sampling = ctx.params.get("run_sampling")
if run_sampling:
dataset = ctx.dataset
inputs.md("""
Selecting "Run sampling" will still first run IAA on all samples but than, the sampling procedure
applies **bootstrapping**, where `k` replicates of size `n` are drawn from the dataset `N` with
replacement, using a fixed random seed (`s`) for reproducibility.
Please consider deligating this operation, since for larger k or n the processing might take
multiple hours.
""", name="mk2")
inputs.int(
"subset_n",
label="Subset Size (n)",
description="Size of the dataset sample replicate n, with maximum size: dataset size - 1",
default=int(len(dataset)*0.1),
min=1,
max=len(dataset)-1,
required=True
)
inputs.int(
"sampling_k",
label="Number of Samples (k)",
description="The number of times the sampling procedure is repeated.",
default=1000,
min=2,
required=True
)
inputs.int(
"random_seed_s",
label="Random Seed (s)",
description="Select a random seed used to sample from the dataset. Available for reproduction purposes.",
default=42,
min=0,
required=True
)
# Add execution mode (if applicable to your use case)
_execution_mode(ctx, inputs)
return types.Property(inputs)
def resolve_delegation(self, ctx):
return ctx.params.get("delegate", False)
def execute(self, ctx):
# Access the dataset
dataset = ctx.dataset
ann_type = ctx.params.get("annotation_type")
iou_thresholds = ctx.params.get("iou_thresholds")
# Add the field to the dataset if it does not already exist
if not dataset.has_sample_field("iaa"):
dataset.add_sample_field(
"iaa",
fo.DictField,
subfield=fo.FloatField
)
if "iaa_analyzed" not in dataset.info:
dataset.info["iaa_analyzed"] = []
dataset.save()
for iou in iou_thresholds:
iou_str = str(iou).replace(".", ",")
key = ann_type + "-" + iou_str
if key not in dataset.info["iaa_analyzed"]:
dataset.info["iaa_analyzed"].append(key)
dataset.save()
alphas = defaultdict(list)
for sample in tqdm(dataset, "Calculating IAA for samples"):
image_name = sample.get_field("filepath").split("/")[-1]
raters_by_image = sample.get_field("rater_list")
if raters_by_image is None:
continue # Skip samples without raters
size_for_image = (sample.metadata.height, sample.metadata.width)
annotations_by_image = []
for rater_id in raters_by_image:
if ann_type == "bounding box":
ann_field = f"detections_{rater_id}"
element_field = "detections"
elif ann_type == "mask":
ann_field = f"segmentations_{rater_id}"
element_field = "detections"
elif ann_type == "polygon":
ann_field = f"segmentations_{rater_id}"
element_field = "polylines"
else:
continue
if not sample.has_field(ann_field):
continue
annotations = sample.get_field(ann_field)
if annotations is None:
continue
for annotation in getattr(annotations, element_field, []):
segmentation = None
if ann_type == "polygon":
segmentation = [
[point for sublist in shape for point in sublist]
for shape in annotation["points"]
]
elif ann_type == "mask":
segmentation = annotation["mask"]
annotations_by_image.append({
"bbox": annotation["bounding_box"] if "bounding_box" in annotation else None,
"category_id": annotation["label"],
"rater": rater_id,
"segmentation": segmentation,
})
# Prepare reliability data
rel_data = reliability_data.ReliabilityData(
image_name, annotations_by_image, raters_by_image, size_for_image
)
for iou_threshold in iou_thresholds:
coincidence_matrix = rel_data.run("bbox" if "bounding box" == ann_type else "segm",
iou_threshold)
alpha = krippendorff_alpha.calculate_alpha(coincidence_matrix)
iaa_dict = sample["iaa"]
if iaa_dict is None:
iaa_dict = {}
iou_str = str(iou_threshold).replace(".", ",")
iaa_dict[ann_type + "-" + iou_str] = alpha
sample["iaa"] = iaa_dict
sample.save()
alphas[str(iou_threshold)].append(alpha)
run_sampling = ctx.params.get("run_sampling")
if run_sampling:
subset_n = ctx.params.get("subset_n", int(len(dataset)*0.1))
sampling_k = ctx.params.get("sampling_k", 1000)
random_seed_s = ctx.params.get("random_seed_s", 42)
if "iaa_sampled" not in dataset.info:
dataset.info["iaa_sampled"] = {}
iaas = dataset.info["iaa_sampled"]
random.seed(random_seed_s)
for idx in range(sampling_k):
# sample iaa value per threshold
indices = random.sample(range(len(dataset)), subset_n)
for iou_threshold in iou_thresholds:
iaa_values = [alphas[str(iou_threshold)][i] for i in indices]
iaas[f"{ann_type}_{iou_threshold}_{random_seed_s}_{subset_n}_{idx}"] = sum(iaa_values) / len(iaa_values)
del dataset.info["iaa_sampled"]
dataset.info["iaa_sampled"] = iaas
dataset.save()
message = "Mean K-Alpha for: \n"
for iou_threshold in iou_thresholds:
u_k_alpha = sum(alphas[str(iou_threshold)]) / len(alphas[str(iou_threshold)])
message += f"\tIoU {iou_threshold} on {ann_type}: {u_k_alpha} \n"
# Include a message for sampling
if run_sampling:
message += f"\tSampling completed with {sampling_k} samples of size {subset_n} using random seed {random_seed_s}. \n"
print(message)
ctx.ops.open_panel("iaa_panel")
return {"message": message}
def resolve_output(self, ctx):
outputs = types.Object()
# Display the message as a notice
outputs.view(
"message",
types.Notice(label=ctx.results.get("message", "")),
)
print(ctx.results.get("message", ""))
return types.Property(outputs)
class IAAPanel(foo.Panel):
@property
def config(self):
return foo.PanelConfig(
name="iaa_panel",
label="IAA Panel",
allow_multiple=False,
surfaces="grid",
help_markdown="A panel to filter IAA values in the views and show summary statistics.",
icon="/assets/icon.svg",
light_icon="/assets/icon-light.svg",
dark_icon="/assets/icon-dark.svg",
)
def on_load(self, ctx):
# load initial values
iaa_list = ctx.dataset.info["iaa_analyzed"]
iaa_dict = defaultdict(list)
for iaa in iaa_list:
ann_type, iou = iaa.split("-")
iaa_dict[ann_type].append(iou)
# set default values
ctx.panel.state.iaa_dict = iaa_dict
if ctx.panel.state.ann_type_selection is None:
ctx.panel.state.ann_type_selection = list(iaa_dict.keys())[0]
if ctx.panel.state.iou_selection is None:
ctx.panel.state.iou_selection = iaa_dict[ctx.panel.state.ann_type_selection][0]
self.apply(ctx)
ctx.ops.split_panel("iaa_panel", layout="horizontal")
def apply(self, ctx):
# store values
ann_type_selection = ctx.panel.state.ann_type_selection
iou_selection = ctx.panel.state.iou_selection
iaa_dict = ctx.panel.state.iaa_dict
# clean values
ctx.ops.clear_panel_state()
# initialize default min/max values
ctx.panel.state.max_value = 1.0
ctx.panel.state.min_value = -1.0
ctx.panel.set_state("v_stack.double_slider", [-1.0,1.0])
# set states
ctx.panel.state.ann_type_selection = ann_type_selection
ctx.panel.state.iou_selection = iou_selection
ctx.panel.state.iaa_dict = iaa_dict
ctx.panel.state.mean_msg = "Waiting for calculation ..."
# run computation and plotting
ctx.panel.state.plot_title = "Inter-Annotat-Agreement: {} {}".format(
ctx.panel.state.ann_type_selection,
ctx.panel.state.iou_selection)
self.select_values(ctx)
self.set_histogram_values(ctx)
ctx.ops.clear_view()
def change_ann_type(self, ctx):
ctx.panel.state.ann_type_selection = ctx.params["value"]
def change_iou_value(self, ctx):
ctx.panel.state.iou_selection = ctx.params["value"]
def select_values(self, ctx):
selected_values = []
unselected_values = []
for sample in ctx.dataset:
value = (sample["iaa"][ctx.panel.state.ann_type_selection + "-" + ctx.panel.state.iou_selection])
if value <= ctx.panel.state.max_value and value >= ctx.panel.state.min_value:
selected_values.append(value)
else:
unselected_values.append(value)
ctx.panel.state.selected_values = selected_values
ctx.panel.state.unselected_values = unselected_values
def set_histogram_values(self, ctx):
# Reset the histogram before setting new data
ctx.panel.state.mean_msg = "Mean IAA for {} samples using {} annotations wih iou-threshold {}: **{:.3f}**".format(
len(ctx.panel.state.selected_values),
ctx.panel.state.ann_type_selection,
ctx.panel.state.iou_selection,
sum(ctx.panel.state.selected_values) / len(ctx.panel.state.selected_values)
)
ctx.ops.clear_panel_data()
ctx.panel.set_data("v_stack.histogram", [{"name": "Selected Values",
"x": ctx.panel.state.selected_values,
"type": "histogram",
"marker": {"color": "#FF6D05"}, # gray #808080
"xbins": {"start": -1.0, "end": 1.0001, "size": 0.1},
},
{"name": "other Values",
"x": ctx.panel.state.unselected_values,
"type": "histogram",
"marker": {"color": "#808080"}, # gray #808080
"xbins": {"start": -1.0, "end": 1.0001, "size": 0.1},
}]
)
def on_histogram_click(self, ctx):
bin_range = ctx.params.get("range")
min_value = bin_range[0]
max_value = bin_range[1]
ann_type = ctx.panel.state.ann_type_selection
iou_value = ctx.panel.state.iou_selection
field_name = "iaa.{}-{}".format(ann_type, iou_value)
ctx.panel.state.min_value = min_value
ctx.panel.state.max_value = max_value
self.select_values(ctx)
self.set_histogram_values(ctx)
view = ctx.dataset.match((F(field_name) >= min_value) & (F(field_name) <= max_value))
if view is not None:
ctx.ops.set_view(view=view)
def slider_change(self,ctx):
bin_range = ctx.params.get("value")
min_value = bin_range[0]
max_value = bin_range[1]
ann_type = ctx.panel.state.ann_type_selection
iou_value = ctx.panel.state.iou_selection
field_name = "iaa.{}-{}".format(ann_type, iou_value)
ctx.panel.state.min_value = min_value
ctx.panel.state.max_value = max_value
self.select_values(ctx)
self.set_histogram_values(ctx)
view = ctx.dataset.match((F(field_name) >= min_value) & (F(field_name) <= max_value))
if view is not None:
ctx.ops.set_view(view=view)
def render(self, ctx):
panel = types.Object()
v_stack = panel.v_stack("v_stack", align_x="center", align_y="center", width=100, gap=2)
h_stack = v_stack.h_stack("h_stack", align_x="center", align_y="center", gap=5)
dropdown_ann_type = types.DropdownView()
for ann_type in ctx.panel.state.iaa_dict.keys():
dropdown_ann_type.add_choice(ann_type, label=ann_type)
h_stack.view(
"dropdown_ann_type",
view=dropdown_ann_type,
label="Annotation Type",
on_change=self.change_ann_type
)
dropdown_iou_value = types.DropdownView()
for iou_type in ctx.panel.state.iaa_dict[ctx.panel.state.ann_type_selection]:
dropdown_iou_value.add_choice(iou_type, label=iou_type)
h_stack.view(
"dropdown_iou_value",
view=dropdown_iou_value,
label="IoU Threshold",
on_change=self.change_iou_value
)
h_stack.btn(
"load",
label="load/reset",
on_click=self.apply
)
v_stack.plot(
"histogram",
layout={
"title": {
"text": ctx.panel.state.plot_title,
"automargin": True,
},
"xaxis": {"title": "K-Alpha"},
"yaxis": {"title": "Count"},
"bargap": 0.05,
"autosize": True, # Enable autosizing for responsive behavior
"responsive": True,
"dragmode": "select",
"selectdirection": "h",
"showlegend": True,
"legend": {
"x": 0.5,
"y": -0.2,
"xanchor": "center",
"orientation": "h",
"bgcolor": "rgba(0, 0, 0, 0)", # Transparent background for the legend
},