Datasets:

ArXiv:
License:
File size: 10,105 Bytes
b837da3
1e9a6e5
 
b837da3
1e9a6e5
b837da3
 
 
 
 
 
1e9a6e5
b837da3
 
 
 
1e9a6e5
b837da3
 
 
 
1e9a6e5
b837da3
 
 
1e9a6e5
 
 
 
 
 
b837da3
 
1e9a6e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b837da3
 
 
 
 
 
 
 
 
 
 
 
6c2a241
b837da3
 
1e9a6e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b837da3
1e9a6e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b837da3
1e9a6e5
b837da3
 
1e9a6e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b837da3
1e9a6e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b837da3
 
 
 
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
import argparse
import json
from pathlib import Path

from src.utils import read_file, check_data_validity, preprocess_merged_tables
from src.layout_evaluation import evaluate_layout
from src.table_evaluation import evaluate_table

def parse_args():
    parser = argparse.ArgumentParser(description="Arguments for evaluation")
    parser.add_argument(
        "--ref-path",
        type=str, required=True,
        help="Path to the ground truth file"
    )
    parser.add_argument(
        "--pred-path",
        type=str, required=True,
        help="Path to the prediction file"
    )
    parser.add_argument(
        "--ignore-classes-for-layout",
        type=list, default=["figure", "table", "chart"],
        help="List of layout classes to ignore. This is used only for layout evaluation."
    )
    parser.add_argument(
        "--filter-by-gt-area",
        action=argparse.BooleanOptionalAction,
        default=True,
        help="Filter out prediction text within GT ignored regions (default: True). Use --no-filter-by-gt-area to disable."
    )
    parser.add_argument(
        "--mode",
        type=str, default="all",
        choices=["layout", "table", "all", "speed"],
        help="Mode for evaluation (layout/table/all/speed). 'all' runs both layout and table evaluations. 'speed' evaluates latency and throughput."
    )
    parser.add_argument(
        "--min-match-score",
        type=float, default=0.1,
        help="Minimum match score for table evaluation"
    )
    parser.add_argument(
        "--max-workers",
        type=int, default=8,
        help="Maximum number of workers for table evaluation"
    )
    parser.add_argument(
        "--evaluate-merged-table",
        action=argparse.BooleanOptionalAction,
        default=False,
        help="Enable merged table evaluation mode. When enabled, tables specified in 'merged_tables' will be preprocessed and merged before evaluation (default: False)."
    )
    return parser.parse_args()


def main():
    args = parse_args()

    print("Arguments:")
    for k, v in vars(args).items():
        print(f"  {k}: {v}")
    print("-" * 50)

    label_data = read_file(args.ref_path)
    pred_data = read_file(args.pred_path)

    # Apply merged table preprocessing if enabled
    if args.evaluate_merged_table:
        print("Merged table evaluation mode enabled")
        print("Preprocessing ground truth data (merging tables)...")
        label_data = preprocess_merged_tables(label_data)
        
        # Check if prediction data has merged_tables key
        has_merged_tables_in_pred = any(
            isinstance(doc, dict) and "merged_tables" in doc
            for doc in pred_data.values()
        )
        
        if has_merged_tables_in_pred:
            print("Preprocessing prediction data (merging tables)...")
            pred_data = preprocess_merged_tables(pred_data)
        else:
            print("Prediction data does not contain 'merged_tables' key - skipping preprocessing (assuming already merged)")

    valid_keys, error_keys, missing_keys = check_data_validity(label_data, pred_data)
    
    # Report data quality statistics
    total_gt_samples = len(label_data)
    print(f"Total GT samples: {total_gt_samples}")
    print(f"Valid predictions: {len(valid_keys)}")
    print(f"Predictions with errors: {len(error_keys)}")
    print(f"Missing predictions: {len(missing_keys)}")
    
    if error_keys:
        print(f"\nSkipping {len(error_keys)} samples with errors:")
        for key in error_keys[:5]:  # Show first 5
            print(f"  - {key}")
        if len(error_keys) > 5:
            print(f"  ... and {len(error_keys) - 5} more")
    
    if missing_keys:
        print(f"\nWarning: {len(missing_keys)} samples missing from predictions")
    
    if not valid_keys:
        raise ValueError("No valid predictions found. Cannot perform evaluation.")
    
    print("-" * 50)
    
    # Filter data to only include valid keys
    filtered_label_data = {k: label_data[k] for k in valid_keys}
    filtered_pred_data = {k: pred_data[k] for k in valid_keys}

    # Prepare output file path
    pred_path_obj = Path(args.pred_path)
    eval_output_path = pred_path_obj.with_suffix(".eval.json")

    # Collect evaluation results
    eval_results = {
        "ref_path": args.ref_path,
        "pred_path": args.pred_path,
        "mode": args.mode,
        "evaluate_merged_table": args.evaluate_merged_table,
        "data_statistics": {
            "total_gt_samples": total_gt_samples,
            "valid_predictions": len(valid_keys),
            "error_predictions": len(error_keys),
            "missing_predictions": len(missing_keys),
        },
        "per_image_results": {}
    }

    if args.mode == "layout" or args.mode == "all":
        if args.mode == "all":
            print("=" * 50)
            print("Layout Evaluation")
            print("=" * 50)
        score, per_image_layout_scores = evaluate_layout(
            filtered_label_data, filtered_pred_data,
            ignore_classes=args.ignore_classes_for_layout,
            filter_by_gt_area=args.filter_by_gt_area,
        )
        print(f"NID Score: {score:.4f}")
        eval_results["layout"] = {
            "nid_score": score,
            "ignore_classes": args.ignore_classes_for_layout,
            "filter_by_gt_area": args.filter_by_gt_area,
        }
        
        # Merge per-image layout scores into per_image_results
        for image_key, scores_dict in per_image_layout_scores.items():
            if image_key not in eval_results["per_image_results"]:
                eval_results["per_image_results"][image_key] = {}
            eval_results["per_image_results"][image_key]["layout"] = scores_dict
        
        if args.filter_by_gt_area:
            print("Note: Spatial filtering by GT area is enabled (predictions within GT ignored regions are filtered)")
        if args.mode == "all":
            print()

    if args.mode == "table" or args.mode == "all":
        if args.mode == "all":
            print("=" * 50)
            print("Table Evaluation")
            print("=" * 50)
        table_f1_score, teds_score, teds_s_score, per_image_table_scores = evaluate_table(
            filtered_label_data, filtered_pred_data,
            min_match_score=args.min_match_score,
            max_workers=args.max_workers,
        )
        print(f"Table F1 Score: {table_f1_score:.4f}")
        print(f"TEDS-S Score: {teds_s_score:.4f}")
        print(f"TEDS Score: {teds_score:.4f}")
        eval_results["table"] = {
            "table_f1_score": table_f1_score,
            "teds_score": teds_score,
            "teds_s_score": teds_s_score,
            "min_match_score": args.min_match_score,
        }
        
        # Merge per-image table scores into per_image_results
        for image_key, scores_dict in per_image_table_scores.items():
            if image_key not in eval_results["per_image_results"]:
                eval_results["per_image_results"][image_key] = {}
            eval_results["per_image_results"][image_key]["table"] = scores_dict

    if args.mode == "speed" or args.mode == "all":
        if args.mode == "all":
            print("=" * 50)
            print("Speed Evaluation")
            print("=" * 50)
        
        # Calculate latency and throughput from time_sec fields (including errors)
        total_time = 0.0
        count = 0
        
        for image_key, image_data in pred_data.items():
            if image_key == "_metadata":
                continue  # Skip metadata entry
            if isinstance(image_data, dict) and "time_sec" in image_data:
                total_time += image_data["time_sec"]
                count += 1
        
        if count > 0:
            avg_latency = total_time / count
            sequential_throughput = 60.0 / avg_latency if avg_latency > 0 else 0.0
            
            print(f"Average Latency: {avg_latency:.4f} sec/image")
            print(f"Sequential Throughput: {sequential_throughput:.2f} images/min (based on avg latency)")
            print(f"Total Images: {count}")
            print(f"Sum of Latencies: {total_time:.2f} sec")
            
            eval_results["speed"] = {
                "avg_latency_sec": avg_latency,
                "sequential_throughput_per_minute": sequential_throughput,
                "total_images": count,
                "sum_of_latencies_sec": total_time,
            }
            
            # Report concurrent throughput from inference metadata if available
            metadata = pred_data.get("_metadata")
            if metadata and "total_elapsed_time_sec" in metadata:
                elapsed_time = metadata["total_elapsed_time_sec"]
                concurrent_limit = metadata.get("concurrent_limit")
                num_files = metadata.get("num_files", count)
                concurrent_throughput = (num_files / elapsed_time) * 60 if elapsed_time > 0 else 0.0
                
                print(f"\nConcurrent Throughput: {concurrent_throughput:.2f} images/min (wall-clock time)")
                print(f"  - Elapsed Time: {elapsed_time:.2f} sec")
                if concurrent_limit:
                    print(f"  - Concurrency: {concurrent_limit}")
                
                eval_results["speed"]["concurrent_throughput_per_minute"] = concurrent_throughput
                eval_results["speed"]["elapsed_time_sec"] = elapsed_time
                eval_results["speed"]["concurrent_limit"] = concurrent_limit
        else:
            print("Warning: No time_sec fields found in prediction data")
            eval_results["speed"] = {
                "avg_latency_sec": None,
                "sequential_throughput_per_minute": None,
                "total_images": 0,
                "sum_of_latencies_sec": 0.0,
            }

    # Save evaluation results to JSON file
    with open(eval_output_path, "w", encoding="utf-8") as f:
        json.dump(eval_results, f, indent=2, ensure_ascii=False)
    
    print(f"\nEvaluation results saved to: {eval_output_path}")


if __name__ == "__main__":
    main()