File size: 5,310 Bytes
514b890
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2f4b13
 
 
 
 
514b890
 
 
 
 
 
 
 
 
 
e2f4b13
514b890
 
 
 
 
 
e2f4b13
514b890
 
 
e2f4b13
514b890
 
 
e2f4b13
514b890
 
 
e2f4b13
514b890
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""
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()