Micro_component_dataset / push_to_hf.py
FaustDerLegende's picture
Upload folder using huggingface_hub (part 84)
693bf28 verified
Raw History Blame Contribute Delete
5.21 kB
"""Hugging Face Hub Dataset Uploader for E-Waste PCB Component Purity Index.
Uploads the 8,190-image YOLO/COCO object detection dataset directly to Hugging Face Hub.
Usage:
.venv/bin/python push_to_hf.py --repo-id <hf-username>/ewaste-pcb-component-purity
"""
from __future__ import annotations
import argparse
import os
import shutil
import sys
from pathlib import Path
def prepare_hf_export_folder(export_dir: Path) -> Path:
"""Stage dataset files and metadata into Hugging Face export directory."""
export_dir.mkdir(parents=True, exist_ok=True)
root_dir = Path(__file__).resolve().parent
splits_src = root_dir / "splits"
if not splits_src.exists():
raise FileNotFoundError(f"Splits directory not found at {splits_src}. Run 'python scraper.py split' first.")
# Copy splits folder (train, val, test, data.yaml)
dst_splits = export_dir / "data"
if dst_splits.exists():
shutil.rmtree(dst_splits)
shutil.copytree(splits_src, dst_splits)
# Write Hugging Face Dataset Card README.md
dataset_card_content = """---
language:
- en
license: cc-by-4.0
tags:
- computer-vision
- object-detection
- yolo
- ewaste
- pcb
- recycling
- hardware-fraud
size_categories:
- 1K<n<10K
task_categories:
- object-detection
task_ids:
- bounding-box-object-detection
dataset_info:
features:
- name: image
dtype: image
- name: label
dtype: string
---
# 🔌 E-Waste PCB Component Purity & Cannibalization Dataset
This dataset contains **8,190 normalized high-resolution PCB images** with **6,377 fine-grained object detection bounding boxes** designed for real-time edge AI cannibalization detection in e-waste recycling platforms.
## 📊 Dataset Splits
| Split | Images & Bounding Box Pairs | Ratio |
| :--- | :--- | :--- |
| **Train** | **5,733 images** | $70\%$ |
| **Validation** | **1,228 images** | $15\%$ |
| **Test** | **1,229 images** | $15\%$ |
| **Total** | **8,190 images** | $100\%$ |
---
## 🏷️ 7 Fine-Grained Component Taxonomy
| Class ID | Class Name | Description |
| :--- | :--- | :--- |
| `0` | `cpu_socket` | LGA, PGA, or ZIF processor socket footprints |
| `1` | `gold_finger` | Gold-plated edge connector contacts (PCIe, RAM contacts) |
| `2` | `ic_chip` | Packaged ICs and BGA microchips |
| `3` | `tantalum_capacitor` | SMD tantalum capacitors (molded yellow/black/orange) |
| `4` | `forcibly_desoldered_pad` | Exposed pads with jagged solder, blowtorch marks, torn traces (**fraud signal**) |
| `5` | `factory_unpopulated_pad` | Clean silkscreen outline with smooth solder dots left empty (**NOT fraud**) |
| `6` | `occluded_region` | Footprints obscured by heatsinks, metal shielding, or heavy dust |
---
## 💻 Usage with Ultralytics YOLOv8
```python
from ultralytics import YOLO
# Load pre-trained model backbone
model = YOLO("yolov8n.pt")
# Fine-tune on Hugging Face dataset
model.train(data="data/data.yaml", epochs=50, imgsz=960, copy_paste=0.8, cls=2.5)
```
## ⚖️ License & Attribution
Released under **Creative Commons Attribution 4.0 International (CC BY 4.0)** for e-waste recycling research and component purity index assaying.
"""
(export_dir / "README.md").write_text(dataset_card_content, encoding="utf-8")
print(f"Staged Hugging Face dataset package at {export_dir}")
return export_dir
def push_to_huggingface(repo_id: str, token: str | None = None, private: bool = False):
"""Upload staged dataset package to Hugging Face Hub using HfApi."""
try:
from huggingface_hub import HfApi
except ImportError:
print("Error: huggingface_hub library is required. Install via 'pip install huggingface_hub'")
sys.exit(1)
export_dir = Path("huggingface_export").resolve()
prepare_hf_export_folder(export_dir)
api = HfApi(token=token or os.getenv("HF_TOKEN"))
print(f"Creating/verifying Hugging Face dataset repo '{repo_id}'...")
api.create_repo(repo_id=repo_id, repo_type="dataset", private=private, exist_ok=True)
print(f"Uploading dataset files from {export_dir} to Hugging Face Hub repo '{repo_id}'...")
api.upload_folder(
folder_path=str(export_dir),
repo_id=repo_id,
repo_type="dataset",
commit_message="Upload E-Waste PCB Component Purity 8.1k dataset with YOLO labels",
)
print(f"SUCCESS! Dataset published to https://huggingface.co/datasets/{repo_id}")
def main():
parser = argparse.ArgumentParser(description="Push E-Waste PCB Dataset to Hugging Face Hub")
parser.add_argument("--repo-id", type=str, required=True, help="Target HF repository ID (e.g. username/ewaste-pcb-purity)")
parser.add_argument("--token", type=str, help="Hugging Face User Access Token (or set HF_TOKEN env var)")
parser.add_argument("--private", action="store_true", help="Set repository to private")
parser.add_argument("--stage-only", action="store_true", help="Only stage export files locally without uploading")
args = parser.parse_args()
if args.stage_only:
prepare_hf_export_folder(Path("huggingface_export").resolve())
else:
push_to_huggingface(args.repo_id, token=args.token, private=args.private)
if __name__ == "__main__":
main()