Download scripts/export_huggingface.py from dezoe/pcb-defect-multi-modal-dataset: direct link, hf CLI and curl.
- Browser
- Download file 6.86 kB
-
https://huggingface.co/datasets/dezoe/pcb-defect-multi-modal-dataset/resolve/main/scripts/export_huggingface.py
- Command line
-
hf download hf://datasets/dezoe/pcb-defect-multi-modal-dataset/scripts/export_huggingface.py
-
curl -L -o export_huggingface.py https://huggingface.co/datasets/dezoe/pcb-defect-multi-modal-dataset/resolve/main/scripts/export_huggingface.py
6.86 kB
| """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() | |