File size: 5,212 Bytes
693bf28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()