File size: 3,658 Bytes
4f24d15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Pack a local ``output/<pipeline>/`` tree of ``*.result.json`` files into the
published JSONL format, keeping only the fields the public evaluators use.

    python tools/pack.py --benchmark parsebench --pipeline datalab_accurate \
        output/datalab_accurate results/datalab_accurate

Every ``request.example_id`` must already be a public id, ``<category>/<stem>``,
where ``<stem>`` is the document file name without extension. Run
``tools/validate.py`` on the result before opening a pull request.
Python 3.9+, standard library only.
"""

import argparse
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from hfresults_common import BENCHMARKS, minimal_record, write_jsonl  # noqa: E402


def iter_result_files(root: str):
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if not d.startswith(".") and not d.endswith(".images")]
        for name in sorted(filenames):
            if name.endswith(".result.json"):
                yield os.path.join(dirpath, name)


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--benchmark", required=True, choices=sorted(BENCHMARKS))
    parser.add_argument("--pipeline", required=True, help="public pipeline name (registered in the public package)")
    parser.add_argument("input_dir", help="output/<pipeline> folder with <category>/<stem>.result.json files")
    parser.add_argument("results_dir", help="destination results/<pipeline> folder")
    parser.add_argument(
        "--keep-provider-raw-for-layout",
        action="store_true",
        help="keep the provider payload (minus harness keys) in layout records; needed by some layout adapters",
    )
    args = parser.parse_args()

    spec = BENCHMARKS[args.benchmark]
    by_category = {c: [] for c in spec["categories"]}
    problems = []
    for path in iter_result_files(args.input_dir):
        with open(path, "r", encoding="utf-8") as fh:
            result = json.load(fh)
        example_id = str(result.get("request", {}).get("example_id", ""))
        category, _, stem = example_id.partition("/")
        if category not in by_category or not stem:
            problems.append("%s: example_id %r is not '<category>/<stem>'" % (path, example_id))
            continue
        source = "" if spec["product_type"] == "parse" else stem + ".pdf"
        try:
            record = minimal_record(
                result,
                public_pipeline=args.pipeline,
                public_id=example_id,
                product_type=spec["product_type"],
                source_file_path=source,
                keep_provider_raw=(category == "layout" and args.keep_provider_raw_for_layout),
            )
        except (KeyError, ValueError, TypeError) as exc:
            problems.append("%s: %s" % (path, exc))
            continue
        by_category[category].append(record)

    if problems:
        for problem in problems:
            print("ERROR " + problem, file=sys.stderr)
        return 1
    os.makedirs(args.results_dir, exist_ok=True)
    total = 0
    for category, records in by_category.items():
        if not records:
            continue
        write_jsonl(os.path.join(args.results_dir, category + ".jsonl"), records)
        print("%s: %d documents" % (category, len(records)))
        total += len(records)
    if not total:
        print("no result files found under %s" % args.input_dir, file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())