parse-bench 1.0.0__py3-none-any.whl

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.
Files changed (227) hide show
  1. parse_bench/__init__.py +3 -0
  2. parse_bench/analysis/__init__.py +6 -0
  3. parse_bench/analysis/aggregation_report.py +582 -0
  4. parse_bench/analysis/cli.py +472 -0
  5. parse_bench/analysis/comparison.py +382 -0
  6. parse_bench/analysis/comparison_core.py +357 -0
  7. parse_bench/analysis/comparison_report.py +2066 -0
  8. parse_bench/analysis/detailed_report.py +2254 -0
  9. parse_bench/analysis/leaderboard_report.py +852 -0
  10. parse_bench/analysis/metric_definitions.py +771 -0
  11. parse_bench/cli.py +267 -0
  12. parse_bench/data/__init__.py +1 -0
  13. parse_bench/data/cli.py +118 -0
  14. parse_bench/data/download.py +127 -0
  15. parse_bench/evaluation/__init__.py +11 -0
  16. parse_bench/evaluation/cli.py +435 -0
  17. parse_bench/evaluation/evaluators/__init__.py +17 -0
  18. parse_bench/evaluation/evaluators/base.py +34 -0
  19. parse_bench/evaluation/evaluators/extract.py +429 -0
  20. parse_bench/evaluation/evaluators/layoutdet.py +1682 -0
  21. parse_bench/evaluation/evaluators/parse.py +1353 -0
  22. parse_bench/evaluation/evaluators/qa.py +199 -0
  23. parse_bench/evaluation/layout_adapters/__init__.py +21 -0
  24. parse_bench/evaluation/layout_adapters/adapters.py +3180 -0
  25. parse_bench/evaluation/layout_adapters/base.py +105 -0
  26. parse_bench/evaluation/layout_adapters/registry.py +109 -0
  27. parse_bench/evaluation/layout_label_mappers/__init__.py +22 -0
  28. parse_bench/evaluation/layout_label_mappers/base.py +66 -0
  29. parse_bench/evaluation/layout_label_mappers/mappers.py +332 -0
  30. parse_bench/evaluation/layout_label_mappers/projection.py +74 -0
  31. parse_bench/evaluation/layout_label_mappers/registry.py +119 -0
  32. parse_bench/evaluation/metric_aggregation.py +56 -0
  33. parse_bench/evaluation/metrics/__init__.py +5 -0
  34. parse_bench/evaluation/metrics/attribution/__init__.py +35 -0
  35. parse_bench/evaluation/metrics/attribution/constants.py +12 -0
  36. parse_bench/evaluation/metrics/attribution/core.py +1108 -0
  37. parse_bench/evaluation/metrics/attribution/evaluate.py +446 -0
  38. parse_bench/evaluation/metrics/attribution/geometry.py +161 -0
  39. parse_bench/evaluation/metrics/attribution/text_utils.py +233 -0
  40. parse_bench/evaluation/metrics/base.py +33 -0
  41. parse_bench/evaluation/metrics/downstream/__init__.py +0 -0
  42. parse_bench/evaluation/metrics/extract/__init__.py +29 -0
  43. parse_bench/evaluation/metrics/extract/json_subset_match.py +473 -0
  44. parse_bench/evaluation/metrics/extract/json_subset_match_metric.py +81 -0
  45. parse_bench/evaluation/metrics/extract/list_unwrap.py +340 -0
  46. parse_bench/evaluation/metrics/extract/rule_based_metric.py +90 -0
  47. parse_bench/evaluation/metrics/extract/test_rules.py +409 -0
  48. parse_bench/evaluation/metrics/extract/test_types.py +11 -0
  49. parse_bench/evaluation/metrics/field_grounding/__init__.py +21 -0
  50. parse_bench/evaluation/metrics/field_grounding/core.py +437 -0
  51. parse_bench/evaluation/metrics/field_grounding/extract_adapter.py +1224 -0
  52. parse_bench/evaluation/metrics/field_grounding/parse_adapter.py +697 -0
  53. parse_bench/evaluation/metrics/field_grounding/rule_filters.py +19 -0
  54. parse_bench/evaluation/metrics/field_grounding/value_compare.py +190 -0
  55. parse_bench/evaluation/metrics/layoutdet/__init__.py +17 -0
  56. parse_bench/evaluation/metrics/layoutdet/classification_utils.py +300 -0
  57. parse_bench/evaluation/metrics/layoutdet/iou.py +76 -0
  58. parse_bench/evaluation/metrics/parse/__init__.py +5 -0
  59. parse_bench/evaluation/metrics/parse/_vendor_grits_reference.py +531 -0
  60. parse_bench/evaluation/metrics/parse/cross_page_table_consistency.py +165 -0
  61. parse_bench/evaluation/metrics/parse/emphasis_spans.py +242 -0
  62. parse_bench/evaluation/metrics/parse/fast_tree_edit.py +282 -0
  63. parse_bench/evaluation/metrics/parse/grits_metric.py +1125 -0
  64. parse_bench/evaluation/metrics/parse/grits_reference_metric.py +142 -0
  65. parse_bench/evaluation/metrics/parse/header_accuracy_metric.py +1662 -0
  66. parse_bench/evaluation/metrics/parse/llm_normalization/__init__.py +51 -0
  67. parse_bench/evaluation/metrics/parse/llm_normalization/base.py +125 -0
  68. parse_bench/evaluation/metrics/parse/llm_normalization/config.py +44 -0
  69. parse_bench/evaluation/metrics/parse/llm_normalization/postprocess.py +322 -0
  70. parse_bench/evaluation/metrics/parse/llm_normalization/strategy_judge.py +541 -0
  71. parse_bench/evaluation/metrics/parse/mermaid_graph.py +682 -0
  72. parse_bench/evaluation/metrics/parse/rule_based_judge_metric.py +56 -0
  73. parse_bench/evaluation/metrics/parse/rule_based_metric.py +434 -0
  74. parse_bench/evaluation/metrics/parse/rules_bag.py +1161 -0
  75. parse_bench/evaluation/metrics/parse/rules_base.py +751 -0
  76. parse_bench/evaluation/metrics/parse/rules_chart.py +1556 -0
  77. parse_bench/evaluation/metrics/parse/rules_diagram.py +591 -0
  78. parse_bench/evaluation/metrics/parse/rules_form.py +2274 -0
  79. parse_bench/evaluation/metrics/parse/rules_formatting.py +1500 -0
  80. parse_bench/evaluation/metrics/parse/rules_heading.py +228 -0
  81. parse_bench/evaluation/metrics/parse/rules_list.py +226 -0
  82. parse_bench/evaluation/metrics/parse/rules_page_decoration.py +276 -0
  83. parse_bench/evaluation/metrics/parse/rules_table.py +1666 -0
  84. parse_bench/evaluation/metrics/parse/rules_text.py +340 -0
  85. parse_bench/evaluation/metrics/parse/rules_watermark.py +105 -0
  86. parse_bench/evaluation/metrics/parse/structural_consistency_metric.py +251 -0
  87. parse_bench/evaluation/metrics/parse/table_extraction.py +152 -0
  88. parse_bench/evaluation/metrics/parse/table_merging.py +195 -0
  89. parse_bench/evaluation/metrics/parse/table_pairing.py +87 -0
  90. parse_bench/evaluation/metrics/parse/table_parsing.py +955 -0
  91. parse_bench/evaluation/metrics/parse/table_record_match_metric.py +1453 -0
  92. parse_bench/evaluation/metrics/parse/table_splitting.py +301 -0
  93. parse_bench/evaluation/metrics/parse/table_title_stripping.py +530 -0
  94. parse_bench/evaluation/metrics/parse/teds_metric.py +600 -0
  95. parse_bench/evaluation/metrics/parse/test_rules.py +120 -0
  96. parse_bench/evaluation/metrics/parse/test_types.py +103 -0
  97. parse_bench/evaluation/metrics/parse/text_content_projection.py +175 -0
  98. parse_bench/evaluation/metrics/parse/text_similarity_metric.py +61 -0
  99. parse_bench/evaluation/metrics/parse/utils.py +885 -0
  100. parse_bench/evaluation/metrics/qa/__init__.py +5 -0
  101. parse_bench/evaluation/metrics/qa/answer_comparison.py +380 -0
  102. parse_bench/evaluation/qa/__init__.py +5 -0
  103. parse_bench/evaluation/qa/llm_service.py +335 -0
  104. parse_bench/evaluation/reports/__init__.py +8 -0
  105. parse_bench/evaluation/reports/csv.py +64 -0
  106. parse_bench/evaluation/reports/html.py +338 -0
  107. parse_bench/evaluation/reports/markdown.py +98 -0
  108. parse_bench/evaluation/reports/rule_csv.py +22 -0
  109. parse_bench/evaluation/runner.py +1864 -0
  110. parse_bench/evaluation/stats.py +104 -0
  111. parse_bench/extensions.py +72 -0
  112. parse_bench/inference/__init__.py +33 -0
  113. parse_bench/inference/chunkr_layout_extraction.py +160 -0
  114. parse_bench/inference/cli.py +484 -0
  115. parse_bench/inference/layout_extraction.py +422 -0
  116. parse_bench/inference/pipelines/__init__.py +59 -0
  117. parse_bench/inference/pipelines/extract.py +39 -0
  118. parse_bench/inference/pipelines/layout.py +142 -0
  119. parse_bench/inference/pipelines/parse.py +2603 -0
  120. parse_bench/inference/pipelines.py +0 -0
  121. parse_bench/inference/providers/__init__.py +28 -0
  122. parse_bench/inference/providers/base.py +196 -0
  123. parse_bench/inference/providers/cancellation.py +137 -0
  124. parse_bench/inference/providers/extract/__init__.py +22 -0
  125. parse_bench/inference/providers/extract/citations.py +549 -0
  126. parse_bench/inference/providers/extract/extend.py +851 -0
  127. parse_bench/inference/providers/extract/llamaextract_v2_api.py +583 -0
  128. parse_bench/inference/providers/layoutdet/__init__.py +25 -0
  129. parse_bench/inference/providers/layoutdet/adapters.py +946 -0
  130. parse_bench/inference/providers/layoutdet/base.py +203 -0
  131. parse_bench/inference/providers/layoutdet/chandra.py +449 -0
  132. parse_bench/inference/providers/layoutdet/docling.py +125 -0
  133. parse_bench/inference/providers/layoutdet/dots_ocr.py +606 -0
  134. parse_bench/inference/providers/layoutdet/layout_v3.py +137 -0
  135. parse_bench/inference/providers/layoutdet/layout_v3_byoc.py +204 -0
  136. parse_bench/inference/providers/layoutdet/paddle.py +117 -0
  137. parse_bench/inference/providers/layoutdet/qwen3vl.py +360 -0
  138. parse_bench/inference/providers/layoutdet/surya.py +250 -0
  139. parse_bench/inference/providers/layoutdet/yolo.py +109 -0
  140. parse_bench/inference/providers/parse/__init__.py +64 -0
  141. parse_bench/inference/providers/parse/_docling_common.py +233 -0
  142. parse_bench/inference/providers/parse/_layout_utils.py +611 -0
  143. parse_bench/inference/providers/parse/amazon_nova.py +515 -0
  144. parse_bench/inference/providers/parse/anthropic.py +882 -0
  145. parse_bench/inference/providers/parse/azure_document_intelligence.py +700 -0
  146. parse_bench/inference/providers/parse/chandra2.py +633 -0
  147. parse_bench/inference/providers/parse/chunkr.py +268 -0
  148. parse_bench/inference/providers/parse/databricks_ai_parse.py +724 -0
  149. parse_bench/inference/providers/parse/datalab.py +370 -0
  150. parse_bench/inference/providers/parse/deepseekocr2.py +382 -0
  151. parse_bench/inference/providers/parse/docling.py +281 -0
  152. parse_bench/inference/providers/parse/docling_serve.py +289 -0
  153. parse_bench/inference/providers/parse/dots_ocr.py +574 -0
  154. parse_bench/inference/providers/parse/extend_parse.py +710 -0
  155. parse_bench/inference/providers/parse/falconocr.py +436 -0
  156. parse_bench/inference/providers/parse/florin_parser_nano.py +559 -0
  157. parse_bench/inference/providers/parse/gemma4.py +472 -0
  158. parse_bench/inference/providers/parse/glm_zai.py +229 -0
  159. parse_bench/inference/providers/parse/google.py +1125 -0
  160. parse_bench/inference/providers/parse/google_agentic_vision.py +819 -0
  161. parse_bench/inference/providers/parse/google_docai.py +776 -0
  162. parse_bench/inference/providers/parse/google_docai_layout_normalization.py +573 -0
  163. parse_bench/inference/providers/parse/granite_vision.py +515 -0
  164. parse_bench/inference/providers/parse/infinity_parser2.py +704 -0
  165. parse_bench/inference/providers/parse/kdl_frontier_nano.py +3327 -0
  166. parse_bench/inference/providers/parse/landingai.py +452 -0
  167. parse_bench/inference/providers/parse/liteparse.py +350 -0
  168. parse_bench/inference/providers/parse/llamaparse.py +677 -0
  169. parse_bench/inference/providers/parse/llamaparse_v2_normalization.py +1013 -0
  170. parse_bench/inference/providers/parse/markitdown.py +138 -0
  171. parse_bench/inference/providers/parse/mineru25.py +405 -0
  172. parse_bench/inference/providers/parse/mineru2605pro.py +432 -0
  173. parse_bench/inference/providers/parse/mineru_diffusion.py +371 -0
  174. parse_bench/inference/providers/parse/mistral_ocr.py +546 -0
  175. parse_bench/inference/providers/parse/nemotron_omni.py +473 -0
  176. parse_bench/inference/providers/parse/oi_parser.py +222 -0
  177. parse_bench/inference/providers/parse/openai.py +740 -0
  178. parse_bench/inference/providers/parse/opendataloader.py +152 -0
  179. parse_bench/inference/providers/parse/paddleocr.py +624 -0
  180. parse_bench/inference/providers/parse/pdf_inspector.py +142 -0
  181. parse_bench/inference/providers/parse/pulse.py +785 -0
  182. parse_bench/inference/providers/parse/pymupdf.py +207 -0
  183. parse_bench/inference/providers/parse/pymupdf4llm.py +356 -0
  184. parse_bench/inference/providers/parse/pypdf.py +179 -0
  185. parse_bench/inference/providers/parse/qwen.py +678 -0
  186. parse_bench/inference/providers/parse/rakedoc_nano.py +70 -0
  187. parse_bench/inference/providers/parse/reducto.py +546 -0
  188. parse_bench/inference/providers/parse/surya2.py +372 -0
  189. parse_bench/inference/providers/parse/tesseract.py +301 -0
  190. parse_bench/inference/providers/parse/textract.py +694 -0
  191. parse_bench/inference/providers/parse/unlimitedocr.py +346 -0
  192. parse_bench/inference/providers/parse/unstructured.py +485 -0
  193. parse_bench/inference/providers/parse/warp_ingest.py +199 -0
  194. parse_bench/inference/providers/registry.py +49 -0
  195. parse_bench/inference/renormalize.py +170 -0
  196. parse_bench/inference/runner.py +2023 -0
  197. parse_bench/layout_label_mapping.py +424 -0
  198. parse_bench/layout_projection.py +179 -0
  199. parse_bench/pipeline/__init__.py +1 -0
  200. parse_bench/pipeline/cli.py +549 -0
  201. parse_bench/schemas/__init__.py +33 -0
  202. parse_bench/schemas/evaluation.py +93 -0
  203. parse_bench/schemas/extract_output.py +36 -0
  204. parse_bench/schemas/layout_detection_output.py +545 -0
  205. parse_bench/schemas/layout_ontology.py +315 -0
  206. parse_bench/schemas/metrics.py +69 -0
  207. parse_bench/schemas/parse_output.py +152 -0
  208. parse_bench/schemas/pipeline.py +22 -0
  209. parse_bench/schemas/pipeline_io.py +106 -0
  210. parse_bench/schemas/product.py +97 -0
  211. parse_bench/test_cases/__init__.py +25 -0
  212. parse_bench/test_cases/bbox_value_strict_comparator.py +880 -0
  213. parse_bench/test_cases/extract_field_paths.py +164 -0
  214. parse_bench/test_cases/layout_attribution_generation.py +287 -0
  215. parse_bench/test_cases/loader.py +652 -0
  216. parse_bench/test_cases/parse_rule_schemas.py +1071 -0
  217. parse_bench/test_cases/rule_filters.py +32 -0
  218. parse_bench/test_cases/rule_ids.py +107 -0
  219. parse_bench/test_cases/schema.py +427 -0
  220. parse_bench/utils/__init__.py +15 -0
  221. parse_bench/utils/gemini_layout_utils.py +670 -0
  222. parse_bench/utils/text_aggregation.py +100 -0
  223. parse_bench-1.0.0.dist-info/METADATA +476 -0
  224. parse_bench-1.0.0.dist-info/RECORD +227 -0
  225. parse_bench-1.0.0.dist-info/WHEEL +4 -0
  226. parse_bench-1.0.0.dist-info/entry_points.txt +2 -0
  227. parse_bench-1.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,531 @@
1
+ """
2
+ Copyright (C) 2021 Microsoft Corporation
3
+ """
4
+
5
+ import itertools
6
+ import xml.etree.ElementTree as ET
7
+ from collections import defaultdict
8
+ from difflib import SequenceMatcher
9
+
10
+ import numpy as np
11
+ from fitz import Rect
12
+
13
+
14
+ def compute_fscore(num_true_positives, num_true, num_positives):
15
+ """
16
+ Compute the f-score or f-measure for a collection of predictions.
17
+
18
+ Conventions:
19
+ - precision is 1 when there are no predicted instances
20
+ - recall is 1 when there are no true instances
21
+ - fscore is 0 when recall or precision is 0
22
+ """
23
+ if num_positives > 0:
24
+ precision = num_true_positives / num_positives
25
+ else:
26
+ precision = 1
27
+ if num_true > 0:
28
+ recall = num_true_positives / num_true
29
+ else:
30
+ recall = 1
31
+
32
+ if precision + recall > 0:
33
+ fscore = 2 * precision * recall / (precision + recall)
34
+ else:
35
+ fscore = 0
36
+
37
+ return fscore, precision, recall
38
+
39
+
40
+ def initialize_DP(sequence1_length, sequence2_length):
41
+ """
42
+ Helper function to initialize dynamic programming data structures.
43
+ """
44
+ # Initialize DP tables
45
+ scores = np.zeros((sequence1_length + 1, sequence2_length + 1))
46
+ pointers = np.zeros((sequence1_length + 1, sequence2_length + 1))
47
+
48
+ # Initialize pointers in DP table
49
+ for seq1_idx in range(1, sequence1_length + 1):
50
+ pointers[seq1_idx, 0] = -1
51
+
52
+ # Initialize pointers in DP table
53
+ for seq2_idx in range(1, sequence2_length + 1):
54
+ pointers[0, seq2_idx] = 1
55
+
56
+ return scores, pointers
57
+
58
+
59
+ def traceback(pointers):
60
+ """
61
+ Dynamic programming traceback to determine the aligned indices
62
+ between the two sequences.
63
+
64
+ Traceback convention: -1 = up, 1 = left, 0 = diag up-left
65
+ """
66
+ seq1_idx = pointers.shape[0] - 1
67
+ seq2_idx = pointers.shape[1] - 1
68
+ aligned_sequence1_indices = []
69
+ aligned_sequence2_indices = []
70
+ while not (seq1_idx == 0 and seq2_idx == 0):
71
+ if pointers[seq1_idx, seq2_idx] == -1:
72
+ seq1_idx -= 1
73
+ elif pointers[seq1_idx, seq2_idx] == 1:
74
+ seq2_idx -= 1
75
+ else:
76
+ seq1_idx -= 1
77
+ seq2_idx -= 1
78
+ aligned_sequence1_indices.append(seq1_idx)
79
+ aligned_sequence2_indices.append(seq2_idx)
80
+
81
+ aligned_sequence1_indices = aligned_sequence1_indices[::-1]
82
+ aligned_sequence2_indices = aligned_sequence2_indices[::-1]
83
+
84
+ return aligned_sequence1_indices, aligned_sequence2_indices
85
+
86
+
87
+ def align_1d(sequence1, sequence2, reward_lookup, return_alignment=False):
88
+ """
89
+ Dynamic programming alignment between two sequences,
90
+ with memoized rewards.
91
+
92
+ Sequences are represented as indices into the rewards lookup table.
93
+
94
+ Traceback convention: -1 = up, 1 = left, 0 = diag up-left
95
+ """
96
+ sequence1_length = len(sequence1)
97
+ sequence2_length = len(sequence2)
98
+
99
+ scores, pointers = initialize_DP(sequence1_length, sequence2_length)
100
+
101
+ for seq1_idx in range(1, sequence1_length + 1):
102
+ for seq2_idx in range(1, sequence2_length + 1):
103
+ reward = reward_lookup[sequence1[seq1_idx - 1] + sequence2[seq2_idx - 1]]
104
+ diag_score = scores[seq1_idx - 1, seq2_idx - 1] + reward
105
+ skip_seq2_score = scores[seq1_idx, seq2_idx - 1]
106
+ skip_seq1_score = scores[seq1_idx - 1, seq2_idx]
107
+
108
+ max_score = max(diag_score, skip_seq1_score, skip_seq2_score)
109
+ scores[seq1_idx, seq2_idx] = max_score
110
+ if diag_score == max_score:
111
+ pointers[seq1_idx, seq2_idx] = 0
112
+ elif skip_seq1_score == max_score:
113
+ pointers[seq1_idx, seq2_idx] = -1
114
+ else: # skip_seq2_score == max_score
115
+ pointers[seq1_idx, seq2_idx] = 1
116
+
117
+ score = scores[-1, -1]
118
+
119
+ if not return_alignment:
120
+ return score
121
+
122
+ # Traceback
123
+ sequence1_indices, sequence2_indices = traceback(pointers)
124
+
125
+ return sequence1_indices, sequence2_indices, score
126
+
127
+
128
+ def align_2d_outer(true_shape, pred_shape, reward_lookup):
129
+ """
130
+ Dynamic programming matrix alignment posed as 2D
131
+ sequence-of-sequences alignment:
132
+ Align two outer sequences whose entries are also sequences,
133
+ where the match reward between the inner sequence entries
134
+ is their 1D sequence alignment score.
135
+
136
+ Traceback convention: -1 = up, 1 = left, 0 = diag up-left
137
+ """
138
+
139
+ scores, pointers = initialize_DP(true_shape[0], pred_shape[0])
140
+
141
+ for row_idx in range(1, true_shape[0] + 1):
142
+ for col_idx in range(1, pred_shape[0] + 1):
143
+ reward = align_1d(
144
+ [(row_idx - 1, tcol) for tcol in range(true_shape[1])],
145
+ [(col_idx - 1, prow) for prow in range(pred_shape[1])],
146
+ reward_lookup,
147
+ )
148
+ diag_score = scores[row_idx - 1, col_idx - 1] + reward
149
+ same_row_score = scores[row_idx, col_idx - 1]
150
+ same_col_score = scores[row_idx - 1, col_idx]
151
+
152
+ max_score = max(diag_score, same_col_score, same_row_score)
153
+ scores[row_idx, col_idx] = max_score
154
+ if diag_score == max_score:
155
+ pointers[row_idx, col_idx] = 0
156
+ elif same_col_score == max_score:
157
+ pointers[row_idx, col_idx] = -1
158
+ else:
159
+ pointers[row_idx, col_idx] = 1
160
+
161
+ score = scores[-1, -1]
162
+
163
+ aligned_true_indices, aligned_pred_indices = traceback(pointers)
164
+
165
+ return aligned_true_indices, aligned_pred_indices, score
166
+
167
+
168
+ def factored_2dmss(true_cell_grid, pred_cell_grid, reward_function):
169
+ """
170
+ Factored 2D-MSS: Factored two-dimensional most-similar substructures
171
+
172
+ This is a polynomial-time heuristic to computing the 2D-MSS of two matrices,
173
+ which is NP hard.
174
+
175
+ A substructure of a matrix is a subset of its rows and its columns.
176
+
177
+ The most similar substructures of two matrices, A and B, are the substructures
178
+ A' and B', where the sum of the similarity over all corresponding entries
179
+ A'(i, j) and B'(i, j) is greatest.
180
+ """
181
+ pre_computed_rewards = {}
182
+ transpose_rewards = {}
183
+ for trow, tcol, prow, pcol in itertools.product(
184
+ range(true_cell_grid.shape[0]),
185
+ range(true_cell_grid.shape[1]),
186
+ range(pred_cell_grid.shape[0]),
187
+ range(pred_cell_grid.shape[1]),
188
+ ):
189
+ reward = reward_function(true_cell_grid[trow, tcol], pred_cell_grid[prow, pcol])
190
+
191
+ pre_computed_rewards[(trow, tcol, prow, pcol)] = reward
192
+ transpose_rewards[(tcol, trow, pcol, prow)] = reward
193
+
194
+ num_pos = pred_cell_grid.shape[0] * pred_cell_grid.shape[1]
195
+ num_true = true_cell_grid.shape[0] * true_cell_grid.shape[1]
196
+
197
+ true_row_nums, pred_row_nums, row_pos_match_score = align_2d_outer(
198
+ true_cell_grid.shape[:2], pred_cell_grid.shape[:2], pre_computed_rewards
199
+ )
200
+
201
+ true_column_nums, pred_column_nums, col_pos_match_score = align_2d_outer(
202
+ true_cell_grid.shape[:2][::-1], pred_cell_grid.shape[:2][::-1], transpose_rewards
203
+ )
204
+
205
+ pos_match_score_upper_bound = min(row_pos_match_score, col_pos_match_score)
206
+ upper_bound_score, _, _ = compute_fscore(pos_match_score_upper_bound, num_pos, num_true)
207
+
208
+ positive_match_score = 0
209
+ for true_row_num, pred_row_num in zip(true_row_nums, pred_row_nums, strict=False):
210
+ for true_column_num, pred_column_num in zip(true_column_nums, pred_column_nums, strict=False):
211
+ positive_match_score += pre_computed_rewards[(true_row_num, true_column_num, pred_row_num, pred_column_num)]
212
+
213
+ fscore, precision, recall = compute_fscore(positive_match_score, num_true, num_pos)
214
+
215
+ return fscore, precision, recall, upper_bound_score
216
+
217
+
218
+ def lcs_similarity(string1, string2):
219
+ s1 = str(string1) if not isinstance(string1, str) else string1
220
+ s2 = str(string2) if not isinstance(string2, str) else string2
221
+ if len(s1) == 0 and len(s2) == 0:
222
+ return 1
223
+ s = SequenceMatcher(None, s1, s2)
224
+ lcs = "".join([s1[block.a : (block.a + block.size)] for block in s.get_matching_blocks()])
225
+ return 2 * len(lcs) / (len(s1) + len(s2))
226
+
227
+
228
+ def _is_scalar(val):
229
+ """Check if a value is a scalar (unoccupied grid cell), not a bbox list."""
230
+ try:
231
+ len(val)
232
+ return False
233
+ except TypeError:
234
+ return True
235
+
236
+
237
+ def iou(bbox1, bbox2):
238
+ """
239
+ Compute the intersection-over-union of two bounding boxes.
240
+ """
241
+ bbox1_scalar = _is_scalar(bbox1)
242
+ bbox2_scalar = _is_scalar(bbox2)
243
+
244
+ # Both unoccupied → both tables agree "no cell here" → perfect match
245
+ if bbox1_scalar and bbox2_scalar:
246
+ return 1.0
247
+ # One occupied, one not → structural mismatch
248
+ if bbox1_scalar or bbox2_scalar:
249
+ return 0.0
250
+
251
+ if len(bbox1) != 4 or len(bbox2) != 4:
252
+ return 0.0
253
+
254
+ # Convert numpy arrays to lists for newer pymupdf compatibility
255
+ if hasattr(bbox1, "tolist"):
256
+ bbox1 = bbox1.tolist()
257
+ if hasattr(bbox2, "tolist"):
258
+ bbox2 = bbox2.tolist()
259
+ intersection = Rect(bbox1).intersect(bbox2)
260
+ union = Rect(bbox1).include_rect(bbox2)
261
+
262
+ union_area = union.get_area()
263
+ if union_area > 0:
264
+ return intersection.get_area() / union.get_area()
265
+
266
+ return 0
267
+
268
+
269
+ def cells_to_grid(cells, key="bbox"):
270
+ """
271
+ Convert from a list of cells to a matrix of grid cell features.
272
+ This matrix representation is the input to GriTS.
273
+
274
+ For key, use:
275
+ - 'bbox' for computing GriTS_Loc
276
+ - 'cell_text' for computing GriTS_Con
277
+ """
278
+ if len(cells) == 0:
279
+ return [[]]
280
+ num_rows = max([max(cell["row_nums"]) for cell in cells]) + 1
281
+ num_columns = max([max(cell["column_nums"]) for cell in cells]) + 1
282
+ cell_grid = np.zeros((num_rows, num_columns)).tolist()
283
+ for cell in cells:
284
+ for row_num in cell["row_nums"]:
285
+ for column_num in cell["column_nums"]:
286
+ cell_grid[row_num][column_num] = cell[key]
287
+
288
+ return cell_grid
289
+
290
+
291
+ def cells_to_relspan_grid(cells):
292
+ """
293
+ Convert from a list of cells to the matrix of grid cell features
294
+ used for computing GriTS_Top.
295
+ """
296
+ if len(cells) == 0:
297
+ return [[]]
298
+ num_rows = max([max(cell["row_nums"]) for cell in cells]) + 1
299
+ num_columns = max([max(cell["column_nums"]) for cell in cells]) + 1
300
+ cell_grid = np.zeros((num_rows, num_columns)).tolist()
301
+ for cell in cells:
302
+ min_row_num = min(cell["row_nums"])
303
+ min_column_num = min(cell["column_nums"])
304
+ max_row_num = max(cell["row_nums"]) + 1
305
+ max_column_num = max(cell["column_nums"]) + 1
306
+ for row_num in cell["row_nums"]:
307
+ for column_num in cell["column_nums"]:
308
+ cell_grid[row_num][column_num] = [
309
+ min_column_num - column_num,
310
+ min_row_num - row_num,
311
+ max_column_num - column_num,
312
+ max_row_num - row_num,
313
+ ]
314
+
315
+ return cell_grid
316
+
317
+
318
+ def get_spanning_cell_rows_and_columns(spanning_cells, rows, columns):
319
+ """
320
+ Determine which grid cell locations (row-column) each spanning cell
321
+ corresponds to.
322
+ """
323
+ matches_by_spanning_cell = []
324
+ all_matches = set()
325
+ for spanning_cell in spanning_cells:
326
+ row_matches = set()
327
+ column_matches = set()
328
+ for row_num, row in enumerate(rows):
329
+ bbox1 = [
330
+ spanning_cell["bbox"][0],
331
+ row["bbox"][1],
332
+ spanning_cell["bbox"][2],
333
+ row["bbox"][3],
334
+ ]
335
+ bbox2 = Rect(spanning_cell["bbox"]).intersect(bbox1)
336
+ if bbox2.get_area() / Rect(bbox1).get_area() >= 0.5:
337
+ row_matches.add(row_num)
338
+ for column_num, column in enumerate(columns):
339
+ bbox1 = [
340
+ column["bbox"][0],
341
+ spanning_cell["bbox"][1],
342
+ column["bbox"][2],
343
+ spanning_cell["bbox"][3],
344
+ ]
345
+ bbox2 = Rect(spanning_cell["bbox"]).intersect(bbox1)
346
+ if bbox2.get_area() / Rect(bbox1).get_area() >= 0.5:
347
+ column_matches.add(column_num)
348
+ already_taken = False
349
+ this_matches = []
350
+ for row_num in row_matches:
351
+ for column_num in column_matches:
352
+ this_matches.append((row_num, column_num))
353
+ if (row_num, column_num) in all_matches:
354
+ already_taken = True
355
+ if not already_taken:
356
+ for match in this_matches:
357
+ all_matches.add(match)
358
+ matches_by_spanning_cell.append(this_matches)
359
+ row_nums = [elem[0] for elem in this_matches]
360
+ column_nums = [elem[1] for elem in this_matches]
361
+ row_rect = Rect()
362
+ for row_num in row_nums:
363
+ row_rect.include_rect(rows[row_num]["bbox"])
364
+ column_rect = Rect()
365
+ for column_num in column_nums:
366
+ column_rect.include_rect(columns[column_num]["bbox"])
367
+ spanning_cell["bbox"] = list(row_rect.intersect(column_rect))
368
+ else:
369
+ matches_by_spanning_cell.append([])
370
+
371
+ return matches_by_spanning_cell
372
+
373
+
374
+ def output_to_dilatedbbox_grid(bboxes, labels, scores):
375
+ """
376
+ Compute the matrix of grid cell features for GriTS_Loc but using the raw predicted
377
+ and ground truth bounding boxes, not the post-processed boxes.
378
+
379
+ In the case of the model used in the PubTables-1M paper, these boxes are
380
+ *dilated*, which means they are larger than the actual ground truth boxes.
381
+
382
+ Computing GriTS_Loc with dilated bounding boxes is probably not very useful
383
+ for model comparison but could be useful for understanding the behavior of
384
+ an individual model.
385
+ """
386
+ rows = [{"bbox": bbox} for bbox, label in zip(bboxes, labels, strict=False) if label == 2]
387
+ columns = [{"bbox": bbox} for bbox, label in zip(bboxes, labels, strict=False) if label == 1]
388
+ spanning_cells = [
389
+ {"bbox": bbox, "score": 1} for bbox, label in zip(bboxes, labels, strict=False) if label in [4, 5]
390
+ ]
391
+ rows.sort(key=lambda x: x["bbox"][1] + x["bbox"][3])
392
+ columns.sort(key=lambda x: x["bbox"][0] + x["bbox"][2])
393
+ spanning_cells.sort(key=lambda x: -x["score"])
394
+ cell_grid = []
395
+ for _row_num, row in enumerate(rows):
396
+ column_grid = []
397
+ for _column_num, column in enumerate(columns):
398
+ bbox = Rect(row["bbox"]).intersect(column["bbox"])
399
+ column_grid.append(list(bbox))
400
+ cell_grid.append(column_grid)
401
+ matches_by_spanning_cell = get_spanning_cell_rows_and_columns(spanning_cells, rows, columns)
402
+ for matches, spanning_cell in zip(matches_by_spanning_cell, spanning_cells, strict=False):
403
+ for match in matches:
404
+ cell_grid[match[0]][match[1]] = spanning_cell["bbox"]
405
+
406
+ return cell_grid
407
+
408
+
409
+ def grits_top(true_relative_span_grid, pred_relative_span_grid):
410
+ """
411
+ Compute GriTS_Top given two matrices of cell relative spans.
412
+
413
+ For the cell at grid location (i,j), let a(i,j) be its rowspan,
414
+ let β(i,j) be its colspan, let p(i,j) be the minimum row it occupies,
415
+ and let θ(i,j) be the minimum column it occupies. Its relative span is
416
+ bounding box [θ(i,j)-j, p(i,j)-i, θ(i,j)-j+β(i,j), p(i,j)-i+a(i,j)].
417
+
418
+ It gives the size and location of the cell each grid cell belongs to
419
+ relative to the current grid cell location, in grid coordinate units.
420
+ Note that for a non-spanning cell this will always be [0, 0, 1, 1].
421
+ """
422
+ return factored_2dmss(true_relative_span_grid, pred_relative_span_grid, reward_function=iou)
423
+
424
+
425
+ def grits_loc(true_bbox_grid, pred_bbox_grid):
426
+ """
427
+ Compute GriTS_Loc given two matrices of cell bounding boxes.
428
+ """
429
+ return factored_2dmss(true_bbox_grid, pred_bbox_grid, reward_function=iou)
430
+
431
+
432
+ def grits_con(true_text_grid, pred_text_grid):
433
+ """
434
+ Compute GriTS_Con given two matrices of cell text strings.
435
+ """
436
+ return factored_2dmss(true_text_grid, pred_text_grid, reward_function=lcs_similarity)
437
+
438
+
439
+ def html_to_cells(table_html):
440
+ """
441
+ Parse an HTML representation of a table into a list of cells.
442
+ """
443
+ try:
444
+ tree = ET.fromstring(table_html)
445
+ except Exception as e:
446
+ print(e)
447
+ return None
448
+
449
+ table_cells = []
450
+
451
+ occupied_columns_by_row = defaultdict(set)
452
+ current_row = -1
453
+
454
+ # Get all td tags
455
+ stack = []
456
+ stack.append((tree, False))
457
+ while len(stack) > 0:
458
+ current, in_header = stack.pop()
459
+
460
+ if current.tag == "tr":
461
+ current_row += 1
462
+
463
+ if current.tag == "td" or current.tag == "th":
464
+ if "colspan" in current.attrib:
465
+ colspan = int(current.attrib["colspan"])
466
+ else:
467
+ colspan = 1
468
+ if "rowspan" in current.attrib:
469
+ rowspan = int(current.attrib["rowspan"])
470
+ else:
471
+ rowspan = 1
472
+ row_nums = list(range(current_row, current_row + rowspan))
473
+ try:
474
+ max_occupied_column = max(occupied_columns_by_row[current_row])
475
+ current_column = min(
476
+ set(range(max_occupied_column + 2)).difference(occupied_columns_by_row[current_row])
477
+ )
478
+ except Exception:
479
+ current_column = 0
480
+ column_nums = list(range(current_column, current_column + colspan))
481
+ for row_num in row_nums:
482
+ occupied_columns_by_row[row_num].update(column_nums)
483
+
484
+ cell_dict = {}
485
+ cell_dict["row_nums"] = row_nums
486
+ cell_dict["column_nums"] = column_nums
487
+ cell_dict["is_column_header"] = current.tag == "th" or in_header
488
+ cell_dict["cell_text"] = " ".join(current.itertext())
489
+ table_cells.append(cell_dict)
490
+
491
+ children = list(current)
492
+ for child in children[::-1]:
493
+ stack.append((child, in_header or current.tag == "th" or current.tag == "thead"))
494
+
495
+ return table_cells
496
+
497
+
498
+ def grits_from_html(true_html, pred_html):
499
+ """
500
+ Compute GriTS_Con and GriTS_Top for two HTML sequences.
501
+ """
502
+
503
+ metrics = {}
504
+
505
+ # Convert HTML to list of cells
506
+ true_cells = html_to_cells(true_html)
507
+ pred_cells = html_to_cells(pred_html)
508
+
509
+ # Convert lists of cells to matrices of grid cells
510
+ true_topology_grid = np.array(cells_to_relspan_grid(true_cells), dtype=object)
511
+ pred_topology_grid = np.array(cells_to_relspan_grid(pred_cells), dtype=object)
512
+ true_text_grid = np.array(cells_to_grid(true_cells, key="cell_text"), dtype=object)
513
+ pred_text_grid = np.array(cells_to_grid(pred_cells, key="cell_text"), dtype=object)
514
+
515
+ # Compute GriTS_Top (topology) for ground truth and predicted matrices
516
+ (
517
+ metrics["grits_top"],
518
+ metrics["grits_precision_top"],
519
+ metrics["grits_recall_top"],
520
+ metrics["grits_top_upper_bound"],
521
+ ) = grits_top(true_topology_grid, pred_topology_grid)
522
+
523
+ # Compute GriTS_Con (text content) for ground truth and predicted matrices
524
+ (
525
+ metrics["grits_con"],
526
+ metrics["grits_precision_con"],
527
+ metrics["grits_recall_con"],
528
+ metrics["grits_con_upper_bound"],
529
+ ) = grits_con(true_text_grid, pred_text_grid)
530
+
531
+ return metrics
@@ -0,0 +1,165 @@
1
+ """Cross-page TABLE formatting-consistency metric (parse).
2
+
3
+ Scores whether a parser formats tables consistently across pages and segments
4
+ them correctly. Reads GT from the test case's
5
+ ``metadata["cross_page_table_consistency"]`` (clusters -> per-member page+header,
6
+ the per-page-fair expected table count, and the logical count); operates on the
7
+ parser's own per-page tables from ``ParseOutput``.
8
+
9
+ Metrics (all 0..1, higher better):
10
+ - cross_page_table_col_consistency : fraction of multi-page clusters whose
11
+ tables agree on column count
12
+ - cross_page_table_header_row_consistency : same, for header-row count
13
+ - cross_page_table_header_similarity : mean pairwise header similarity in clusters
14
+ - cross_page_table_count_accuracy : 1 - |parser_tables - expected| / max(...),
15
+ where `expected` is the per-page-fair
16
+ count an ideal per-page parser can emit.
17
+
18
+ This is table-scoped (vs. future cross_page_section_* metrics).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ from collections import Counter
25
+ from difflib import SequenceMatcher
26
+ from typing import Any
27
+
28
+ from bs4 import BeautifulSoup
29
+
30
+ from parse_bench.schemas.evaluation import MetricValue
31
+
32
+ _WS = re.compile(r"\s+")
33
+
34
+
35
+ def _norm(s: str) -> str:
36
+ return _WS.sub(" ", (s or "").strip()).lower()
37
+
38
+
39
+ def _row_width(tr: Any) -> int:
40
+ w = 0
41
+ for c in tr.find_all(["td", "th"], recursive=False):
42
+ try:
43
+ w += int(c.get("colspan", 1) or 1)
44
+ except (TypeError, ValueError):
45
+ w += 1
46
+ return w
47
+
48
+
49
+ def _describe(tbl: Any) -> tuple[int, int, str]:
50
+ rows = tbl.find_all("tr")
51
+ thead = tbl.find("thead")
52
+ if thead is not None:
53
+ hrows = thead.find_all("tr", recursive=False)
54
+ else:
55
+ hrows = []
56
+ for tr in rows:
57
+ cells = tr.find_all(["td", "th"], recursive=False)
58
+ if cells and all(c.name == "th" for c in cells):
59
+ hrows.append(tr)
60
+ else:
61
+ break
62
+ header_ids = {id(r) for r in hrows}
63
+ body = [r for r in rows if id(r) not in header_ids]
64
+ widths = [w for w in (_row_width(r) for r in (body or rows)) if w > 0]
65
+ n_cols = 0
66
+ if widths:
67
+ c = Counter(widths)
68
+ n_cols = max(c, key=lambda w: (c[w], w))
69
+ header = " | ".join(
70
+ _norm(c.get_text(" ", strip=True)) for tr in hrows for c in tr.find_all(["td", "th"], recursive=False)
71
+ )
72
+ return n_cols, len(hrows), header
73
+
74
+
75
+ def _tables_by_page(parse_output: Any) -> dict[int, list[tuple[int, int, str]]]:
76
+ out: dict[int, list[tuple[int, int, str]]] = {}
77
+ for i, page in enumerate(getattr(parse_output, "pages", []) or []):
78
+ pg = int(getattr(page, "page_index", i)) + 1
79
+ md = getattr(page, "markdown", "") or ""
80
+ out[pg] = [_describe(t) for t in BeautifulSoup(md, "lxml").find_all("table")]
81
+ return out
82
+
83
+
84
+ def _select_cluster_tables(
85
+ members: list[Any], by_page: dict[int, list[tuple[int, int, str]]]
86
+ ) -> list[tuple[int, int, str]]:
87
+ """Pick one parser table per cluster member — the best header match on that
88
+ member's page.
89
+
90
+ We do NOT drop poor matches: a parser that mangles a recurring table's header
91
+ is exactly what this metric must catch, so the mangled table stays in and its
92
+ low similarity / differing structure shows the inconsistency. A member is
93
+ skipped only when the parser produced no tables at all on its page. Legacy GT
94
+ (members are page numbers) pools every table on those pages.
95
+ """
96
+ selected: list[tuple[int, int, str]] = []
97
+ for m in members:
98
+ if isinstance(m, dict):
99
+ cands = by_page.get(int(m["page"]), [])
100
+ if not cands:
101
+ continue
102
+ gt_header = str(m.get("header", ""))
103
+ selected.append(max(cands, key=lambda t: SequenceMatcher(None, t[2], gt_header).ratio()))
104
+ else:
105
+ selected.extend(by_page.get(int(m), []))
106
+ return selected
107
+
108
+
109
+ def compute_cross_page_table_metrics(parse_output: Any, gt: dict[str, Any]) -> list[MetricValue]:
110
+ by_page = _tables_by_page(parse_output)
111
+ # Count parser tables only on the GT's annotated pages.
112
+ pages_of_interest = {int(p) for p in (gt.get("logical_tables_per_page") or {})}
113
+ if pages_of_interest:
114
+ total = sum(len(by_page.get(p, [])) for p in pages_of_interest)
115
+ else:
116
+ total = sum(len(v) for v in by_page.values())
117
+ # Per-page-fair target: an ideal *per-page* parser cannot merge tables across a
118
+ # page break, and side-by-side fragments are naturally separate, so the
119
+ # achievable count is the de-segmented total plus the splits the GT merged
120
+ # back (logical + merge_fragments). Falls back to the logical count.
121
+ expected = int(gt.get("expected_page_table_count") or gt.get("logical_table_count") or 0)
122
+ count_acc = 1.0 - abs(total - expected) / max(total, expected, 1)
123
+
124
+ clusters = gt.get("clusters") or {}
125
+ col_ok = hrow_ok = n_multi = 0
126
+ sims: list[float] = []
127
+ details: list[str] = []
128
+ for name, members in clusters.items():
129
+ tbls = _select_cluster_tables(members, by_page)
130
+ if len(tbls) < 2:
131
+ continue
132
+ n_multi += 1
133
+ cols = {t[0] for t in tbls}
134
+ hrows = {t[1] for t in tbls}
135
+ col_ok += len(cols) == 1
136
+ hrow_ok += len(hrows) == 1
137
+ hdrs = [t[2] for t in tbls]
138
+ ratios = [
139
+ SequenceMatcher(None, hdrs[i], hdrs[j]).ratio() for i in range(len(hdrs)) for j in range(i + 1, len(hdrs))
140
+ ]
141
+ sim = sum(ratios) / len(ratios) if ratios else 1.0
142
+ sims.append(sim)
143
+ if len(cols) > 1 or len(hrows) > 1:
144
+ details.append(f"{name}: cols={sorted(cols)} hrows={sorted(hrows)} sim={sim:.2f}")
145
+
146
+ md = {"parser_tables": total, "expected_page_tables": expected, "n_multi_clusters": n_multi}
147
+ return [
148
+ MetricValue(
149
+ metric_name="cross_page_table_col_consistency",
150
+ value=col_ok / n_multi if n_multi else 1.0,
151
+ metadata=md,
152
+ details=details,
153
+ ),
154
+ MetricValue(
155
+ metric_name="cross_page_table_header_row_consistency",
156
+ value=hrow_ok / n_multi if n_multi else 1.0,
157
+ metadata=md,
158
+ ),
159
+ MetricValue(
160
+ metric_name="cross_page_table_header_similarity",
161
+ value=sum(sims) / len(sims) if sims else 1.0,
162
+ metadata=md,
163
+ ),
164
+ MetricValue(metric_name="cross_page_table_count_accuracy", value=count_acc, metadata=md),
165
+ ]