File size: 27,283 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# E-Waste Image Dataset Pipeline: Revised Plan (v2)

## 0. What changed from v1

v1 framed the work as a scraping problem. v2 treats it as a **dataset-quality problem** in which scraping is one input. The main changes:

| Area | v1 | v2 |
| :--- | :--- | :--- |
| Class definitions | Scrape folders and annotation classes disagreed | One taxonomy defined first; queries derived from it |
| Deduplication | MD5 only (byte-identical) | Exact hash + perceptual hash (flip-aware) + embedding clusters, global across classes |
| Aspect-ratio filter | Discarded > 3:1 (removes RAM/edge-finger images) | Flag > 3:1, discard only > 6:1 |
| Min resolution | 250 px | Short side β‰₯ 480 px, long side β‰₯ 800 px |
| Relevance | None | CLIP zero-shot filter + manual review queue |
| Domain gap | Web images only | Real-world capture set, held-out real-world test split |
| Splits | Random train/val | Cluster-aware train/val + separate real-world test |
| Small objects | Not addressed | Resolution policy, `imgsz=1280`, tiling/two-stage inference |
| Image handling | `verify()` only, JPEG q90 | `verify()` + `load()`, EXIF fix, alpha compositing, q95, originals preserved |
| Resilience | Claimed backoff/fallback that `icrawler` lacks | Custom downloader with retries, backoff, per-domain rate limits |
| Provenance | Sequential filenames | Hash filenames + SQLite manifest, resumable stages |
| Targets & metrics | None | Per-class image/instance targets, evaluation plan |
| BIS | Undefined | Proposed definition (needs sign-off) |

---

## 1. Objective & Scope

Build a repeatable pipeline that produces a clean, deduplicated, well-documented image dataset for a YOLO detector that finds components on PCBs and supports an on-device **Board Integrity Score (BIS)** in a mobile app.

**In scope:** collection, validation, normalization, deduplication, relevance filtering, manifesting, splitting, annotation guidelines, training/evaluation plan, export.
**Out of scope for this document:** app UI, backend, pricing/valuation logic beyond BIS inputs.

### Success criteria

- β‰₯ 1,500 labeled images per class and β‰₯ 10,000 labeled instances per class in the training set (common YOLO guideline; revisit after the first training run).
- Zero train/val/test leakage (no near-duplicate or same-board pairs across splits).
- β‰₯ 40% of the final set is "in-the-wild" imagery (dirty, cluttered, phone-shot), not clean listing photos.
- Held-out real-world test set of β‰₯ 300 images that is never used for tuning.
- Every image traceable to its source URL, query, and processing history via the manifest.

---

## 2. Phase 0: Decisions to lock before writing code

### 2.1 Detection taxonomy (fixes the v1 class mismatch)

Define **object classes** (what YOLO detects) separately from **image-level tags** (metadata used for search and stratification).

**Detection classes (v1 of the label set):**

| Class | Definition | Notes |
| :--- | :--- | :--- |
| `cpu_socket` | LGA, PGA, or ZIF processor socket footprint (populated or empty) | Sockets only; see BGA note below |
| `gold_finger` | Gold-plated edge-connector contacts (PCIe, RAM, edge cards) | Long, thin objects; boxes must not be forced square |
| `ic_chip` | Packaged ICs, including BGA-package chips soldered to the board | Optional sub-attribute `bga` in annotation tool |
| `tantalum_capacitor` | SMD tantalum capacitors (typically yellow/orange/black molded bodies with polarity bar) | Small object; needs labeling rules |
| `desoldered_zone` | Region with exposed pads/solder residue where a component was removed | Ambiguous; needs a precise definition and example gallery |

> **BGA correction:** BGA (ball grid array) is a chip *package* soldered onto the board. LGA/PGA are *sockets*. v1's `bga_cpu_socket` conflated them. In v2, BGA chips fall under `ic_chip`, and socket queries target LGA/PGA only.

**Image-level tags (manifest metadata, not YOLO classes):**

- `board_type`: desktop, laptop, phone, server, GPU, other
- `condition`: intact, stripped, burnt/damaged
- `source_type`: listing (white background), in_the_wild, recycling_yard, render/diagram (to be discarded)

Folders are **not labels**. Search-query hints are noisy and are stored only as `class_hint` metadata.

### 2.2 Target counts and attrition budget

Boards contain several classes per image, so ~3,000-4,000 unique labeled images may cover all classes, but the rare/small classes drive the budget.

| Class | Target images | Target instances | Difficulty |
| :--- | :--- | :--- | :--- |
| `ic_chip` | 1,500 | 15,000+ | Easy (abundant) |
| `cpu_socket` | 1,500 | 3,000+ | Medium |
| `gold_finger` | 1,500 | 5,000+ | Medium |
| `tantalum_capacitor` | 1,500 | 10,000+ | Hard (small, visually varied) |
| `desoldered_zone` | 1,500 | 5,000+ | Hard (ambiguous) |

Expect **50-70% attrition** across validation, dedup, and relevance filtering, so plan to harvest roughly **3x the target** (about 10,000-12,000 raw downloads). Set the exact harvest budget after a 500-image pilot measures the real attrition rate.

### 2.3 Board Integrity Score (BIS): proposed definition

BIS must be defined now because it determines which labels are needed.

Proposal (needs domain-owner sign-off):

```
V_present = Ξ£ over detected high-value classes c of  w_c Γ— count_c
            (cpu_socket, gold_finger, ic_chip, tantalum_capacitor)
V_missing = w_d Γ— (number or area-normalized sum of desoldered_zone detections)

BIS = 100 Γ— V_present / (V_present + V_missing)
```

Open questions: value weights `w_c` (need recycler input), whether to use counts or area, per-board-type normalization, and how detector confidence thresholds affect BIS stability. Log these as decisions in `docs/decisions.md`.

---

## 3. System Architecture

```mermaid
flowchart TD
    A["Config: taxonomy + query matrix"] --> B["URL harvest via icrawler: Bing / Baidu / Flickr"]
    B --> C["Resilient downloader: retry, backoff, rate limit"]
    RW["Real-world photo capture"] --> E
    C --> D[("Originals store: untouched bytes, sha256 names")]
    D --> E{"Validation"}
    E -- "fail: corrupt, under 20 KB, below min resolution, over 6:1" --> X["Discard and log reason"]
    E -- "pass (flag if over 3:1)" --> F["Normalize: EXIF fix, RGB, JPEG q95"]
    F --> G{"Dedup: exact + perceptual, global"}
    G -- "duplicate" --> X
    G -- "unique" --> H{"CLIP relevance filter"}
    H -- "irrelevant" --> X
    H -- "borderline" --> R["Manual review queue"]
    H -- "relevant" --> M["Manifest: SQLite"]
    R --> M
    M --> S["Cluster-aware split: train / val / test"]
    S --> L["Annotation: CVAT or Roboflow"]
    L --> T["YOLO training and evaluation"]
```

Design principles:

1. **Stages are idempotent and resumable.** Each image has a `status` in the manifest; reruns skip completed work.
2. **Originals are never modified.** Normalized copies are derived artifacts and can be regenerated with different settings.
3. **Every discard is logged with a reason** so thresholds can be tuned from data instead of guesses.

---

## 4. Directory & Dataset Schema

```
ewaste_dataset_pipeline/
β”œβ”€β”€ scraper.py                  # CLI entry point (subcommands: harvest, validate, process, dedup, filter, split, report)
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ config.yaml             # thresholds, engines, rate limits, seeds
β”‚   β”œβ”€β”€ taxonomy.yaml           # classes, definitions, image-level tags
β”‚   └── queries.yaml            # query matrix (see Β§5.1)
β”œβ”€β”€ pipeline/
β”‚   β”œβ”€β”€ crawler.py              # URL harvest + custom downloader
β”‚   β”œβ”€β”€ validator.py
β”‚   β”œβ”€β”€ processor.py            # normalization
β”‚   β”œβ”€β”€ dedup.py                # exact + perceptual + embedding clusters
β”‚   β”œβ”€β”€ relevance.py            # CLIP zero-shot filter
β”‚   β”œβ”€β”€ manifest.py             # SQLite state store + JSONL/CSV export
β”‚   β”œβ”€β”€ split.py                # cluster-aware splitting
β”‚   └── report.py               # summary statistics
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ fixtures/               # truncated JPEG, RGBA PNG, EXIF-rotated, CMYK, animated GIF, 5:1 RAM image
β”‚   └── test_*.py
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ originals/              # untouched downloaded bytes: <sha256[:16]>.<orig_ext>
β”‚   β”œβ”€β”€ images/                 # normalized JPEGs: <sha256[:16]>.jpg (flat store)
β”‚   β”œβ”€β”€ review/                 # borderline / flagged images for manual review
β”‚   β”œβ”€β”€ realworld/              # own captures, organized by session_id
β”‚   β”œβ”€β”€ manifest.db             # SQLite source of truth
β”‚   └── manifest.jsonl          # export for tooling
β”œβ”€β”€ splits/
β”‚   └── splits.json             # frozen image_id -> split mapping (versioned)
β”œβ”€β”€ reports/
β”‚   └── summary.json
β”œβ”€β”€ dataset_annotated/          # YOLO export after labeling
β”‚   β”œβ”€β”€ data.yaml
β”‚   β”œβ”€β”€ train/
β”‚   β”œβ”€β”€ val/
β”‚   └── test/                   # real-world sessions only
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ decisions.md
β”‚   └── labeling_guide.md
└── requirements.txt
```

The flat `images/` store replaces per-class folders because one image can match several queries. Per-hint browsing views can be generated from the manifest on demand.

---

## 5. Core Modules

### 5.1 Query & Category Registry (`queries.yaml`)

Queries are **derived from the taxonomy**, then expanded along diversity axes. Two or three queries per class, as in v1, will not produce enough variety.

**Expansion matrix:** `class term Γ— board_type Γ— condition Γ— view/lighting Γ— language`

| Axis | Example values |
| :--- | :--- |
| Board type | desktop motherboard, laptop mainboard, smartphone PCB, server board, GPU PCB |
| Condition | intact, stripped, burnt, corroded, dusty |
| View / setting | top view, close-up macro, angled, recycling bin, workbench, e-waste pile, hand-held |
| Language | English, plus Chinese, Spanish, German, Hindi, Vietnamese (recycling hubs and local marketplaces) |

Example seed terms per class:

- `cpu_socket`: "LGA 1151 socket close up", "LGA 1700 socket bent pins", "PGA socket AM4 motherboard", "empty CPU socket motherboard scrap"
- `gold_finger`: "PCIe x16 gold fingers PCB", "RAM module gold contacts scrap", "edge connector gold plated board"
- `ic_chip`: "BGA chip on motherboard close up", "SMD IC laptop motherboard", "chipset heatsink removed motherboard"
- `tantalum_capacitor`: "SMD tantalum capacitor yellow PCB", "tantalum capacitor polarity stripe board", "tantalum capacitors recycling"
- `desoldered_zone`: "desoldered components exposed pads PCB", "cannibalized motherboard ewaste scrap", "hot air removed chips board", "burnt circuit board blowtorch"

Notes:

- Search engines cap results per query (often a few hundred at best), so **volume comes from query variety**, not from raising `max_num`.
- Record `query`, `engine`, and `class_hint` per URL in the manifest.

### 5.2 Harvesting & Download Engine (`crawler.py`)

- **Engines:** `icrawler` Bing, Baidu, and Flickr crawlers. The Google crawler is unreliable and optional. **DuckDuckGo is not natively supported by `icrawler`** and is removed from v1 scope; add it later only through a separate adapter.
- **Two-step design:**
  1. Use `icrawler` to harvest URLs and metadata into the manifest with status `pending`.
  2. A custom downloader (subclass of `icrawler`'s `ImageDownloader`, or a `requests` session pool) performs the fetch.
- **Resilience (implemented explicitly, since `icrawler` does not provide it):**
  - Exponential backoff with jitter (e.g., `tenacity`), max 4 retries
  - Per-domain rate limiting and concurrency caps
  - Connect/read timeouts (e.g., 5s / 20s), maximum download size (e.g., 25 MB)
  - Content-Type and magic-byte sniffing before saving
  - Rotating realistic User-Agent strings
  - Respect HTTP 429 / `Retry-After`
- **Concurrency:** 4-8 downloader threads per query, global cap across queries.
- **Resumability:** URL-normalized dedup at the manifest level so reruns never re-fetch a URL already tried (successful or permanently failed).
- **Storage:** save untouched bytes to `data/originals/` under `<sha256[:16]>.<ext>`.

### 5.3 Validation Engine (`validator.py`)

Checks run in a fixed order so cheap checks fail first:

| # | Check | Rule | Action |
| :--- | :--- | :--- | :--- |
| 1 | File size | < 20 KB | Discard (`too_small_file`) |
| 2 | Integrity | `Image.open()` β†’ `verify()` β†’ **reopen** β†’ `load()` (catches truncation that `verify()` misses) | Discard (`corrupt`) |
| 3 | Animated | Multi-frame GIF/WEBP | Use first frame; flag `animated` |
| 4 | Resolution | Short side < 480 px **or** long side < 800 px | Discard (`low_resolution`) |
| 5 | Aspect ratio | > 3:1 or < 1:3 | **Flag** `extreme_aspect`, send to review |
| 6 | Aspect ratio (hard) | > 6:1 or < 1:6 | Discard (`extreme_aspect_hard`) |

Why the aspect-ratio change: RAM modules and edge-finger crops are naturally ~4.5-5:1. A 3:1 hard cutoff would remove exactly the images the `gold_finger` class needs.

Why the resolution change: tantalum capacitors and desoldered zones occupy very few pixels; a 250 px image contains almost no usable detail for them.

### 5.4 Normalization Engine (`processor.py`)

Applied to a **copy** of each validated image:

1. **`ImageOps.exif_transpose()`** first, so phone photos are not rotated incorrectly.
2. **Mode conversion to RGB:**
   - RGBA / LA / P-with-transparency: composite onto a **white** background (a naive `convert("RGB")` turns transparency black).
   - CMYK: convert via embedded ICC profile when present (`ImageCms`), otherwise standard conversion.
   - Grayscale: replicate to 3 channels.
3. **Size cap:** if the long side > 2560 px, downscale with LANCZOS (never upscale). This bounds storage while preserving detail for small objects.
4. **Encode:** JPEG **quality 95**, 4:4:4 chroma subsampling (`subsampling=0`), `optimize=True`. This limits the extra lossy generation and keeps fine solder/pad detail that q90 with default 4:2:0 would blur.
5. **Metadata:** strip EXIF (privacy and size); store dimensions and original format in the manifest.
6. Output name: `data/images/<sha256[:16]>.jpg`, where the hash is of the original file bytes.

### 5.5 Deduplication Engine (`dedup.py`)

MD5 catches only byte-identical files. A resized or recompressed copy of the same photo gets a different hash, and near-duplicates that straddle train/val inflate metrics. v2 uses three layers, applied **globally across all classes and all queries**:

| Layer | Method | Catches |
| :--- | :--- | :--- |
| 1. Exact | SHA-256 of original bytes (pre-decode) and of decoded pixel array | Byte-identical and re-saved-identical images |
| 2. Near-duplicate | Perceptual hash (`imagehash` pHash, 64-bit, plus dHash) with Hamming distance ≀ 6; also hash the **horizontally flipped** image and compare | Resizes, recompression, minor crops/edits, mirror copies |
| 3. Semantic clusters | CLIP image embeddings; cosine similarity β‰₯ 0.95 β†’ same cluster (agglomerative or connected components) | Same board photographed from slightly different angles, same listing series |

Implementation notes:

- For ≀ 100k images, pairwise Hamming comparison with vectorized NumPy popcount is fast enough; use a BK-tree or LSH banding beyond that.
- Within a duplicate group, **keep the highest-resolution member** and record all members' URLs under it in the manifest.
- Every image gets a `cluster_id`. Layers 1-2 remove images; layer 3 does **not** remove images, it only labels clusters for leakage-safe splitting (Β§6).

### 5.6 Relevance Filter (`relevance.py`)

Search results contain many stock illustrations, renders, diagrams, product boxes, logos, and off-topic hardware.

- **Model:** `open_clip` (e.g., ViT-B/32) zero-shot scoring.
- **Positive prompts:** "a photo of a printed circuit board", "a photo of a computer motherboard", "a photo of electronic waste".
- **Negative prompts:** "a 3D render", "a diagram or schematic", "a product box", "a logo", "a screenshot", "a computer case", "a person", "an image with a watermark".
- **Buckets:** `relevant` (auto-keep), `borderline` (manual review), `irrelevant` (discard). Tune the two thresholds on a **hand-labeled sample of ~200 images**, then report precision/recall of the filter.
- **`source_type` tagging:** use zero-shot prompts to estimate `listing` vs `in_the_wild` so the domain mix can be monitored.
- **Watermarks/stock:** flagged, not auto-discarded (zero-shot watermark detection is unreliable). Flagged images go to review.

### 5.7 Manual Review

- Review **all** `borderline` and `extreme_aspect` items, plus a **10% random sample** of auto-kept images to estimate residual noise.
- Use a contact-sheet tool (FiftyOne or a simple generated HTML grid) that supports keep/discard/re-tag.
- Record reviewer decisions in the manifest (`review_status`, `reviewer`, `reviewed_at`).

### 5.8 Manifest & Provenance (`manifest.py`)

SQLite is the source of truth, exported to JSONL/CSV for tooling. One row per image (plus a table of source URLs per image).

| Field | Description |
| :--- | :--- |
| `image_id` | sha256[:16] of original bytes |
| `source_urls[]` | all URLs that produced this image |
| `engine`, `queries[]`, `class_hints[]` | how it was found |
| `scraped_at` | timestamp |
| `orig_format`, `width`, `height`, `filesize`, `aspect_ratio` | measured properties |
| `flags[]` | `extreme_aspect`, `animated`, `watermark_suspect`, etc. |
| `phash`, `dhash` | perceptual hashes |
| `cluster_id` | duplicate/semantic cluster |
| `clip_score`, `relevance_bucket` | filter outputs |
| `board_type`, `condition`, `source_type` | image-level tags |
| `status` | `pending β†’ downloaded β†’ validated β†’ normalized β†’ deduped β†’ filtered β†’ kept` or `discarded` |
| `discard_reason` | why it was removed |
| `review_status` | reviewer outcome |
| `split` | `train` / `val` / `test` (set by Β§6) |
| `session_id`, `board_id` | for real-world captures |

---

## 6. Real-World Data & Splitting

### 6.1 Real-world capture set (closes the domain gap)

Web results skew toward clean listing photos. The deployed app will see dirty, cluttered, phone-shot boards under poor lighting.

- Capture **β‰₯ 300 test images plus β‰₯ 300 additional training images** from recycling partners or a bench setup.
- Vary: phone models, lighting (daylight, warm, harsh flash, dim), backgrounds, distances (macro to whole-board), angles, board types, and conditions.
- Record `session_id` (one per visit/location/day) and `board_id` (one per physical board). Photograph each board from multiple angles.
- Capture at native phone resolution; keep originals.

### 6.2 Split policy (leakage-safe)

| Split | Composition | Rule |
| :--- | :--- | :--- |
| `train` | Web + real-world training sessions | ~80% of the non-test pool |
| `val` | Web + real-world training sessions | ~20% of the non-test pool; used for model selection |
| `test` | **Real-world sessions only, held out** | Never used for tuning or threshold selection; sessions not present in train/val |

- Split by **group**, not by image: use `cluster_id` for web images and `board_id`/`session_id` for real-world images (`GroupShuffleSplit` or similar), so near-duplicates and same-board photos never straddle splits.
- Stratify on `class_hints` and `source_type` where feasible so val reflects the domain mix.
- Freeze the result in `splits/splits.json` with the random seed; regenerate only by explicit version bump.

---

## 7. Annotation

- Write `docs/labeling_guide.md` **before** labeling: definitions and 10+ positive/negative example crops per class, plus edge cases (partially occluded, damaged, blurry).
- **Label at full resolution** (never label downscaled copies).
- **Minimum object size policy:** objects smaller than ~16 px at the intended training resolution are either marked `ignore` or excluded consistently; document the choice.
- Boxes: tight; `gold_finger` boxes follow the actual (elongated) strip; no padding to squares.
- **Quality control:** double-annotate a 10% sample, compute IoU/agreement per class, and resolve disagreements to refine the guide. `desoldered_zone` is the class most likely to need a redefinition.
- Tools: CVAT or Roboflow. Export in YOLO format with the frozen splits.

---

## 8. Training & Evaluation Plan

### 8.1 Small-object strategy

- Train with **`imgsz=1280`** (or 960 as a compromise) rather than the 640 default.
- For on-device use, avoid running the full nano model at 1280 on a phone. Two options to evaluate:
  1. **Tiled inference** (SAHI-style): overlapping 640 px tiles with merged detections.
  2. **Two-stage:** a light board detector at 640 β†’ crop board β†’ component detector on the crop.
- Consider mosaic/scale augmentation tuned for small objects; verify augmentations do not destroy `gold_finger` aspect ratios.

### 8.2 Metrics

- mAP@50 and mAP@50-95 **per class**, not just overall.
- **Recall by object-size bucket** (small / medium / large by pixel area), to expose the small-object problem.
- Report results on `val` and, separately, on the real-world `test` split. **The test-set number is the headline number.**
- BIS validation: compare BIS from ground-truth labels vs BIS from detections on the test set, and report the error.

### 8.3 Export checks

- Export to ONNX / TFLite and **re-evaluate on the test set after export and after quantization**; set an acceptable mAP-drop budget (e.g., ≀ 2 points) before shipping to `mobile/`.

---

## 9. Technical Stack

| Tool / Library | Role |
| :--- | :--- |
| Python 3.10+ | Runtime |
| `icrawler` | URL harvesting (Bing, Baidu, Flickr; Google optional) |
| `requests`, `tenacity` | Custom downloader with retry/backoff |
| `Pillow` | Validation, EXIF handling, normalization, ICC conversion |
| `numpy` | Vectorized hash comparison |
| `imagehash` | Perceptual hashing (pHash/dHash) |
| `hashlib` | Exact SHA-256 hashing |
| `open_clip_torch` + `torch` | Relevance filter and embeddings for clustering |
| `scikit-learn` | Group-aware splitting, clustering |
| `PyYAML` | Configuration |
| `tqdm` | Progress monitoring |
| `fiftyone` (optional) | Review UI, embedding visualization |
| `ultralytics`, `sahi` | Training and tiled inference |
| `pytest` | Tests |

Pin exact versions in `requirements.txt` and record them in every report.

---

## 10. Execution Plan

### Step 1: Install

```bash
pip install -r requirements.txt
```

### Step 2: Run stages (each is resumable)

```bash
python3 scraper.py harvest   --config config/config.yaml   # collect URLs into manifest
python3 scraper.py download                                 # fetch originals with retries
python3 scraper.py validate                                 # integrity, size, aspect
python3 scraper.py process                                  # EXIF fix, RGB, JPEG q95
python3 scraper.py dedup                                    # exact + perceptual + clusters
python3 scraper.py filter                                   # CLIP relevance + review queue
python3 scraper.py split                                    # cluster-aware splits
python3 scraper.py report                                   # summary statistics
```

### Step 3: Verification report (`reports/summary.json` and printed table)

Per `class_hint` and overall:

- Raw URLs harvested, downloads succeeded/failed
- Discards **by reason** (corrupt, too small, low resolution, hard aspect, exact dup, near dup, irrelevant)
- Flagged and reviewed counts
- Final kept count vs target (Β§2.2)
- Resolution distribution and `source_type` mix (in-the-wild share vs the 40% goal)
- Number of duplicate clusters and largest cluster size
- Split sizes and a leakage check (no `cluster_id`/`board_id` shared across splits)

---

## 11. Testing

Unit tests using fixtures in `tests/fixtures/`:

| Test | Expectation |
| :--- | :--- |
| Truncated JPEG | Rejected by the `verify()` + `load()` sequence |
| RGBA PNG with transparency | Composited on white, not black |
| EXIF-rotated phone photo | Output is upright |
| CMYK JPEG | Correct RGB conversion |
| Animated GIF | First frame used, `animated` flag set |
| 5:1 RAM image | Flagged, **not** discarded |
| 8:1 banner | Discarded with `extreme_aspect_hard` |
| Resized / recompressed / flipped copy of a fixture | Detected as near-duplicate |
| Rerun after interruption | No re-download, no duplicate rows |
| Leakage check | No shared `cluster_id` across splits |

---

## 12. Milestones & Acceptance Criteria

| Phase | Deliverable | Acceptance criterion |
| :--- | :--- | :--- |
| 0. Decisions | `taxonomy.yaml`, target counts, BIS definition in `docs/decisions.md` | Signed off by project owner |
| 1. Pipeline build | All modules + tests passing | Fixtures behave as specified in Β§11 |
| 2. Pilot | ~500-image end-to-end run | Attrition rate measured; CLIP thresholds tuned on 200 hand-labeled images |
| 3. Full collection | Harvest budget executed; real-world capture β‰₯ 600 images | Kept counts meet Β§2.2 or gaps identified and queries extended |
| 4. QA | Manual review complete; frozen `splits.json` | Leakage check clean; β‰₯ 40% in-the-wild |
| 5. Annotation | Labeled dataset + `labeling_guide.md` | Inter-annotator agreement acceptable per class |
| 6. Training & eval | Baseline model, per-class and size-bucket metrics | Test-set results reported; failure analysis written |
| 7. Export | ONNX/TFLite + post-quantization test results | mAP drop within budget; BIS error reported |

---

## 13. Risks & Mitigations

| Risk | Mitigation |
| :--- | :--- |
| Search engines return too few unique images per query | Wide query matrix (Β§5.1), multiple engines, multilingual queries, real-world capture |
| Heavy overrepresentation of clean listing photos | `source_type` monitoring; explicit in-the-wild target; real-world capture |
| Tiny objects (tantalum caps) undetectable | Higher min resolution, `imgsz=1280`, tiling/two-stage, small-object metrics |
| `desoldered_zone` label ambiguity | Precise definition, example gallery, double annotation, willingness to redefine or move to segmentation |
| Near-duplicate leakage inflates metrics | Cluster-aware splits, leakage check in CI, held-out real-world test set |
| CLIP filter discards valid images | Threshold tuned on hand-labeled sample; borderline goes to review, not discard |
| Class imbalance (ICs abundant, tantalum rare) | Per-class targets, targeted queries and captures for rare classes, per-class metrics |
| Quantization degrades small-object accuracy | Post-export evaluation with a mAP-drop budget; consider mixed precision |
| Pipeline state lost mid-run | SQLite manifest, idempotent stages, originals preserved |
| BIS unstable or not meaningful | Define and validate BIS against ground-truth labels early (Β§2.3, Β§8.2) |

---

## 14. Immediate Next Actions

1. Review and finalize the taxonomy and class definitions (Β§2.1).
2. Get domain input on BIS weights and whether BIS uses counts or area (Β§2.3).
3. Stand up the repository skeleton from Β§4, with config, manifest schema, and test fixtures.
4. Run the 500-image pilot to measure attrition and tune the relevance thresholds.
5. Schedule the first real-world capture session so the test set starts accumulating early.