File size: 4,143 Bytes
0fa28ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import argparse
import json
import math
import sys
from pathlib import Path

from finixdoc_md_eval.omnidocbench_adapter import evaluate_md_dirs


def parse_args():
    parser = argparse.ArgumentParser(
        description="Evaluate Markdown OCR/parsing results with text, reading-order, and table metrics."
    )
    parser.add_argument("--gt_dir", required=True, help="Directory containing ground-truth .md files.")
    parser.add_argument("--pred_dir", required=True, help="Directory containing prediction .md files.")
    parser.add_argument(
        "--output_json",
        default="eval_result.json",
        help="Path to write metric results. Default: eval_result.json",
    )
    parser.add_argument(
        "--allow_name_mismatch",
        action="store_true",
        help="Do not fail when gt/pred .md file names differ. Missing predictions are scored as empty.",
    )
    return parser.parse_args()


def md_names(path):
    return {p.name for p in Path(path).iterdir() if p.is_file() and p.suffix == ".md"}


def validate_inputs(gt_dir, pred_dir, allow_name_mismatch=False):
    gt_path = Path(gt_dir)
    pred_path = Path(pred_dir)
    if not gt_path.is_dir():
        raise ValueError(f"GT directory does not exist: {gt_path}")
    if not pred_path.is_dir():
        raise ValueError(f"Prediction directory does not exist: {pred_path}")

    gt_files = md_names(gt_path)
    pred_files = md_names(pred_path)
    if not gt_files:
        raise ValueError(f"No .md files found in GT directory: {gt_path}")
    if not pred_files:
        raise ValueError(f"No .md files found in prediction directory: {pred_path}")

    missing = sorted(gt_files - pred_files)
    extra = sorted(pred_files - gt_files)
    if not allow_name_mismatch and (missing or extra):
        message = [
            "GT and prediction .md file names must match.",
            f"GT files: {len(gt_files)}",
            f"Prediction files: {len(pred_files)}",
        ]
        if missing:
            message.append(f"Missing predictions: {len(missing)}; first: {missing[0]}")
        if extra:
            message.append(f"Unexpected predictions: {len(extra)}; first: {extra[0]}")
        raise ValueError(" ".join(message))

    return {
        "gt_files": len(gt_files),
        "pred_files": len(pred_files),
        "missing_predictions": len(missing),
        "unexpected_predictions": len(extra),
    }


def rounded_metrics(metrics):
    clean = {}
    for key, value in metrics.items():
        if isinstance(value, float):
            clean[key] = None if math.isnan(value) else round(value, 6)
        else:
            clean[key] = value
    clean["score"] = clean["overall"]
    return clean


def main():
    args = parse_args()
    try:
        input_summary = validate_inputs(args.gt_dir, args.pred_dir, args.allow_name_mismatch)
        metrics = evaluate_md_dirs(args.gt_dir, args.pred_dir)
        result = {
            "success": True,
            "metrics": rounded_metrics(metrics),
            "inputs": input_summary,
        }
        output_path = Path(args.output_json)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        output_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")

        print("FinixDoc Markdown Evaluation")
        print(f"  samples: {metrics['num_samples']}")
        print(f"  text_block_Edit_dist: {metrics['text_block_Edit_dist']:.6f}")
        print(f"  reading_order_Edit_dist: {metrics['reading_order_Edit_dist']:.6f}")
        print(f"  table_TEDS: {metrics['table_TEDS']:.6f}")
        print(f"  overall: {metrics['overall']:.6f}")
        print(f"  result_json: {output_path}")
    except Exception as exc:
        result = {
            "success": False,
            "error": str(exc),
        }
        output_path = Path(args.output_json)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        output_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
        print(f"Evaluation failed: {exc}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()