deepdoctection 1.3.0__tar.gz → 1.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/PKG-INFO +1 -1
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/pyproject.toml +1 -1
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/__init__.py +12 -5
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/eval/__init__.py +1 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/eval/eval.py +93 -33
- deepdoctection-1.4.0/src/deepdoctection/eval/record_align.py +579 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/anngen.py +4 -2
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/lm.py +3 -3
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/train/__init__.py +3 -3
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection.egg-info/PKG-INFO +1 -1
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection.egg-info/SOURCES.txt +1 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/README.md +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/setup.cfg +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/analyzer/__init__.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/analyzer/config.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/analyzer/dd.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/analyzer/factory.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/configs/__init__.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/configs/conf_dd_one.yaml +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/configs/conf_tesseract.yaml +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/configs/profiles.jsonl +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/eval/accmetric.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/eval/base.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/eval/cocometric.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/eval/registry.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/eval/tedsmetric.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/__init__.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/base.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/d2detect.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/deskew.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/doctrocr.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/hfdetr.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/hflayoutlm.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/hflm.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/model.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/pdftext.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/tessocr.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/extern/texocr.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/__init__.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/base.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/common.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/concurrency.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/doctectionpipe.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/language.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/layout.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/order.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/refine.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/registry.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/segment.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/sub_layout.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/text.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/pipe/transform.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/py.typed +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/train/d2_frcnn_train.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/train/hf_detr_train.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/train/hf_layoutlm_train.py +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection.egg-info/dependency_links.txt +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection.egg-info/requires.txt +0 -0
- {deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection.egg-info/top_level.txt +0 -0
|
@@ -12,7 +12,7 @@ from dd_core.utils.env_info import collect_env_info
|
|
|
12
12
|
from dd_core.utils.file_utils import _LazyModule
|
|
13
13
|
from dd_core.utils.logger import LoggingRecord, logger
|
|
14
14
|
|
|
15
|
-
__version__ = "1.
|
|
15
|
+
__version__ = "1.4.0"
|
|
16
16
|
_IMPORT_STRUCTURE = {
|
|
17
17
|
"analyzer": ["config_sanity_checks", "get_dd_analyzer", "ServiceFactory", "update_cfg_from_defaults"],
|
|
18
18
|
"eval": [
|
|
@@ -29,6 +29,17 @@ _IMPORT_STRUCTURE = {
|
|
|
29
29
|
"Evaluator",
|
|
30
30
|
"metric_registry",
|
|
31
31
|
"get_metric",
|
|
32
|
+
"bag_similarity",
|
|
33
|
+
"align",
|
|
34
|
+
"Counts",
|
|
35
|
+
"field_counts",
|
|
36
|
+
"RecordAlignMetric",
|
|
37
|
+
"RecordAlignPrecisionMetric",
|
|
38
|
+
"RecordAlignRecallMetric",
|
|
39
|
+
"RecordAlignF1Metric",
|
|
40
|
+
"RecordAlignPrecisionMetricMicro",
|
|
41
|
+
"RecordAlignRecallMetricMicro",
|
|
42
|
+
"RecordAlignF1MetricMicro",
|
|
32
43
|
"TableTree",
|
|
33
44
|
"CustomConfig",
|
|
34
45
|
"TEDS",
|
|
@@ -57,7 +68,6 @@ _IMPORT_STRUCTURE = {
|
|
|
57
68
|
"DoctrTextRecognizer",
|
|
58
69
|
"DocTrRotationTransformer",
|
|
59
70
|
"HFDetrDerivedDetector",
|
|
60
|
-
"get_tokenizer_from_architecture",
|
|
61
71
|
"HFLayoutLmTokenClassifierBase",
|
|
62
72
|
"HFLayoutLmTokenClassifier",
|
|
63
73
|
"HFLayoutLmv2TokenClassifier",
|
|
@@ -83,9 +93,6 @@ _IMPORT_STRUCTURE = {
|
|
|
83
93
|
"pipe": [
|
|
84
94
|
"DatapointManager",
|
|
85
95
|
"PipelineComponent",
|
|
86
|
-
"PredictorPipelineComponent",
|
|
87
|
-
"LanguageModelPipelineComponent",
|
|
88
|
-
"ImageTransformPipelineComponent",
|
|
89
96
|
"Pipeline",
|
|
90
97
|
"DetectResultGenerator",
|
|
91
98
|
"SubImageLayoutService",
|
|
@@ -69,6 +69,11 @@ class Evaluator:
|
|
|
69
69
|
erasing process and after that passing the predictor. Predicted and gt datapoints will be converted into the
|
|
70
70
|
required metric input format and dumped into lists. Both lists will be passed to `MetricBase.get_distance`.
|
|
71
71
|
|
|
72
|
+
Alternatively, if predictions have already been generated elsewhere and saved as a dataset (e.g. via
|
|
73
|
+
`DocumentDatasetFactory.make` reading back saved `doc.Document` JSON), pass that dataset as `predictions_dataset`
|
|
74
|
+
instead of `component_or_pipeline`. In this mode no prediction step is run: both datasets' dataflows are built
|
|
75
|
+
and passed directly to the metric.
|
|
76
|
+
|
|
72
77
|
Note:
|
|
73
78
|
You can evaluate the predictor on a subset of categories by filtering the ground truth dataset. When using
|
|
74
79
|
the coco metric all predicted objects that are not in the set of filtered objects will be not taken into
|
|
@@ -90,53 +95,85 @@ class Evaluator:
|
|
|
90
95
|
output = evaluator.run(max_datapoints=10)
|
|
91
96
|
```
|
|
92
97
|
|
|
98
|
+
Example (evaluating against predictions saved elsewhere):
|
|
99
|
+
```python
|
|
100
|
+
gt_dataset = get_dataset("publaynet")
|
|
101
|
+
predictions_dataset = DocumentDatasetFactory.make(
|
|
102
|
+
name="my_predictions", location="my_predictions_dir",
|
|
103
|
+
dataset_type=DatasetKind.OBJECT_DETECTION, init_categories=[...],
|
|
104
|
+
)
|
|
105
|
+
coco_metric = metric_registry.get("coco")
|
|
106
|
+
evaluator = Evaluator(gt_dataset, metric=coco_metric, predictions_dataset=predictions_dataset)
|
|
107
|
+
|
|
108
|
+
output = evaluator.run()
|
|
109
|
+
```
|
|
110
|
+
|
|
93
111
|
For another example check the script in `Evaluation` of table recognition`
|
|
94
112
|
"""
|
|
95
113
|
|
|
96
114
|
def __init__(
|
|
97
115
|
self,
|
|
98
116
|
dataset: DatasetBase,
|
|
99
|
-
component_or_pipeline: Union[PipelineComponent, DoctectionPipe],
|
|
100
|
-
metric: Union[Type[MetricBase], MetricBase],
|
|
117
|
+
component_or_pipeline: Optional[Union[PipelineComponent, DoctectionPipe]] = None,
|
|
118
|
+
metric: Union[Type[MetricBase], MetricBase] = None, # type: ignore[assignment]
|
|
101
119
|
num_threads: int = 2,
|
|
102
120
|
run: Optional[wandb.sdk.wandb_run.Run] = None,
|
|
121
|
+
predictions_dataset: Optional[DatasetBase] = None,
|
|
103
122
|
) -> None:
|
|
104
123
|
"""
|
|
105
|
-
Evaluating a pipeline component on a dataset with a given metric
|
|
124
|
+
Evaluating a pipeline component on a dataset with a given metric, or evaluating a dataset of
|
|
125
|
+
precomputed predictions against a ground truth dataset.
|
|
106
126
|
|
|
107
127
|
Args:
|
|
108
|
-
dataset: dataset
|
|
109
|
-
component_or_pipeline: A pipeline component with predictor and annotation factory.
|
|
128
|
+
dataset: Ground truth dataset.
|
|
129
|
+
component_or_pipeline: A pipeline component with predictor and annotation factory. Mutually
|
|
130
|
+
exclusive with `predictions_dataset`.
|
|
110
131
|
metric: metric
|
|
132
|
+
predictions_dataset: A dataset of already computed predictions, e.g. built via
|
|
133
|
+
`DocumentDatasetFactory.make` from saved `doc.Document` JSON. When given, no
|
|
134
|
+
prediction step is run: both dataflows are passed directly to the metric.
|
|
135
|
+
Mutually exclusive with `component_or_pipeline`.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
ValueError: If both or neither of `component_or_pipeline` and `predictions_dataset` are given.
|
|
111
139
|
"""
|
|
112
140
|
|
|
141
|
+
if component_or_pipeline is not None and predictions_dataset is not None:
|
|
142
|
+
raise ValueError("Pass either component_or_pipeline or predictions_dataset, but not both")
|
|
143
|
+
if component_or_pipeline is None and predictions_dataset is None:
|
|
144
|
+
raise ValueError("component_or_pipeline or predictions_dataset must be provided")
|
|
145
|
+
|
|
113
146
|
self.dataset = dataset
|
|
114
147
|
self.pipe_component: Optional[MultiThreadPipelineComponent] = None
|
|
115
148
|
self.pipe: Optional[DoctectionPipe] = None
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
if
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
149
|
+
self.predictions_dataset: Optional[DatasetBase] = None
|
|
150
|
+
|
|
151
|
+
if component_or_pipeline is not None:
|
|
152
|
+
# when passing a component, we will process prediction on num_threads
|
|
153
|
+
if isinstance(component_or_pipeline, PipelineComponent):
|
|
154
|
+
logger.info(
|
|
155
|
+
LoggingRecord(
|
|
156
|
+
f"Building multi threading pipeline component to increase prediction throughput. "
|
|
157
|
+
f"Using {num_threads} threads"
|
|
158
|
+
)
|
|
123
159
|
)
|
|
124
|
-
|
|
125
|
-
pipeline_components: list[PipelineComponent] = []
|
|
160
|
+
pipeline_components: list[PipelineComponent] = []
|
|
126
161
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
162
|
+
for _ in range(num_threads - 1):
|
|
163
|
+
copy_pipe_component = component_or_pipeline.clone()
|
|
164
|
+
pipeline_components.append(copy_pipe_component)
|
|
130
165
|
|
|
131
|
-
|
|
166
|
+
pipeline_components.append(component_or_pipeline)
|
|
132
167
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
168
|
+
self.pipe_component = MultiThreadPipelineComponent(
|
|
169
|
+
pipeline_components=pipeline_components,
|
|
170
|
+
pre_proc_func=maybe_load_image, # type:ignore
|
|
171
|
+
post_proc_func=maybe_remove_image, # type:ignore
|
|
172
|
+
)
|
|
173
|
+
else:
|
|
174
|
+
self.pipe = component_or_pipeline
|
|
138
175
|
else:
|
|
139
|
-
self.
|
|
176
|
+
self.predictions_dataset = predictions_dataset
|
|
140
177
|
|
|
141
178
|
self.metric = metric
|
|
142
179
|
if not isinstance(metric, MetricBase):
|
|
@@ -199,18 +236,27 @@ class Evaluator:
|
|
|
199
236
|
Args:
|
|
200
237
|
output_as_dict: Return result in a list or dict.
|
|
201
238
|
dataflow_build_kwargs: Pass the necessary arguments in order to build the dataflow, e.g. `split`,
|
|
202
|
-
`build_mode`, `max_datapoints` etc.
|
|
239
|
+
`build_mode`, `max_datapoints` etc. When `predictions_dataset` was passed to
|
|
240
|
+
the constructor, the same kwargs are passed to both dataflow builds; a
|
|
241
|
+
builder ignores keys it does not recognize.
|
|
203
242
|
|
|
204
243
|
Returns:
|
|
205
244
|
dict with metric results.
|
|
206
245
|
"""
|
|
207
246
|
|
|
208
247
|
df_gt = self.dataset.dataflow.build(**dataflow_build_kwargs)
|
|
209
|
-
df_pr = self.dataset.dataflow.build(**dataflow_build_kwargs)
|
|
210
248
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
249
|
+
if self.predictions_dataset is not None:
|
|
250
|
+
df_pr = self.predictions_dataset.dataflow.build(**dataflow_build_kwargs)
|
|
251
|
+
if self.wandb_table_agent is not None:
|
|
252
|
+
df_pr_list = CacheData(df_pr).get_cache()
|
|
253
|
+
df_pr_list = [self.wandb_table_agent.dump(dp) for dp in df_pr_list]
|
|
254
|
+
df_pr = DataFromList(df_pr_list)
|
|
255
|
+
else:
|
|
256
|
+
df_pr = self.dataset.dataflow.build(**dataflow_build_kwargs)
|
|
257
|
+
df_pr = MapData(df_pr, deepcopy)
|
|
258
|
+
df_pr = self._clean_up_predict_dataflow_annotations(df_pr)
|
|
259
|
+
df_pr = self._run_pipe_or_component(df_pr)
|
|
214
260
|
|
|
215
261
|
logger.info(LoggingRecord("Starting evaluation..."))
|
|
216
262
|
result = self.metric.get_distance(df_gt, df_pr, self.dataset.dataflow.categories)
|
|
@@ -226,6 +272,17 @@ class Evaluator:
|
|
|
226
272
|
|
|
227
273
|
def _sanity_checks(self) -> None:
|
|
228
274
|
assert self.dataset.dataflow.categories is not None
|
|
275
|
+
if self.predictions_dataset is not None:
|
|
276
|
+
assert self.predictions_dataset.dataflow.categories is not None
|
|
277
|
+
gt_cats = set(self.dataset.dataflow.categories.get_categories(as_dict=False, filtered=True))
|
|
278
|
+
pr_cats = set(self.predictions_dataset.dataflow.categories.get_categories(as_dict=False, filtered=True))
|
|
279
|
+
if gt_cats != pr_cats:
|
|
280
|
+
logger.warning(
|
|
281
|
+
LoggingRecord(
|
|
282
|
+
f"Category mismatch between ground truth and predictions dataset. "
|
|
283
|
+
f"gt only: {gt_cats - pr_cats}, predictions only: {pr_cats - gt_cats}"
|
|
284
|
+
)
|
|
285
|
+
)
|
|
229
286
|
|
|
230
287
|
def _run_pipe_or_component(self, df_pr: DataFlow) -> DataFlow:
|
|
231
288
|
if self.pipe_component:
|
|
@@ -296,6 +353,12 @@ class Evaluator:
|
|
|
296
353
|
Image as `np.array`
|
|
297
354
|
"""
|
|
298
355
|
|
|
356
|
+
if self.pipe_component is None and self.pipe is None:
|
|
357
|
+
raise ValueError(
|
|
358
|
+
"Neither pipe_component nor pipe has been defined; compare() is not supported when "
|
|
359
|
+
"Evaluator was constructed with predictions_dataset"
|
|
360
|
+
)
|
|
361
|
+
|
|
299
362
|
show_tables = kwargs.pop("show_tables", True)
|
|
300
363
|
show_layouts = kwargs.pop("show_layouts", True)
|
|
301
364
|
show_table_structure = kwargs.pop("show_table_structure", True)
|
|
@@ -323,11 +386,8 @@ class Evaluator:
|
|
|
323
386
|
pipe_component = self.pipe_component.pipe_components[0]
|
|
324
387
|
df_pr = pipe_component.predict_dataflow(df_pr)
|
|
325
388
|
df_pr = page_parsing_component.predict_dataflow(df_pr)
|
|
326
|
-
|
|
327
|
-
elif self.pipe:
|
|
328
|
-
df_pr = self.pipe.analyze(dataset_dataflow=df_pr)
|
|
329
389
|
else:
|
|
330
|
-
|
|
390
|
+
df_pr = self.pipe.analyze(dataset_dataflow=df_pr) # type: ignore
|
|
331
391
|
|
|
332
392
|
df_pr.reset_state()
|
|
333
393
|
df_gt.reset_state()
|
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# File: record_align.py
|
|
3
|
+
|
|
4
|
+
# Copyright 2026 Dr. Janis Meyer. All rights reserved.
|
|
5
|
+
#
|
|
6
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
# you may not use this file except in compliance with the License.
|
|
8
|
+
# You may obtain a copy of the License at
|
|
9
|
+
#
|
|
10
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
#
|
|
12
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
# See the License for the specific language governing permissions and
|
|
16
|
+
# limitations under the License.
|
|
17
|
+
|
|
18
|
+
"""
|
|
19
|
+
Record alignment and the metrics induced by it.
|
|
20
|
+
|
|
21
|
+
Records are nested structures of mappings, sequences and scalars, e.g. a single booking of a bank
|
|
22
|
+
statement together with its postings. Before two records can be aligned they have to be compared
|
|
23
|
+
without relying on the ordering of their sub-records. `bag_similarity` provides such an
|
|
24
|
+
order-independent score on top of `flatten`, and `align` uses that score to pair up two lists of
|
|
25
|
+
records.
|
|
26
|
+
|
|
27
|
+
On top of that, `field_counts` compares two structured outputs, e.g. the JSON returned by an
|
|
28
|
+
information extraction pipeline against a ground truth JSON of the same schema, and the
|
|
29
|
+
`RecordAlign*` metrics report precision, recall and F1 per field path with micro averaged variants.
|
|
30
|
+
Aligning arrays of records first is what makes a single missing record cost only its own values
|
|
31
|
+
instead of shifting every following record against the wrong partner.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
from collections import Counter, defaultdict
|
|
37
|
+
from dataclasses import dataclass
|
|
38
|
+
from typing import TYPE_CHECKING, Any, Optional, Sequence, Union
|
|
39
|
+
|
|
40
|
+
import numpy as np
|
|
41
|
+
from lazy_imports import try_import
|
|
42
|
+
from tabulate import tabulate
|
|
43
|
+
from termcolor import colored
|
|
44
|
+
|
|
45
|
+
from dd_core.dataflow import DataFlow
|
|
46
|
+
from dd_core.mapper import image_or_doc_to_structured_output
|
|
47
|
+
from dd_core.utils.file_utils import Requirement, get_scipy_requirement
|
|
48
|
+
from dd_core.utils.logger import LoggingRecord, logger
|
|
49
|
+
from dd_core.utils.object_types import ObjectTypes, TypeOrStr, get_type
|
|
50
|
+
from dd_core.utils.types import MetricResults
|
|
51
|
+
from dd_core.utils.utils import as_string, flatten
|
|
52
|
+
|
|
53
|
+
from .base import MetricBase
|
|
54
|
+
from .registry import metric_registry
|
|
55
|
+
|
|
56
|
+
with try_import() as scipy_import_guard:
|
|
57
|
+
from scipy.optimize import linear_sum_assignment
|
|
58
|
+
|
|
59
|
+
if TYPE_CHECKING:
|
|
60
|
+
from dd_datasets.info import DatasetCategories
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
"bag_similarity",
|
|
64
|
+
"align",
|
|
65
|
+
"Counts",
|
|
66
|
+
"field_counts",
|
|
67
|
+
"RecordAlignMetric",
|
|
68
|
+
"RecordAlignPrecisionMetric",
|
|
69
|
+
"RecordAlignRecallMetric",
|
|
70
|
+
"RecordAlignF1Metric",
|
|
71
|
+
"RecordAlignPrecisionMetricMicro",
|
|
72
|
+
"RecordAlignRecallMetricMicro",
|
|
73
|
+
"RecordAlignF1MetricMicro",
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
MIN_SIMILARITY = 0.1
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _value_bag(record: Any) -> Counter[tuple[str, str]]:
|
|
80
|
+
"""
|
|
81
|
+
Reduces a record to the multiset of its `(field_path, value)` pairs.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
record: An arbitrarily nested structure of mappings, sequences and scalars.
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
A counter over the `(field_path, value)` pairs of the record.
|
|
88
|
+
"""
|
|
89
|
+
return Counter((path, value) for path, values in flatten(record).items() for value in values)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def bag_similarity(record_gt: Any, record_pred: Any) -> float:
|
|
93
|
+
"""
|
|
94
|
+
Computes the similarity of two records as the Jaccard index over their bags of values.
|
|
95
|
+
|
|
96
|
+
Both records are flattened into `{field_path: [values]}` first. Values are then matched per field
|
|
97
|
+
path as multisets, so that neither the ordering of sub-records nor the ordering of the field paths
|
|
98
|
+
has any influence on the score.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
record_gt: The ground truth record. An arbitrarily nested structure of mappings, sequences and
|
|
102
|
+
scalars.
|
|
103
|
+
record_pred: The predicted record, in the same format as `record_gt`.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
The Jaccard index in `[0.0, 1.0]`, where `1.0` means that both bags of values are identical.
|
|
107
|
+
|
|
108
|
+
Example:
|
|
109
|
+
```python
|
|
110
|
+
gt = {"amount": ["450,00-"], "postings": [{"postingType": ["net"]}]}
|
|
111
|
+
pred = {"amount": ["450,00-"], "postings": []}
|
|
112
|
+
bag_similarity(gt, pred)
|
|
113
|
+
# Output: 0.5
|
|
114
|
+
```
|
|
115
|
+
"""
|
|
116
|
+
bag_gt = _value_bag(record_gt)
|
|
117
|
+
bag_pred = _value_bag(record_pred)
|
|
118
|
+
|
|
119
|
+
matches = sum((bag_gt & bag_pred).values())
|
|
120
|
+
total = sum(bag_gt.values()) + sum(bag_pred.values()) - matches
|
|
121
|
+
|
|
122
|
+
# total is zero exactly when both records carry no value at all
|
|
123
|
+
return matches / total if total else 1.0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def align(
|
|
127
|
+
records_gt: list[Any],
|
|
128
|
+
records_pred: list[Any],
|
|
129
|
+
min_similarity: float = MIN_SIMILARITY,
|
|
130
|
+
) -> tuple[list[tuple[int, int]], list[int], list[int]]:
|
|
131
|
+
"""
|
|
132
|
+
Assigns predicted records to ground truth records.
|
|
133
|
+
|
|
134
|
+
The cost of pairing two records is `1.0 - bag_similarity(...)`, so that identical records cost
|
|
135
|
+
zero and records without any common value cost one. Solving the linear sum assignment problem on
|
|
136
|
+
that cost matrix yields the pairing with the lowest total cost.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
records_gt: Ground truth records, e.g. the elements of `bookings`.
|
|
140
|
+
records_pred: Predicted records for the same field path.
|
|
141
|
+
min_similarity: Lowest bag similarity that still counts as a pair. Zero accepts every pairing
|
|
142
|
+
the solver produces.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
A tuple of three items. The first holds the accepted pairs as `(gt_index, pred_index)`, sorted
|
|
146
|
+
by ground truth index.
|
|
147
|
+
|
|
148
|
+
Note:
|
|
149
|
+
Requires `scipy`.
|
|
150
|
+
|
|
151
|
+
Example:
|
|
152
|
+
```python
|
|
153
|
+
gt = [{"amount": ["1,00-"]}, {"amount": ["2,00-"]}]
|
|
154
|
+
pred = [{"amount": ["2,00-"]}, {"amount": ["9,00-"]}]
|
|
155
|
+
align(gt, pred)
|
|
156
|
+
# Output: ([(1, 0)], [0], [1])
|
|
157
|
+
```
|
|
158
|
+
"""
|
|
159
|
+
if not records_gt or not records_pred:
|
|
160
|
+
return [], list(range(len(records_gt))), list(range(len(records_pred)))
|
|
161
|
+
|
|
162
|
+
bags_gt = [_value_bag(record) for record in records_gt]
|
|
163
|
+
bags_pred = [_value_bag(record) for record in records_pred]
|
|
164
|
+
sizes_gt = [sum(bag.values()) for bag in bags_gt]
|
|
165
|
+
sizes_pred = [sum(bag.values()) for bag in bags_pred]
|
|
166
|
+
|
|
167
|
+
cost = np.empty((len(bags_gt), len(bags_pred)), dtype=np.float64)
|
|
168
|
+
for row, (bag_gt, size_gt) in enumerate(zip(bags_gt, sizes_gt)):
|
|
169
|
+
for column, (bag_pred, size_pred) in enumerate(zip(bags_pred, sizes_pred)):
|
|
170
|
+
matches = sum(min(count, bag_pred[value]) for value, count in bag_gt.items())
|
|
171
|
+
total = size_gt + size_pred - matches
|
|
172
|
+
cost[row, column] = 1.0 - (matches / total if total else 1.0)
|
|
173
|
+
|
|
174
|
+
rows, columns = linear_sum_assignment(cost)
|
|
175
|
+
|
|
176
|
+
max_cost = 1.0 - min_similarity
|
|
177
|
+
pairs: list[tuple[int, int]] = [
|
|
178
|
+
(row, column) for row, column in zip(rows.tolist(), columns.tolist()) if cost[row, column] <= max_cost
|
|
179
|
+
]
|
|
180
|
+
|
|
181
|
+
paired_gt = {row for row, _ in pairs}
|
|
182
|
+
paired_pred = {column for _, column in pairs}
|
|
183
|
+
unmatched_gt = [index for index in range(len(records_gt)) if index not in paired_gt]
|
|
184
|
+
unmatched_pred = [index for index in range(len(records_pred)) if index not in paired_pred]
|
|
185
|
+
|
|
186
|
+
return pairs, unmatched_gt, unmatched_pred
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@dataclass
|
|
190
|
+
class Counts:
|
|
191
|
+
"""
|
|
192
|
+
Confusion counts for a single field path.
|
|
193
|
+
|
|
194
|
+
Attributes:
|
|
195
|
+
tp (int): Values present in both ground truth and prediction.
|
|
196
|
+
fp (int): Values predicted but not present in the ground truth.
|
|
197
|
+
fn (int): Values in the ground truth but not predicted.
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
tp: int = 0
|
|
201
|
+
fp: int = 0
|
|
202
|
+
fn: int = 0
|
|
203
|
+
|
|
204
|
+
def __add__(self, other: Counts) -> Counts:
|
|
205
|
+
return Counts(self.tp + other.tp, self.fp + other.fp, self.fn + other.fn)
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
def precision(self) -> float:
|
|
209
|
+
"""Share of predicted values that are correct, or zero if nothing was predicted"""
|
|
210
|
+
denominator = self.tp + self.fp
|
|
211
|
+
return self.tp / denominator if denominator else 0.0
|
|
212
|
+
|
|
213
|
+
@property
|
|
214
|
+
def recall(self) -> float:
|
|
215
|
+
"""Share of ground truth values that were found, or zero if there are none"""
|
|
216
|
+
denominator = self.tp + self.fn
|
|
217
|
+
return self.tp / denominator if denominator else 0.0
|
|
218
|
+
|
|
219
|
+
@property
|
|
220
|
+
def f1(self) -> float:
|
|
221
|
+
"""Harmonic mean of precision and recall, or zero if both are zero"""
|
|
222
|
+
denominator = 2 * self.tp + self.fp + self.fn
|
|
223
|
+
return 2 * self.tp / denominator if denominator else 0.0
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _charge_record(record: Any, prefix: str, counts: dict[str, Counts], as_false_negative: bool) -> None:
|
|
227
|
+
"""
|
|
228
|
+
Charges every non empty value of an unmatched record as an error.
|
|
229
|
+
|
|
230
|
+
Args:
|
|
231
|
+
record: A record without a partner in the other structure.
|
|
232
|
+
prefix: Field path the record sits at, e.g. `bookings`.
|
|
233
|
+
counts: Accumulator, modified in place.
|
|
234
|
+
as_false_negative: True for a ground truth record, False for a predicted one.
|
|
235
|
+
"""
|
|
236
|
+
for relative_path, values in flatten(record).items():
|
|
237
|
+
path = f"{prefix}.{relative_path}" if relative_path else prefix
|
|
238
|
+
for _ in values:
|
|
239
|
+
if as_false_negative:
|
|
240
|
+
counts[path].fn += 1
|
|
241
|
+
else:
|
|
242
|
+
counts[path].fp += 1
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _walk(node_gt: Any, node_pred: Any, path: str, counts: dict[str, Counts]) -> None:
|
|
246
|
+
"""
|
|
247
|
+
Recurses through both structures in parallel and fills the accumulator.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
node_gt: Current ground truth node.
|
|
251
|
+
node_pred: Current predicted node.
|
|
252
|
+
path: Field path of the current node, empty at the root.
|
|
253
|
+
counts: Accumulator, modified in place.
|
|
254
|
+
"""
|
|
255
|
+
if isinstance(node_gt, dict) or isinstance(node_pred, dict):
|
|
256
|
+
left = node_gt if isinstance(node_gt, dict) else {}
|
|
257
|
+
right = node_pred if isinstance(node_pred, dict) else {}
|
|
258
|
+
# a set union would not be order stable and the accumulator order would then differ across runs
|
|
259
|
+
for key in list(left) + [key for key in right if key not in left]:
|
|
260
|
+
child_path = f"{path}.{key}" if path else key
|
|
261
|
+
_walk(left.get(key), right.get(key), child_path, counts)
|
|
262
|
+
return
|
|
263
|
+
|
|
264
|
+
gt_is_record_list = isinstance(node_gt, list) and any(isinstance(item, dict) for item in node_gt)
|
|
265
|
+
pred_is_record_list = isinstance(node_pred, list) and any(isinstance(item, dict) for item in node_pred)
|
|
266
|
+
|
|
267
|
+
if gt_is_record_list or pred_is_record_list:
|
|
268
|
+
records_gt = node_gt if gt_is_record_list else []
|
|
269
|
+
records_pred = node_pred if pred_is_record_list else []
|
|
270
|
+
pairs, unmatched_gt, unmatched_pred = align(records_gt, records_pred)
|
|
271
|
+
|
|
272
|
+
for gt_index, pred_index in pairs:
|
|
273
|
+
_walk(records_gt[gt_index], records_pred[pred_index], path, counts)
|
|
274
|
+
for gt_index in unmatched_gt:
|
|
275
|
+
_charge_record(records_gt[gt_index], path, counts, as_false_negative=True)
|
|
276
|
+
for pred_index in unmatched_pred:
|
|
277
|
+
_charge_record(records_pred[pred_index], path, counts, as_false_negative=False)
|
|
278
|
+
return
|
|
279
|
+
|
|
280
|
+
left_value = as_string(node_gt)
|
|
281
|
+
right_value = as_string(node_pred)
|
|
282
|
+
if not left_value and not right_value:
|
|
283
|
+
return
|
|
284
|
+
if left_value == right_value:
|
|
285
|
+
counts[path].tp += 1
|
|
286
|
+
return
|
|
287
|
+
if left_value:
|
|
288
|
+
counts[path].fn += 1
|
|
289
|
+
if right_value:
|
|
290
|
+
counts[path].fp += 1
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def field_counts(node_gt: Any, node_pred: Any) -> dict[str, Counts]:
|
|
294
|
+
"""
|
|
295
|
+
Compares two structured outputs and counts matches per field path.
|
|
296
|
+
|
|
297
|
+
Dicts are compared key by key, which is unambiguous because the schema fixes the keys. Arrays of
|
|
298
|
+
records are aligned first, so that a missing record costs only its own values instead of shifting
|
|
299
|
+
every following record against the wrong partner.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
node_gt: Ground truth structure, normally the whole document.
|
|
303
|
+
node_pred: Predicted structure following the same schema.
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
Mapping from field path to its counts. Paths carry no list index, so all records of one array
|
|
307
|
+
accumulate under the same path.
|
|
308
|
+
|
|
309
|
+
Example:
|
|
310
|
+
```python
|
|
311
|
+
gt = {"amount": "1,00-", "iban": "DE95"}
|
|
312
|
+
pred = {"amount": "1,00-", "iban": "DE96"}
|
|
313
|
+
field_counts(gt, pred)
|
|
314
|
+
# Output: {'amount': Counts(tp=1, fp=0, fn=0), 'iban': Counts(tp=0, fp=1, fn=1)}
|
|
315
|
+
```
|
|
316
|
+
"""
|
|
317
|
+
counts: dict[str, Counts] = defaultdict(Counts)
|
|
318
|
+
_walk(node_gt, node_pred, "", counts)
|
|
319
|
+
return dict(counts)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
class RecordAlignMetric(MetricBase):
|
|
323
|
+
"""
|
|
324
|
+
Base metric class for comparing structured outputs of two dataflows.
|
|
325
|
+
|
|
326
|
+
Attributes:
|
|
327
|
+
metric: The function that turns two structured outputs into counts per field path.
|
|
328
|
+
mapper: Function to map an `Image` or `doc.Document` to its resolved structured output. Works
|
|
329
|
+
the same way for both `mode="image"` and `mode="doc"` dataflows.
|
|
330
|
+
_summary_sub_cats: Sequence of `ObjectTypes` naming the summary sub categories to compare, e.g.
|
|
331
|
+
`structured_output`.
|
|
332
|
+
"""
|
|
333
|
+
|
|
334
|
+
# a plain function assigned as a class attribute is returned unbound via cls.metric, which is why
|
|
335
|
+
# field_counts takes no cls. mypy assumes a method here and binds the first argument away.
|
|
336
|
+
metric = field_counts # type: ignore[assignment]
|
|
337
|
+
mapper = image_or_doc_to_structured_output
|
|
338
|
+
_summary_sub_cats: Optional[Sequence[ObjectTypes]] = None
|
|
339
|
+
|
|
340
|
+
@classmethod
|
|
341
|
+
def dump(
|
|
342
|
+
cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories
|
|
343
|
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
344
|
+
dataflow_gt.reset_state()
|
|
345
|
+
dataflow_predictions.reset_state()
|
|
346
|
+
|
|
347
|
+
cls._category_sanity_checks(categories)
|
|
348
|
+
mapper_with_setting = cls.mapper(cls._summary_sub_cats)
|
|
349
|
+
|
|
350
|
+
# returned images of gt and predictions are likely not in the same order. We therefore first
|
|
351
|
+
# stream all data into a dict and pair them by image_id thereafter.
|
|
352
|
+
structured_per_image_gt: dict[str, Any] = {}
|
|
353
|
+
structured_per_image_predictions: dict[str, Any] = {}
|
|
354
|
+
for dp_gt, dp_pd in zip(dataflow_gt, dataflow_predictions):
|
|
355
|
+
node_gt, image_id_gt = mapper_with_setting(dp_gt) # pylint: disable=E1102
|
|
356
|
+
structured_per_image_gt[image_id_gt] = node_gt
|
|
357
|
+
node_pd, image_id_pd = mapper_with_setting(dp_pd) # pylint: disable=E1102
|
|
358
|
+
structured_per_image_predictions[image_id_pd] = node_pd
|
|
359
|
+
|
|
360
|
+
structured_gt: dict[str, Any] = {}
|
|
361
|
+
structured_predictions: dict[str, Any] = {}
|
|
362
|
+
for image_id, node_gt in structured_per_image_gt.items():
|
|
363
|
+
structured_gt[image_id] = node_gt
|
|
364
|
+
structured_predictions[image_id] = structured_per_image_predictions.get(image_id, {})
|
|
365
|
+
|
|
366
|
+
return structured_gt, structured_predictions
|
|
367
|
+
|
|
368
|
+
@classmethod
|
|
369
|
+
def _get_counts_per_path(
|
|
370
|
+
cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories
|
|
371
|
+
) -> dict[str, Counts]:
|
|
372
|
+
structured_gt, structured_predictions = cls.dump(dataflow_gt, dataflow_predictions, categories)
|
|
373
|
+
|
|
374
|
+
counts_per_path: dict[str, Counts] = defaultdict(Counts)
|
|
375
|
+
for image_id, node_gt in structured_gt.items():
|
|
376
|
+
for path, entry in cls.metric(node_gt, structured_predictions[image_id]).items():
|
|
377
|
+
counts_per_path[path] = counts_per_path[path] + entry
|
|
378
|
+
return counts_per_path
|
|
379
|
+
|
|
380
|
+
@classmethod
|
|
381
|
+
def set_categories(cls, summary_sub_category_names: Union[TypeOrStr, Sequence[TypeOrStr]]) -> None:
|
|
382
|
+
"""
|
|
383
|
+
Set the summary sub categories that are supposed to be evaluated, e.g. `structured_output`.
|
|
384
|
+
|
|
385
|
+
Args:
|
|
386
|
+
summary_sub_category_names: String or list of summary sub categories
|
|
387
|
+
"""
|
|
388
|
+
cls._summary_sub_cats = (
|
|
389
|
+
[get_type(summary_sub_category_names)]
|
|
390
|
+
if isinstance(summary_sub_category_names, str)
|
|
391
|
+
else [get_type(category) for category in summary_sub_category_names]
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
@classmethod
|
|
395
|
+
def _category_sanity_checks(cls, categories: DatasetCategories) -> None: # pylint: disable=W0613
|
|
396
|
+
if cls._summary_sub_cats is None:
|
|
397
|
+
logger.warning(
|
|
398
|
+
LoggingRecord(
|
|
399
|
+
"RecordAlign metric has not correctly been set up: No summary sub category has been "
|
|
400
|
+
"defined, therefore it is undefined what to evaluate."
|
|
401
|
+
)
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
@classmethod
|
|
405
|
+
def get_requirements(cls) -> list[Requirement]:
|
|
406
|
+
return [get_scipy_requirement()]
|
|
407
|
+
|
|
408
|
+
@classmethod
|
|
409
|
+
def print_result(cls) -> None:
|
|
410
|
+
table = tabulate(
|
|
411
|
+
[x.values() for x in cls._results],
|
|
412
|
+
list(cls._results[0].keys()),
|
|
413
|
+
tablefmt="pipe",
|
|
414
|
+
stralign="center",
|
|
415
|
+
numalign="left",
|
|
416
|
+
)
|
|
417
|
+
logger.info(LoggingRecord(f"{cls.name} results:\n {colored(table, 'cyan')}"))
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
@metric_registry.register("record_align_precision")
|
|
421
|
+
class RecordAlignPrecisionMetric(RecordAlignMetric):
|
|
422
|
+
"""
|
|
423
|
+
Metric induced by `field_counts`. Will calculate the precision per field path
|
|
424
|
+
"""
|
|
425
|
+
|
|
426
|
+
name = "Record Align Precision"
|
|
427
|
+
|
|
428
|
+
@classmethod
|
|
429
|
+
def get_distance(
|
|
430
|
+
cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories
|
|
431
|
+
) -> list[MetricResults]:
|
|
432
|
+
counts_per_path = cls._get_counts_per_path(dataflow_gt, dataflow_predictions, categories)
|
|
433
|
+
|
|
434
|
+
results = []
|
|
435
|
+
for path in sorted(counts_per_path):
|
|
436
|
+
entry = counts_per_path[path]
|
|
437
|
+
results.append(
|
|
438
|
+
{
|
|
439
|
+
"key": path,
|
|
440
|
+
"val": float(entry.precision),
|
|
441
|
+
"num_samples": entry.tp + entry.fn,
|
|
442
|
+
}
|
|
443
|
+
)
|
|
444
|
+
cls._results = results
|
|
445
|
+
return results
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
@metric_registry.register("record_align_recall")
|
|
449
|
+
class RecordAlignRecallMetric(RecordAlignMetric):
|
|
450
|
+
"""
|
|
451
|
+
Metric induced by `field_counts`. Will calculate the recall per field path
|
|
452
|
+
"""
|
|
453
|
+
|
|
454
|
+
name = "Record Align Recall"
|
|
455
|
+
|
|
456
|
+
@classmethod
|
|
457
|
+
def get_distance(
|
|
458
|
+
cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories
|
|
459
|
+
) -> list[MetricResults]:
|
|
460
|
+
counts_per_path = cls._get_counts_per_path(dataflow_gt, dataflow_predictions, categories)
|
|
461
|
+
|
|
462
|
+
results = []
|
|
463
|
+
for path in sorted(counts_per_path):
|
|
464
|
+
entry = counts_per_path[path]
|
|
465
|
+
results.append(
|
|
466
|
+
{
|
|
467
|
+
"key": path,
|
|
468
|
+
"val": float(entry.recall),
|
|
469
|
+
"num_samples": entry.tp + entry.fn,
|
|
470
|
+
}
|
|
471
|
+
)
|
|
472
|
+
cls._results = results
|
|
473
|
+
return results
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
@metric_registry.register("record_align_f1")
|
|
477
|
+
class RecordAlignF1Metric(RecordAlignMetric):
|
|
478
|
+
"""
|
|
479
|
+
Metric induced by `field_counts`. Will calculate the F1 per field path
|
|
480
|
+
"""
|
|
481
|
+
|
|
482
|
+
name = "Record Align F1"
|
|
483
|
+
|
|
484
|
+
@classmethod
|
|
485
|
+
def get_distance(
|
|
486
|
+
cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories
|
|
487
|
+
) -> list[MetricResults]:
|
|
488
|
+
counts_per_path = cls._get_counts_per_path(dataflow_gt, dataflow_predictions, categories)
|
|
489
|
+
|
|
490
|
+
results = []
|
|
491
|
+
for path in sorted(counts_per_path):
|
|
492
|
+
entry = counts_per_path[path]
|
|
493
|
+
results.append(
|
|
494
|
+
{
|
|
495
|
+
"key": path,
|
|
496
|
+
"val": float(entry.f1),
|
|
497
|
+
"num_samples": entry.tp + entry.fn,
|
|
498
|
+
}
|
|
499
|
+
)
|
|
500
|
+
cls._results = results
|
|
501
|
+
return results
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
@metric_registry.register("record_align_precision_micro")
|
|
505
|
+
class RecordAlignPrecisionMetricMicro(RecordAlignMetric):
|
|
506
|
+
"""
|
|
507
|
+
Metric induced by `field_counts`. Will calculate the micro average precision
|
|
508
|
+
"""
|
|
509
|
+
|
|
510
|
+
name = "Record Align Micro Precision"
|
|
511
|
+
|
|
512
|
+
@classmethod
|
|
513
|
+
def get_distance(
|
|
514
|
+
cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories
|
|
515
|
+
) -> list[MetricResults]:
|
|
516
|
+
counts_per_path = cls._get_counts_per_path(dataflow_gt, dataflow_predictions, categories)
|
|
517
|
+
|
|
518
|
+
summed = sum(counts_per_path.values(), Counts())
|
|
519
|
+
results = [
|
|
520
|
+
{
|
|
521
|
+
"key": "total",
|
|
522
|
+
"val": float(summed.precision),
|
|
523
|
+
"num_samples": summed.tp + summed.fn,
|
|
524
|
+
}
|
|
525
|
+
]
|
|
526
|
+
cls._results = results
|
|
527
|
+
return results
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
@metric_registry.register("record_align_recall_micro")
|
|
531
|
+
class RecordAlignRecallMetricMicro(RecordAlignMetric):
|
|
532
|
+
"""
|
|
533
|
+
Metric induced by `field_counts`. Will calculate the micro average recall
|
|
534
|
+
"""
|
|
535
|
+
|
|
536
|
+
name = "Record Align Micro Recall"
|
|
537
|
+
|
|
538
|
+
@classmethod
|
|
539
|
+
def get_distance(
|
|
540
|
+
cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories
|
|
541
|
+
) -> list[MetricResults]:
|
|
542
|
+
counts_per_path = cls._get_counts_per_path(dataflow_gt, dataflow_predictions, categories)
|
|
543
|
+
|
|
544
|
+
summed = sum(counts_per_path.values(), Counts())
|
|
545
|
+
results = [
|
|
546
|
+
{
|
|
547
|
+
"key": "total",
|
|
548
|
+
"val": float(summed.recall),
|
|
549
|
+
"num_samples": summed.tp + summed.fn,
|
|
550
|
+
}
|
|
551
|
+
]
|
|
552
|
+
cls._results = results
|
|
553
|
+
return results
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
@metric_registry.register("record_align_f1_micro")
|
|
557
|
+
class RecordAlignF1MetricMicro(RecordAlignMetric):
|
|
558
|
+
"""
|
|
559
|
+
Metric induced by `field_counts`. Will calculate the micro average F1
|
|
560
|
+
"""
|
|
561
|
+
|
|
562
|
+
name = "Record Align Micro F1"
|
|
563
|
+
|
|
564
|
+
@classmethod
|
|
565
|
+
def get_distance(
|
|
566
|
+
cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories
|
|
567
|
+
) -> list[MetricResults]:
|
|
568
|
+
counts_per_path = cls._get_counts_per_path(dataflow_gt, dataflow_predictions, categories)
|
|
569
|
+
|
|
570
|
+
summed = sum(counts_per_path.values(), Counts())
|
|
571
|
+
results = [
|
|
572
|
+
{
|
|
573
|
+
"key": "total",
|
|
574
|
+
"val": float(summed.f1),
|
|
575
|
+
"num_samples": summed.tp + summed.fn,
|
|
576
|
+
}
|
|
577
|
+
]
|
|
578
|
+
cls._results = results
|
|
579
|
+
return results
|
|
@@ -637,7 +637,7 @@ class DatapointManager:
|
|
|
637
637
|
summary_key: ObjectTypes,
|
|
638
638
|
summary_name: ObjectTypes,
|
|
639
639
|
summary_number: Optional[int] = None,
|
|
640
|
-
summary_value: Optional[Union[str, int, float, list[str], dict[str, Any]]] = None,
|
|
640
|
+
summary_value: Optional[Union[str, int, float, bool, list[str], dict[str, Any], ReferencePayload]] = None,
|
|
641
641
|
summary_score: Optional[float] = None,
|
|
642
642
|
annotation_id: Optional[str] = None,
|
|
643
643
|
job_id: str | None = None,
|
|
@@ -651,7 +651,9 @@ class DatapointManager:
|
|
|
651
651
|
summary_key: Stores the category annotation as a subcategory.
|
|
652
652
|
summary_name: Creates the summary name as the category name.
|
|
653
653
|
summary_number: Stores the value in `category_id`.
|
|
654
|
-
summary_value: Creates a `ContainerAnnotation` and stores the corresponding value.
|
|
654
|
+
summary_value: Creates a `ContainerAnnotation` and stores the corresponding value. A
|
|
655
|
+
`ReferencePayload`, e.g. the structured output of an LLM task, is stored as
|
|
656
|
+
is and can be resolved later with `Page.resolve_reference_payload`.
|
|
655
657
|
summary_score: Stores the score.
|
|
656
658
|
annotation_id: The id of the parent annotation. Note that the parent annotation must have `image` not None.
|
|
657
659
|
job_id: Optional job identifier for async routing.
|
|
@@ -26,7 +26,7 @@ from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Sequence, Un
|
|
|
26
26
|
|
|
27
27
|
from dd_core.datapoint.image import Image, MetaAnnotation
|
|
28
28
|
from dd_core.mapper.laylmstruct import image_to_layoutlm_features, image_to_lm_features
|
|
29
|
-
from dd_core.utils.object_types import BioTagLabel, LayoutLabel, ObjectTypes,
|
|
29
|
+
from dd_core.utils.object_types import BioTagLabel, DocumentKey, LayoutLabel, ObjectTypes, TokenClassLabel, WordKey
|
|
30
30
|
|
|
31
31
|
from ..extern.base import SequenceClassResult
|
|
32
32
|
from .base import PipelineComponent
|
|
@@ -389,7 +389,7 @@ class LMSequenceClassifierService(PipelineComponent):
|
|
|
389
389
|
lm_output = self.language_model.predict(**lm_input)
|
|
390
390
|
if lm_output:
|
|
391
391
|
self.dp_manager.set_summary_annotation(
|
|
392
|
-
|
|
392
|
+
DocumentKey.DOCUMENT_TYPE, lm_output.class_name, lm_output.class_id, None, lm_output.score
|
|
393
393
|
)
|
|
394
394
|
|
|
395
395
|
def clone(self) -> LMSequenceClassifierService:
|
|
@@ -403,7 +403,7 @@ class LMSequenceClassifierService(PipelineComponent):
|
|
|
403
403
|
|
|
404
404
|
def get_meta_annotation(self) -> MetaAnnotation:
|
|
405
405
|
return MetaAnnotation(
|
|
406
|
-
image_annotations=(), sub_categories={}, relationships={}, summaries=(
|
|
406
|
+
image_annotations=(), sub_categories={}, relationships={}, summaries=(DocumentKey.DOCUMENT_TYPE,)
|
|
407
407
|
)
|
|
408
408
|
|
|
409
409
|
def _get_name(self) -> str:
|
|
@@ -22,8 +22,8 @@ Init module for train package
|
|
|
22
22
|
from dd_core.utils.file_utils import detectron2_available, transformers_available
|
|
23
23
|
|
|
24
24
|
if detectron2_available():
|
|
25
|
-
from .d2_frcnn_train import train_d2_faster_rcnn
|
|
25
|
+
from .d2_frcnn_train import D2Trainer, train_d2_faster_rcnn
|
|
26
26
|
|
|
27
27
|
if transformers_available():
|
|
28
|
-
from .hf_detr_train import train_hf_detr
|
|
29
|
-
from .hf_layoutlm_train import train_hf_layoutlm
|
|
28
|
+
from .hf_detr_train import DetrDerivedTrainer, train_hf_detr
|
|
29
|
+
from .hf_layoutlm_train import LayoutLMTrainer, train_hf_layoutlm
|
|
@@ -20,6 +20,7 @@ src/deepdoctection/eval/accmetric.py
|
|
|
20
20
|
src/deepdoctection/eval/base.py
|
|
21
21
|
src/deepdoctection/eval/cocometric.py
|
|
22
22
|
src/deepdoctection/eval/eval.py
|
|
23
|
+
src/deepdoctection/eval/record_align.py
|
|
23
24
|
src/deepdoctection/eval/registry.py
|
|
24
25
|
src/deepdoctection/eval/tedsmetric.py
|
|
25
26
|
src/deepdoctection/extern/__init__.py
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection/configs/conf_tesseract.yaml
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{deepdoctection-1.3.0 → deepdoctection-1.4.0}/src/deepdoctection.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|