-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathlayout_evaluator.py
More file actions
1242 lines (1072 loc) · 48 KB
/
layout_evaluator.py
File metadata and controls
1242 lines (1072 loc) · 48 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 glob
import logging
import re
from collections import defaultdict
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import torch
from datasets import Dataset, load_dataset
from docling_core.types.doc.document import (
DEFAULT_EXPORT_LABELS,
ContentLayer,
DocItem,
DoclingDocument,
)
from docling_core.types.doc.labels import DocItemLabel
from pydantic import BaseModel
from torchmetrics.detection.mean_ap import MeanAveragePrecision
from tqdm import tqdm # type: ignore
from docling_eval.datamodels.cvat_page_mapping import CvatPageMapping, PageRef
from docling_eval.datamodels.dataset_record import DatasetRecordWithPrediction
from docling_eval.datamodels.types import BenchMarkColumns, PredictionFormats
from docling_eval.evaluators.base_evaluator import (
BaseEvaluator,
DatasetEvaluation,
EvaluationRejectionType,
UnitEvaluation,
docling_document_from_doctags,
)
from docling_eval.evaluators.stats import DatasetStatistics, compute_stats
from docling_eval.utils.external_docling_document_loader import (
ExternalDoclingDocumentLoader,
)
from docling_eval.utils.utils import tensor_to_float
_log = logging.getLogger(__name__)
class MissingPredictionStrategy(Enum):
"""Strategy for handling missing predictions."""
PENALIZE = "penalize" # Treat missing predictions as zero score
IGNORE = "ignore" # Skip the GT-Pred pair entirely
class LabelFilteringStrategy(Enum):
"""Strategy for determining which labels to evaluate."""
INTERSECTION = (
"intersection" # Only evaluate labels present in both GT and predictions
)
UNION = "union" # Evaluate all labels present in the label mapping
class ClassLayoutEvaluation(BaseModel):
r"""
Class based layout evaluation
"""
name: str
label: str
value: float # AP[0.5:0.05:0.95]
class ImageLayoutEvaluation(UnitEvaluation):
r"""
Image based layout evaluation
"""
name: str
doc_name: str
image_name: str
page_no: int
value: float # Area weighted average IoU for label-matched GT/pred bboxes for IoU thres = 0.5
map_val: float # AP at IoU thres=0.50
map_50: float # AP at IoU thres=0.50
map_75: float # AP at IoU thres=0.75
# Weighted average IoU for the page bboxes with matching labels (between GT and pred)
# The weight is the bbox size and each measurement corresponds to a different IoU threshold
avg_weighted_label_matched_iou_50: float
avg_weighted_label_matched_iou_75: float
avg_weighted_label_matched_iou_90: float
avg_weighted_label_matched_iou_95: float
segmentation_precision: float
segmentation_recall: float
segmentation_f1: float
# Area-level metrics excluding PICTURE labels
segmentation_precision_no_pictures: Optional[float] = None
segmentation_recall_no_pictures: Optional[float] = None
segmentation_f1_no_pictures: Optional[float] = None
# New per-sample element count metrics
true_element_count: int
pred_element_count: int
true_table_count: int
pred_table_count: int
true_picture_count: int
pred_picture_count: int
element_count_diff: int
table_count_diff: int
picture_count_diff: int
class DatasetLayoutEvaluation(DatasetEvaluation):
true_labels: Dict[str, int]
pred_labels: Dict[str, int]
mAP: float # The mean AP[0.5:0.05:0.95] across all classes
intersecting_labels: List[str]
evaluations_per_class: List[ClassLayoutEvaluation]
evaluations_per_image: List[ImageLayoutEvaluation]
# Statistics
map_stats: DatasetStatistics # Stats for the mAP[0.5:0.05:0.95] across all images
map_50_stats: DatasetStatistics
map_75_stats: DatasetStatistics
weighted_map_50_stats: DatasetStatistics
weighted_map_75_stats: DatasetStatistics
weighted_map_90_stats: DatasetStatistics
weighted_map_95_stats: DatasetStatistics
segmentation_precision_stats: DatasetStatistics
segmentation_recall_stats: DatasetStatistics
segmentation_f1_stats: DatasetStatistics
# Statistics for metrics excluding PICTURE labels
segmentation_precision_no_pictures_stats: Optional[DatasetStatistics] = None
segmentation_recall_no_pictures_stats: Optional[DatasetStatistics] = None
segmentation_f1_no_pictures_stats: Optional[DatasetStatistics] = None
def to_table(self) -> Tuple[List[List[str]], List[str]]:
headers = ["label", "Class mAP[0.5:0.95]"]
self.evaluations_per_class = sorted(
self.evaluations_per_class, key=lambda x: x.value, reverse=True
)
table = []
for i in range(len(self.evaluations_per_class)):
table.append(
[
f"{self.evaluations_per_class[i].label}",
f"{100.0*self.evaluations_per_class[i].value:.2f}",
]
)
return table, headers
class LayoutEvaluator(BaseEvaluator):
def __init__(
self,
label_mapping: Optional[Dict[DocItemLabel, Optional[DocItemLabel]]] = None,
intermediate_evaluations_path: Optional[Path] = None,
prediction_sources: List[PredictionFormats] = [],
missing_prediction_strategy: MissingPredictionStrategy = MissingPredictionStrategy.PENALIZE,
label_filtering_strategy: LabelFilteringStrategy = LabelFilteringStrategy.INTERSECTION,
page_mapping_path: Optional[Path] = None,
):
supported_prediction_formats: List[PredictionFormats] = [
PredictionFormats.DOCLING_DOCUMENT,
PredictionFormats.DOCTAGS,
PredictionFormats.JSON,
PredictionFormats.YAML,
]
if not prediction_sources:
prediction_sources = supported_prediction_formats
super().__init__(
intermediate_evaluations_path=intermediate_evaluations_path,
prediction_sources=prediction_sources,
supported_prediction_formats=supported_prediction_formats,
)
self.filter_labels = []
self.label_names = {}
self.label_mapping = label_mapping or {v: v for v in DocItemLabel}
self.missing_prediction_strategy = missing_prediction_strategy
self.label_filtering_strategy = label_filtering_strategy
self._page_mapping_path = page_mapping_path
self._page_mapping: Optional[CvatPageMapping] = None
for i, _ in enumerate(DEFAULT_EXPORT_LABELS):
self.filter_labels.append(_)
self.label_names[i] = _
def __call__(
self,
ds_path: Path,
split: str = "test",
external_predictions_path: Optional[Path] = None,
) -> DatasetLayoutEvaluation:
logging.info("Loading the split '%s' from: '%s'", split, ds_path)
ext_docdoc_loader: Optional[ExternalDoclingDocumentLoader] = None
if external_predictions_path is not None:
ext_docdoc_loader = ExternalDoclingDocumentLoader(external_predictions_path)
# Load the dataset
split_path = str(ds_path / split / "*.parquet")
split_files = glob.glob(split_path)
logging.info("#-files: %s", len(split_files))
ds = load_dataset("parquet", data_files={split: split_files})
logging.info("Overview of dataset: %s", ds)
# Select the split
ds_selection: Dataset = ds[split]
(
true_labels,
pred_labels,
intersection_labels,
union_labels,
) = self._find_intersecting_labels(ds_selection, ext_docdoc_loader)
true_labels_str = ", ".join(sorted(true_labels))
logging.info(f"True labels: {true_labels_str}")
pred_labels_str = ", ".join(sorted(pred_labels))
logging.info(f"Pred labels: {pred_labels_str}")
intersection_labels_str = ", ".join(sorted(intersection_labels))
logging.info(f"Intersection labels: {intersection_labels_str}")
union_labels_str = ", ".join(sorted(union_labels))
logging.info(f"Union labels: {union_labels_str}")
logging.info(
f"Using missing prediction strategy: {self.missing_prediction_strategy.value}"
)
logging.info(
f"Using label filtering strategy: {self.label_filtering_strategy.value}"
)
# Determine which labels to use for evaluation based on strategy
if self.label_filtering_strategy == LabelFilteringStrategy.INTERSECTION:
filter_labels = intersection_labels
elif self.label_filtering_strategy == LabelFilteringStrategy.UNION:
# Use all labels from the mapping that have non-None values
filter_labels = [
DocItemLabel(mapped_label)
for mapped_label in set(self.label_mapping.values())
if mapped_label is not None
]
else:
raise ValueError(
f"Unknown label filtering strategy: {self.label_filtering_strategy}"
)
# Filter out any labels not in DEFAULT_EXPORT_LABELS as a safeguard
filter_labels = [
label for label in filter_labels if label in DEFAULT_EXPORT_LABELS
]
filter_labels_str = ", ".join(sorted([label.value for label in filter_labels]))
logging.info(f"Filter labels for evaluation: {filter_labels_str}")
page_mapping = self._get_page_mapping()
doc_ids = []
ground_truths = []
predictions = []
per_page_meta: List[Tuple[str, str, str, int]] = []
rejected_samples: Dict[EvaluationRejectionType, int] = {
EvaluationRejectionType.INVALID_CONVERSION_STATUS: 0,
EvaluationRejectionType.MISSING_PREDICTION: 0,
EvaluationRejectionType.MISMATHCED_DOCUMENT: 0,
}
doc_stats: Dict[str, Dict[str, int]] = {}
for i, data in tqdm(
enumerate(ds_selection),
desc="Layout evaluations",
ncols=120,
total=len(ds_selection),
):
data_record = DatasetRecordWithPrediction.model_validate(data)
doc_id = data_record.doc_id
if (
ext_docdoc_loader is None
and data_record.status not in self._accepted_status
):
_log.error(
"Skipping record without successfull conversion status: %s", doc_id
)
rejected_samples[EvaluationRejectionType.INVALID_CONVERSION_STATUS] += 1
continue
true_doc = data_record.ground_truth_doc
# Get the predicted document
pred_doc = self._get_pred_doc(data_record, ext_docdoc_loader)
if not pred_doc:
_log.error("There is no prediction for doc_id=%s", doc_id)
rejected_samples[EvaluationRejectionType.MISSING_PREDICTION] += 1
continue
doc_stats[doc_id] = {
"true_element_count": len(true_doc.texts)
+ len(true_doc.tables)
+ len(true_doc.pictures),
"pred_element_count": len(pred_doc.texts)
+ len(pred_doc.tables)
+ len(pred_doc.pictures),
"true_table_count": len(true_doc.tables),
"pred_table_count": len(pred_doc.tables),
"true_picture_count": len(true_doc.pictures),
"pred_picture_count": len(pred_doc.pictures),
}
gts, preds = self._extract_layout_data(
true_doc=true_doc,
pred_doc=pred_doc,
filter_labels=filter_labels,
)
# Track mismatched documents when using PENALIZE strategy and there are missing pages
true_pages = set()
for item, level in true_doc.iterate_items(
included_content_layers={c for c in ContentLayer},
traverse_pictures=True,
):
if isinstance(item, DocItem):
mapped_label = self.label_mapping.get(item.label)
if mapped_label is not None and mapped_label in filter_labels:
for prov in item.prov:
true_pages.add(prov.page_no)
pred_pages = set()
for item, level in pred_doc.iterate_items(
included_content_layers={c for c in ContentLayer},
traverse_pictures=True,
):
if isinstance(item, DocItem):
mapped_label = self.label_mapping.get(item.label)
if mapped_label is not None and mapped_label in filter_labels:
for prov in item.prov:
pred_pages.add(prov.page_no)
if (
self.missing_prediction_strategy == MissingPredictionStrategy.PENALIZE
and len(true_pages - pred_pages) > 0
):
rejected_samples[EvaluationRejectionType.MISMATHCED_DOCUMENT] += 1
# The new _extract_layout_data method ensures proper alignment
# gts and preds are guaranteed to have the same length and corresponding indices
if len(gts) > 0:
for (page_no, gt_tensor), (pred_page_no, pred_tensor) in zip(
gts, preds
):
assert (
page_no == pred_page_no
), "Layout evaluator misaligned ground-truth and prediction pages"
page_doc_id = f"{data_record.doc_id}-page-{page_no}"
doc_name, image_name = self._resolve_page_metadata(
page_mapping=page_mapping,
data_record=data_record,
base_doc_id=data_record.doc_id,
page_no=page_no,
)
doc_ids.append(page_doc_id)
per_page_meta.append(
(data_record.doc_id, doc_name, image_name, page_no)
)
ground_truths.append(gt_tensor)
predictions.append(pred_tensor)
# Note: We no longer need to check for mismatched documents since
# _extract_layout_data ensures proper alignment based on missing_prediction_strategy
assert len(doc_ids) == len(ground_truths), "doc_ids==len(ground_truths)"
assert len(doc_ids) == len(predictions), "doc_ids==len(predictions)"
assert len(doc_ids) == len(per_page_meta), "metadata alignment failure"
# Initialize metric for the bboxes of the entire document
metric = MeanAveragePrecision(iou_type="bbox", class_metrics=True)
# Update metric with predictions and ground truths
metric.update(predictions, ground_truths)
# Compute mAP and other metrics per class
result = metric.compute()
evaluations_per_class: List[ClassLayoutEvaluation] = []
total_mAP = result["map"]
if "map_per_class" in result:
for label_idx, class_map in enumerate(result["map_per_class"]):
label = filter_labels[label_idx].value
evaluations_per_class.append(
ClassLayoutEvaluation(
name="Class AP[0.5:0.95]",
label=label,
value=class_map,
)
)
# Compute mAP for each image individually
map_values = []
map_50_values = []
map_75_values = []
weighted_map_50_values = []
weighted_map_75_values = []
weighted_map_90_values = []
weighted_map_95_values = []
evaluations_per_image: List[ImageLayoutEvaluation] = []
for i, (doc_id_page, meta, pred, gt) in enumerate(
zip(doc_ids, per_page_meta, predictions, ground_truths)
):
# logging.info(f"gt: {gt}")
# logging.info(f"pred: {pred}")
base_doc_id, doc_name, image_name, page_no = meta
statistics = doc_stats.get(
base_doc_id,
{
"true_element_count": 0,
"pred_element_count": 0,
"true_table_count": 0,
"pred_table_count": 0,
"true_picture_count": 0,
"pred_picture_count": 0,
},
)
precision, recall, f1 = self._compute_area_level_metrics_for_tensors(
gt_boxes=gt["boxes"],
pred_boxes=pred["boxes"],
page_width=100,
page_height=100,
mask_width=512,
mask_height=512,
)
# Compute metrics excluding PICTURE labels
precision_no_pics, recall_no_pics, f1_no_pics = (
self._compute_area_level_metrics_excluding_pictures(
gt_boxes=gt["boxes"],
gt_labels=gt["labels"],
pred_boxes=pred["boxes"],
pred_labels=pred["labels"],
filter_labels=filter_labels,
page_width=100,
page_height=100,
mask_width=512,
mask_height=512,
)
)
# Reset the metric for the next image
metric = MeanAveragePrecision(iou_type="bbox", class_metrics=True)
# Update with single image - these are already tensor-only dicts
metric.update([pred], [gt])
# Compute metrics
result = metric.compute()
# Extract mAP for this image
map_value = tensor_to_float(result["map_50"])
map_50 = tensor_to_float(result["map_50"])
map_75 = tensor_to_float(result["map_75"])
result = self._compute_average_iou_with_labels_across_iou(
pred_boxes=pred["boxes"],
pred_labels=pred["labels"],
gt_boxes=gt["boxes"],
gt_labels=gt["labels"],
)
average_iou_50 = tensor_to_float(result["average_iou_50"])
average_iou_75 = tensor_to_float(result["average_iou_75"])
average_iou_90 = tensor_to_float(result["average_iou_90"])
average_iou_95 = tensor_to_float(result["average_iou_95"])
# Set the stats
map_values.append(map_value)
map_50_values.append(map_50)
map_75_values.append(map_75)
weighted_map_50_values.append(average_iou_50)
weighted_map_75_values.append(average_iou_75)
weighted_map_90_values.append(average_iou_90)
weighted_map_95_values.append(average_iou_95)
_log.debug(
"doc: %s\tprecision: %.2f, recall: %.2f, f1: %.2f, map_50: %.2f, "
"precision_no_pics: %.2f, recall_no_pics: %.2f, f1_no_pics: %.2f",
doc_id_page,
precision,
recall,
f1,
map_50,
precision_no_pics,
recall_no_pics,
f1_no_pics,
)
true_element_count = int(statistics["true_element_count"])
pred_element_count = int(statistics["pred_element_count"])
true_table_count = int(statistics["true_table_count"])
pred_table_count = int(statistics["pred_table_count"])
true_picture_count = int(statistics["true_picture_count"])
pred_picture_count = int(statistics["pred_picture_count"])
image_evaluation = ImageLayoutEvaluation(
name=doc_id_page,
doc_name=doc_name,
image_name=image_name,
page_no=page_no,
value=average_iou_50,
map_val=map_value,
map_50=map_50,
map_75=map_75,
avg_weighted_label_matched_iou_50=average_iou_50,
avg_weighted_label_matched_iou_75=average_iou_75,
avg_weighted_label_matched_iou_90=average_iou_90,
avg_weighted_label_matched_iou_95=average_iou_95,
segmentation_precision=precision,
segmentation_recall=recall,
segmentation_f1=f1,
segmentation_precision_no_pictures=precision_no_pics,
segmentation_recall_no_pictures=recall_no_pics,
segmentation_f1_no_pictures=f1_no_pics,
true_element_count=true_element_count,
pred_element_count=pred_element_count,
true_table_count=true_table_count,
pred_table_count=pred_table_count,
true_picture_count=true_picture_count,
pred_picture_count=pred_picture_count,
table_count_diff=abs(true_table_count - pred_table_count),
picture_count_diff=abs(true_picture_count - pred_picture_count),
element_count_diff=abs(true_element_count - pred_element_count),
)
evaluations_per_image.append(image_evaluation)
if self._intermediate_evaluations_path:
self.save_intermediate_evaluations(
"Layout_image", i, doc_id_page, evaluations_per_image
)
evaluations_per_class = sorted(evaluations_per_class, key=lambda x: -x.value)
evaluations_per_image = sorted(evaluations_per_image, key=lambda x: -x.value)
dataset_layout_evaluation = DatasetLayoutEvaluation(
evaluated_samples=len(evaluations_per_image),
rejected_samples=rejected_samples,
mAP=total_mAP,
evaluations_per_class=evaluations_per_class,
evaluations_per_image=evaluations_per_image,
map_stats=compute_stats(map_values),
map_50_stats=compute_stats(map_50_values),
map_75_stats=compute_stats(map_75_values),
weighted_map_50_stats=compute_stats(weighted_map_50_values),
weighted_map_75_stats=compute_stats(weighted_map_75_values),
weighted_map_90_stats=compute_stats(weighted_map_90_values),
weighted_map_95_stats=compute_stats(weighted_map_95_values),
segmentation_precision_stats=compute_stats(
[_.segmentation_precision for _ in evaluations_per_image]
),
segmentation_recall_stats=compute_stats(
[_.segmentation_recall for _ in evaluations_per_image]
),
segmentation_f1_stats=compute_stats(
[_.segmentation_f1 for _ in evaluations_per_image]
),
segmentation_precision_no_pictures_stats=compute_stats(
[
_.segmentation_precision_no_pictures
for _ in evaluations_per_image
if _.segmentation_precision_no_pictures is not None
]
),
segmentation_recall_no_pictures_stats=compute_stats(
[
_.segmentation_recall_no_pictures
for _ in evaluations_per_image
if _.segmentation_recall_no_pictures is not None
]
),
segmentation_f1_no_pictures_stats=compute_stats(
[
_.segmentation_f1_no_pictures
for _ in evaluations_per_image
if _.segmentation_f1_no_pictures is not None
]
),
true_labels=true_labels,
pred_labels=pred_labels,
intersecting_labels=[_.value for _ in filter_labels],
)
return dataset_layout_evaluation
def _get_pred_doc(
self,
data_record: DatasetRecordWithPrediction,
ext_docdoc_loader: Optional[ExternalDoclingDocumentLoader] = None,
) -> Optional[DoclingDocument]:
r"""
Get the predicted DoclingDocument
"""
pred_doc = None
if ext_docdoc_loader is not None:
pred_doc = ext_docdoc_loader(data_record)
return pred_doc
for prediction_format in self._prediction_sources:
if prediction_format == PredictionFormats.DOCLING_DOCUMENT:
pred_doc = data_record.predicted_doc
elif prediction_format == PredictionFormats.JSON:
if data_record.original_prediction:
pred_doc = DoclingDocument.load_from_json(
data_record.original_prediction
)
elif prediction_format == PredictionFormats.YAML:
if data_record.original_prediction:
pred_doc = DoclingDocument.load_from_yaml(
data_record.original_prediction
)
elif prediction_format == PredictionFormats.DOCTAGS:
pred_doc = docling_document_from_doctags(data_record)
if pred_doc is not None:
break
return pred_doc
def _get_page_mapping(self) -> Optional[CvatPageMapping]:
if self._page_mapping_path is None:
return None
if self._page_mapping is None:
self._page_mapping = CvatPageMapping.from_overview_path(
self._page_mapping_path
)
return self._page_mapping
def _resolve_page_metadata(
self,
*,
page_mapping: Optional[CvatPageMapping],
data_record: DatasetRecordWithPrediction,
base_doc_id: str,
page_no: int,
) -> Tuple[str, str]:
doc_name = data_record.ground_truth_doc.name or base_doc_id
doc_hash = data_record.doc_hash or self._extract_hash_from_doc_id(base_doc_id)
default_image_name = (
f"doc_{doc_hash}_page_{page_no:06d}.png"
if doc_hash
else f"{base_doc_id}-page-{page_no}"
)
if page_mapping is None:
return doc_name, default_image_name
ref = self._find_page_ref(
page_mapping=page_mapping,
data_record=data_record,
base_doc_id=base_doc_id,
page_no=page_no,
)
if ref is not None:
return ref.doc_name, ref.image_name
return doc_name, default_image_name
@staticmethod
def _extract_hash_from_doc_id(doc_id: str) -> Optional[str]:
match = re.match(r"doc_([0-9a-f]{64})_page_", doc_id)
if match:
return match.group(1)
return None
def _find_page_ref(
self,
*,
page_mapping: CvatPageMapping,
data_record: DatasetRecordWithPrediction,
base_doc_id: str,
page_no: int,
) -> Optional[PageRef]:
hash_candidates: List[str] = []
if data_record.doc_hash:
hash_candidates.append(data_record.doc_hash)
extracted_hash = self._extract_hash_from_doc_id(base_doc_id)
if extracted_hash:
hash_candidates.append(extracted_hash)
for candidate_hash in hash_candidates:
for ref in page_mapping.pages_for_doc_hash(candidate_hash):
if ref.page_no == page_no:
return ref
doc_name_candidates: List[str] = []
if data_record.doc_path is not None:
doc_path_str = str(data_record.doc_path)
doc_name_candidates.append(doc_path_str)
doc_name_candidates.append(Path(doc_path_str).stem)
gt_name = data_record.ground_truth_doc.name
if gt_name:
doc_name_candidates.append(gt_name)
doc_name_candidates.append(Path(gt_name).stem)
doc_name_candidates.append(base_doc_id)
seen: set[str] = set()
for candidate in doc_name_candidates:
if not candidate:
continue
if candidate in seen:
continue
seen.add(candidate)
for ref in page_mapping.pages_for_doc_name(candidate):
if ref.page_no == page_no:
return ref
return None
def _compute_iou(self, box1, box2):
"""Compute IoU between two bounding boxes."""
x1 = torch.max(box1[0], box2[0])
y1 = torch.max(box1[1], box2[1])
x2 = torch.min(box1[2], box2[2])
y2 = torch.min(box1[3], box2[3])
intersection = torch.max(x2 - x1, torch.tensor(0.0)) * torch.max(
y2 - y1, torch.tensor(0.0)
)
box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
union = box1_area + box2_area - intersection
return intersection / union if union > 0 else 0
def _compute_average_iou_with_labels(
self, pred_boxes, pred_labels, gt_boxes, gt_labels, iou_thresh=0.5
):
"""
Compute the average IoU for label-matched detections and weight by bbox area.
FIXED: Now ensures mathematical consistency between weights and IoU values.
Only matched predictions contribute to both numerator and denominator.
Args:
pred_boxes (torch.Tensor): Predicted bounding boxes (N x 4).
pred_labels (torch.Tensor): Labels for predicted boxes (N).
gt_boxes (torch.Tensor): Ground truth bounding boxes (M x 4).
gt_labels (torch.Tensor): Labels for ground truth boxes (M).
iou_thresh (float): IoU threshold for a match.
Returns:
dict: Average IoU and unmatched ground truth information.
"""
if len(pred_boxes) == 0 or len(gt_boxes) == 0:
return {
"average_iou": 0.0,
"unmatched_gt": len(gt_boxes),
"matched_gt": 0,
}
matched_gt = set()
matched_predictions = [] # Store (weight, iou) for matched predictions only
for pred_box, pred_label in zip(pred_boxes, pred_labels):
pred_area = abs((pred_box[2] - pred_box[0]) * (pred_box[3] - pred_box[1]))
# Try to match this prediction with a GT box
for gt_idx, (gt_box, gt_label) in enumerate(zip(gt_boxes, gt_labels)):
if gt_idx not in matched_gt and pred_label == gt_label:
iou = self._compute_iou(pred_box, gt_box)
if iou >= iou_thresh:
matched_gt.add(gt_idx)
matched_predictions.append((pred_area, iou.item()))
break
# Compute weighted average IoU using only matched predictions
if not matched_predictions:
avg_iou = 0.0
else:
total_weighted_iou = 0.0
total_weight = 0.0
for weight, iou in matched_predictions:
total_weighted_iou += weight * iou
total_weight += weight
avg_iou = total_weighted_iou / total_weight
return {
"average_iou": avg_iou,
"unmatched_gt": len(gt_boxes) - len(matched_gt),
"matched_gt": len(matched_gt),
}
def _compute_average_iou_with_labels_across_iou(
self, pred_boxes, pred_labels, gt_boxes, gt_labels
):
res_50 = self._compute_average_iou_with_labels(
pred_boxes, pred_labels, gt_boxes, gt_labels, iou_thresh=0.50
)
res_75 = self._compute_average_iou_with_labels(
pred_boxes, pred_labels, gt_boxes, gt_labels, iou_thresh=0.75
)
res_90 = self._compute_average_iou_with_labels(
pred_boxes, pred_labels, gt_boxes, gt_labels, iou_thresh=0.90
)
res_95 = self._compute_average_iou_with_labels(
pred_boxes, pred_labels, gt_boxes, gt_labels, iou_thresh=0.95
)
return {
"average_iou_50": res_50["average_iou"],
"average_iou_75": res_75["average_iou"],
"average_iou_90": res_90["average_iou"],
"average_iou_95": res_95["average_iou"],
}
def _find_intersecting_labels(
self,
ds: Dataset,
ext_docdoc_loader: Optional[ExternalDoclingDocumentLoader] = None,
) -> tuple[dict[str, int], dict[str, int], list[DocItemLabel], list[DocItemLabel]]:
r"""
Compute counters per labels for the groundtruth, prediciton and their intersections
Returns
-------
true_labels: dict[label -> counter]
pred_labels: dict[label -> counter]
intersection_labels: list[DocItemLabel]
"""
true_labels: Dict[str, int] = {}
pred_labels: Dict[str, int] = {}
for i, data in enumerate(ds):
data_record = DatasetRecordWithPrediction.model_validate(data)
true_doc = data_record.ground_truth_doc
pred_doc = self._get_pred_doc(data_record, ext_docdoc_loader)
for item, level in true_doc.iterate_items(
included_content_layers={
c for c in ContentLayer if c != ContentLayer.BACKGROUND
},
traverse_pictures=True,
):
if isinstance(item, DocItem):
mapped_label = self.label_mapping.get(item.label)
if mapped_label is not None:
for prov in item.prov:
if mapped_label in true_labels:
true_labels[mapped_label] += 1
else:
true_labels[mapped_label] = 1
if pred_doc:
for item, level in pred_doc.iterate_items(
included_content_layers={
c for c in ContentLayer if c != ContentLayer.BACKGROUND
},
traverse_pictures=True,
):
if isinstance(item, DocItem):
mapped_label = self.label_mapping.get(item.label)
if mapped_label is not None:
for prov in item.prov:
if mapped_label in pred_labels:
pred_labels[mapped_label] += 1
else:
pred_labels[mapped_label] = 1
"""
logging.info(f"True labels:")
for label, count in true_labels.items():
logging.info(f" => {label}: {count}")
logging.info(f"Pred labels:")
for label, count in pred_labels.items():
logging.info(f" => {label}: {count}")
"""
intersection_labels: List[DocItemLabel] = []
union_labels: List[DocItemLabel] = []
for label, count in true_labels.items():
# Handle both string and DocItemLabel enum keys
if isinstance(label, str):
label_enum = DocItemLabel(label)
else:
label_enum = label
# Only include labels that are in DEFAULT_EXPORT_LABELS
if label_enum in DEFAULT_EXPORT_LABELS:
union_labels.append(label_enum)
if label in pred_labels:
intersection_labels.append(label_enum)
for label, count in pred_labels.items():
if label not in true_labels:
# Handle both string and DocItemLabel enum keys
if isinstance(label, str):
label_enum = DocItemLabel(label)
else:
label_enum = label
# Only include labels that are in DEFAULT_EXPORT_LABELS
if label_enum in DEFAULT_EXPORT_LABELS:
union_labels.append(label_enum)
return true_labels, pred_labels, intersection_labels, union_labels
def _collect_items_by_page(
self,
doc: DoclingDocument,
filter_labels: List[DocItemLabel],
) -> Dict[int, List[DocItem]]:
"""
Collect DocItems by page number for the given document and filter labels.
Args:
doc: The DoclingDocument to process
filter_labels: List of labels to include in the collection
Returns:
Dictionary mapping page numbers to lists of DocItems
"""
pages_to_objects: Dict[int, List[DocItem]] = defaultdict(list)
for item, level in doc.iterate_items(
included_content_layers={
c for c in ContentLayer if c != ContentLayer.BACKGROUND
},
traverse_pictures=True,
with_groups=True,
):
if isinstance(item, DocItem):
mapped_label = self.label_mapping.get(item.label)
if mapped_label is not None and mapped_label in filter_labels:
for prov in item.prov:
pages_to_objects[prov.page_no].append(item)
return pages_to_objects
def _extract_layout_data(
self,
true_doc: DoclingDocument,
pred_doc: DoclingDocument,
filter_labels: List[DocItemLabel],
) -> Tuple[
List[Tuple[int, Dict[str, torch.Tensor]]],
List[Tuple[int, Dict[str, torch.Tensor]]],
]:
r"""
Filter to keep only bboxes from the given labels
Convert each bbox to top-left-origin, normalize to page size and scale 100
This method ensures proper page-wise alignment between GT and predictions.
Each returned GT tensor at index i corresponds exactly to the prediction tensor at index i.
Returns
-------
ground_truths: List of (page_no, tensor_dict) tuples
predictions: List of (page_no, tensor_dict) tuples
"""
# Collect all DocItems by page for both GT and predictions
true_pages_to_objects = self._collect_items_by_page(true_doc, filter_labels)
pred_pages_to_objects = self._collect_items_by_page(pred_doc, filter_labels)
# Get all pages that have GT data (we evaluate based on GT pages)
gt_pages = set(true_pages_to_objects.keys())
pred_pages = set(pred_pages_to_objects.keys())
_log.debug(f"GT pages: {sorted(gt_pages)}, Pred pages: {sorted(pred_pages)}")
# Process pages in sorted order to ensure consistent alignment
# List[Tuple[page_no, Dict[str, torch.Tensor]]]. The dict has tensors with bboxes, labels:
# "boxes": torch.tensor(bboxes, dtype=torch.float32),
# "labels": torch.tensor(labels, dtype=torch.long),
# "scores": torch.tensor(scores, dtype=torch.float32) # Only for the predictions
# The bboxes are in top-left origin, in x1y1x2y2 format, normalized and scaled to 100
ground_truths: List[Tuple[int, Dict[str, torch.Tensor]]] = []
predictions: List[Tuple[int, Dict[str, torch.Tensor]]] = []
for page_no in sorted(gt_pages):
# Always process GT for this page
gt_data = self._extract_page_data(
page_no=page_no,
items=true_pages_to_objects[page_no],
doc=true_doc,
filter_labels=filter_labels,
is_prediction=False,
)
# Handle prediction for this page based on strategy
if page_no in pred_pages:
# We have prediction data for this page
pred_data = self._extract_page_data(
page_no=page_no,
items=pred_pages_to_objects[page_no],
doc=pred_doc,
filter_labels=filter_labels,