| 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) |
|
|
| |
| 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) |
| |
| |
| 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) |
| |
| |
| 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]: |
| 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) |
| |
| |
| filtered_label_data = {k: label_data[k] for k in valid_keys} |
| filtered_pred_data = {k: pred_data[k] for k in valid_keys} |
|
|
| |
| pred_path_obj = Path(args.pred_path) |
| eval_output_path = pred_path_obj.with_suffix(".eval.json") |
|
|
| |
| 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, |
| } |
| |
| |
| 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, |
| } |
| |
| |
| 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) |
| |
| |
| total_time = 0.0 |
| count = 0 |
| |
| for image_key, image_data in pred_data.items(): |
| if image_key == "_metadata": |
| continue |
| 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, |
| } |
| |
| |
| 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, |
| } |
|
|
| |
| 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() |
|
|