ConfBench / load_dataset.py
mmiakashs's picture
Loader: resolve documents under assets/
e2f4b13 verified
Raw
History Blame Contribute Delete
5.31 kB
"""
FCC Invoices Verified Augmented - Dataset Loader
Usage:
from huggingface_hub import snapshot_download
from load_dataset import FCCInvoicesDataset
local_dir = snapshot_download(repo_id="amazon/ConfBench", repo_type="dataset")
ds = FCCInvoicesDataset(local_dir=local_dir)
# Iterate all (document, pipeline) pairs
for sample in ds:
print(sample["doc_id"], sample["pipeline_name"])
gt = sample["ground_truth"]["inference_result"]
print(gt["Agency"], gt["GrossTotal"])
# Get the local path to a single noisy PDF
path = ds.pdf_path(doc_id="033f718b16cb597c065930410752c294", pipeline_name="custom13")
Requirements:
pip install huggingface_hub
"""
import json
from pathlib import Path
from typing import Iterator
PIPELINES = [
"default", "archetype3", "archetype4", "archetype7", "archetype9",
"archetype10", "archetype11", "custom12", "custom13", "custom14",
"custom15", "custom16", "custom17", "custom18", "custom19",
"custom20", "custom21", "custom22",
]
class FCCInvoicesDataset:
"""Lazy iterator over all (document, pipeline) pairs in a local ConfBench checkout."""
def __init__(self, local_dir: str):
self.local_dir = Path(local_dir)
# Documents live under assets/; accept a checkout root or the assets dir itself.
if (self.local_dir / "assets").is_dir():
self.assets_dir = self.local_dir / "assets"
else:
self.assets_dir = self.local_dir
self._doc_ids: list[str] | None = None
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def doc_ids(self) -> list[str]:
"""Return all document IDs (md5 hashes)."""
if self._doc_ids is None:
self._doc_ids = sorted(
p.name for p in self.assets_dir.iterdir()
if p.is_dir() and (p / "metadata.json").exists()
)
return self._doc_ids
def load_ground_truth(self, doc_id: str) -> dict:
"""Read and parse gt.json for a document."""
return json.loads((self.assets_dir / doc_id / "gt.json").read_text())
def load_metadata(self, doc_id: str) -> dict:
"""Read and parse metadata.json (pipeline manifest) for a document."""
return json.loads((self.assets_dir / doc_id / "metadata.json").read_text())
def pdf_path(self, doc_id: str, pipeline_name: str) -> str:
"""Return the local path to a noisy PDF."""
return str(self.assets_dir / doc_id / pipeline_name / f"{pipeline_name}_noisy.pdf")
def original_pdf_path(self, doc_id: str) -> str:
"""Return the local path to the original clean PDF."""
return str(self.assets_dir / doc_id / "original.pdf")
def get_sample(self, doc_id: str, pipeline_name: str) -> dict:
"""Return a single sample dict."""
gt = self.load_ground_truth(doc_id)
return {
"doc_id": doc_id,
"pipeline_name": pipeline_name,
"pipeline_type": "archetype" if not pipeline_name.startswith("custom") else "custom",
"original_pdf": self.original_pdf_path(doc_id),
"noisy_pdf": self.pdf_path(doc_id, pipeline_name),
"ground_truth": gt,
}
def __iter__(self) -> Iterator[dict]:
"""Yield one dict per (document, pipeline) pair."""
for doc_id in self.doc_ids():
meta = self.load_metadata(doc_id)
gt = self.load_ground_truth(doc_id)
for pipeline in meta.get("pipelines", []):
name = pipeline["pipeline_name"]
yield {
"doc_id": doc_id,
"pipeline_name": name,
"pipeline_type": "archetype" if not name.startswith("custom") else "custom",
"original_pdf": self.original_pdf_path(doc_id),
"noisy_pdf": self.pdf_path(doc_id, name),
"ground_truth": gt,
}
def __len__(self) -> int:
return len(self.doc_ids()) * len(PIPELINES)
# ------------------------------------------------------------------
# CLI convenience
# ------------------------------------------------------------------
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="FCC Invoices dataset helper")
parser.add_argument("--local-dir", default=".", help="Path to local ConfBench checkout")
sub = parser.add_subparsers(dest="cmd")
p_list = sub.add_parser("list", help="List all document IDs")
p_gt = sub.add_parser("gt", help="Print ground truth for a document")
p_gt.add_argument("doc_id")
p_path = sub.add_parser("path", help="Print the local path to a noisy PDF")
p_path.add_argument("doc_id")
p_path.add_argument("pipeline_name")
args = parser.parse_args()
ds = FCCInvoicesDataset(local_dir=args.local_dir)
if args.cmd == "list":
for d in ds.doc_ids():
print(d)
elif args.cmd == "gt":
print(json.dumps(ds.load_ground_truth(args.doc_id), indent=2))
elif args.cmd == "path":
print(ds.pdf_path(args.doc_id, args.pipeline_name))
else:
parser.print_help()