File size: 4,463 Bytes
e593510 | 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 | #!/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
python tools/pack.py --benchmark parsebench-2 --pipeline datalab_accurate \
output/parsebench-2 results/datalab_accurate
For ParseBench-2 the input is the run's output/parsebench-2 folder; only its
``<subset>/<pipeline>/`` folders are read.
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, drop_unscored_layout_items, minimal_record, write_jsonl # noqa: E402
def iter_result_files(root: str, pipeline_dir: str = ""):
"""Every ``*.result.json`` under ``root``.
With ``pipeline_dir``, only the ones under ``<root>/<category>/<pipeline_dir>/``.
"""
for dirpath, dirnames, filenames in os.walk(root):
rel = os.path.relpath(dirpath, root).split(os.sep)
if pipeline_dir and (len(rel) < 2 or rel[1] != pipeline_dir):
if len(rel) >= 2:
dirnames[:] = []
continue
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 = []
pipeline_dir = args.pipeline if spec.get("output_layout") == "category/pipeline" else ""
for path in iter_result_files(args.input_dir, pipeline_dir):
with open(path, 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(f"{path}: example_id {example_id!r} is not '<category>/<stem>'")
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(f"{path}: {exc}")
continue
by_category[category].append(drop_unscored_layout_items(args.benchmark, category, 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(f"no result files found under {args.input_dir}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
|