File size: 6,858 Bytes
c5e5c45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
"""Export the existing sample splits as self-contained Hugging Face Parquet files.

Only main images are embedded. The complete original sample is preserved in
sample_json; its evidence paths refer to the full release archive. This command
does not upload files or change source licenses or redistribution status.
"""
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import tempfile

import pyarrow as pa
import pyarrow.parquet as pq
from datasets import Features, Image, List, Value


ROOT = Path(__file__).resolve().parents[1]
SPLITS = ("train", "validation", "test")
TEXT = Value("string")
TEXT_LIST = List(TEXT)
FEATURES = Features({
    "id": TEXT,
    "image": Image(),
    "labels_zh": TEXT_LIST,
    "caption_zh": TEXT,
    "modality": TEXT,
    "labels": TEXT_LIST,
    "primary_label": TEXT,
    "width": Value("int32"),
    "height": Value("int32"),
    "source_id": TEXT,
    "source_url": TEXT,
    "source_license": TEXT,
    "rights_status": TEXT,
    "split": TEXT,
    "split_group": TEXT,
    "root_cause": {
        "status": TEXT,
        "possible_causes_zh": TEXT_LIST,
        "confirmation_checks_zh": TEXT_LIST,
        "limitation_zh": TEXT,
    },
    "repair": {
        "status": TEXT,
        "steps_zh": TEXT_LIST,
        "verification_zh": TEXT_LIST,
        "limitation_zh": TEXT,
    },
    "sample_json": TEXT,
})


def read_jsonl(path):
    with path.open(encoding="utf-8") as stream:
        return [json.loads(line) for line in stream if line.strip()]


def digest(path):
    checksum = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            checksum.update(block)
    return checksum.hexdigest()


def export_row(sample, root):
    image = (root / sample["image"]).read_bytes()
    if hashlib.sha256(image).hexdigest() != sample["sha256"]:
        raise ValueError(f"Image hash mismatch: {sample['id']}")
    row = {key: sample[key] for key in (
        "id", "labels_zh", "caption_zh", "labels", "primary_label",
        "width", "height", "split", "split_group",
    )}
    row["image"] = {"bytes": image, "path": None}
    source = sample["source"]
    for column, source_key in (
        ("modality", "modality"), ("source_id", "source_id"),
        ("source_url", "page_url"), ("source_license", "license"),
        ("rights_status", "rights_status"),
    ):
        row[column] = source[source_key]
    for column in ("root_cause", "repair"):
        row[column] = {key: sample[column].get(key) for key in FEATURES[column]}
    row["sample_json"] = json.dumps(sample, ensure_ascii=False, separators=(",", ":"))
    return row


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=ROOT)
    parser.add_argument("--out", type=Path, default=Path("hf_data"),
                        help="New output directory, relative to --root unless absolute.")
    parser.add_argument("--rows-per-shard", type=int, default=1000)
    args = parser.parse_args()
    if args.rows_per_shard < 1:
        parser.error("--rows-per-shard must be positive")
    root = args.root.resolve()
    output = args.out if args.out.is_absolute() else root / args.out
    if output.exists():
        parser.error("Output already exists; choose a new --out to preserve earlier exports.")

    annotations = root / "data/annotations"
    samples = read_jsonl(annotations / "samples.jsonl")
    by_id = {sample["id"]: sample for sample in samples}
    if len(by_id) != len(samples):
        raise ValueError("Duplicate sample IDs in samples.jsonl")
    split_rows = {}
    seen = set()
    groups = {}
    for split in SPLITS:
        rows = read_jsonl(annotations / f"{split}.jsonl")
        if not rows:
            raise ValueError(f"Empty split: {split}")
        for row in rows:
            if row["id"] in seen or row != by_id.get(row["id"]) or row["split"] != split:
                raise ValueError(f"Inconsistent or duplicate split record: {row['id']}")
            seen.add(row["id"])
            group = row["split_group"]
            if groups.setdefault(group, split) != split:
                raise ValueError(f"Group appears in multiple splits: {group}")
        split_rows[split] = rows
    if seen != set(by_id):
        raise ValueError("Split files do not cover every sample")

    manifest = {
        "format": "parquet_with_embedded_main_images",
        "config_name": "default",
        "splits": {split: len(rows) for split, rows in split_rows.items()},
        "source_samples_sha256": digest(annotations / "samples.jsonl"),
        "source_split_sha256": {
            split: digest(annotations / f"{split}.jsonl") for split in SPLITS
        },
        "sample_rights_status_counts": dict(Counter(
            row["source"]["rights_status"] for row in samples
        )),
        "note": "Original licenses and rights statuses are unchanged. Main images are embedded; "
                "sample_json preserves complete annotations and evidence paths into the release archive.",
        "files": [],
    }
    output.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=".hf-export-", dir=output.parent) as temp:
        staging = Path(temp) / "hf_data"
        staging.mkdir()
        for split, rows in split_rows.items():
            count = (len(rows) + args.rows_per_shard - 1) // args.rows_per_shard
            for index, start in enumerate(range(0, len(rows), args.rows_per_shard)):
                chunk = rows[start:start + args.rows_per_shard]
                path = staging / f"{split}-{index:05d}-of-{count:05d}.parquet"
                with pq.ParquetWriter(path, FEATURES.arrow_schema, compression="zstd",
                                      write_page_index=True) as writer:
                    # Small row groups keep the viewer's first-page reads bounded.
                    for offset in range(0, len(chunk), 32):
                        batch = [export_row(row, root) for row in chunk[offset:offset + 32]]
                        table = pa.Table.from_pylist(batch, schema=FEATURES.arrow_schema)
                        writer.write_table(table, row_group_size=32)
                manifest["files"].append({
                    "path": path.name, "split": split, "rows": len(chunk),
                    "bytes": path.stat().st_size, "sha256": digest(path),
                })
                print(f"Exported {path.name}: {len(chunk)} rows", flush=True)
        (staging / "manifest.json").write_text(
            json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
        )
        staging.rename(output)
    print(json.dumps({"output": str(output), "splits": manifest["splits"]}, ensure_ascii=False))


if __name__ == "__main__":
    main()