FaustDerLegende commited on
Commit
11a414e
·
verified ·
1 Parent(s): 7a84478

Upload folder using huggingface_hub (part 61)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. google_drive_export/dataset_annotated/labels/ff68ae13360237cc.txt +0 -0
  2. google_drive_export/dataset_annotated/labels/ff7d2d8a4486b8c0.txt +0 -0
  3. google_drive_export/dataset_annotated/labels/ffaa8463e3e8d6be.txt +4 -0
  4. google_drive_export/dataset_annotated/labels/ffb5399479b415ea.txt +0 -0
  5. google_drive_export/dataset_annotated/labels/ffd9ca6aff7641b9.txt +2 -0
  6. google_drive_export/dataset_annotated/labels/ffeac303cb5ada59.txt +1 -0
  7. google_drive_export/docs/PROJECT_CONTEXT_AND_ACTION_PLAN.md +127 -0
  8. google_drive_export/docs/implementation_plan.md +72 -0
  9. google_drive_export/docs/implementation_plan_component_purity_index.md +148 -0
  10. google_drive_export/docs/scraper_plan_v2.md +485 -0
  11. google_drive_export/pipeline/__init__.py +0 -0
  12. google_drive_export/pipeline/auto_annotate.py +157 -0
  13. google_drive_export/pipeline/config.py +109 -0
  14. google_drive_export/pipeline/crawler.py +275 -0
  15. google_drive_export/pipeline/dedup.py +271 -0
  16. google_drive_export/pipeline/manifest.py +404 -0
  17. google_drive_export/pipeline/processor.py +145 -0
  18. google_drive_export/pipeline/queries.py +77 -0
  19. google_drive_export/pipeline/requirements.txt +7 -0
  20. google_drive_export/pipeline/scraper.py +260 -0
  21. google_drive_export/pipeline/splitter.py +120 -0
  22. google_drive_export/pipeline/validator.py +159 -0
  23. implementation_plan.md +72 -0
  24. implementation_plan_component_purity_index.md +148 -0
  25. manifest.db +0 -0
  26. pipeline/__init__.py +0 -0
  27. pipeline/__pycache__/__init__.cpython-312.pyc +0 -0
  28. pipeline/__pycache__/config.cpython-312.pyc +0 -0
  29. pipeline/__pycache__/crawler.cpython-312.pyc +0 -0
  30. pipeline/__pycache__/dedup.cpython-312.pyc +0 -0
  31. pipeline/__pycache__/manifest.cpython-312.pyc +0 -0
  32. pipeline/__pycache__/processor.cpython-312.pyc +0 -0
  33. pipeline/__pycache__/queries.cpython-312.pyc +0 -0
  34. pipeline/__pycache__/splitter.cpython-312.pyc +0 -0
  35. pipeline/__pycache__/validator.cpython-312.pyc +0 -0
  36. pipeline/auto_annotate.py +176 -0
  37. pipeline/config.py +109 -0
  38. pipeline/crawler.py +275 -0
  39. pipeline/dedup.py +271 -0
  40. pipeline/manifest.py +404 -0
  41. pipeline/processor.py +145 -0
  42. pipeline/queries.py +77 -0
  43. pipeline/splitter.py +129 -0
  44. pipeline/validator.py +159 -0
  45. purity_engine/__init__.py +17 -0
  46. purity_engine/__pycache__/__init__.cpython-312.pyc +0 -0
  47. purity_engine/__pycache__/model_client.cpython-312.pyc +0 -0
  48. purity_engine/__pycache__/pcb_analyzer.cpython-312.pyc +0 -0
  49. purity_engine/__pycache__/purity_assay.cpython-312.pyc +0 -0
  50. purity_engine/__pycache__/vernacular_voice.cpython-312.pyc +0 -0
google_drive_export/dataset_annotated/labels/ff68ae13360237cc.txt ADDED
File without changes
google_drive_export/dataset_annotated/labels/ff7d2d8a4486b8c0.txt ADDED
File without changes
google_drive_export/dataset_annotated/labels/ffaa8463e3e8d6be.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ 0 0.514721 0.497057 0.880708 0.976686
2
+ 0 0.423462 0.528546 0.748916 0.847120
3
+ 0 0.466082 0.417253 0.343521 0.313060
4
+ 0 0.467098 0.348551 0.345282 0.453801
google_drive_export/dataset_annotated/labels/ffb5399479b415ea.txt ADDED
File without changes
google_drive_export/dataset_annotated/labels/ffd9ca6aff7641b9.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ 0 0.868601 0.535727 0.058631 0.056538
2
+ 0 0.312879 0.238340 0.054033 0.049270
google_drive_export/dataset_annotated/labels/ffeac303cb5ada59.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 0 0.488530 0.502639 0.955919 0.993613
google_drive_export/docs/PROJECT_CONTEXT_AND_ACTION_PLAN.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # E-Waste PCB Component Purity & Cannibalization Index: Project Context, System Architecture & Master Action Plan
2
+
3
+ ## 1. Project Overview & Business Context
4
+
5
+ The **Component Purity & Cannibalization Index** is an edge-AI system built for Kabadiwala Connect (e-waste recycling platform). It detects real-time, on-device PCB cannibalization (the illicit stripping of valuable components like CPU sockets, gold edge connector fingers, IC microchips, and SMD tantalum capacitors) to:
6
+ 1. Calculate a dynamic **Board Integrity Score (BIS)**.
7
+ 2. Emit **8-language vernacular voice warnings** to scrap collectors for fair purchasing price adjustments.
8
+ 3. Propagate component integrity data across the **Collector → Dealer → Recycler** supply chain to catch mid-chain cannibalization fraud.
9
+
10
+ ---
11
+
12
+ ## 2. Current Project State & Progress Summary
13
+
14
+ | Category | Current Status | Details & Artifacts |
15
+ | :--- | :--- | :--- |
16
+ | **Dataset Size** | **3,923 Normalized JPEGs** | Located in `data/images/` and `data/annotated_auto/images/` (6,864 total tracked). Average resolution: $1315 \times 1029\text{ px}$. |
17
+ | **Auto-Annotation** | **3,784 Draft Bounding Boxes** | Auto-labeled via YOLO-World zero-shot model (`pipeline/auto_annotate.py`, `conf=0.02`). |
18
+ | **Dataset Spec** | **YOLO Format Ready** | Specification saved to [`data/annotated_auto/data.yaml`](file:///home/taruns/Downloads/scraper/data/annotated_auto/data.yaml). Summary in [`data/annotated_auto/auto_annotation_summary.json`](file:///home/taruns/Downloads/scraper/data/annotated_auto/auto_annotation_summary.json). |
19
+ | **Updated Taxonomy** | **7 Fine-Grained Classes** | Defined in [`config/taxonomy.yaml`](file:///home/taruns/Downloads/scraper/config/taxonomy.yaml) (separates fraud desoldered pads from factory empty pads). |
20
+ | **Scraper Status** | **Harvest Completed (+681 Net New)** | Incremental harvest executed across 298 queries (`config/queries.yaml`). |
21
+ | **Pipeline Tests** | **11 / 11 Passed** | Test suite (`tests/test_pipeline.py`) fully compliant. |
22
+
23
+ ---
24
+
25
+ ## 3. Architecture & Dual-Track Execution Strategy
26
+
27
+ Development is decoupled into two parallel tracks linked by a frozen contract ([`model_contract.md`](file:///home/taruns/Downloads/scraper/implementation_plan_component_purity_index.md#L61)):
28
+
29
+ ```
30
+ ┌────────────────────────────────────────────────────────┐
31
+ │ model_contract.md (Frozen Schema) │
32
+ └──────────────────────────┬─────────────────────────────┘
33
+ │
34
+ ┌────────────────────────┴────────────────────────┐
35
+ │ │
36
+ ┌────────▼───────────────────────┐ ┌─────────────────▼─────────────────────┐
37
+ │ Track A: Model & Dataset │ │ Track B: Application & Integration │
38
+ ├────────────────────────────────┤ ├───────────────────────────────────────┤
39
+ │ • 7-Class Refined Taxonomy │ │ • `MockModelClient` for Dev/Testing │
40
+ │ • Multi-Scale YOLOv8 Training │ │ • Integrity Engine (`purity_assay.py`) │
41
+ │ • Focal Loss for Desoldered │ │ • Offline Pre-Recorded Audio Warnings │
42
+ │ • TFLite INT8 Quantization │ │ • Collector Lite & Recycler Portal │
43
+ │ • Real-World Test Evaluation │ │ • BIS-Delta Fraud Discrepancy UI │
44
+ └────────────────┬───────────────┘ └─────────────────┬─────────────────────┘
45
+ │ │
46
+ └─────────────────┬───────────────────────┘
47
+ ▼
48
+ Swap Mock for Quantized Model (`TFLiteModelClient`)
49
+ (1-Line Config Change)
50
+ ```
51
+
52
+ ---
53
+
54
+ ## 4. System Requirements & Architectural Adjustments
55
+
56
+ Based on technical analysis and field realities, the following system-level changes are enforced:
57
+
58
+ ### A. Edge Hardware & Memory Optimization (Low-End Android 2GB–3GB RAM)
59
+ * **Sequential Model Execution**: Running the 21-class category model and YOLOv8 micro-model simultaneously triggers browser tab memory crashes.
60
+ * **Fix**: Enforce explicit tensor disposal (`model.dispose()`) after Stage 1 classification before loading Stage 2 micro-component detection.
61
+
62
+ ### B. Taxonomy Refinement (Eliminating False Fraud Signals)
63
+ * **Fix**: Split generic desoldered footprints into:
64
+ 1. `forcibly_desoldered_pad`: Exposed pads with jagged solder peaks, torn traces, or blowtorch/burnt flux residue (**fraud signal**).
65
+ 2. `factory_unpopulated_pad`: Clean silkscreen outline with smooth solder dots left unpopulated from factory (**NOT fraud**).
66
+ 3. `occluded_region`: Footprints covered by heatsinks, metal shields, or thick dust.
67
+
68
+ ### C. Dynamic Scrap Grade Pricing Floor
69
+ * **Fix**: Replace rigid 35% hardcoded floor with category scrap grade floors:
70
+ $$\text{Adjusted Price} = \text{Base Price} \times \left( \text{Floor}_{\text{category}} + (1 - \text{Floor}_{\text{category}}) \times \frac{\text{BIS}}{100} \right)$$
71
+ * Server/GPU PCBs: $\text{Floor} = 0.15$
72
+ * Desktop PCBs: $\text{Floor} = 0.30$
73
+ * Low-grade Power PCBs: $\text{Floor} = 0.60$
74
+
75
+ ### D. Multi-Angle 2-Sided Inspection Protocol
76
+ * **Fix**: Standardize a 2-photo workflow (Front Top-Down + Reverse Bottom-Down / Edge) in Collector Lite to inspect both sides of the PCB.
77
+
78
+ ### E. Supply Chain Fraud Tolerance Bands
79
+ * **Fix**: Update Recycler Portal intake discrepancy bands to:
80
+ * $< 12\%$ BIS Drop $\rightarrow$ Normal capture variance (Pass).
81
+ * $12\text{--}25\%$ BIS Drop $\rightarrow$ Advisory Warning / Discrepancy Flag.
82
+ * $> 25\%$ BIS Drop $\rightarrow$ Critical Fraud Alert & CPCB Form 6 PDF Audit Log Entry.
83
+
84
+ ### F. Offline Vernacular Audio Reliability
85
+ * **Fix**: Standardize pre-recorded `.opus` audio playback via Service Worker `CacheStorage` as a fallback when Web Speech API regional voice packs are missing offline.
86
+
87
+ ---
88
+
89
+ ## 5. Master Plan of Action (Step-by-Step Roadmap)
90
+
91
+ ### Phase 1: Baseline Model Training (Track A)
92
+ - [x] Auto-annotate dataset with 3,130 draft boxes (`pipeline/auto_annotate.py`).
93
+ - [ ] Fine-tune baseline **YOLOv8n / YOLOv8s** on `data/annotated_auto/data.yaml` (`imgsz=960` or `1280`).
94
+ - [ ] Evaluate per-class mAP@50 and fraud recall on `forcibly_desoldered_pad`.
95
+ - [ ] Quantize model to TFLite INT8 ($<15\text{ MB}$, target $<1\text{s}$ latency).
96
+
97
+ ### Phase 2: Incremental Harvest & Synthetic Data (Optional Extension)
98
+ - [ ] Execute optional incremental scraper batch (~500–1,000 images) using updated [`config/queries.yaml`](file:///home/taruns/Downloads/scraper/config/queries.yaml).
99
+ - [ ] Apply CutMix / Copy-Paste synthetic desoldered pad data synthesis during training.
100
+
101
+ ### Phase 3: Purity Engine Module Build (Track B)
102
+ - [ ] Build `purity_engine/model_client.py` (`MockModelClient` & `TFLiteModelClient`).
103
+ - [ ] Build `purity_engine/purity_assay.py` (Form-factor baseline matching + dynamic scrap pricing formula).
104
+ - [ ] Build `purity_engine/vernacular_voice.py` (Web Speech API + `.opus` fallback).
105
+
106
+ ### Phase 4: App Integration & End-to-End Verification
107
+ - [ ] Extend Collector Lite (`mobile/kabadiwala-lite.html`) with 2-photo workflow & inline BIS display.
108
+ - [ ] Extend Recycler Portal (`recycler-dashboard-frontend/`) with BIS-delta view ($12\% / 25\%$ flags).
109
+ - [ ] Run automated test suite (`tests/test_purity_assay.py`, `tests/test_bis_delta_api.py`).
110
+
111
+ ---
112
+
113
+ ## 6. Key Configuration & Pipeline Commands Quick Reference
114
+
115
+ * **Run Automated Tests**:
116
+ ```bash
117
+ .venv/bin/python -m pytest
118
+ ```
119
+ * **Run Auto-Annotation Script**:
120
+ ```bash
121
+ .venv/bin/python pipeline/auto_annotate.py
122
+ ```
123
+ * **Run Incremental Web Scraper**:
124
+ ```bash
125
+ .venv/bin/python scraper.py harvest
126
+ ```
127
+ * **Dataset Location**: `data/annotated_auto/`
google_drive_export/docs/implementation_plan.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Implementation Plan: E-Waste Dataset Scraper & Pipeline (v2 Architecture)
2
+
3
+ Build a modular, production-grade Python web scraper and image preprocessing pipeline following `scraper_plan_v2.md` to harvest, clean, deduplicate, and prepare high-resolution e-waste PCB dataset images for fine-tuning YOLOv8 micro-component detectors.
4
+
5
+ ## User Review Required
6
+
7
+ > [!IMPORTANT]
8
+ > **Scraping Target & Volume:** The pilot harvest target will be set to **500 images per query batch** across Bing and Flickr to keep the pilot run under 10–15 minutes while establishing real attrition rates.
9
+ > **Dependency Note:** `icrawler`, `pillow`, `imagehash`, and `open_clip_torch` (or lightweight CLIP filtering) will be installed in the environment.
10
+
11
+ ## Open Questions
12
+
13
+ > [!NOTE]
14
+ > **CLIP Relevance Filter Mode:** Should the initial script execute CLIP zero-shot relevance filtering locally via PyTorch, or fall back to rule-based aspect-ratio/color-histogram heuristic filtering if PyTorch GPU memory is constrained during background runs? (Default: Rule-based + optional CLIP module).
15
+
16
+ ---
17
+
18
+ ## Proposed Changes
19
+
20
+ ### Scraping & Pipeline Package (`ewaste_dataset_pipeline/`)
21
+
22
+ Creation of a self-contained, modular Python CLI pipeline under `ewaste_dataset_pipeline/`.
23
+
24
+ #### [NEW] [`config/taxonomy.yaml`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/config/taxonomy.yaml)
25
+ - Defines the 5 target YOLO detection classes: `cpu_socket`, `gold_finger`, `ic_chip`, `tantalum_capacitor`, `desoldered_zone`.
26
+ - Defines image-level tags: `board_type`, `condition`, `source_type`.
27
+
28
+ #### [NEW] [`config/queries.yaml`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/config/queries.yaml)
29
+ - Search query expansion matrix across search terms, condition variants, board types, and multilingual terms.
30
+
31
+ #### [NEW] [`pipeline/manifest.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/manifest.py)
32
+ - SQLite database abstraction layer (`manifest.db`) tracking URL provenance, download status, MD5 checksums, resolution, pHash values, cluster IDs, and split assignments.
33
+
34
+ #### [NEW] [`pipeline/crawler.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/crawler.py)
35
+ - URL harvester using `icrawler` (Bing, Flickr, Baidu) with exponential backoff retries, custom headers, and rate limiting. Saves raw bytes to `data/originals/`.
36
+
37
+ #### [NEW] [`pipeline/validator.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/validator.py)
38
+ - Validation engine checking file integrity (`verify()` + `load()`), short/long resolution cutoffs ($\ge 480\text{ px}$ short side), and aspect ratio bounds (flag $> 3:1$, drop $> 6:1$).
39
+
40
+ #### [NEW] [`pipeline/processor.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/processor.py)
41
+ - Image normalizer handling EXIF auto-rotation (`exif_transpose`), RGBA alpha white-background compositing, CMYK to RGB conversion, and JPEG 95 quality encoding.
42
+
43
+ #### [NEW] [`pipeline/dedup.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/dedup.py)
44
+ - Multi-tier deduplication engine (SHA-256 exact byte hash + perceptual `pHash`/`dHash` with horizontal flip awareness).
45
+
46
+ #### [NEW] [`scraper.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/scraper.py)
47
+ - Unified CLI entry point supporting subcommands: `harvest`, `validate`, `process`, `dedup`, `report`.
48
+
49
+ #### [NEW] [`requirements.txt`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/requirements.txt)
50
+ - Dependency specifications (`icrawler`, `Pillow`, `imagehash`, `pyyaml`, `tqdm`).
51
+
52
+ ---
53
+
54
+ ## Verification Plan
55
+
56
+ ### Automated Verification
57
+ 1. **Unit & Module Tests:**
58
+ - Test image validation on corrupted, truncated, transparent PNG, CMYK, and EXIF-rotated sample images.
59
+ - Verify pHash deduplication on identical vs resized/flipped images.
60
+ 2. **CLI Execution Runs:**
61
+ - Execute pilot harvest run:
62
+ ```bash
63
+ cd ewaste_dataset_pipeline
64
+ python3 scraper.py harvest --max-num 50
65
+ python3 scraper.py validate
66
+ python3 scraper.py process
67
+ python3 scraper.py dedup
68
+ python3 scraper.py report
69
+ ```
70
+
71
+ ### Manual Verification
72
+ - Inspect generated `reports/summary.json` to verify image yield, discard counts by reason, and clean `dataset_raw/` outputs.
google_drive_export/docs/implementation_plan_component_purity_index.md ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Implementation Plan: Edge "Component Purity & Cannibalization Index" (Updated)
2
+
3
+ This feature delivers real-time, on-device detection of PCB cannibalization (stripping/depopulation of valuable components like CPU sockets, gold edge fingers, and tantalum capacitors) to calculate a **Board Integrity Score (BIS)**, generate vernacular voice warnings for scrap pricing adjustments, and propagate integrity data through the Dealer → Recycler chain to catch mid-chain stripping fraud.
4
+
5
+ Model training data collection is still in progress, so this plan is split into two tracks joined by a single frozen interface (`model_contract.md`): **Track A** builds and trains the detection model; **Track B** builds the full app pipeline against a mock model conforming to that same contract, so integration is not blocked on model readiness. Swapping the mock for the trained model later is a one-line config change, not a rewrite.
6
+
7
+ ---
8
+
9
+ ## User Review Required
10
+
11
+ > [!IMPORTANT]
12
+ > - **Labeling taxonomy refinement**: Split desoldered footprints into `forcibly_desoldered_pad` (jagged, torn traces, burnt flux) and `factory_unpopulated_pad` (pristine silkscreen, smooth solder dots) to eliminate false cannibalization alerts on unpopulated board regions. Added `occluded_region` to prevent penalizing components covered by heatsinks/dust.
13
+ > - **Form-factor baselines**: Replaced static class-wide component counts with form-factor sub-profiles (`desktop_atx`, `desktop_micro_atx`, `server_1u`, `gpu_pcb`, `ram_dimm`) in `board_profiles.json` to prevent small intact boards from receiving low BIS scores.
14
+ > - **Dynamic price floor**: Replaced the rigid 35% hardcoded price floor with category-based scrap grade floors ($\text{Floor}_{\text{category}}$ = 15% for high-grade server/GPU boards up to 60% for low-grade power boards).
15
+ > - **Sequential edge execution**: Adopted sequential model loading (`dispose()` calls between 21-class category classifier and YOLOv8 micro-model) to prevent memory crashes on 2GB–3GB RAM Android phones.
16
+ > - **BIS-delta tolerance bands**: Updated recycler intake fraud threshold to $>12\%$ for advisory flags and $>25\%$ for critical alerts (up from 5%) to accommodate field-vs-warehouse camera & lighting variances.
17
+ > - **Offline voice fallback**: Standardized pre-recorded `.opus` audio snippets via Service Worker `CacheStorage` as a fallback when Web Speech API offline regional voice packs are missing.
18
+ > - **Data sourcing strategy**: Confirmed that existing open datasets can bootstrap the generic (`*_intact`) component classes, removing most of the annotation burden for those; the fraud-specific classes (`forcibly_desoldered_pad`, `occluded_region`) still require primarily field-staged photography, supplemented — not replaced — by mined web sources. See Phase 1, Component 2a. **Requires a decision on whether forum/marketplace-sourced supplemental images are approved for use** (see licensing note in Component 2a) before any scraping work begins.
19
+
20
+ ---
21
+
22
+ ## Track A: Micro-Component Detection Model
23
+
24
+ ### Phase 1: Data Collection & Labeling (Updated Guidelines)
25
+
26
+ #### Component 1: Refined Labeling Taxonomy (`taxonomy/component_classes.yaml`)
27
+ - [NEW] Defines fine-grained class states to eliminate false positives:
28
+ - `bga_cpu_socket_intact`, `bga_cpu_socket_missing`
29
+ - `gold_edge_finger_intact`, `gold_edge_finger_stripped`
30
+ - `tantalum_cap_intact`, `tantalum_cap_missing`
31
+ - `ram_dimm_slot_intact`, `ram_dimm_slot_stripped`
32
+ - `forcibly_desoldered_pad` (jagged solder, torn traces, blowtorch/burnt flux residue — primary fraud signal)
33
+ - `factory_unpopulated_pad` (clean silkscreen outline, smooth solder dots — unpopulated from factory, NOT fraud)
34
+ - `occluded_region` (heatsinks, metal shields, heavy dirt/dust covering component pads)
35
+
36
+ #### Component 2: Data Collection & Sourcing Protocol (`data_collection/`)
37
+ - [NEW] `capture_protocol.md` — multi-angle capture protocol (Front side top-down, Reverse side top-down, and macro gold edge connector shot) to handle 2-sided PCB inspection.
38
+ - [NEW] `board_sourcing_log.csv` — logs board type, source, form factor (`desktop_atx`, `micro_atx`, `server_4u`, etc.), and intentional stripping state (pristine, blowtorched, organically degraded, factory unpopulated).
39
+ - Sourcing requirements: Must harvest dirty, corroded, dusty, and factory-unpopulated boards alongside pristine and stripped examples to match field scrap yard conditions.
40
+
41
+ #### Component 2a: Data Sourcing Strategy — Open Datasets, Mined Web Sources, and Field Photography (`data_collection/sourcing_strategy.md`)
42
+
43
+ Research into publicly available data confirms a **three-tier sourcing strategy**, since scraping alone cannot cover the fraud-specific classes:
44
+
45
+ **Tier 1 — Open datasets, for bootstrapping `*_intact` classes (use directly, no scraping needed):**
46
+ - A Dataset Ninja "PCB Component Detection" set — 1,410 images, 11,119 bounding-box-labeled objects across 9 classes (capacitor, transformer, MOSFET, resistor, etc.), released CC0 and explicitly tagged for the waste-recycling use case.
47
+ - HuggingFace `PCB_COMPONENTS_LABELLED` — 17-class YOLO-format set (IC, capacitor, connector, crystal oscillator, diode, ferrite bead, fuse, inductor, LED, resistor, switch, transistor, pins, pads, test points).
48
+ - HuggingFace `pcb-object-detection-dataset` — 21-class YOLO set including heatsinks and connectors.
49
+ - Roboflow Universe community PCB datasets (component-level bounding boxes, CC BY 4.0).
50
+ - **Use**: pretrain the detection backbone and pad out the `*_intact` and generic-component classes; re-map class names to `taxonomy/component_classes.yaml`. This does not reduce the need for field data on fraud-specific classes below, but meaningfully cuts the annotation volume needed for the "board still has its parts" side of the taxonomy.
51
+
52
+ **Tier 2 — Mined web sources, as a supplemental seed set for `forcibly_desoldered_pad` only (not a primary source):**
53
+ - Gold-recovery/e-waste hobbyist forums (e.g. Gold Refining Forum, finishing.com) contain user-posted photos of boards before, during, and after chip/pin removal, and active community discussion distinguishing "unpopulated" from "depopulated" boards — the closest organic analog to the `forcibly_desoldered_pad` class available online.
54
+ - Hobbyist "gold recovery" / heat-gun chip-pulling YouTube videos are a higher-yield variant of the same source: frame-extraction from a single video can produce many more usable images than a forum thread.
55
+ - **Known limitations, by design not treated as a primary source**:
56
+ - Low volume per source and inconsistent photo quality/angle — doesn't match the phone-camera, scrap-yard conditions defined in `capture_protocol.md`.
57
+ - No existing bounding boxes — still requires full manual annotation, same as field photos.
58
+ - Licensing: forum and video content is user-generated and not freely licensed for reuse; scraping is low-risk for an internal/hackathon prototype but is **not cleared for production training data** without explicit permission or a licensed dataset. Flagged in User Review Required above — treat as blocked until a decision is made.
59
+ - **Use**: a small supplemental set to diversify what "stripped" looks like beyond staged photos, mined and annotated in parallel with, not instead of, Tier 3.
60
+
61
+ **Tier 3 — Deliberately staged field photography, mandatory and primary for fraud classes (this is the existing Component 2 protocol above):**
62
+ - Only source that guarantees: domain match to real collector phone conditions, controlled multi-angle capture, and clean separation between `forcibly_desoldered_pad`, `factory_unpopulated_pad`, and `occluded_region` at capture time (know the ground truth because you staged it, rather than inferring it after the fact from a forum photo).
63
+ - Remains the dataset of record for Phase 4 evaluation thresholds; Tier 1/2 data is for pretraining and augmentation only, not held-out test data.
64
+
65
+ #### Component 3: Annotation & QA
66
+ - [NEW] Bounding-box annotation via CVAT or Label Studio, exported in COCO/YOLO format.
67
+ - [NEW] `qa_annotation_review.py` — inter-annotator agreement check (min. 2 annotators per image, flag disagreement >10% of boxes for adjudication).
68
+ - Target: minimum 300 images per class, with at least 30% deliberately-stripped/burnt negative examples, before first training run.
69
+
70
+ ### Phase 2: Form-Factor Baseline Definitions
71
+
72
+ #### Component 4: Dynamic Board Profiles (`baselines/board_profiles.json`)
73
+ - [NEW] Defines expected component counts/area ratios per board class **and form factor**:
74
+ - `desktop_atx`, `desktop_micro_atx`, `desktop_itx`
75
+ - `server_1u_2u`, `server_blade_4u`
76
+ - `gpu_pcb_high_end`, `gpu_pcb_budget`
77
+ - `ram_dimm_desktop`, `ram_so_dimm_laptop`
78
+ - Sourced from recycling domain experts — consumed downstream by `purity_assay.py`.
79
+
80
+ ### Phase 3: Model Training
81
+
82
+ #### Component 5: Training Pipeline (`training/train.py`)
83
+ - [NEW] YOLOv8n/s fine-tuning with multi-scale training (`imgsz=960` or `1280`) and custom anchor ratios for elongated `gold_finger` boxes ($>4:1$).
84
+ - Heavy augmentations for field realities: specular glare on gold fingers, lighting variance, dirt noise, and angle tilt.
85
+ - [NEW] `train_config.yaml` — Focal loss & elevated class weights for `forcibly_desoldered_pad` vs `factory_unpopulated_pad`.
86
+
87
+ #### Component 6: Auxiliary Desoldered Pad Classifier Head
88
+ - [NEW] Secondary classification head specifically trained to distinguish desoldered blowtorch pads from factory empty pads.
89
+
90
+ #### Component 7: Export & Quantization (`export/export_tflite.py`)
91
+ - [NEW] Export to TFLite INT8 quantized, target size <15MB, target inference <1s on low-end Android hardware.
92
+ - [NEW] `model_contract.md` — freezes input/output tensor schema.
93
+
94
+ ### Phase 4: Evaluation
95
+
96
+ #### Component 8: Model Evaluation (`eval/evaluate.py`)
97
+ - [NEW] Per-class mAP, plus dedicated fraud recall on `forcibly_desoldered_pad` and false-positive rate on `factory_unpopulated_pad`.
98
+ - Thresholds: $\ge 90\%$ recall on intact classes, $\ge 85\%$ recall on desoldered pad classes, and $\le 5\%$ false positive rate on factory unpopulated pads.
99
+
100
+ ---
101
+
102
+ ## Track B: Integration into Kabadiwala Connect
103
+
104
+ ### Component 9: Purity Engine & Memory-Conscious Orchestrator (`purity_engine/`)
105
+
106
+ - [NEW] `purity_engine/model_client.py` — wrapper supporting `MockModelClient` and `TFLiteModelClient` with explicit tensor memory management (`model.dispose()` between Stage 1 and Stage 2).
107
+ - [NEW] `purity_engine/purity_assay.py` — implements `calculate_board_integrity_score(detected_components, form_factor)`:
108
+ - Dynamic price formula:
109
+ $$\text{Adjusted Price} = \text{Base Price} \times \left( \text{Floor}_{\text{category}} + (1 - \text{Floor}_{\text{category}}) \times \frac{\text{BIS}}{100} \right)$$
110
+ - Scrap Grade Floors: Server/GPU = 15%, Desktop = 30%, Low-grade Power = 60%.
111
+ - [NEW] `purity_engine/pcb_analyzer.py` — single entry point for Collector Lite & Recycler Portal.
112
+
113
+ ### Component 10: Vernacular Voice Alerts with Audio Fallback (`purity_engine/vernacular_voice.py`)
114
+
115
+ - [NEW] Extends Collector Lite's 8-language Web Speech API audio system with Service Worker pre-recorded `.opus` audio fallbacks for offline devices lacking regional voice packs.
116
+ - Message templates parameterized by BIS band (Pristine $\ge 85\%$, Partial $50\text{--}84\%$, Severe $<50\%$).
117
+
118
+ ### Component 11: Collector Lite Multi-Angle UI Integration (`mobile/kabadiwala-lite.html`)
119
+
120
+ - Extend Step 1 of Collector Lite: Stage 1 21-class classifier detects `PCB` $\rightarrow$ prompts guided Front/Back photo capture $\rightarrow$ triggers `pcb_analyzer`.
121
+ - Displays BIS score, missing-component breakdown, and transparent price adjustment in Step 3.
122
+ - Persists assay JSON into IndexedDB with the scrap slip.
123
+
124
+ ### Component 12: QR Handover Payload Enrichment (`mobile/dealer.html`, backend)
125
+
126
+ - QR payload includes collector BIS score, form factor, and assay report hash.
127
+
128
+ ### Component 13: Recycler Portal BIS-Delta View (`recycler-dashboard-frontend/`)
129
+
130
+ - Re-scan intake lot via `pcb_analyzer`.
131
+ - Tolerance Bands:
132
+ - $< 12\%$ BIS Drop $\rightarrow$ Normal capture variance (Pass).
133
+ - $12\text{--}25\%$ BIS Drop $\rightarrow$ Discrepancy Flagged.
134
+ - $> 25\%$ BIS Drop $\rightarrow$ Critical Fraud Alert & CPCB Form 6 PDF Audit Log Entry.
135
+
136
+ ### Component 14: Backend API Changes (`backend/`)
137
+
138
+ - [NEW] `POST /api/lots/{lot_id}/assay` & `GET /api/lots/{lot_id}/bis-delta`.
139
+
140
+ ---
141
+
142
+ ## Sequencing Summary
143
+
144
+ | | Track A (Model & Dataset) | Track B (App Integration) |
145
+ |---|---|---|
146
+ | Now | Tier 1: bootstrap from open datasets. Tier 3: harvest dirty/stripped/unpopulated boards; annotate fine-grained taxonomy. Tier 2 (mined web sources) blocked pending licensing decision | Build multi-angle UI & pricing engine against `MockModelClient` |
147
+ | Parallel | Multi-scale YOLOv8 training with focal loss & TFLite INT8 quantization | Collector Lite, audio fallbacks, Recycler Portal BIS-delta tolerance UI |
148
+ | Hand-off | Ship model clearing Phase 4 thresholds | Swap `TFLiteModelClient` in with zero code changes |
google_drive_export/docs/scraper_plan_v2.md ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # E-Waste Image Dataset Pipeline: Revised Plan (v2)
2
+
3
+ ## 0. What changed from v1
4
+
5
+ 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:
6
+
7
+ | Area | v1 | v2 |
8
+ | :--- | :--- | :--- |
9
+ | Class definitions | Scrape folders and annotation classes disagreed | One taxonomy defined first; queries derived from it |
10
+ | Deduplication | MD5 only (byte-identical) | Exact hash + perceptual hash (flip-aware) + embedding clusters, global across classes |
11
+ | Aspect-ratio filter | Discarded > 3:1 (removes RAM/edge-finger images) | Flag > 3:1, discard only > 6:1 |
12
+ | Min resolution | 250 px | Short side ≥ 480 px, long side ≥ 800 px |
13
+ | Relevance | None | CLIP zero-shot filter + manual review queue |
14
+ | Domain gap | Web images only | Real-world capture set, held-out real-world test split |
15
+ | Splits | Random train/val | Cluster-aware train/val + separate real-world test |
16
+ | Small objects | Not addressed | Resolution policy, `imgsz=1280`, tiling/two-stage inference |
17
+ | Image handling | `verify()` only, JPEG q90 | `verify()` + `load()`, EXIF fix, alpha compositing, q95, originals preserved |
18
+ | Resilience | Claimed backoff/fallback that `icrawler` lacks | Custom downloader with retries, backoff, per-domain rate limits |
19
+ | Provenance | Sequential filenames | Hash filenames + SQLite manifest, resumable stages |
20
+ | Targets & metrics | None | Per-class image/instance targets, evaluation plan |
21
+ | BIS | Undefined | Proposed definition (needs sign-off) |
22
+
23
+ ---
24
+
25
+ ## 1. Objective & Scope
26
+
27
+ 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.
28
+
29
+ **In scope:** collection, validation, normalization, deduplication, relevance filtering, manifesting, splitting, annotation guidelines, training/evaluation plan, export.
30
+ **Out of scope for this document:** app UI, backend, pricing/valuation logic beyond BIS inputs.
31
+
32
+ ### Success criteria
33
+
34
+ - ≥ 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).
35
+ - Zero train/val/test leakage (no near-duplicate or same-board pairs across splits).
36
+ - ≥ 40% of the final set is "in-the-wild" imagery (dirty, cluttered, phone-shot), not clean listing photos.
37
+ - Held-out real-world test set of ≥ 300 images that is never used for tuning.
38
+ - Every image traceable to its source URL, query, and processing history via the manifest.
39
+
40
+ ---
41
+
42
+ ## 2. Phase 0: Decisions to lock before writing code
43
+
44
+ ### 2.1 Detection taxonomy (fixes the v1 class mismatch)
45
+
46
+ Define **object classes** (what YOLO detects) separately from **image-level tags** (metadata used for search and stratification).
47
+
48
+ **Detection classes (v1 of the label set):**
49
+
50
+ | Class | Definition | Notes |
51
+ | :--- | :--- | :--- |
52
+ | `cpu_socket` | LGA, PGA, or ZIF processor socket footprint (populated or empty) | Sockets only; see BGA note below |
53
+ | `gold_finger` | Gold-plated edge-connector contacts (PCIe, RAM, edge cards) | Long, thin objects; boxes must not be forced square |
54
+ | `ic_chip` | Packaged ICs, including BGA-package chips soldered to the board | Optional sub-attribute `bga` in annotation tool |
55
+ | `tantalum_capacitor` | SMD tantalum capacitors (typically yellow/orange/black molded bodies with polarity bar) | Small object; needs labeling rules |
56
+ | `desoldered_zone` | Region with exposed pads/solder residue where a component was removed | Ambiguous; needs a precise definition and example gallery |
57
+
58
+ > **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.
59
+
60
+ **Image-level tags (manifest metadata, not YOLO classes):**
61
+
62
+ - `board_type`: desktop, laptop, phone, server, GPU, other
63
+ - `condition`: intact, stripped, burnt/damaged
64
+ - `source_type`: listing (white background), in_the_wild, recycling_yard, render/diagram (to be discarded)
65
+
66
+ Folders are **not labels**. Search-query hints are noisy and are stored only as `class_hint` metadata.
67
+
68
+ ### 2.2 Target counts and attrition budget
69
+
70
+ 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.
71
+
72
+ | Class | Target images | Target instances | Difficulty |
73
+ | :--- | :--- | :--- | :--- |
74
+ | `ic_chip` | 1,500 | 15,000+ | Easy (abundant) |
75
+ | `cpu_socket` | 1,500 | 3,000+ | Medium |
76
+ | `gold_finger` | 1,500 | 5,000+ | Medium |
77
+ | `tantalum_capacitor` | 1,500 | 10,000+ | Hard (small, visually varied) |
78
+ | `desoldered_zone` | 1,500 | 5,000+ | Hard (ambiguous) |
79
+
80
+ 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.
81
+
82
+ ### 2.3 Board Integrity Score (BIS): proposed definition
83
+
84
+ BIS must be defined now because it determines which labels are needed.
85
+
86
+ Proposal (needs domain-owner sign-off):
87
+
88
+ ```
89
+ V_present = Σ over detected high-value classes c of w_c × count_c
90
+ (cpu_socket, gold_finger, ic_chip, tantalum_capacitor)
91
+ V_missing = w_d × (number or area-normalized sum of desoldered_zone detections)
92
+
93
+ BIS = 100 × V_present / (V_present + V_missing)
94
+ ```
95
+
96
+ 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`.
97
+
98
+ ---
99
+
100
+ ## 3. System Architecture
101
+
102
+ ```mermaid
103
+ flowchart TD
104
+ A["Config: taxonomy + query matrix"] --> B["URL harvest via icrawler: Bing / Baidu / Flickr"]
105
+ B --> C["Resilient downloader: retry, backoff, rate limit"]
106
+ RW["Real-world photo capture"] --> E
107
+ C --> D[("Originals store: untouched bytes, sha256 names")]
108
+ D --> E{"Validation"}
109
+ E -- "fail: corrupt, under 20 KB, below min resolution, over 6:1" --> X["Discard and log reason"]
110
+ E -- "pass (flag if over 3:1)" --> F["Normalize: EXIF fix, RGB, JPEG q95"]
111
+ F --> G{"Dedup: exact + perceptual, global"}
112
+ G -- "duplicate" --> X
113
+ G -- "unique" --> H{"CLIP relevance filter"}
114
+ H -- "irrelevant" --> X
115
+ H -- "borderline" --> R["Manual review queue"]
116
+ H -- "relevant" --> M["Manifest: SQLite"]
117
+ R --> M
118
+ M --> S["Cluster-aware split: train / val / test"]
119
+ S --> L["Annotation: CVAT or Roboflow"]
120
+ L --> T["YOLO training and evaluation"]
121
+ ```
122
+
123
+ Design principles:
124
+
125
+ 1. **Stages are idempotent and resumable.** Each image has a `status` in the manifest; reruns skip completed work.
126
+ 2. **Originals are never modified.** Normalized copies are derived artifacts and can be regenerated with different settings.
127
+ 3. **Every discard is logged with a reason** so thresholds can be tuned from data instead of guesses.
128
+
129
+ ---
130
+
131
+ ## 4. Directory & Dataset Schema
132
+
133
+ ```
134
+ ewaste_dataset_pipeline/
135
+ ├── scraper.py # CLI entry point (subcommands: harvest, validate, process, dedup, filter, split, report)
136
+ ├── config/
137
+ │ ├── config.yaml # thresholds, engines, rate limits, seeds
138
+ │ ├── taxonomy.yaml # classes, definitions, image-level tags
139
+ │ └── queries.yaml # query matrix (see §5.1)
140
+ ├── pipeline/
141
+ │ ├── crawler.py # URL harvest + custom downloader
142
+ │ ├── validator.py
143
+ │ ├── processor.py # normalization
144
+ │ ├── dedup.py # exact + perceptual + embedding clusters
145
+ │ ├── relevance.py # CLIP zero-shot filter
146
+ │ ├── manifest.py # SQLite state store + JSONL/CSV export
147
+ │ ├── split.py # cluster-aware splitting
148
+ │ └── report.py # summary statistics
149
+ ├── tests/
150
+ │ ├── fixtures/ # truncated JPEG, RGBA PNG, EXIF-rotated, CMYK, animated GIF, 5:1 RAM image
151
+ │ └── test_*.py
152
+ ├── data/
153
+ │ ├── originals/ # untouched downloaded bytes: <sha256[:16]>.<orig_ext>
154
+ │ ├── images/ # normalized JPEGs: <sha256[:16]>.jpg (flat store)
155
+ │ ├── review/ # borderline / flagged images for manual review
156
+ │ ├── realworld/ # own captures, organized by session_id
157
+ │ ├── manifest.db # SQLite source of truth
158
+ │ └── manifest.jsonl # export for tooling
159
+ ├── splits/
160
+ │ └── splits.json # frozen image_id -> split mapping (versioned)
161
+ ├── reports/
162
+ │ └── summary.json
163
+ ├── dataset_annotated/ # YOLO export after labeling
164
+ │ ├── data.yaml
165
+ │ ├── train/
166
+ │ ├── val/
167
+ │ └── test/ # real-world sessions only
168
+ ├── docs/
169
+ │ ├── decisions.md
170
+ │ └── labeling_guide.md
171
+ └── requirements.txt
172
+ ```
173
+
174
+ 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.
175
+
176
+ ---
177
+
178
+ ## 5. Core Modules
179
+
180
+ ### 5.1 Query & Category Registry (`queries.yaml`)
181
+
182
+ 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.
183
+
184
+ **Expansion matrix:** `class term × board_type × condition × view/lighting × language`
185
+
186
+ | Axis | Example values |
187
+ | :--- | :--- |
188
+ | Board type | desktop motherboard, laptop mainboard, smartphone PCB, server board, GPU PCB |
189
+ | Condition | intact, stripped, burnt, corroded, dusty |
190
+ | View / setting | top view, close-up macro, angled, recycling bin, workbench, e-waste pile, hand-held |
191
+ | Language | English, plus Chinese, Spanish, German, Hindi, Vietnamese (recycling hubs and local marketplaces) |
192
+
193
+ Example seed terms per class:
194
+
195
+ - `cpu_socket`: "LGA 1151 socket close up", "LGA 1700 socket bent pins", "PGA socket AM4 motherboard", "empty CPU socket motherboard scrap"
196
+ - `gold_finger`: "PCIe x16 gold fingers PCB", "RAM module gold contacts scrap", "edge connector gold plated board"
197
+ - `ic_chip`: "BGA chip on motherboard close up", "SMD IC laptop motherboard", "chipset heatsink removed motherboard"
198
+ - `tantalum_capacitor`: "SMD tantalum capacitor yellow PCB", "tantalum capacitor polarity stripe board", "tantalum capacitors recycling"
199
+ - `desoldered_zone`: "desoldered components exposed pads PCB", "cannibalized motherboard ewaste scrap", "hot air removed chips board", "burnt circuit board blowtorch"
200
+
201
+ Notes:
202
+
203
+ - Search engines cap results per query (often a few hundred at best), so **volume comes from query variety**, not from raising `max_num`.
204
+ - Record `query`, `engine`, and `class_hint` per URL in the manifest.
205
+
206
+ ### 5.2 Harvesting & Download Engine (`crawler.py`)
207
+
208
+ - **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.
209
+ - **Two-step design:**
210
+ 1. Use `icrawler` to harvest URLs and metadata into the manifest with status `pending`.
211
+ 2. A custom downloader (subclass of `icrawler`'s `ImageDownloader`, or a `requests` session pool) performs the fetch.
212
+ - **Resilience (implemented explicitly, since `icrawler` does not provide it):**
213
+ - Exponential backoff with jitter (e.g., `tenacity`), max 4 retries
214
+ - Per-domain rate limiting and concurrency caps
215
+ - Connect/read timeouts (e.g., 5s / 20s), maximum download size (e.g., 25 MB)
216
+ - Content-Type and magic-byte sniffing before saving
217
+ - Rotating realistic User-Agent strings
218
+ - Respect HTTP 429 / `Retry-After`
219
+ - **Concurrency:** 4-8 downloader threads per query, global cap across queries.
220
+ - **Resumability:** URL-normalized dedup at the manifest level so reruns never re-fetch a URL already tried (successful or permanently failed).
221
+ - **Storage:** save untouched bytes to `data/originals/` under `<sha256[:16]>.<ext>`.
222
+
223
+ ### 5.3 Validation Engine (`validator.py`)
224
+
225
+ Checks run in a fixed order so cheap checks fail first:
226
+
227
+ | # | Check | Rule | Action |
228
+ | :--- | :--- | :--- | :--- |
229
+ | 1 | File size | < 20 KB | Discard (`too_small_file`) |
230
+ | 2 | Integrity | `Image.open()` → `verify()` → **reopen** → `load()` (catches truncation that `verify()` misses) | Discard (`corrupt`) |
231
+ | 3 | Animated | Multi-frame GIF/WEBP | Use first frame; flag `animated` |
232
+ | 4 | Resolution | Short side < 480 px **or** long side < 800 px | Discard (`low_resolution`) |
233
+ | 5 | Aspect ratio | > 3:1 or < 1:3 | **Flag** `extreme_aspect`, send to review |
234
+ | 6 | Aspect ratio (hard) | > 6:1 or < 1:6 | Discard (`extreme_aspect_hard`) |
235
+
236
+ 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.
237
+
238
+ Why the resolution change: tantalum capacitors and desoldered zones occupy very few pixels; a 250 px image contains almost no usable detail for them.
239
+
240
+ ### 5.4 Normalization Engine (`processor.py`)
241
+
242
+ Applied to a **copy** of each validated image:
243
+
244
+ 1. **`ImageOps.exif_transpose()`** first, so phone photos are not rotated incorrectly.
245
+ 2. **Mode conversion to RGB:**
246
+ - RGBA / LA / P-with-transparency: composite onto a **white** background (a naive `convert("RGB")` turns transparency black).
247
+ - CMYK: convert via embedded ICC profile when present (`ImageCms`), otherwise standard conversion.
248
+ - Grayscale: replicate to 3 channels.
249
+ 3. **Size cap:** if the long side > 2560 px, downscale with LANCZOS (never upscale). This bounds storage while preserving detail for small objects.
250
+ 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.
251
+ 5. **Metadata:** strip EXIF (privacy and size); store dimensions and original format in the manifest.
252
+ 6. Output name: `data/images/<sha256[:16]>.jpg`, where the hash is of the original file bytes.
253
+
254
+ ### 5.5 Deduplication Engine (`dedup.py`)
255
+
256
+ 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**:
257
+
258
+ | Layer | Method | Catches |
259
+ | :--- | :--- | :--- |
260
+ | 1. Exact | SHA-256 of original bytes (pre-decode) and of decoded pixel array | Byte-identical and re-saved-identical images |
261
+ | 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 |
262
+ | 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 |
263
+
264
+ Implementation notes:
265
+
266
+ - For ≤ 100k images, pairwise Hamming comparison with vectorized NumPy popcount is fast enough; use a BK-tree or LSH banding beyond that.
267
+ - Within a duplicate group, **keep the highest-resolution member** and record all members' URLs under it in the manifest.
268
+ - 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).
269
+
270
+ ### 5.6 Relevance Filter (`relevance.py`)
271
+
272
+ Search results contain many stock illustrations, renders, diagrams, product boxes, logos, and off-topic hardware.
273
+
274
+ - **Model:** `open_clip` (e.g., ViT-B/32) zero-shot scoring.
275
+ - **Positive prompts:** "a photo of a printed circuit board", "a photo of a computer motherboard", "a photo of electronic waste".
276
+ - **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".
277
+ - **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.
278
+ - **`source_type` tagging:** use zero-shot prompts to estimate `listing` vs `in_the_wild` so the domain mix can be monitored.
279
+ - **Watermarks/stock:** flagged, not auto-discarded (zero-shot watermark detection is unreliable). Flagged images go to review.
280
+
281
+ ### 5.7 Manual Review
282
+
283
+ - Review **all** `borderline` and `extreme_aspect` items, plus a **10% random sample** of auto-kept images to estimate residual noise.
284
+ - Use a contact-sheet tool (FiftyOne or a simple generated HTML grid) that supports keep/discard/re-tag.
285
+ - Record reviewer decisions in the manifest (`review_status`, `reviewer`, `reviewed_at`).
286
+
287
+ ### 5.8 Manifest & Provenance (`manifest.py`)
288
+
289
+ SQLite is the source of truth, exported to JSONL/CSV for tooling. One row per image (plus a table of source URLs per image).
290
+
291
+ | Field | Description |
292
+ | :--- | :--- |
293
+ | `image_id` | sha256[:16] of original bytes |
294
+ | `source_urls[]` | all URLs that produced this image |
295
+ | `engine`, `queries[]`, `class_hints[]` | how it was found |
296
+ | `scraped_at` | timestamp |
297
+ | `orig_format`, `width`, `height`, `filesize`, `aspect_ratio` | measured properties |
298
+ | `flags[]` | `extreme_aspect`, `animated`, `watermark_suspect`, etc. |
299
+ | `phash`, `dhash` | perceptual hashes |
300
+ | `cluster_id` | duplicate/semantic cluster |
301
+ | `clip_score`, `relevance_bucket` | filter outputs |
302
+ | `board_type`, `condition`, `source_type` | image-level tags |
303
+ | `status` | `pending → downloaded → validated → normalized → deduped → filtered → kept` or `discarded` |
304
+ | `discard_reason` | why it was removed |
305
+ | `review_status` | reviewer outcome |
306
+ | `split` | `train` / `val` / `test` (set by §6) |
307
+ | `session_id`, `board_id` | for real-world captures |
308
+
309
+ ---
310
+
311
+ ## 6. Real-World Data & Splitting
312
+
313
+ ### 6.1 Real-world capture set (closes the domain gap)
314
+
315
+ Web results skew toward clean listing photos. The deployed app will see dirty, cluttered, phone-shot boards under poor lighting.
316
+
317
+ - Capture **≥ 300 test images plus ≥ 300 additional training images** from recycling partners or a bench setup.
318
+ - Vary: phone models, lighting (daylight, warm, harsh flash, dim), backgrounds, distances (macro to whole-board), angles, board types, and conditions.
319
+ - Record `session_id` (one per visit/location/day) and `board_id` (one per physical board). Photograph each board from multiple angles.
320
+ - Capture at native phone resolution; keep originals.
321
+
322
+ ### 6.2 Split policy (leakage-safe)
323
+
324
+ | Split | Composition | Rule |
325
+ | :--- | :--- | :--- |
326
+ | `train` | Web + real-world training sessions | ~80% of the non-test pool |
327
+ | `val` | Web + real-world training sessions | ~20% of the non-test pool; used for model selection |
328
+ | `test` | **Real-world sessions only, held out** | Never used for tuning or threshold selection; sessions not present in train/val |
329
+
330
+ - 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.
331
+ - Stratify on `class_hints` and `source_type` where feasible so val reflects the domain mix.
332
+ - Freeze the result in `splits/splits.json` with the random seed; regenerate only by explicit version bump.
333
+
334
+ ---
335
+
336
+ ## 7. Annotation
337
+
338
+ - Write `docs/labeling_guide.md` **before** labeling: definitions and 10+ positive/negative example crops per class, plus edge cases (partially occluded, damaged, blurry).
339
+ - **Label at full resolution** (never label downscaled copies).
340
+ - **Minimum object size policy:** objects smaller than ~16 px at the intended training resolution are either marked `ignore` or excluded consistently; document the choice.
341
+ - Boxes: tight; `gold_finger` boxes follow the actual (elongated) strip; no padding to squares.
342
+ - **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.
343
+ - Tools: CVAT or Roboflow. Export in YOLO format with the frozen splits.
344
+
345
+ ---
346
+
347
+ ## 8. Training & Evaluation Plan
348
+
349
+ ### 8.1 Small-object strategy
350
+
351
+ - Train with **`imgsz=1280`** (or 960 as a compromise) rather than the 640 default.
352
+ - For on-device use, avoid running the full nano model at 1280 on a phone. Two options to evaluate:
353
+ 1. **Tiled inference** (SAHI-style): overlapping 640 px tiles with merged detections.
354
+ 2. **Two-stage:** a light board detector at 640 → crop board → component detector on the crop.
355
+ - Consider mosaic/scale augmentation tuned for small objects; verify augmentations do not destroy `gold_finger` aspect ratios.
356
+
357
+ ### 8.2 Metrics
358
+
359
+ - mAP@50 and mAP@50-95 **per class**, not just overall.
360
+ - **Recall by object-size bucket** (small / medium / large by pixel area), to expose the small-object problem.
361
+ - Report results on `val` and, separately, on the real-world `test` split. **The test-set number is the headline number.**
362
+ - BIS validation: compare BIS from ground-truth labels vs BIS from detections on the test set, and report the error.
363
+
364
+ ### 8.3 Export checks
365
+
366
+ - 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/`.
367
+
368
+ ---
369
+
370
+ ## 9. Technical Stack
371
+
372
+ | Tool / Library | Role |
373
+ | :--- | :--- |
374
+ | Python 3.10+ | Runtime |
375
+ | `icrawler` | URL harvesting (Bing, Baidu, Flickr; Google optional) |
376
+ | `requests`, `tenacity` | Custom downloader with retry/backoff |
377
+ | `Pillow` | Validation, EXIF handling, normalization, ICC conversion |
378
+ | `numpy` | Vectorized hash comparison |
379
+ | `imagehash` | Perceptual hashing (pHash/dHash) |
380
+ | `hashlib` | Exact SHA-256 hashing |
381
+ | `open_clip_torch` + `torch` | Relevance filter and embeddings for clustering |
382
+ | `scikit-learn` | Group-aware splitting, clustering |
383
+ | `PyYAML` | Configuration |
384
+ | `tqdm` | Progress monitoring |
385
+ | `fiftyone` (optional) | Review UI, embedding visualization |
386
+ | `ultralytics`, `sahi` | Training and tiled inference |
387
+ | `pytest` | Tests |
388
+
389
+ Pin exact versions in `requirements.txt` and record them in every report.
390
+
391
+ ---
392
+
393
+ ## 10. Execution Plan
394
+
395
+ ### Step 1: Install
396
+
397
+ ```bash
398
+ pip install -r requirements.txt
399
+ ```
400
+
401
+ ### Step 2: Run stages (each is resumable)
402
+
403
+ ```bash
404
+ python3 scraper.py harvest --config config/config.yaml # collect URLs into manifest
405
+ python3 scraper.py download # fetch originals with retries
406
+ python3 scraper.py validate # integrity, size, aspect
407
+ python3 scraper.py process # EXIF fix, RGB, JPEG q95
408
+ python3 scraper.py dedup # exact + perceptual + clusters
409
+ python3 scraper.py filter # CLIP relevance + review queue
410
+ python3 scraper.py split # cluster-aware splits
411
+ python3 scraper.py report # summary statistics
412
+ ```
413
+
414
+ ### Step 3: Verification report (`reports/summary.json` and printed table)
415
+
416
+ Per `class_hint` and overall:
417
+
418
+ - Raw URLs harvested, downloads succeeded/failed
419
+ - Discards **by reason** (corrupt, too small, low resolution, hard aspect, exact dup, near dup, irrelevant)
420
+ - Flagged and reviewed counts
421
+ - Final kept count vs target (§2.2)
422
+ - Resolution distribution and `source_type` mix (in-the-wild share vs the 40% goal)
423
+ - Number of duplicate clusters and largest cluster size
424
+ - Split sizes and a leakage check (no `cluster_id`/`board_id` shared across splits)
425
+
426
+ ---
427
+
428
+ ## 11. Testing
429
+
430
+ Unit tests using fixtures in `tests/fixtures/`:
431
+
432
+ | Test | Expectation |
433
+ | :--- | :--- |
434
+ | Truncated JPEG | Rejected by the `verify()` + `load()` sequence |
435
+ | RGBA PNG with transparency | Composited on white, not black |
436
+ | EXIF-rotated phone photo | Output is upright |
437
+ | CMYK JPEG | Correct RGB conversion |
438
+ | Animated GIF | First frame used, `animated` flag set |
439
+ | 5:1 RAM image | Flagged, **not** discarded |
440
+ | 8:1 banner | Discarded with `extreme_aspect_hard` |
441
+ | Resized / recompressed / flipped copy of a fixture | Detected as near-duplicate |
442
+ | Rerun after interruption | No re-download, no duplicate rows |
443
+ | Leakage check | No shared `cluster_id` across splits |
444
+
445
+ ---
446
+
447
+ ## 12. Milestones & Acceptance Criteria
448
+
449
+ | Phase | Deliverable | Acceptance criterion |
450
+ | :--- | :--- | :--- |
451
+ | 0. Decisions | `taxonomy.yaml`, target counts, BIS definition in `docs/decisions.md` | Signed off by project owner |
452
+ | 1. Pipeline build | All modules + tests passing | Fixtures behave as specified in §11 |
453
+ | 2. Pilot | ~500-image end-to-end run | Attrition rate measured; CLIP thresholds tuned on 200 hand-labeled images |
454
+ | 3. Full collection | Harvest budget executed; real-world capture ≥ 600 images | Kept counts meet §2.2 or gaps identified and queries extended |
455
+ | 4. QA | Manual review complete; frozen `splits.json` | Leakage check clean; ≥ 40% in-the-wild |
456
+ | 5. Annotation | Labeled dataset + `labeling_guide.md` | Inter-annotator agreement acceptable per class |
457
+ | 6. Training & eval | Baseline model, per-class and size-bucket metrics | Test-set results reported; failure analysis written |
458
+ | 7. Export | ONNX/TFLite + post-quantization test results | mAP drop within budget; BIS error reported |
459
+
460
+ ---
461
+
462
+ ## 13. Risks & Mitigations
463
+
464
+ | Risk | Mitigation |
465
+ | :--- | :--- |
466
+ | Search engines return too few unique images per query | Wide query matrix (§5.1), multiple engines, multilingual queries, real-world capture |
467
+ | Heavy overrepresentation of clean listing photos | `source_type` monitoring; explicit in-the-wild target; real-world capture |
468
+ | Tiny objects (tantalum caps) undetectable | Higher min resolution, `imgsz=1280`, tiling/two-stage, small-object metrics |
469
+ | `desoldered_zone` label ambiguity | Precise definition, example gallery, double annotation, willingness to redefine or move to segmentation |
470
+ | Near-duplicate leakage inflates metrics | Cluster-aware splits, leakage check in CI, held-out real-world test set |
471
+ | CLIP filter discards valid images | Threshold tuned on hand-labeled sample; borderline goes to review, not discard |
472
+ | Class imbalance (ICs abundant, tantalum rare) | Per-class targets, targeted queries and captures for rare classes, per-class metrics |
473
+ | Quantization degrades small-object accuracy | Post-export evaluation with a mAP-drop budget; consider mixed precision |
474
+ | Pipeline state lost mid-run | SQLite manifest, idempotent stages, originals preserved |
475
+ | BIS unstable or not meaningful | Define and validate BIS against ground-truth labels early (§2.3, §8.2) |
476
+
477
+ ---
478
+
479
+ ## 14. Immediate Next Actions
480
+
481
+ 1. Review and finalize the taxonomy and class definitions (§2.1).
482
+ 2. Get domain input on BIS weights and whether BIS uses counts or area (§2.3).
483
+ 3. Stand up the repository skeleton from §4, with config, manifest schema, and test fixtures.
484
+ 4. Run the 500-image pilot to measure attrition and tune the relevance thresholds.
485
+ 5. Schedule the first real-world capture session so the test set starts accumulating early.
google_drive_export/pipeline/__init__.py ADDED
File without changes
google_drive_export/pipeline/auto_annotate.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Automated Zero-Shot Auto-Annotation Pipeline using YOLO-World.
2
+
3
+ Auto-labels all images in `data/images/` using the updated taxonomy:
4
+ 0: cpu_socket
5
+ 1: gold_finger
6
+ 2: ic_chip
7
+ 3: tantalum_capacitor
8
+ 4: forcibly_desoldered_pad
9
+ 5: factory_unpopulated_pad
10
+ 6: occluded_region
11
+
12
+ Generates YOLO format bounding box label files (.txt) and data.yaml in `data/annotated_auto/`.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ import os
19
+ import shutil
20
+ from pathlib import Path
21
+
22
+ import yaml
23
+ from PIL import Image
24
+ from tqdm import tqdm
25
+
26
+ # Ensure cache directories reside within workspace
27
+ cache_dir = Path("data/cache").resolve()
28
+ cache_dir.mkdir(parents=True, exist_ok=True)
29
+ os.environ["TORCH_HOME"] = str(cache_dir)
30
+ os.environ["HF_HOME"] = str(cache_dir)
31
+
32
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
33
+ log = logging.getLogger(__name__)
34
+
35
+ CLASS_NAMES = [
36
+ "cpu_socket",
37
+ "gold_finger",
38
+ "ic_chip",
39
+ "tantalum_capacitor",
40
+ "forcibly_desoldered_pad",
41
+ "factory_unpopulated_pad",
42
+ "occluded_region",
43
+ ]
44
+
45
+ # Prompts tuned for zero-shot YOLO-World detector
46
+ CLASS_PROMPTS = [
47
+ "CPU socket",
48
+ "gold finger edge connector",
49
+ "microchip",
50
+ "tantalum capacitor",
51
+ "desoldered solder pad",
52
+ "unpopulated solder pad",
53
+ "heatsink shield",
54
+ ]
55
+
56
+
57
+ def run_auto_annotation(
58
+ data_dir: str | Path = "data",
59
+ output_dir: str | Path = "data/annotated_auto",
60
+ conf_threshold: float = 0.02,
61
+ max_images: int | None = None,
62
+ ) -> dict:
63
+ data_dir = Path(data_dir)
64
+ output_dir = Path(output_dir)
65
+ images_in_dir = data_dir / "images"
66
+
67
+ images_out_dir = output_dir / "images"
68
+ labels_out_dir = output_dir / "labels"
69
+ images_out_dir.mkdir(parents=True, exist_ok=True)
70
+ labels_out_dir.mkdir(parents=True, exist_ok=True)
71
+
72
+ log.info("Loading YOLO-World zero-shot model...")
73
+ from ultralytics import YOLOWorld
74
+
75
+ model = YOLOWorld("yolov8s-worldv2.pt")
76
+ model.set_classes(CLASS_PROMPTS)
77
+ log.info("YOLO-World model configured with %d classes (conf threshold: %.3f).", len(CLASS_PROMPTS), conf_threshold)
78
+
79
+ image_files = sorted(list(images_in_dir.glob("*.jpg")) + list(images_in_dir.glob("*.png")))
80
+ if max_images:
81
+ image_files = image_files[:max_images]
82
+
83
+ log.info("Found %d images to auto-annotate.", len(image_files))
84
+
85
+ class_detection_counts = {name: 0 for name in CLASS_NAMES}
86
+ total_images_processed = 0
87
+ total_boxes_generated = 0
88
+
89
+ for img_path in tqdm(image_files, desc="Auto-annotating images", unit="img"):
90
+ img_name = img_path.name
91
+ stem = img_path.stem
92
+
93
+ # Copy image to output directory
94
+ target_img_path = images_out_dir / img_name
95
+ if not target_img_path.exists():
96
+ try:
97
+ shutil.copy2(img_path, target_img_path)
98
+ except Exception as e:
99
+ log.warning("Could not copy %s: %s", img_name, e)
100
+
101
+ # Run inference
102
+ results = model.predict(str(img_path), conf=conf_threshold, verbose=False)
103
+ label_file = labels_out_dir / f"{stem}.txt"
104
+
105
+ lines = []
106
+ if results and len(results) > 0:
107
+ boxes = results[0].boxes
108
+ if boxes is not None and len(boxes) > 0:
109
+ xywhn = boxes.xywhn.cpu().numpy()
110
+ cls_ids = boxes.cls.cpu().numpy().astype(int)
111
+
112
+ for (x, y, w, h), cls_id in zip(xywhn, cls_ids):
113
+ if 0 <= cls_id < len(CLASS_NAMES):
114
+ lines.append(f"{cls_id} {x:.6f} {y:.6f} {w:.6f} {h:.6f}")
115
+ class_name = CLASS_NAMES[cls_id]
116
+ class_detection_counts[class_name] += 1
117
+ total_boxes_generated += 1
118
+
119
+ with open(label_file, "w", encoding="utf-8") as f:
120
+ f.write("\n".join(lines) + ("\n" if lines else ""))
121
+
122
+ total_images_processed += 1
123
+
124
+ # Create dataset yaml specification
125
+ dataset_yaml = {
126
+ "path": str(output_dir.resolve()),
127
+ "train": "images",
128
+ "val": "images",
129
+ "names": {i: name for i, name in enumerate(CLASS_NAMES)},
130
+ }
131
+ yaml_path = output_dir / "data.yaml"
132
+ with open(yaml_path, "w", encoding="utf-8") as f:
133
+ yaml.dump(dataset_yaml, f, default_flow_style=False)
134
+
135
+ summary = {
136
+ "total_images_processed": total_images_processed,
137
+ "total_boxes_generated": total_boxes_generated,
138
+ "conf_threshold": conf_threshold,
139
+ "class_detection_counts": class_detection_counts,
140
+ "output_directory": str(output_dir.resolve()),
141
+ "data_yaml": str(yaml_path.resolve()),
142
+ }
143
+
144
+ summary_path = output_dir / "auto_annotation_summary.json"
145
+ with open(summary_path, "w", encoding="utf-8") as f:
146
+ json.dump(summary, f, indent=2)
147
+
148
+ log.info("Auto-annotation complete! Summary saved to %s", summary_path)
149
+ return summary
150
+
151
+
152
+ if __name__ == "__main__":
153
+ import sys
154
+ max_imgs = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else None
155
+ conf_val = float(sys.argv[2]) if len(sys.argv) > 2 else 0.02
156
+ run_auto_annotation(conf_threshold=conf_val, max_images=max_imgs)
157
+
google_drive_export/pipeline/config.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration loading, filesystem layout and logging setup."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import logging
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import yaml
12
+
13
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
14
+
15
+
16
+ def load_yaml(path: Path) -> dict[str, Any]:
17
+ with open(path, "r", encoding="utf-8") as fh:
18
+ return yaml.safe_load(fh) or {}
19
+
20
+
21
+ def deep_update(base: dict, override: dict) -> dict:
22
+ """Recursively merge ``override`` into ``base`` (in place) and return it."""
23
+ for key, value in override.items():
24
+ if isinstance(value, dict) and isinstance(base.get(key), dict):
25
+ deep_update(base[key], value)
26
+ else:
27
+ base[key] = copy.deepcopy(value)
28
+ return base
29
+
30
+
31
+ def load_config(path: str | Path | None = None, overrides: dict | None = None) -> dict[str, Any]:
32
+ cfg_path = Path(path) if path else PROJECT_ROOT / "config" / "config.yaml"
33
+ cfg = load_yaml(cfg_path)
34
+ cfg["_config_dir"] = str(cfg_path.resolve().parent)
35
+ if overrides:
36
+ deep_update(cfg, overrides)
37
+ return cfg
38
+
39
+
40
+ def load_taxonomy(cfg: dict) -> dict[str, Any]:
41
+ return load_yaml(Path(cfg["_config_dir"]) / "taxonomy.yaml")
42
+
43
+
44
+ def load_queries(cfg: dict) -> dict[str, Any]:
45
+ return load_yaml(Path(cfg["_config_dir"]) / "queries.yaml")
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Paths:
50
+ """Filesystem layout. Manifest paths are stored relative to ``data``."""
51
+
52
+ base: Path
53
+ data: Path
54
+ originals: Path
55
+ images: Path
56
+ review: Path
57
+ realworld: Path
58
+ reports: Path
59
+ splits: Path
60
+ manifest_db: Path
61
+ manifest_jsonl: Path
62
+
63
+ def abs(self, rel: str | Path) -> Path:
64
+ return self.data / rel
65
+
66
+ def rel(self, path: str | Path) -> str:
67
+ return str(Path(path).resolve().relative_to(self.data.resolve()))
68
+
69
+ def ensure(self) -> None:
70
+ for p in (self.data, self.originals, self.images, self.review, self.realworld,
71
+ self.reports, self.splits):
72
+ p.mkdir(parents=True, exist_ok=True)
73
+
74
+
75
+ def get_paths(cfg: dict, base: str | Path | None = None) -> Paths:
76
+ base_dir = Path(base).resolve() if base else PROJECT_ROOT
77
+ pcfg = cfg.get("paths", {})
78
+ data = base_dir / pcfg.get("data_dir", "data")
79
+ return Paths(
80
+ base=base_dir,
81
+ data=data,
82
+ originals=data / "originals",
83
+ images=data / "images",
84
+ review=data / "review",
85
+ realworld=data / "realworld",
86
+ reports=base_dir / pcfg.get("reports_dir", "reports"),
87
+ splits=base_dir / pcfg.get("splits_dir", "splits"),
88
+ manifest_db=data / "manifest.db",
89
+ manifest_jsonl=data / "manifest.jsonl",
90
+ )
91
+
92
+
93
+ def setup_logging(verbose: bool = False) -> None:
94
+ """Configure logging *before* icrawler is imported.
95
+
96
+ icrawler calls ``logging.basicConfig`` when a crawler is constructed; that is a
97
+ no-op once the root logger already has handlers, so configuring first keeps our
98
+ format and level in charge.
99
+ """
100
+ level = logging.DEBUG if verbose else logging.INFO
101
+ root = logging.getLogger()
102
+ if not root.handlers:
103
+ handler = logging.StreamHandler(sys.stderr)
104
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-7s %(name)s: %(message)s",
105
+ datefmt="%H:%M:%S"))
106
+ root.addHandler(handler)
107
+ root.setLevel(level)
108
+ logging.getLogger("urllib3").setLevel(logging.WARNING)
109
+ logging.getLogger("PIL").setLevel(logging.WARNING)
google_drive_export/pipeline/crawler.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harvesting engine: query search engines (icrawler / HTTP fallback) and download raw image binaries.
2
+
3
+ Flow:
4
+ 1. Build query list from queries.yaml matrix.
5
+ 2. For each query and engine:
6
+ - Skip if `harvest_runs` records the run as done.
7
+ - Surface image URLs and store in `sources` and `hits` tables via `manifest.add_hit`.
8
+ - Record completed run in `harvest_runs`.
9
+ 3. Download pending URLs into `data/originals/`, computing SHA-256 ID.
10
+ 4. Register downloaded files in `images` table with status 'downloaded'.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import logging
16
+ import mimetypes
17
+ import urllib.request
18
+ import urllib.error
19
+ from concurrent.futures import ThreadPoolExecutor, as_completed
20
+ from pathlib import Path
21
+ from typing import Sequence
22
+
23
+ from tqdm import tqdm
24
+
25
+ from .manifest import Manifest, normalize_url
26
+ from .queries import QuerySpec, build_queries
27
+
28
+ log = logging.getLogger(__name__)
29
+
30
+ HEADERS = {
31
+ "User-Agent": (
32
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
33
+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
34
+ ),
35
+ "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
36
+ }
37
+
38
+ EXT_MAP = {
39
+ "image/jpeg": ".jpg",
40
+ "image/jpg": ".jpg",
41
+ "image/png": ".png",
42
+ "image/webp": ".webp",
43
+ "image/gif": ".gif",
44
+ "image/bmp": ".bmp",
45
+ "image/tiff": ".tif",
46
+ "image/heic": ".heic",
47
+ "image/heif": ".heif",
48
+ }
49
+
50
+
51
+ def download_single_url(
52
+ source: dict, originals_dir: Path, timeout: float = 10.0
53
+ ) -> tuple[dict, str | None, str | None, int | None, str | None]:
54
+ """Download raw binary for one URL.
55
+
56
+ Returns (source, image_id, filepath, http_status, error_message).
57
+ """
58
+ url = source["url"]
59
+ url_norm = source["url_norm"]
60
+ req = urllib.request.Request(url, headers=HEADERS)
61
+
62
+ try:
63
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
64
+ content_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower()
65
+ data = resp.read()
66
+ http_status = resp.status
67
+ except urllib.error.HTTPError as exc:
68
+ return source, None, None, exc.code, f"HTTPError: {exc.code}"
69
+ except Exception as exc:
70
+ return source, None, None, None, f"{type(exc).__name__}: {exc}"
71
+
72
+ if len(data) < 500:
73
+ return source, None, None, http_status, "file_too_small_raw"
74
+
75
+ sha = hashlib.sha256(data).hexdigest()
76
+ image_id = sha[:16]
77
+
78
+ ext = EXT_MAP.get(content_type) or Path(url).suffix.lower()
79
+ if not ext or len(ext) > 5 or ext not in (".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".tif", ".heic"):
80
+ ext = ".jpg"
81
+
82
+ dst = originals_dir / f"{image_id}{ext}"
83
+ if not dst.exists():
84
+ originals_dir.mkdir(parents=True, exist_ok=True)
85
+ tmp = dst.with_name(dst.name + f".tmp")
86
+ tmp.write_bytes(data)
87
+ tmp.replace(dst)
88
+
89
+ return source, image_id, str(dst), http_status, None
90
+
91
+
92
+ def download_pending_sources(
93
+ manifest: Manifest, originals_dir: Path, data_dir: Path, cfg: dict
94
+ ) -> dict[str, int]:
95
+ """Download pending URLs from manifest into `originals_dir`."""
96
+ ccfg = cfg.get("crawler", {})
97
+ workers = int(ccfg.get("threads", 4))
98
+ timeout = float(ccfg.get("timeout", 10.0))
99
+
100
+ pending = manifest.pending_sources()
101
+ stats = {"downloaded": 0, "download_failed": 0}
102
+ if not pending:
103
+ log.info("crawler: no pending sources to download")
104
+ return stats
105
+
106
+ log.info("crawler: downloading %d pending URL(s)", len(pending))
107
+
108
+ def work(src: dict):
109
+ return download_single_url(src, originals_dir, timeout=timeout)
110
+
111
+ with ThreadPoolExecutor(max_workers=workers) as ex:
112
+ futures = [ex.submit(work, s) for s in pending]
113
+ with manifest.transaction():
114
+ for fut in tqdm(as_completed(futures), total=len(futures), desc="download", unit="url"):
115
+ src, image_id, dst_path, http_status, err = fut.result()
116
+ if err is None and image_id and dst_path:
117
+ data_file = Path(dst_path)
118
+ data = data_file.read_bytes()
119
+ sha = hashlib.sha256(data).hexdigest()
120
+ rel_path = str(data_file.relative_to(data_dir))
121
+
122
+ manifest.add_image(
123
+ image_id=image_id,
124
+ sha256=sha,
125
+ origin="web",
126
+ source_ref=src["url"],
127
+ orig_path=rel_path,
128
+ orig_format=data_file.suffix.lstrip(".").lower(),
129
+ filesize=len(data),
130
+ status="downloaded",
131
+ )
132
+ manifest.mark_source(
133
+ src["url_norm"],
134
+ status="downloaded",
135
+ http_status=http_status,
136
+ image_id=image_id,
137
+ attempts=1,
138
+ )
139
+ stats["downloaded"] += 1
140
+ else:
141
+ manifest.mark_source(
142
+ src["url_norm"],
143
+ status="failed",
144
+ http_status=http_status,
145
+ error=err,
146
+ attempts=1,
147
+ )
148
+ stats["download_failed"] += 1
149
+
150
+ log.info("crawler download stats: %s", stats)
151
+ return stats
152
+
153
+
154
+ def run_icrawler_harvest(
155
+ manifest: Manifest,
156
+ queries: Sequence[QuerySpec],
157
+ data_dir: Path,
158
+ engine_name: str = "bing",
159
+ max_num: int = 50,
160
+ force: bool = False,
161
+ filter_classes: set[str] | Sequence[str] | None = None,
162
+ ) -> dict[str, int]:
163
+ """Harvest image binaries using icrawler, save to data/originals, and register in manifest."""
164
+ stats = {"runs": 0, "urls_found": 0, "urls_new": 0, "images_harvested": 0}
165
+ try:
166
+ if engine_name.lower() == "bing":
167
+ from icrawler.builtin import BingImageCrawler as CrawlerEngine
168
+ elif engine_name.lower() == "flickr":
169
+ from icrawler.builtin import FlickrImageCrawler as CrawlerEngine
170
+ elif engine_name.lower() == "baidu":
171
+ from icrawler.builtin import BaiduImageCrawler as CrawlerEngine
172
+ else:
173
+ log.warning("Unknown engine '%s', defaulting to Bing", engine_name)
174
+ from icrawler.builtin import BingImageCrawler as CrawlerEngine
175
+ except ImportError:
176
+ log.warning("icrawler is not installed; skipping search engine crawling")
177
+ return stats
178
+
179
+ import tempfile
180
+ import shutil
181
+
182
+ originals_dir = data_dir / "originals"
183
+ originals_dir.mkdir(parents=True, exist_ok=True)
184
+
185
+ filter_set = set(filter_classes) if filter_classes else None
186
+
187
+ for qspec in queries:
188
+ if filter_set and qspec.class_hint not in filter_set:
189
+ continue
190
+ if not force and manifest.run_done(engine_name, qspec.query):
191
+ log.debug("Skip harvest done run: %s / %s", engine_name, qspec.query)
192
+ continue
193
+
194
+ tmp_dir = Path(tempfile.mkdtemp(prefix="icrawler_"))
195
+ try:
196
+ crawler = CrawlerEngine(
197
+ downloader_threads=2,
198
+ storage={"root_dir": str(tmp_dir)},
199
+ log_level=logging.WARNING,
200
+ )
201
+ crawler.crawl(keyword=qspec.query, max_num=max_num)
202
+
203
+ found_count = 0
204
+ new_count = 0
205
+ with manifest.transaction():
206
+ for img_file in tmp_dir.glob("*"):
207
+ if img_file.is_file() and img_file.stat().st_size > 500:
208
+ found_count += 1
209
+ data = img_file.read_bytes()
210
+ sha = hashlib.sha256(data).hexdigest()
211
+ image_id = sha[:16]
212
+ ext = img_file.suffix.lower()
213
+ if not ext or len(ext) > 5 or ext not in (".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"):
214
+ ext = ".jpg"
215
+
216
+ dst_file = originals_dir / f"{image_id}{ext}"
217
+ if not dst_file.exists():
218
+ dst_file.write_bytes(data)
219
+
220
+ source_url = f"icrawler://{engine_name}/{qspec.class_hint}/{image_id}"
221
+ is_new = manifest.add_hit(
222
+ source_url, engine_name, qspec.query, class_hint=qspec.class_hint, lang=qspec.lang
223
+ )
224
+ if is_new:
225
+ new_count += 1
226
+
227
+ rel_path = str(dst_file.relative_to(data_dir))
228
+ manifest.add_image(
229
+ image_id=image_id,
230
+ sha256=sha,
231
+ origin="web",
232
+ source_ref=source_url,
233
+ orig_path=rel_path,
234
+ orig_format=ext.lstrip("."),
235
+ filesize=len(data),
236
+ status="downloaded",
237
+ )
238
+ manifest.mark_source(
239
+ source_url,
240
+ status="downloaded",
241
+ image_id=image_id,
242
+ )
243
+ stats["images_harvested"] += 1
244
+
245
+ manifest.record_run(
246
+ engine_name, qspec.query, qspec.class_hint, max_num, found_count, new_count
247
+ )
248
+ stats["runs"] += 1
249
+ stats["urls_found"] += found_count
250
+ stats["urls_new"] += new_count
251
+ except Exception as exc:
252
+ log.error("icrawler harvest failed for %s (%s): %s", qspec.query, engine_name, exc)
253
+ finally:
254
+ shutil.rmtree(tmp_dir, ignore_errors=True)
255
+
256
+ log.info("harvest stats (%s): %s", engine_name, stats)
257
+ return stats
258
+
259
+
260
+ def run(
261
+ manifest: Manifest, cfg: dict, data_dir: Path, engine: str = "bing", max_num: int = 50, force: bool = False, filter_classes: set[str] | Sequence[str] | None = None
262
+ ) -> dict[str, int]:
263
+ """Full crawler workflow: harvest queries and download raw images."""
264
+ qcfg = cfg.get("queries") or {}
265
+ if not qcfg:
266
+ from .config import load_queries
267
+ qcfg = load_queries(cfg)
268
+
269
+ queries = build_queries(qcfg)
270
+ harvest_stats = run_icrawler_harvest(manifest, queries, data_dir, engine_name=engine, max_num=max_num, force=force, filter_classes=filter_classes)
271
+
272
+ originals_dir = data_dir / "originals"
273
+ download_stats = download_pending_sources(manifest, originals_dir, data_dir, cfg)
274
+
275
+ return {**harvest_stats, **download_stats}
google_drive_export/pipeline/dedup.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deduplication engine (global across all classes and queries).
2
+
3
+ Layer 1 exact SHA-256 of the original bytes (already the image_id, so identical downloads
4
+ collapse at download time) + SHA-256 of the decoded normalized pixels.
5
+ Layer 2 near-dup pHash AND dHash (64-bit each) within a Hamming-distance budget. Every image
6
+ also stores the hashes of its horizontally FLIPPED version, and a pair counts
7
+ as a duplicate if it matches in either orientation (mirror copies).
8
+ Layer 3 semantic CLIP-embedding cosine clustering. This layer never deletes anything; it only
9
+ merges cluster ids so the splitter keeps "same board, different angle" together.
10
+
11
+ Layers 1-2 remove images: within a duplicate group the keeper is chosen by
12
+ (already-processed before new) > (real-world before web) > higher resolution > larger file > id
13
+ so re-running the pipeline never swaps out an image that was already kept or annotated.
14
+ Duplicate groups are connected components (union-find), so chains A~B~C collapse into one group.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from collections import defaultdict
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
21
+ from pathlib import Path
22
+ from typing import Sequence
23
+
24
+ import imagehash
25
+ import numpy as np
26
+ from PIL import Image, ImageOps
27
+ from tqdm import tqdm
28
+
29
+ from .manifest import Manifest
30
+
31
+ log = logging.getLogger(__name__)
32
+
33
+ # Statuses whose images are candidates for duplicate comparison (hashes present).
34
+ _PROCESSED = ("deduped", "kept", "review")
35
+ _CANDIDATES = ("normalized",) + _PROCESSED
36
+
37
+ _POP8 = np.array([bin(i).count("1") for i in range(256)], dtype=np.uint8)
38
+
39
+
40
+ # ------------------------------------------------------------------------------------ hashing
41
+ def compute_hashes(path: str | Path) -> dict[str, str]:
42
+ """pHash/dHash (8x8 => 64 bit, hex) for an image and for its horizontal mirror."""
43
+ with Image.open(path) as im:
44
+ im.draft("RGB", (512, 512)) # cheap JPEG downscale on decode; same procedure for all images
45
+ im = ImageOps.exif_transpose(im).convert("RGB")
46
+ flipped = ImageOps.mirror(im)
47
+ return {
48
+ "phash": str(imagehash.phash(im, hash_size=8)),
49
+ "dhash": str(imagehash.dhash(im, hash_size=8)),
50
+ "phash_flip": str(imagehash.phash(flipped, hash_size=8)),
51
+ "dhash_flip": str(imagehash.dhash(flipped, hash_size=8)),
52
+ }
53
+
54
+
55
+ def hex_to_u64(values: Sequence[str]) -> np.ndarray:
56
+ return np.array([int(v, 16) for v in values], dtype=np.uint64)
57
+
58
+
59
+ def popcount64(x: np.ndarray) -> np.ndarray:
60
+ """Per-element population count of a uint64 array."""
61
+ if hasattr(np, "bitwise_count"): # numpy >= 2.0
62
+ return np.bitwise_count(x)
63
+ x = np.ascontiguousarray(x)
64
+ return _POP8[x.view(np.uint8).reshape(*x.shape, 8)].sum(axis=-1)
65
+
66
+
67
+ # --------------------------------------------------------------------------------- union-find
68
+ class UnionFind:
69
+ def __init__(self, n: int):
70
+ self.parent = list(range(n))
71
+
72
+ def find(self, a: int) -> int:
73
+ while self.parent[a] != a:
74
+ self.parent[a] = self.parent[self.parent[a]]
75
+ a = self.parent[a]
76
+ return a
77
+
78
+ def union(self, a: int, b: int) -> None:
79
+ ra, rb = self.find(a), self.find(b)
80
+ if ra != rb:
81
+ self.parent[max(ra, rb)] = min(ra, rb)
82
+
83
+ def groups(self) -> list[list[int]]:
84
+ out: dict[int, list[int]] = defaultdict(list)
85
+ for i in range(len(self.parent)):
86
+ out[self.find(i)].append(i)
87
+ return [g for g in out.values() if len(g) > 1]
88
+
89
+
90
+ def near_duplicate_pairs(ph: np.ndarray, dh: np.ndarray, phf: np.ndarray, dhf: np.ndarray,
91
+ phash_max: int, dhash_max: int, block_cells: int = 4_000_000):
92
+ """Yield (i, j), i < j, whose pHash *and* dHash are within budget in the same orientation
93
+ (direct, or with j mirrored). Vectorized in row blocks to bound memory."""
94
+ n = len(ph)
95
+ if n < 2:
96
+ return
97
+ block = max(1, block_cells // n)
98
+ cols = np.arange(n)
99
+ for a in range(0, n, block):
100
+ b = min(n, a + block)
101
+ upper = cols[None, :] > np.arange(a, b)[:, None]
102
+ direct = (popcount64(ph[a:b, None] ^ ph[None, :]) <= phash_max) & \
103
+ (popcount64(dh[a:b, None] ^ dh[None, :]) <= dhash_max)
104
+ mirrored = (popcount64(ph[a:b, None] ^ phf[None, :]) <= phash_max) & \
105
+ (popcount64(dh[a:b, None] ^ dhf[None, :]) <= dhash_max)
106
+ ii, jj = np.nonzero((direct | mirrored) & upper)
107
+ for i, j in zip(ii + a, jj):
108
+ yield int(i), int(j)
109
+
110
+
111
+ def find_duplicate_groups(rows: list[dict], phash_max: int, dhash_max: int) -> list[list[int]]:
112
+ """Group row indices by exact pixel hash + near-duplicate hashes (connected components)."""
113
+ n = len(rows)
114
+ uf = UnionFind(n)
115
+ by_pixels: dict[str, int] = {}
116
+ for i, r in enumerate(rows):
117
+ px = r.get("pixel_sha256")
118
+ if px:
119
+ if px in by_pixels:
120
+ uf.union(by_pixels[px], i)
121
+ else:
122
+ by_pixels[px] = i
123
+ if n >= 2:
124
+ ph = hex_to_u64([r["phash"] for r in rows])
125
+ dh = hex_to_u64([r["dhash"] for r in rows])
126
+ phf = hex_to_u64([r["phash_flip"] for r in rows])
127
+ dhf = hex_to_u64([r["dhash_flip"] for r in rows])
128
+ for i, j in near_duplicate_pairs(ph, dh, phf, dhf, phash_max, dhash_max):
129
+ uf.union(i, j)
130
+ return uf.groups()
131
+
132
+
133
+ def keeper_rank(row: dict) -> tuple:
134
+ """Lower sorts first = preferred keeper."""
135
+ processed = 0 if row["status"] in _PROCESSED else 1
136
+ realworld = 0 if row.get("origin") == "realworld" else 1
137
+ pixels = (row.get("norm_width") or row.get("width") or 0) * (row.get("norm_height") or row.get("height") or 0)
138
+ return (processed, realworld, -pixels, -(row.get("filesize") or 0), row["image_id"])
139
+
140
+
141
+ # ------------------------------------------------------------------------------------- stage
142
+ def run(manifest: Manifest, cfg: dict, data_dir: Path) -> dict[str, int]:
143
+ """Hash new images, then discard exact/near duplicates across the whole candidate pool."""
144
+ dcfg = cfg["dedup"]
145
+ stats = {"hashed": 0, "exact_duplicate": 0, "near_duplicate": 0, "deduped": 0, "hash_failed": 0}
146
+
147
+ # 1. hashes for images that do not have them yet
148
+ fresh = [r for r in manifest.images(statuses=["normalized"]) if not r["phash"]]
149
+ if fresh:
150
+ def work(r: dict):
151
+ try:
152
+ return r, compute_hashes(data_dir / r["norm_path"]), None
153
+ except Exception as exc: # noqa: BLE001
154
+ return r, None, exc
155
+
156
+ with ThreadPoolExecutor(max_workers=int(dcfg.get("hash_workers", 4))) as ex:
157
+ futures = [ex.submit(work, r) for r in fresh]
158
+ with manifest.transaction():
159
+ for fut in tqdm(as_completed(futures), total=len(futures), desc="hash", unit="img"):
160
+ r, hashes, err = fut.result()
161
+ if err is not None:
162
+ log.warning("hashing failed for %s: %s", r["image_id"], err)
163
+ manifest.discard(r["image_id"], "hash_failed")
164
+ stats["hash_failed"] += 1
165
+ else:
166
+ manifest.update_image(r["image_id"], **hashes)
167
+ stats["hashed"] += 1
168
+
169
+ # 2. group duplicates over the full candidate pool (new + previously processed)
170
+ rows = [r for r in manifest.images(statuses=_CANDIDATES) if r["phash"]]
171
+ groups = find_duplicate_groups(rows, int(dcfg["phash_max_dist"]), int(dcfg["dhash_max_dist"]))
172
+ log.info("dedup: %d candidates, %d duplicate group(s)", len(rows), len(groups))
173
+
174
+ discarded: set[str] = set()
175
+ cluster_of: dict[str, str] = {} # cluster ids assigned during this run
176
+ with manifest.transaction():
177
+ for group in groups:
178
+ members = sorted((rows[i] for i in group), key=keeper_rank)
179
+ keeper, losers = members[0], members[1:]
180
+ # Reuse the keeper's existing cluster id: a previous semantic merge may have
181
+ # renamed it, and a rerun must never undo that.
182
+ cid = keeper["cluster_id"] or keeper["image_id"]
183
+ for member in members:
184
+ cluster_of[member["image_id"]] = cid
185
+ manifest.update_image(member["image_id"], cluster_id=cid)
186
+ for loser in losers:
187
+ exact = bool(loser["pixel_sha256"]) and loser["pixel_sha256"] == keeper["pixel_sha256"]
188
+ reason = "exact_duplicate" if exact else "near_duplicate"
189
+ if loser["status"] == "normalized":
190
+ manifest.discard(loser["image_id"], reason, dup_of=keeper["image_id"])
191
+ discarded.add(loser["image_id"])
192
+ stats[reason] += 1
193
+ else:
194
+ # An already-processed image is never removed retroactively (it may already
195
+ # be annotated); it only joins the cluster so splits stay leak-free.
196
+ log.warning("kept %s although it duplicates %s (already processed)",
197
+ loser["image_id"], keeper["image_id"])
198
+ # Survivors advance; singletons get their own cluster id.
199
+ for r in rows:
200
+ if r["status"] != "normalized" or r["image_id"] in discarded:
201
+ continue
202
+ updates = {"status": "deduped"}
203
+ if not cluster_of.get(r["image_id"]) and not r["cluster_id"]:
204
+ updates["cluster_id"] = r["image_id"]
205
+ manifest.update_image(r["image_id"], **updates)
206
+ stats["deduped"] += 1
207
+ log.info("dedup: %s", stats)
208
+ return stats
209
+
210
+
211
+ # ------------------------------------------------------------------------- semantic clustering
212
+ def semantic_clusters(ids: list[str], emb: np.ndarray, threshold: float,
213
+ existing: dict[str, str] | None = None, block_cells: int = 4_000_000) -> dict[str, str]:
214
+ """Merge images into clusters by embedding cosine >= threshold (and by existing cluster ids).
215
+
216
+ Returns image_id -> cluster id (the smallest image_id in the component, deterministic).
217
+ Assumes rows of ``emb`` are L2-normalized.
218
+ """
219
+ n = len(ids)
220
+ uf = UnionFind(n)
221
+ if existing:
222
+ first_seen: dict[str, int] = {}
223
+ for i, image_id in enumerate(ids):
224
+ cid = existing.get(image_id)
225
+ if cid:
226
+ if cid in first_seen:
227
+ uf.union(first_seen[cid], i)
228
+ else:
229
+ first_seen[cid] = i
230
+ if n >= 2:
231
+ block = max(1, block_cells // n)
232
+ cols = np.arange(n)
233
+ for a in range(0, n, block):
234
+ b = min(n, a + block)
235
+ sim = emb[a:b] @ emb.T
236
+ ii, jj = np.nonzero((sim >= threshold) & (cols[None, :] > np.arange(a, b)[:, None]))
237
+ for i, j in zip(ii + a, jj):
238
+ uf.union(int(i), int(j))
239
+ comp: dict[int, list[str]] = defaultdict(list)
240
+ for i, image_id in enumerate(ids):
241
+ comp[uf.find(i)].append(image_id)
242
+ return {image_id: min(members) for members in comp.values() for image_id in members}
243
+
244
+
245
+ def run_semantic(manifest: Manifest, cfg: dict) -> dict[str, int]:
246
+ """Layer 3: merge cluster ids using stored CLIP embeddings (labels only, deletes nothing)."""
247
+ rows = manifest.images(statuses=["kept", "review"])
248
+ ids, emb = manifest.load_embeddings([r["image_id"] for r in rows])
249
+ if not ids:
250
+ log.warning("cluster: no embeddings found (run `filter` with CLIP first); skipping")
251
+ return {"clustered": 0, "merged_clusters": 0}
252
+ existing = {r["image_id"]: r["cluster_id"] or r["image_id"] for r in rows}
253
+ norms = np.linalg.norm(emb, axis=1, keepdims=True)
254
+ emb = emb / np.clip(norms, 1e-9, None)
255
+ new_ids = semantic_clusters(ids, emb, float(cfg["dedup"]["semantic_cosine"]), existing)
256
+
257
+ remap: dict[str, str] = {}
258
+ for image_id, new in new_ids.items():
259
+ old = existing[image_id]
260
+ if old != new:
261
+ remap[old] = new
262
+ with manifest.transaction():
263
+ # Update *all* rows (incl. discarded duplicates) that carry a merged cluster id.
264
+ for old, new in remap.items():
265
+ manifest.execute("UPDATE images SET cluster_id=? WHERE cluster_id=?", (new, old))
266
+ for image_id, new in new_ids.items():
267
+ if image_id not in remap and existing[image_id] != new:
268
+ manifest.update_image(image_id, cluster_id=new)
269
+ stats = {"clustered": len(ids), "merged_clusters": len(remap)}
270
+ log.info("cluster: %s", stats)
271
+ return stats
google_drive_export/pipeline/manifest.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SQLite manifest: the single source of truth for provenance and pipeline state.
2
+
3
+ Tables
4
+ ------
5
+ sources one row per (normalized) URL; download state
6
+ hits every (url, engine, query) that surfaced a URL -> class hints and provenance
7
+ harvest_runs completed (engine, query) harvests so reruns skip them
8
+ images one row per unique image (sha256 of original bytes) with all pipeline state
9
+ embeddings optional CLIP embeddings (float16 blobs)
10
+
11
+ Image status flow
12
+ -----------------
13
+ downloaded -> validated -> normalized -> deduped -> kept | review | discarded
14
+ Every stage only touches rows in its own input status, so all stages are idempotent
15
+ and a rerun after an interruption never repeats finished work.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import sqlite3
21
+ import threading
22
+ from contextlib import contextmanager
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+ from typing import Any, Iterable, Iterator
26
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
27
+
28
+ import numpy as np
29
+
30
+ STATUSES = ("downloaded", "validated", "normalized", "deduped", "kept", "review", "discarded")
31
+
32
+ SCHEMA = """
33
+ PRAGMA journal_mode=WAL;
34
+ PRAGMA synchronous=NORMAL;
35
+
36
+ CREATE TABLE IF NOT EXISTS sources (
37
+ url_norm TEXT PRIMARY KEY,
38
+ url TEXT NOT NULL,
39
+ status TEXT NOT NULL DEFAULT 'pending',
40
+ attempts INTEGER NOT NULL DEFAULT 0,
41
+ http_status INTEGER,
42
+ error TEXT,
43
+ image_id TEXT,
44
+ harvested_at TEXT,
45
+ downloaded_at TEXT
46
+ );
47
+ CREATE INDEX IF NOT EXISTS idx_sources_status ON sources(status);
48
+ CREATE INDEX IF NOT EXISTS idx_sources_image ON sources(image_id);
49
+
50
+ CREATE TABLE IF NOT EXISTS hits (
51
+ url_norm TEXT NOT NULL,
52
+ engine TEXT NOT NULL,
53
+ query TEXT NOT NULL,
54
+ class_hint TEXT,
55
+ lang TEXT,
56
+ harvested_at TEXT,
57
+ PRIMARY KEY (url_norm, engine, query)
58
+ );
59
+
60
+ CREATE TABLE IF NOT EXISTS harvest_runs (
61
+ engine TEXT NOT NULL,
62
+ query TEXT NOT NULL,
63
+ class_hint TEXT,
64
+ max_num INTEGER,
65
+ urls_found INTEGER,
66
+ urls_new INTEGER,
67
+ finished_at TEXT,
68
+ PRIMARY KEY (engine, query)
69
+ );
70
+
71
+ CREATE TABLE IF NOT EXISTS images (
72
+ image_id TEXT PRIMARY KEY,
73
+ sha256 TEXT NOT NULL,
74
+ origin TEXT NOT NULL DEFAULT 'web',
75
+ source_ref TEXT,
76
+ orig_path TEXT,
77
+ orig_format TEXT,
78
+ filesize INTEGER,
79
+ width INTEGER,
80
+ height INTEGER,
81
+ aspect_ratio REAL,
82
+ norm_path TEXT,
83
+ norm_width INTEGER,
84
+ norm_height INTEGER,
85
+ pixel_sha256 TEXT,
86
+ phash TEXT,
87
+ dhash TEXT,
88
+ phash_flip TEXT,
89
+ dhash_flip TEXT,
90
+ flags TEXT NOT NULL DEFAULT '[]',
91
+ status TEXT NOT NULL,
92
+ discard_reason TEXT,
93
+ dup_of TEXT,
94
+ cluster_id TEXT,
95
+ clip_score REAL,
96
+ relevance_bucket TEXT,
97
+ board_type TEXT,
98
+ condition TEXT,
99
+ source_type TEXT,
100
+ review_status TEXT,
101
+ reviewer TEXT,
102
+ reviewed_at TEXT,
103
+ split TEXT,
104
+ session_id TEXT,
105
+ board_id TEXT,
106
+ created_at TEXT,
107
+ updated_at TEXT
108
+ );
109
+ CREATE INDEX IF NOT EXISTS idx_images_status ON images(status);
110
+ CREATE INDEX IF NOT EXISTS idx_images_cluster ON images(cluster_id);
111
+ CREATE INDEX IF NOT EXISTS idx_images_dup_of ON images(dup_of);
112
+
113
+ CREATE TABLE IF NOT EXISTS embeddings (
114
+ image_id TEXT PRIMARY KEY,
115
+ dim INTEGER NOT NULL,
116
+ vec BLOB NOT NULL
117
+ );
118
+ """
119
+
120
+ IMAGE_COLUMNS = {
121
+ "image_id", "sha256", "origin", "source_ref", "orig_path", "orig_format", "filesize", "width",
122
+ "height", "aspect_ratio", "norm_path", "norm_width", "norm_height", "pixel_sha256", "phash",
123
+ "dhash", "phash_flip", "dhash_flip", "flags", "status", "discard_reason", "dup_of", "cluster_id",
124
+ "clip_score", "relevance_bucket", "board_type", "condition", "source_type", "review_status",
125
+ "reviewer", "reviewed_at", "split", "session_id", "board_id", "created_at", "updated_at",
126
+ }
127
+
128
+ _TRACKING_PARAMS = {"fbclid", "gclid", "msclkid", "yclid"}
129
+ _DEFAULT_PORTS = {"http": 80, "https": 443}
130
+
131
+
132
+ def utcnow() -> str:
133
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
134
+
135
+
136
+ def normalize_url(url: str) -> str:
137
+ """Canonical form used as the dedup key for URLs (case, default ports, fragment, tracking)."""
138
+ parts = urlsplit(url.strip())
139
+ scheme = parts.scheme.lower()
140
+ host = (parts.hostname or "").lower()
141
+ try:
142
+ port = parts.port
143
+ except ValueError:
144
+ port = None
145
+ netloc = host
146
+ if port and port != _DEFAULT_PORTS.get(scheme):
147
+ netloc = f"{host}:{port}"
148
+ query = sorted(
149
+ (k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
150
+ if not k.lower().startswith("utm_") and k.lower() not in _TRACKING_PARAMS
151
+ )
152
+ return urlunsplit((scheme, netloc, parts.path or "/", urlencode(query), ""))
153
+
154
+
155
+ def _check_columns(fields: Iterable[str]) -> None:
156
+ bad = set(fields) - IMAGE_COLUMNS
157
+ if bad:
158
+ raise KeyError(f"unknown image column(s): {sorted(bad)}")
159
+
160
+
161
+ class Manifest:
162
+ """Thread-safe SQLite wrapper (one connection, serialized by an RLock)."""
163
+
164
+ def __init__(self, db_path: str | Path):
165
+ self.db_path = Path(db_path)
166
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
167
+ self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False,
168
+ isolation_level=None, timeout=60)
169
+ self._conn.row_factory = sqlite3.Row
170
+ self._lock = threading.RLock()
171
+ self._tx_depth = 0
172
+ with self._lock:
173
+ self._conn.executescript(SCHEMA)
174
+
175
+ # -- infrastructure -----------------------------------------------------------------
176
+ def close(self) -> None:
177
+ with self._lock:
178
+ self._conn.close()
179
+
180
+ def __enter__(self) -> "Manifest":
181
+ return self
182
+
183
+ def __exit__(self, *exc) -> None:
184
+ self.close()
185
+
186
+ @contextmanager
187
+ def transaction(self) -> Iterator[None]:
188
+ """Group many writes into one commit (re-entrant)."""
189
+ with self._lock:
190
+ outer = self._tx_depth == 0
191
+ if outer:
192
+ self._conn.execute("BEGIN")
193
+ self._tx_depth += 1
194
+ try:
195
+ yield
196
+ except BaseException:
197
+ self._tx_depth -= 1
198
+ if outer:
199
+ self._conn.execute("ROLLBACK")
200
+ raise
201
+ else:
202
+ self._tx_depth -= 1
203
+ if outer:
204
+ self._conn.execute("COMMIT")
205
+
206
+ def execute(self, sql: str, params: Iterable[Any] = ()) -> sqlite3.Cursor:
207
+ with self._lock:
208
+ return self._conn.execute(sql, tuple(params))
209
+
210
+ def query(self, sql: str, params: Iterable[Any] = ()) -> list[sqlite3.Row]:
211
+ with self._lock:
212
+ return self._conn.execute(sql, tuple(params)).fetchall()
213
+
214
+ # -- sources / hits -------------------------------------------------------------------
215
+ def add_hit(self, url: str, engine: str, query: str, class_hint: str | None = None,
216
+ lang: str | None = None) -> bool:
217
+ """Record a harvested URL. Returns True if the URL was new."""
218
+ url_norm = normalize_url(url)
219
+ now = utcnow()
220
+ with self._lock:
221
+ cur = self._conn.execute(
222
+ "INSERT OR IGNORE INTO sources(url_norm, url, status, harvested_at) "
223
+ "VALUES (?, ?, 'pending', ?)", (url_norm, url, now))
224
+ is_new = cur.rowcount == 1
225
+ self._conn.execute(
226
+ "INSERT OR IGNORE INTO hits(url_norm, engine, query, class_hint, lang, harvested_at) "
227
+ "VALUES (?, ?, ?, ?, ?, ?)", (url_norm, engine, query, class_hint, lang, now))
228
+ return is_new
229
+
230
+ def pending_sources(self, limit: int | None = None, include_transient: bool = False) -> list[dict]:
231
+ statuses = ("pending", "failed_transient") if include_transient else ("pending",)
232
+ sql = f"SELECT * FROM sources WHERE status IN ({','.join('?' * len(statuses))}) ORDER BY harvested_at, url_norm"
233
+ params: list[Any] = list(statuses)
234
+ if limit:
235
+ sql += " LIMIT ?"
236
+ params.append(limit)
237
+ return [dict(r) for r in self.query(sql, params)]
238
+
239
+ def mark_source(self, url_norm: str, status: str, http_status: int | None = None,
240
+ error: str | None = None, image_id: str | None = None, attempts: int = 0) -> None:
241
+ self.execute(
242
+ "UPDATE sources SET status=?, http_status=?, error=?, image_id=?, "
243
+ "attempts=attempts+?, downloaded_at=? WHERE url_norm=?",
244
+ (status, http_status, error, image_id, attempts, utcnow(), url_norm))
245
+
246
+ # -- harvest runs ---------------------------------------------------------------------
247
+ def run_done(self, engine: str, query: str) -> bool:
248
+ return bool(self.query("SELECT 1 FROM harvest_runs WHERE engine=? AND query=?", (engine, query)))
249
+
250
+ def record_run(self, engine: str, query: str, class_hint: str | None, max_num: int,
251
+ found: int, new: int) -> None:
252
+ self.execute(
253
+ "INSERT OR REPLACE INTO harvest_runs VALUES (?, ?, ?, ?, ?, ?, ?)",
254
+ (engine, query, class_hint, max_num, found, new, utcnow()))
255
+
256
+ # -- images ----------------------------------------------------------------------------
257
+ def add_image(self, **fields: Any) -> bool:
258
+ """Insert an image row if its image_id is new. Returns True if inserted."""
259
+ _check_columns(fields)
260
+ fields.setdefault("origin", "web")
261
+ now = utcnow()
262
+ fields.setdefault("created_at", now)
263
+ fields.setdefault("updated_at", now)
264
+ if isinstance(fields.get("flags"), (list, tuple, set)):
265
+ fields["flags"] = json.dumps(sorted(fields["flags"]))
266
+ cols = list(fields)
267
+ cur = self.execute(
268
+ f"INSERT OR IGNORE INTO images({','.join(cols)}) VALUES ({','.join('?' * len(cols))})",
269
+ [fields[c] for c in cols])
270
+ return cur.rowcount == 1
271
+
272
+ @staticmethod
273
+ def _row(row: sqlite3.Row | None) -> dict | None:
274
+ if row is None:
275
+ return None
276
+ d = dict(row)
277
+ d["flags"] = json.loads(d.get("flags") or "[]")
278
+ return d
279
+
280
+ def get_image(self, image_id: str) -> dict | None:
281
+ rows = self.query("SELECT * FROM images WHERE image_id=?", (image_id,))
282
+ return self._row(rows[0]) if rows else None
283
+
284
+ def images(self, statuses: Iterable[str] | None = None, origin: str | None = None,
285
+ where: str | None = None, params: Iterable[Any] = ()) -> list[dict]:
286
+ clauses, args = [], []
287
+ if statuses:
288
+ statuses = tuple(statuses)
289
+ clauses.append(f"status IN ({','.join('?' * len(statuses))})")
290
+ args += list(statuses)
291
+ if origin:
292
+ clauses.append("origin=?")
293
+ args.append(origin)
294
+ if where:
295
+ clauses.append(f"({where})")
296
+ args += list(params)
297
+ sql = "SELECT * FROM images" + (" WHERE " + " AND ".join(clauses) if clauses else "")
298
+ sql += " ORDER BY image_id"
299
+ return [self._row(r) for r in self.query(sql, args)]
300
+
301
+ def update_image(self, image_id: str, **fields: Any) -> None:
302
+ _check_columns(fields)
303
+ if not fields:
304
+ return
305
+ if isinstance(fields.get("flags"), (list, tuple, set)):
306
+ fields["flags"] = json.dumps(sorted(fields["flags"]))
307
+ fields["updated_at"] = utcnow()
308
+ sets = ", ".join(f"{c}=?" for c in fields)
309
+ self.execute(f"UPDATE images SET {sets} WHERE image_id=?", [*fields.values(), image_id])
310
+
311
+ def add_flags(self, image_id: str, *new_flags: str) -> None:
312
+ img = self.get_image(image_id)
313
+ if img is None:
314
+ return
315
+ merged = sorted(set(img["flags"]) | set(new_flags))
316
+ self.update_image(image_id, flags=merged)
317
+
318
+ def discard(self, image_id: str, reason: str, dup_of: str | None = None) -> None:
319
+ self.update_image(image_id, status="discarded", discard_reason=reason, dup_of=dup_of)
320
+
321
+ def count_by(self, column: str, where: str = "1=1", params: Iterable[Any] = ()) -> dict[str, int]:
322
+ _check_columns([column])
323
+ rows = self.query(
324
+ f"SELECT {column} AS k, COUNT(*) AS n FROM images WHERE {where} GROUP BY {column}", params)
325
+ return {(r["k"] if r["k"] is not None else "none"): r["n"] for r in rows}
326
+
327
+ # -- provenance ----------------------------------------------------------------------
328
+ def class_hints_by_image(self) -> dict[str, set[str]]:
329
+ """image_id -> class hints, folding duplicates (dup_of) into their keeper."""
330
+ rows = self.query(
331
+ "SELECT s.image_id AS image_id, h.class_hint AS class_hint "
332
+ "FROM sources s JOIN hits h ON h.url_norm = s.url_norm "
333
+ "WHERE s.image_id IS NOT NULL AND h.class_hint IS NOT NULL")
334
+ direct: dict[str, set[str]] = {}
335
+ for r in rows:
336
+ direct.setdefault(r["image_id"], set()).add(r["class_hint"])
337
+ result = {k: set(v) for k, v in direct.items()}
338
+ for r in self.query("SELECT image_id, dup_of FROM images WHERE dup_of IS NOT NULL"):
339
+ if r["image_id"] in direct:
340
+ result.setdefault(r["dup_of"], set()).update(direct[r["image_id"]])
341
+ return result
342
+
343
+ def provenance(self, image_id: str) -> dict[str, list[str]]:
344
+ """Source URLs, queries, engines and class hints for an image incl. its duplicates."""
345
+ rows = self.query(
346
+ "SELECT s.url AS url, h.engine AS engine, h.query AS query, h.class_hint AS class_hint "
347
+ "FROM sources s LEFT JOIN hits h ON h.url_norm = s.url_norm "
348
+ "WHERE s.image_id IN (SELECT ? UNION SELECT image_id FROM images WHERE dup_of = ?)",
349
+ (image_id, image_id))
350
+ out: dict[str, set[str]] = {"source_urls": set(), "engines": set(), "queries": set(),
351
+ "class_hints": set()}
352
+ for r in rows:
353
+ out["source_urls"].add(r["url"])
354
+ if r["engine"]:
355
+ out["engines"].add(r["engine"])
356
+ if r["query"]:
357
+ out["queries"].add(r["query"])
358
+ if r["class_hint"]:
359
+ out["class_hints"].add(r["class_hint"])
360
+ return {k: sorted(v) for k, v in out.items()}
361
+
362
+ def valid_counts_by_class(self, valid_statuses: Iterable[str] = ("deduped", "kept", "validated", "normalized")) -> dict[str, int]:
363
+ """Return a mapping of class_hint -> count of valid (non-discarded) images."""
364
+ statuses = tuple(valid_statuses)
365
+ sql = f"""
366
+ SELECT h.class_hint, COUNT(DISTINCT i.image_id)
367
+ FROM images i
368
+ JOIN sources s ON i.source_ref = s.url_norm OR i.image_id = s.image_id
369
+ JOIN hits h ON s.url_norm = h.url_norm
370
+ WHERE i.status IN ({','.join('?' * len(statuses))})
371
+ GROUP BY h.class_hint
372
+ """
373
+ rows = self.query(sql, statuses)
374
+ return {r[0]: r[1] for r in rows if r[0]}
375
+
376
+ def export_jsonl(self, path: str | Path) -> int:
377
+ path = Path(path)
378
+ path.parent.mkdir(parents=True, exist_ok=True)
379
+ n = 0
380
+ with open(path, "w", encoding="utf-8") as fh:
381
+ for img in self.images():
382
+ img.update(self.provenance(img["image_id"]))
383
+ fh.write(json.dumps(img, ensure_ascii=False) + "\n")
384
+ n += 1
385
+ return n
386
+
387
+ # -- embeddings ----------------------------------------------------------------------
388
+ def save_embeddings(self, vectors: dict[str, np.ndarray]) -> None:
389
+ with self.transaction():
390
+ for image_id, vec in vectors.items():
391
+ arr = np.asarray(vec, dtype=np.float16)
392
+ self.execute("INSERT OR REPLACE INTO embeddings VALUES (?, ?, ?)",
393
+ (image_id, int(arr.shape[0]), arr.tobytes()))
394
+
395
+ def load_embeddings(self, image_ids: Iterable[str] | None = None) -> tuple[list[str], np.ndarray]:
396
+ rows = self.query("SELECT image_id, dim, vec FROM embeddings ORDER BY image_id")
397
+ if image_ids is not None:
398
+ wanted = set(image_ids)
399
+ rows = [r for r in rows if r["image_id"] in wanted]
400
+ if not rows:
401
+ return [], np.zeros((0, 0), dtype=np.float32)
402
+ ids = [r["image_id"] for r in rows]
403
+ mat = np.stack([np.frombuffer(r["vec"], dtype=np.float16).astype(np.float32) for r in rows])
404
+ return ids, mat
google_drive_export/pipeline/processor.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Normalization engine: turn any validated original into a standard RGB JPEG.
2
+
3
+ Order matters and follows the plan:
4
+
5
+ 1. EXIF transpose first (phone photos would otherwise end up rotated).
6
+ 2. Colour handling to RGB:
7
+ - RGBA / LA / PA / palette-with-transparency -> composited on WHITE
8
+ (a naive convert("RGB") turns transparent pixels black)
9
+ - CMYK -> sRGB through the embedded ICC profile when there is one
10
+ - RGB with a non-sRGB ICC profile -> converted to sRGB when possible
11
+ - grayscale / 1-bit / 16-bit -> RGB
12
+ 3. Downscale (never upscale) if the long side exceeds ``max_long_side`` (LANCZOS).
13
+ 4. Encode as JPEG q95, 4:4:4 chroma (subsampling=0), optimized, metadata stripped.
14
+
15
+ Originals are never modified; this only ever writes a derived copy.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import io
21
+ import logging
22
+ import os
23
+ from concurrent.futures import ThreadPoolExecutor, as_completed
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ from PIL import Image, ImageCms, ImageOps
29
+ from tqdm import tqdm
30
+
31
+ from .manifest import Manifest
32
+ from .validator import register_heif
33
+
34
+ log = logging.getLogger(__name__)
35
+ register_heif()
36
+
37
+ Image.MAX_IMAGE_PIXELS = None # size is already policed by the validator
38
+
39
+
40
+ @dataclass
41
+ class NormalizeResult:
42
+ width: int
43
+ height: int
44
+ pixel_sha256: str
45
+
46
+
47
+ def _icc_to_srgb(img: Image.Image) -> Image.Image:
48
+ """Convert to sRGB via the embedded ICC profile; fall back to a plain convert."""
49
+ icc = img.info.get("icc_profile")
50
+ if not icc:
51
+ return img.convert("RGB")
52
+ try:
53
+ src = ImageCms.ImageCmsProfile(io.BytesIO(icc))
54
+ if img.mode == "RGB" and "srgb" in ImageCms.getProfileDescription(src).lower():
55
+ return img
56
+ dst = ImageCms.createProfile("sRGB")
57
+ return ImageCms.profileToProfile(img, src, dst, outputMode="RGB")
58
+ except Exception:
59
+ return img.convert("RGB")
60
+
61
+
62
+ def _wide_mode_to_rgb(img: Image.Image) -> Image.Image:
63
+ """16-bit / int / float single-channel images -> 8-bit RGB with min/max scaling."""
64
+ arr = np.asarray(img, dtype=np.float64)
65
+ lo, hi = float(arr.min()), float(arr.max())
66
+ scaled = np.zeros_like(arr) if hi <= lo else (arr - lo) / (hi - lo) * 255.0
67
+ return Image.fromarray(scaled.astype(np.uint8), mode="L").convert("RGB")
68
+
69
+
70
+ def to_rgb(img: Image.Image) -> Image.Image:
71
+ mode = img.mode
72
+ if mode in ("RGBA", "LA", "PA", "RGBa", "La") or (mode == "P" and "transparency" in img.info):
73
+ rgba = img.convert("RGBA")
74
+ background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
75
+ return Image.alpha_composite(background, rgba).convert("RGB")
76
+ if mode == "CMYK":
77
+ return _icc_to_srgb(img)
78
+ if mode in ("I", "I;16", "I;16L", "I;16B", "F"):
79
+ return _wide_mode_to_rgb(img)
80
+ if mode == "RGB":
81
+ return _icc_to_srgb(img) if img.info.get("icc_profile") else img
82
+ return img.convert("RGB") # L, 1, P (opaque), YCbCr, LAB, HSV, ...
83
+
84
+
85
+ def normalize_image(src: str | Path, dst: str | Path, pcfg: dict) -> NormalizeResult:
86
+ src, dst = Path(src), Path(dst)
87
+ with Image.open(src) as opened:
88
+ opened.seek(0) # first frame of animated files
89
+ img = ImageOps.exif_transpose(opened)
90
+ img.load()
91
+ img = to_rgb(img)
92
+
93
+ max_long = int(pcfg.get("max_long_side", 2560))
94
+ long_side = max(img.size)
95
+ if max_long and long_side > max_long:
96
+ scale = max_long / long_side
97
+ new_size = (max(1, round(img.width * scale)), max(1, round(img.height * scale)))
98
+ img = img.resize(new_size, Image.Resampling.LANCZOS)
99
+
100
+ digest = hashlib.sha256(f"{img.width}x{img.height}".encode() + img.tobytes()).hexdigest()
101
+
102
+ dst.parent.mkdir(parents=True, exist_ok=True)
103
+ tmp = dst.with_name(dst.name + f".{os.getpid()}.tmp")
104
+ try:
105
+ img.save(tmp, format="JPEG", quality=int(pcfg.get("jpeg_quality", 95)),
106
+ subsampling=int(pcfg.get("jpeg_subsampling", 0)), optimize=True)
107
+ os.replace(tmp, dst) # atomic: a crash never leaves a half-written JPEG
108
+ finally:
109
+ if tmp.exists():
110
+ tmp.unlink()
111
+ return NormalizeResult(img.width, img.height, digest)
112
+
113
+
114
+ def run(manifest: Manifest, cfg: dict, data_dir: Path, images_dir: Path) -> dict[str, int]:
115
+ """Normalize every image in status 'validated'."""
116
+ pcfg = cfg["process"]
117
+ todo = manifest.images(statuses=["validated"])
118
+ stats = {"normalized": 0, "normalize_failed": 0}
119
+ if not todo:
120
+ log.info("process: nothing to do")
121
+ return stats
122
+
123
+ def work(img: dict):
124
+ dst = images_dir / f"{img['image_id']}.jpg"
125
+ try:
126
+ return img, normalize_image(data_dir / img["orig_path"], dst, pcfg), dst, None
127
+ except Exception as exc: # noqa: BLE001 - any decode/encode failure discards the image
128
+ return img, None, dst, exc
129
+
130
+ with ThreadPoolExecutor(max_workers=int(pcfg.get("workers", 4))) as ex:
131
+ futures = [ex.submit(work, img) for img in todo]
132
+ with manifest.transaction():
133
+ for fut in tqdm(as_completed(futures), total=len(futures), desc="process", unit="img"):
134
+ img, res, dst, err = fut.result()
135
+ if err is None and res is not None:
136
+ manifest.update_image(
137
+ img["image_id"], status="normalized", norm_path=str(dst.relative_to(data_dir)),
138
+ norm_width=res.width, norm_height=res.height, pixel_sha256=res.pixel_sha256)
139
+ stats["normalized"] += 1
140
+ else:
141
+ log.warning("normalize failed for %s: %s", img["image_id"], err)
142
+ manifest.discard(img["image_id"], "normalize_failed")
143
+ stats["normalize_failed"] += 1
144
+ log.info("process: %s", stats)
145
+ return stats
google_drive_export/pipeline/queries.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Query registry: expand seed terms along diversity axes (deterministically)."""
2
+ from __future__ import annotations
3
+
4
+ import random
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class QuerySpec:
10
+ class_hint: str
11
+ query: str
12
+ lang: str = "en"
13
+ kind: str = "seed" # seed | expanded | lang
14
+
15
+
16
+ def _overlap(phrase: str, words: set[str]) -> float:
17
+ toks = phrase.lower().split()
18
+ return sum(t in words for t in toks) / len(toks) if toks else 1.0
19
+
20
+
21
+ def build_queries(
22
+ qcfg: dict,
23
+ classes: list[str] | None = None,
24
+ langs: list[str] | None = None,
25
+ ) -> list[QuerySpec]:
26
+ """Build the full query list.
27
+
28
+ For every seed term: the seed itself plus up to ``max_variants_per_seed`` variants that
29
+ append one or two randomly chosen axis values (board type, condition, view/setting).
30
+ A class may override any axis (e.g. ``desoldered_zone`` never pairs with "intact").
31
+ Multilingual terms are hand-written per class and appended as-is.
32
+
33
+ Output order and content are fully determined by ``expansion.seed``.
34
+ """
35
+ exp = qcfg.get("expansion", {}) or {}
36
+ rng = random.Random(exp.get("seed", 7))
37
+ per_seed = int(exp.get("max_variants_per_seed", 8))
38
+ global_axes = qcfg.get("axes", {}) or {}
39
+
40
+ out: list[QuerySpec] = []
41
+ seen: set[tuple[str, str]] = set()
42
+
43
+ def add(spec: QuerySpec) -> None:
44
+ key = (spec.class_hint, spec.query.strip().lower())
45
+ if key not in seen and spec.query.strip():
46
+ seen.add(key)
47
+ out.append(spec)
48
+
49
+ for cls, body in (qcfg.get("classes") or {}).items():
50
+ if classes and cls not in classes:
51
+ continue
52
+ body = body or {}
53
+ axes = {**global_axes, **(body.get("axes") or {})}
54
+ axis_names = sorted(a for a, vals in axes.items() if vals)
55
+
56
+ for seed in body.get("seeds", []) or []:
57
+ add(QuerySpec(cls, seed, "en", "seed"))
58
+ seed_words = set(seed.lower().split())
59
+ variants: set[str] = set()
60
+ attempts = 0
61
+ while axis_names and len(variants) < per_seed and attempts < per_seed * 10:
62
+ attempts += 1
63
+ chosen = rng.sample(axis_names, min(rng.choice([1, 2]), len(axis_names)))
64
+ parts = [rng.choice(axes[a]) for a in sorted(chosen)]
65
+ # Skip axis values the seed already (mostly) says, e.g. "close up" + "close up macro".
66
+ parts = [p for p in parts if _overlap(p, seed_words) < 0.5]
67
+ if parts:
68
+ variants.add(f"{seed} {' '.join(parts)}")
69
+ for v in sorted(variants):
70
+ add(QuerySpec(cls, v, "en", "expanded"))
71
+
72
+ for lang, terms in (body.get("multilingual") or {}).items():
73
+ if langs and lang not in langs:
74
+ continue
75
+ for term in terms or []:
76
+ add(QuerySpec(cls, term, lang, "lang"))
77
+ return out
google_drive_export/pipeline/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ icrawler>=0.6.6
2
+ Pillow>=9.0.0
3
+ imagehash>=4.3.1
4
+ pyyaml>=6.0
5
+ tqdm>=4.64.0
6
+ numpy>=1.22.0
7
+ pytest>=7.0.0
google_drive_export/pipeline/scraper.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Unified CLI entry point for E-Waste dataset harvest and pipeline processing.
3
+
4
+ Subcommands:
5
+ harvest Query search engines and download raw images
6
+ validate Verify image integrity, dimensions, format, and aspect ratios
7
+ process Normalize images (EXIF transpose, alpha composite, JPEG q95)
8
+ dedup Multi-layer deduplication (exact SHA-256 + flip-aware pHash/dHash)
9
+ report Print pipeline statistics and summary report
10
+ export Export SQLite manifest metadata to JSONL
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import logging
17
+ import os
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ # Auto-reexec inside project .venv if not already active
22
+ _script_dir = Path(__file__).resolve().parent
23
+ _venv_python = _script_dir / ".venv" / "bin" / "python3"
24
+ if _venv_python.exists() and sys.executable != str(_venv_python):
25
+ os.execv(str(_venv_python), [str(_venv_python)] + sys.argv)
26
+
27
+ from pipeline.config import get_paths, load_config, setup_logging, load_queries
28
+ from pipeline.manifest import Manifest
29
+ from pipeline import validator, processor, dedup, crawler, splitter
30
+
31
+ log = logging.getLogger("scraper")
32
+
33
+
34
+ def cmd_harvest(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
35
+ force = getattr(args, "force", False)
36
+ log.info("Starting harvest (engine=%s, max_num=%d, force=%s)...", args.engine, args.max_num, force)
37
+ stats = crawler.run(manifest, cfg, paths.data, engine=args.engine, max_num=args.max_num, force=force)
38
+ print(json.dumps(stats, indent=2))
39
+ return 0
40
+
41
+
42
+ def cmd_validate(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
43
+ force = getattr(args, "force", False)
44
+ log.info("Starting validation (force=%s)...", force)
45
+ stats = validator.run(manifest, cfg, paths.data, force=force)
46
+ print(json.dumps(stats, indent=2))
47
+ return 0
48
+
49
+
50
+ def cmd_process(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
51
+ log.info("Starting normalization processing...")
52
+ stats = processor.run(manifest, cfg, paths.data, paths.images)
53
+ print(json.dumps(stats, indent=2))
54
+ return 0
55
+
56
+
57
+ def cmd_dedup(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
58
+ log.info("Starting deduplication...")
59
+ stats = dedup.run(manifest, cfg, paths.data)
60
+ if args.semantic:
61
+ log.info("Running semantic CLIP clustering...")
62
+ sem_stats = dedup.run_semantic(manifest, cfg)
63
+ stats.update(sem_stats)
64
+ print(json.dumps(stats, indent=2))
65
+ return 0
66
+
67
+
68
+ def cmd_report(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
69
+ by_status = manifest.count_by("status")
70
+ by_discard = manifest.count_by("discard_reason", where="status='discarded'")
71
+ class_hints = manifest.class_hints_by_image()
72
+
73
+ hint_counts: dict[str, int] = {}
74
+ for hints in class_hints.values():
75
+ for h in hints:
76
+ hint_counts[h] = hint_counts.get(h, 0) + 1
77
+
78
+ report_data = {
79
+ "status_distribution": by_status,
80
+ "discard_reasons": by_discard,
81
+ "class_hint_counts": hint_counts,
82
+ "total_images": sum(by_status.values()),
83
+ }
84
+
85
+ if args.json:
86
+ print(json.dumps(report_data, indent=2))
87
+ else:
88
+ print("\n=== E-Waste Dataset Pipeline Summary Report ===")
89
+ print(f"Total Images Tracked: {report_data['total_images']}")
90
+ print("\nStatus Distribution:")
91
+ for k, v in by_status.items():
92
+ print(f" {k:15s}: {v}")
93
+ if by_discard:
94
+ print("\nDiscard Reasons:")
95
+ for k, v in by_discard.items():
96
+ print(f" {k:20s}: {v}")
97
+ if hint_counts:
98
+ print("\nClass Hints (via Search Provenance):")
99
+ for k, v in sorted(hint_counts.items()):
100
+ print(f" {k:20s}: {v}")
101
+ print("================================================\n")
102
+
103
+ # Save summary report to file
104
+ paths.reports.mkdir(parents=True, exist_ok=True)
105
+ report_file = paths.reports / "summary.json"
106
+ report_file.write_text(json.dumps(report_data, indent=2), encoding="utf-8")
107
+ log.info("Wrote summary report to %s", report_file)
108
+ return 0
109
+
110
+
111
+ def cmd_export(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
112
+ out_path = Path(args.output) if args.output else paths.manifest_jsonl
113
+ log.info("Exporting manifest to %s...", out_path)
114
+ count = manifest.export_jsonl(out_path)
115
+ log.info("Exported %d image metadata entries to %s", count, out_path)
116
+ return 0
117
+
118
+
119
+ def cmd_split(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
120
+ log.info("Starting cluster-aware dataset splitting (train=%.2f, val=%.2f, test=%.2f)...", args.train_ratio, args.val_ratio, args.test_ratio)
121
+ stats = splitter.run(
122
+ manifest, cfg, paths.data, paths.splits,
123
+ train_ratio=args.train_ratio, val_ratio=args.val_ratio, test_ratio=args.test_ratio
124
+ )
125
+ print(json.dumps(stats, indent=2))
126
+ return 0
127
+
128
+
129
+ def cmd_all(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
130
+ log.info("Running complete pipeline: harvest -> validate -> process -> dedup -> report")
131
+ cmd_harvest(args, cfg, manifest, paths)
132
+ cmd_validate(args, cfg, manifest, paths)
133
+ cmd_process(args, cfg, manifest, paths)
134
+ cmd_dedup(args, cfg, manifest, paths)
135
+ return cmd_report(args, cfg, manifest, paths)
136
+
137
+
138
+ def cmd_auto(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
139
+ target = getattr(args, "target_per_class", 1500)
140
+ engines = ["bing", "flickr", "baidu"]
141
+ all_classes = set(cfg.get("queries", {}).get("classes", {}).keys()) or {
142
+ "cpu_socket", "gold_finger", "ic_chip", "tantalum_capacitor", "desoldered_zone"
143
+ }
144
+ log.info("Starting automated target loop: goal=%d valid images for ALL classes (%s)", target, sorted(all_classes))
145
+
146
+ iteration = 0
147
+ while True:
148
+ iteration += 1
149
+ valid_counts = manifest.valid_counts_by_class()
150
+ log.info("Iteration %d - Current valid counts per class: %s", iteration, valid_counts)
151
+
152
+ unsatisfied = {c: target - valid_counts.get(c, 0) for c in all_classes if valid_counts.get(c, 0) < target}
153
+ if not unsatisfied:
154
+ log.info("SUCCESS: All classes reached target of %d valid images!", target)
155
+ break
156
+
157
+ log.info("Iteration %d - Deficit classes remaining to satisfy: %s", iteration, unsatisfied)
158
+
159
+ eng = engines[(iteration - 1) % len(engines)]
160
+ log.info("Harvesting batch for deficit classes using engine=%s (max_num=%d)...", eng, args.max_num)
161
+
162
+ crawler.run(manifest, cfg, paths.data, engine=eng, max_num=args.max_num, force=True, filter_classes=set(unsatisfied.keys()))
163
+ validator.run(manifest, cfg, paths.data)
164
+ processor.run(manifest, cfg, paths.data, paths.images)
165
+ dedup.run(manifest, cfg, paths.data)
166
+
167
+ v_now = manifest.valid_counts_by_class()
168
+ still_needed = {c: target - v_now.get(c, 0) for c in all_classes if v_now.get(c, 0) < target}
169
+ if not still_needed:
170
+ log.info("SUCCESS: All classes reached target of %d valid images!", target)
171
+ break
172
+
173
+ return cmd_report(args, cfg, manifest, paths)
174
+
175
+
176
+ def main() -> int:
177
+ parser = argparse.ArgumentParser(description="E-Waste PCB Dataset Harvester & Preprocessing Pipeline")
178
+ parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose DEBUG logging")
179
+ parser.add_argument("-c", "--config", type=str, help="Path to config.yaml file")
180
+
181
+ subparsers = parser.add_subparsers(dest="command", required=True, help="Pipeline subcommand")
182
+
183
+ # auto
184
+ p_auto = subparsers.add_parser("auto", help="Automated loop: harvest/validate/process/dedup until ALL classes reach target count")
185
+ p_auto.add_argument("--target-per-class", type=int, default=1500, help="Target valid images per class (default: 1500)")
186
+ p_auto.add_argument("--max-num", type=int, default=50, help="Max images per query per batch")
187
+ p_auto.add_argument("--semantic", action="store_true", help="Also run semantic CLIP clustering in dedup stage")
188
+ p_auto.add_argument("--json", action="store_true", help="Output summary report as raw JSON")
189
+
190
+ # all
191
+ p_all = subparsers.add_parser("all", help="Run full pipeline: harvest -> validate -> process -> dedup -> report")
192
+ p_all.add_argument("--engine", default="bing", choices=["bing", "flickr", "baidu"], help="Crawler engine")
193
+ p_all.add_argument("--max-num", type=int, default=50, help="Max images per query")
194
+ p_all.add_argument("-f", "--force", action="store_true", help="Force re-harvest queries even if already recorded as done")
195
+ p_all.add_argument("--semantic", action="store_true", help="Also run semantic CLIP clustering in dedup stage")
196
+ p_all.add_argument("--json", action="store_true", help="Output summary report as raw JSON")
197
+
198
+ # harvest
199
+ p_harvest = subparsers.add_parser("harvest", help="Harvest images from web search engines")
200
+ p_harvest.add_argument("--engine", default="bing", choices=["bing", "flickr", "baidu"], help="Crawler engine")
201
+ p_harvest.add_argument("--max-num", type=int, default=50, help="Max images per query")
202
+ p_harvest.add_argument("-f", "--force", action="store_true", help="Force re-harvest queries even if already recorded as done")
203
+
204
+ # validate
205
+ p_validate = subparsers.add_parser("validate", help="Validate raw images for integrity and dimensions")
206
+ p_validate.add_argument("-f", "--force", action="store_true", help="Re-check previously validated images for AI metadata")
207
+
208
+ # process
209
+ subparsers.add_parser("process", help="Normalize images (EXIF, alpha composite, JPEG q95)")
210
+
211
+ # dedup
212
+ p_dedup = subparsers.add_parser("dedup", help="Deduplicate images (exact + pHash/dHash)")
213
+ p_dedup.add_argument("--semantic", action="store_true", help="Also run semantic CLIP clustering")
214
+
215
+ # report
216
+ p_report = subparsers.add_parser("report", help="Display dataset statistics summary")
217
+ p_report.add_argument("--json", action="store_true", help="Output summary as raw JSON")
218
+
219
+ # export
220
+ p_export = subparsers.add_parser("export", help="Export manifest metadata to JSONL file")
221
+ p_export.add_argument("-o", "--output", type=str, help="Output path for jsonl export")
222
+
223
+ # split
224
+ p_split = subparsers.add_parser("split", help="Partition dataset into leak-free train/val/test splits")
225
+ p_split.add_argument("--train-ratio", type=float, default=0.70, help="Train split ratio (default: 0.70)")
226
+ p_split.add_argument("--val-ratio", type=float, default=0.15, help="Val split ratio (default: 0.15)")
227
+ p_split.add_argument("--test-ratio", type=float, default=0.15, help="Test split ratio (default: 0.15)")
228
+
229
+ args = parser.parse_args()
230
+ setup_logging(verbose=args.verbose)
231
+
232
+ cfg = load_config(args.config)
233
+ paths = get_paths(cfg)
234
+ paths.ensure()
235
+
236
+ with Manifest(paths.manifest_db) as manifest:
237
+ if args.command == "auto":
238
+ return cmd_auto(args, cfg, manifest, paths)
239
+ elif args.command == "all":
240
+ return cmd_all(args, cfg, manifest, paths)
241
+ elif args.command == "harvest":
242
+ return cmd_harvest(args, cfg, manifest, paths)
243
+ elif args.command == "validate":
244
+ return cmd_validate(args, cfg, manifest, paths)
245
+ elif args.command == "process":
246
+ return cmd_process(args, cfg, manifest, paths)
247
+ elif args.command == "dedup":
248
+ return cmd_dedup(args, cfg, manifest, paths)
249
+ elif args.command == "split":
250
+ return cmd_split(args, cfg, manifest, paths)
251
+ elif args.command == "report":
252
+ return cmd_report(args, cfg, manifest, paths)
253
+ elif args.command == "export":
254
+ return cmd_export(args, cfg, manifest, paths)
255
+
256
+ return 0
257
+
258
+
259
+ if __name__ == "__main__":
260
+ sys.exit(main())
google_drive_export/pipeline/splitter.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dataset Splitter Engine.
2
+
3
+ Stratified, cluster-aware train / val / test dataset partitioning:
4
+ - Prevents data leakage by ensuring all images in the same visual `cluster_id`
5
+ are assigned to the SAME split (train, val, or test).
6
+ - Maintains balanced class distributions across splits according to target ratios (e.g. 70 / 15 / 15).
7
+ - Exports organized image directory symlinks/copies under `splits/` for YOLOv8 training.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import random
13
+ import shutil
14
+ from collections import defaultdict
15
+ from pathlib import Path
16
+ from typing import Sequence
17
+
18
+ from .manifest import Manifest
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+
23
+ def create_cluster_splits(
24
+ manifest: Manifest,
25
+ train_ratio: float = 0.70,
26
+ val_ratio: float = 0.15,
27
+ test_ratio: float = 0.15,
28
+ seed: int = 42,
29
+ ) -> dict[str, list[dict]]:
30
+ """Partition valid images into cluster-isolated train/val/test splits."""
31
+ random.seed(seed)
32
+
33
+ # Load all valid/kept images
34
+ rows = manifest.images(statuses=["deduped", "kept", "validated", "normalized"])
35
+ if not rows:
36
+ log.warning("splitter: no valid images found to split")
37
+ return {"train": [], "val": [], "test": []}
38
+
39
+ # Group image records by cluster_id
40
+ clusters: dict[str, list[dict]] = defaultdict(list)
41
+ for r in rows:
42
+ cid = r["cluster_id"] or r["image_id"]
43
+ clusters[cid].append(r)
44
+
45
+ cluster_items = list(clusters.items())
46
+ random.shuffle(cluster_items)
47
+
48
+ total_count = len(rows)
49
+ target_train = int(total_count * train_ratio)
50
+ target_val = int(total_count * val_ratio)
51
+
52
+ splits: dict[str, list[dict]] = {"train": [], "val": [], "test": []}
53
+
54
+ current_train = 0
55
+ current_val = 0
56
+
57
+ for cid, members in cluster_items:
58
+ mem_len = len(members)
59
+ if current_train + mem_len <= target_train or not splits["val"]:
60
+ splits["train"].extend(members)
61
+ current_train += mem_len
62
+ elif current_val + mem_len <= target_val or not splits["test"]:
63
+ splits["val"].extend(members)
64
+ current_val += mem_len
65
+ else:
66
+ splits["test"].extend(members)
67
+
68
+ return splits
69
+
70
+
71
+ def run(
72
+ manifest: Manifest,
73
+ cfg: dict,
74
+ data_dir: Path,
75
+ splits_dir: Path,
76
+ train_ratio: float = 0.70,
77
+ val_ratio: float = 0.15,
78
+ test_ratio: float = 0.15,
79
+ copy_files: bool = True,
80
+ seed: int = 42,
81
+ ) -> dict[str, int]:
82
+ """Execute cluster-isolated dataset split and write files to splits directory."""
83
+ splits = create_cluster_splits(
84
+ manifest, train_ratio=train_ratio, val_ratio=val_ratio, test_ratio=test_ratio, seed=seed
85
+ )
86
+
87
+ stats = {
88
+ "train": len(splits["train"]),
89
+ "val": len(splits["val"]),
90
+ "test": len(splits["test"]),
91
+ "total_split": sum(len(s) for s in splits.values()),
92
+ }
93
+
94
+ if not stats["total_split"]:
95
+ log.warning("splitter: 0 images split")
96
+ return stats
97
+
98
+ # Update database split assignments
99
+ with manifest.transaction():
100
+ for split_name, members in splits.items():
101
+ for m in members:
102
+ manifest.update_image(m["image_id"], split=split_name)
103
+
104
+ # Export split files to disk
105
+ if copy_files:
106
+ for split_name, members in splits.items():
107
+ dst_img_dir = splits_dir / split_name / "images"
108
+ dst_img_dir.mkdir(parents=True, exist_ok=True)
109
+ for m in members:
110
+ src_rel = m.get("norm_path") or m.get("orig_path")
111
+ if not src_rel:
112
+ continue
113
+ src_path = data_dir / src_rel
114
+ if src_path.exists():
115
+ dst_path = dst_img_dir / src_path.name
116
+ if not dst_path.exists():
117
+ shutil.copy2(src_path, dst_path)
118
+
119
+ log.info("splitter split summary: %s", stats)
120
+ return stats
google_drive_export/pipeline/validator.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validation engine.
2
+
3
+ Checks run cheapest-first so most bad files fail early:
4
+
5
+ 1. file size < min_file_bytes -> discard too_small_file
6
+ 2. integrity open -> verify() -> reopen -> load() -> discard corrupt
7
+ 3. animated multi-frame GIF/WEBP/APNG -> flag animated (first frame used)
8
+ 4. resolution short/long side below minimum -> discard low_resolution
9
+ 5. aspect (hard) > hard_aspect : 1 -> discard extreme_aspect_hard
10
+ 6. aspect (soft) > flag_aspect : 1 -> flag extreme_aspect (goes to review)
11
+
12
+ `verify()` alone does not detect truncated JPEGs, so the file is reopened and fully decoded
13
+ with `load()` (verify() invalidates the image object, hence the reopen).
14
+ The soft aspect limit is a *flag*, not a discard: RAM modules and edge-finger strips are
15
+ naturally ~4.5-5:1 and must survive.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+
24
+ from PIL import Image, ImageFile
25
+ from tqdm import tqdm
26
+
27
+ from .manifest import Manifest
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+ ImageFile.LOAD_TRUNCATED_IMAGES = False # never silently accept truncated files
32
+ # Pillow's own bomb check works through process-global warnings (not thread-safe), so it is
33
+ # disabled and replaced by an explicit header-size check in validate_image().
34
+ Image.MAX_IMAGE_PIXELS = None
35
+
36
+ ALLOWED_FORMATS = {"JPEG", "MPO", "PNG", "WEBP", "GIF", "BMP", "TIFF"}
37
+
38
+
39
+ def register_heif() -> bool:
40
+ """Enable iPhone HEIC/HEIF photos if the optional `pillow-heif` package is installed."""
41
+ try:
42
+ import pillow_heif # type: ignore
43
+
44
+ pillow_heif.register_heif_opener()
45
+ ALLOWED_FORMATS.add("HEIF")
46
+ return True
47
+ except Exception: # pragma: no cover - optional dependency
48
+ return False
49
+
50
+
51
+ register_heif()
52
+
53
+
54
+ @dataclass
55
+ class ValidationResult:
56
+ ok: bool
57
+ reason: str | None = None
58
+ flags: list[str] = field(default_factory=list)
59
+ width: int | None = None
60
+ height: int | None = None
61
+ fmt: str | None = None
62
+ aspect: float | None = None
63
+
64
+
65
+ DEFAULT_AI_KEYWORDS = {
66
+ "midjourney", "stable diffusion", "dall-e", "dalle", "comfyui",
67
+ "novelai", "c2pa", "firefly", "bing image creator", "flux.1",
68
+ "fooocus", "automatic1111", "ai_generated", "generated by"
69
+ }
70
+
71
+
72
+ def check_ai_metadata(img: Image.Image, custom_keywords: list[str] | set[str] | None = None) -> bool:
73
+ """Return True if image metadata contains AI generator signatures."""
74
+ keywords = set(custom_keywords) if custom_keywords else DEFAULT_AI_KEYWORDS
75
+ info = getattr(img, "info", {})
76
+ if not isinstance(info, dict):
77
+ return False
78
+ raw_str = " ".join(f"{k} {v}" for k, v in info.items()).lower()
79
+ return any(kw.lower() in raw_str for kw in keywords)
80
+
81
+
82
+ def validate_image(path: str | Path, vcfg: dict) -> ValidationResult:
83
+ path = Path(path)
84
+ try:
85
+ size = path.stat().st_size
86
+ except OSError:
87
+ return ValidationResult(False, "missing_file")
88
+ if size < int(vcfg["min_file_bytes"]):
89
+ return ValidationResult(False, "too_small_file")
90
+
91
+ max_pixels = int(vcfg.get("max_pixels", 120_000_000))
92
+ flags: list[str] = []
93
+ try:
94
+ with Image.open(path) as img: # lazy: reads the header only
95
+ if img.width * img.height > max_pixels:
96
+ return ValidationResult(False, "decompression_bomb", width=img.width, height=img.height)
97
+ img.verify()
98
+ with Image.open(path) as img: # reopen: verify() leaves the object unusable
99
+ fmt = img.format
100
+ if fmt not in ALLOWED_FORMATS:
101
+ return ValidationResult(False, "unsupported_format", fmt=fmt)
102
+ animated = bool(getattr(img, "is_animated", False))
103
+ img.load() # full decode -> catches truncation that verify() misses
104
+ width, height = img.size
105
+
106
+ if check_ai_metadata(img, vcfg.get("ai_keywords")):
107
+ return ValidationResult(False, "ai_generated_metadata", width=width, height=height, fmt=fmt)
108
+ except Exception: # OSError, SyntaxError, ValueError, struct errors, ...
109
+ return ValidationResult(False, "corrupt")
110
+
111
+ if animated:
112
+ flags.append("animated")
113
+
114
+ short, long_ = min(width, height), max(width, height)
115
+ if short < int(vcfg["min_short_side"]) or long_ < int(vcfg["min_long_side"]):
116
+ return ValidationResult(False, "low_resolution", flags, width, height, fmt)
117
+
118
+ aspect = long_ / short if short else float("inf")
119
+ if aspect > float(vcfg["hard_aspect"]):
120
+ return ValidationResult(False, "extreme_aspect_hard", flags, width, height, fmt, aspect)
121
+ if aspect > float(vcfg["flag_aspect"]):
122
+ flags.append("extreme_aspect")
123
+
124
+ return ValidationResult(True, None, flags, width, height, fmt, round(aspect, 4))
125
+
126
+
127
+ def run(manifest: Manifest, cfg: dict, data_dir: Path, force: bool = False) -> dict[str, int]:
128
+ """Validate images. If force=True, re-checks previously validated/normalized images for AI metadata."""
129
+ vcfg = cfg["validate"]
130
+ statuses = ["downloaded", "validated", "normalized", "kept"] if force else ["downloaded"]
131
+ todo = manifest.images(statuses=statuses)
132
+ stats: dict[str, int] = {"validated": 0}
133
+ if not todo:
134
+ log.info("validate: nothing to do")
135
+ return stats
136
+
137
+ def work(img: dict) -> tuple[dict, ValidationResult]:
138
+ return img, validate_image(data_dir / img["orig_path"], vcfg)
139
+
140
+ workers = int(vcfg.get("workers", 4))
141
+ with ThreadPoolExecutor(max_workers=workers) as ex:
142
+ futures = [ex.submit(work, img) for img in todo]
143
+ with manifest.transaction():
144
+ for fut in tqdm(as_completed(futures), total=len(futures), desc="validate", unit="img"):
145
+ img, res = fut.result()
146
+ if res.ok:
147
+ flags = sorted(set(img["flags"]) | set(res.flags))
148
+ manifest.update_image(
149
+ img["image_id"], status="validated", width=res.width, height=res.height,
150
+ aspect_ratio=res.aspect, orig_format=(res.fmt or "").lower(), flags=flags)
151
+ stats["validated"] += 1
152
+ else:
153
+ manifest.update_image(
154
+ img["image_id"], status="discarded", discard_reason=res.reason,
155
+ width=res.width, height=res.height, aspect_ratio=res.aspect,
156
+ flags=sorted(set(img["flags"]) | set(res.flags)))
157
+ stats[res.reason or "discarded"] = stats.get(res.reason or "discarded", 0) + 1
158
+ log.info("validate: %s", stats)
159
+ return stats
implementation_plan.md ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Implementation Plan: E-Waste Dataset Scraper & Pipeline (v2 Architecture)
2
+
3
+ Build a modular, production-grade Python web scraper and image preprocessing pipeline following `scraper_plan_v2.md` to harvest, clean, deduplicate, and prepare high-resolution e-waste PCB dataset images for fine-tuning YOLOv8 micro-component detectors.
4
+
5
+ ## User Review Required
6
+
7
+ > [!IMPORTANT]
8
+ > **Scraping Target & Volume:** The pilot harvest target will be set to **500 images per query batch** across Bing and Flickr to keep the pilot run under 10–15 minutes while establishing real attrition rates.
9
+ > **Dependency Note:** `icrawler`, `pillow`, `imagehash`, and `open_clip_torch` (or lightweight CLIP filtering) will be installed in the environment.
10
+
11
+ ## Open Questions
12
+
13
+ > [!NOTE]
14
+ > **CLIP Relevance Filter Mode:** Should the initial script execute CLIP zero-shot relevance filtering locally via PyTorch, or fall back to rule-based aspect-ratio/color-histogram heuristic filtering if PyTorch GPU memory is constrained during background runs? (Default: Rule-based + optional CLIP module).
15
+
16
+ ---
17
+
18
+ ## Proposed Changes
19
+
20
+ ### Scraping & Pipeline Package (`ewaste_dataset_pipeline/`)
21
+
22
+ Creation of a self-contained, modular Python CLI pipeline under `ewaste_dataset_pipeline/`.
23
+
24
+ #### [NEW] [`config/taxonomy.yaml`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/config/taxonomy.yaml)
25
+ - Defines the 5 target YOLO detection classes: `cpu_socket`, `gold_finger`, `ic_chip`, `tantalum_capacitor`, `desoldered_zone`.
26
+ - Defines image-level tags: `board_type`, `condition`, `source_type`.
27
+
28
+ #### [NEW] [`config/queries.yaml`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/config/queries.yaml)
29
+ - Search query expansion matrix across search terms, condition variants, board types, and multilingual terms.
30
+
31
+ #### [NEW] [`pipeline/manifest.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/manifest.py)
32
+ - SQLite database abstraction layer (`manifest.db`) tracking URL provenance, download status, MD5 checksums, resolution, pHash values, cluster IDs, and split assignments.
33
+
34
+ #### [NEW] [`pipeline/crawler.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/crawler.py)
35
+ - URL harvester using `icrawler` (Bing, Flickr, Baidu) with exponential backoff retries, custom headers, and rate limiting. Saves raw bytes to `data/originals/`.
36
+
37
+ #### [NEW] [`pipeline/validator.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/validator.py)
38
+ - Validation engine checking file integrity (`verify()` + `load()`), short/long resolution cutoffs ($\ge 480\text{ px}$ short side), and aspect ratio bounds (flag $> 3:1$, drop $> 6:1$).
39
+
40
+ #### [NEW] [`pipeline/processor.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/processor.py)
41
+ - Image normalizer handling EXIF auto-rotation (`exif_transpose`), RGBA alpha white-background compositing, CMYK to RGB conversion, and JPEG 95 quality encoding.
42
+
43
+ #### [NEW] [`pipeline/dedup.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/pipeline/dedup.py)
44
+ - Multi-tier deduplication engine (SHA-256 exact byte hash + perceptual `pHash`/`dHash` with horizontal flip awareness).
45
+
46
+ #### [NEW] [`scraper.py`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/scraper.py)
47
+ - Unified CLI entry point supporting subcommands: `harvest`, `validate`, `process`, `dedup`, `report`.
48
+
49
+ #### [NEW] [`requirements.txt`](file:///home/taruns/sih2026_kabadiwala/ewaste_dataset_pipeline/requirements.txt)
50
+ - Dependency specifications (`icrawler`, `Pillow`, `imagehash`, `pyyaml`, `tqdm`).
51
+
52
+ ---
53
+
54
+ ## Verification Plan
55
+
56
+ ### Automated Verification
57
+ 1. **Unit & Module Tests:**
58
+ - Test image validation on corrupted, truncated, transparent PNG, CMYK, and EXIF-rotated sample images.
59
+ - Verify pHash deduplication on identical vs resized/flipped images.
60
+ 2. **CLI Execution Runs:**
61
+ - Execute pilot harvest run:
62
+ ```bash
63
+ cd ewaste_dataset_pipeline
64
+ python3 scraper.py harvest --max-num 50
65
+ python3 scraper.py validate
66
+ python3 scraper.py process
67
+ python3 scraper.py dedup
68
+ python3 scraper.py report
69
+ ```
70
+
71
+ ### Manual Verification
72
+ - Inspect generated `reports/summary.json` to verify image yield, discard counts by reason, and clean `dataset_raw/` outputs.
implementation_plan_component_purity_index.md ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Implementation Plan: Edge "Component Purity & Cannibalization Index" (Updated)
2
+
3
+ This feature delivers real-time, on-device detection of PCB cannibalization (stripping/depopulation of valuable components like CPU sockets, gold edge fingers, and tantalum capacitors) to calculate a **Board Integrity Score (BIS)**, generate vernacular voice warnings for scrap pricing adjustments, and propagate integrity data through the Dealer → Recycler chain to catch mid-chain stripping fraud.
4
+
5
+ Model training data collection is still in progress, so this plan is split into two tracks joined by a single frozen interface (`model_contract.md`): **Track A** builds and trains the detection model; **Track B** builds the full app pipeline against a mock model conforming to that same contract, so integration is not blocked on model readiness. Swapping the mock for the trained model later is a one-line config change, not a rewrite.
6
+
7
+ ---
8
+
9
+ ## User Review Required
10
+
11
+ > [!IMPORTANT]
12
+ > - **Labeling taxonomy refinement**: Split desoldered footprints into `forcibly_desoldered_pad` (jagged, torn traces, burnt flux) and `factory_unpopulated_pad` (pristine silkscreen, smooth solder dots) to eliminate false cannibalization alerts on unpopulated board regions. Added `occluded_region` to prevent penalizing components covered by heatsinks/dust.
13
+ > - **Form-factor baselines**: Replaced static class-wide component counts with form-factor sub-profiles (`desktop_atx`, `desktop_micro_atx`, `server_1u`, `gpu_pcb`, `ram_dimm`) in `board_profiles.json` to prevent small intact boards from receiving low BIS scores.
14
+ > - **Dynamic price floor**: Replaced the rigid 35% hardcoded price floor with category-based scrap grade floors ($\text{Floor}_{\text{category}}$ = 15% for high-grade server/GPU boards up to 60% for low-grade power boards).
15
+ > - **Sequential edge execution**: Adopted sequential model loading (`dispose()` calls between 21-class category classifier and YOLOv8 micro-model) to prevent memory crashes on 2GB–3GB RAM Android phones.
16
+ > - **BIS-delta tolerance bands**: Updated recycler intake fraud threshold to $>12\%$ for advisory flags and $>25\%$ for critical alerts (up from 5%) to accommodate field-vs-warehouse camera & lighting variances.
17
+ > - **Offline voice fallback**: Standardized pre-recorded `.opus` audio snippets via Service Worker `CacheStorage` as a fallback when Web Speech API offline regional voice packs are missing.
18
+ > - **Data sourcing strategy**: Confirmed that existing open datasets can bootstrap the generic (`*_intact`) component classes, removing most of the annotation burden for those; the fraud-specific classes (`forcibly_desoldered_pad`, `occluded_region`) still require primarily field-staged photography, supplemented — not replaced — by mined web sources. See Phase 1, Component 2a. **Requires a decision on whether forum/marketplace-sourced supplemental images are approved for use** (see licensing note in Component 2a) before any scraping work begins.
19
+
20
+ ---
21
+
22
+ ## Track A: Micro-Component Detection Model
23
+
24
+ ### Phase 1: Data Collection & Labeling (Updated Guidelines)
25
+
26
+ #### Component 1: Refined Labeling Taxonomy (`taxonomy/component_classes.yaml`)
27
+ - [NEW] Defines fine-grained class states to eliminate false positives:
28
+ - `bga_cpu_socket_intact`, `bga_cpu_socket_missing`
29
+ - `gold_edge_finger_intact`, `gold_edge_finger_stripped`
30
+ - `tantalum_cap_intact`, `tantalum_cap_missing`
31
+ - `ram_dimm_slot_intact`, `ram_dimm_slot_stripped`
32
+ - `forcibly_desoldered_pad` (jagged solder, torn traces, blowtorch/burnt flux residue — primary fraud signal)
33
+ - `factory_unpopulated_pad` (clean silkscreen outline, smooth solder dots — unpopulated from factory, NOT fraud)
34
+ - `occluded_region` (heatsinks, metal shields, heavy dirt/dust covering component pads)
35
+
36
+ #### Component 2: Data Collection & Sourcing Protocol (`data_collection/`)
37
+ - [NEW] `capture_protocol.md` — multi-angle capture protocol (Front side top-down, Reverse side top-down, and macro gold edge connector shot) to handle 2-sided PCB inspection.
38
+ - [NEW] `board_sourcing_log.csv` — logs board type, source, form factor (`desktop_atx`, `micro_atx`, `server_4u`, etc.), and intentional stripping state (pristine, blowtorched, organically degraded, factory unpopulated).
39
+ - Sourcing requirements: Must harvest dirty, corroded, dusty, and factory-unpopulated boards alongside pristine and stripped examples to match field scrap yard conditions.
40
+
41
+ #### Component 2a: Data Sourcing Strategy — Open Datasets, Mined Web Sources, and Field Photography (`data_collection/sourcing_strategy.md`)
42
+
43
+ Research into publicly available data confirms a **three-tier sourcing strategy**, since scraping alone cannot cover the fraud-specific classes:
44
+
45
+ **Tier 1 — Open datasets, for bootstrapping `*_intact` classes (use directly, no scraping needed):**
46
+ - A Dataset Ninja "PCB Component Detection" set — 1,410 images, 11,119 bounding-box-labeled objects across 9 classes (capacitor, transformer, MOSFET, resistor, etc.), released CC0 and explicitly tagged for the waste-recycling use case.
47
+ - HuggingFace `PCB_COMPONENTS_LABELLED` — 17-class YOLO-format set (IC, capacitor, connector, crystal oscillator, diode, ferrite bead, fuse, inductor, LED, resistor, switch, transistor, pins, pads, test points).
48
+ - HuggingFace `pcb-object-detection-dataset` — 21-class YOLO set including heatsinks and connectors.
49
+ - Roboflow Universe community PCB datasets (component-level bounding boxes, CC BY 4.0).
50
+ - **Use**: pretrain the detection backbone and pad out the `*_intact` and generic-component classes; re-map class names to `taxonomy/component_classes.yaml`. This does not reduce the need for field data on fraud-specific classes below, but meaningfully cuts the annotation volume needed for the "board still has its parts" side of the taxonomy.
51
+
52
+ **Tier 2 — Mined web sources, as a supplemental seed set for `forcibly_desoldered_pad` only (not a primary source):**
53
+ - Gold-recovery/e-waste hobbyist forums (e.g. Gold Refining Forum, finishing.com) contain user-posted photos of boards before, during, and after chip/pin removal, and active community discussion distinguishing "unpopulated" from "depopulated" boards — the closest organic analog to the `forcibly_desoldered_pad` class available online.
54
+ - Hobbyist "gold recovery" / heat-gun chip-pulling YouTube videos are a higher-yield variant of the same source: frame-extraction from a single video can produce many more usable images than a forum thread.
55
+ - **Known limitations, by design not treated as a primary source**:
56
+ - Low volume per source and inconsistent photo quality/angle — doesn't match the phone-camera, scrap-yard conditions defined in `capture_protocol.md`.
57
+ - No existing bounding boxes — still requires full manual annotation, same as field photos.
58
+ - Licensing: forum and video content is user-generated and not freely licensed for reuse; scraping is low-risk for an internal/hackathon prototype but is **not cleared for production training data** without explicit permission or a licensed dataset. Flagged in User Review Required above — treat as blocked until a decision is made.
59
+ - **Use**: a small supplemental set to diversify what "stripped" looks like beyond staged photos, mined and annotated in parallel with, not instead of, Tier 3.
60
+
61
+ **Tier 3 — Deliberately staged field photography, mandatory and primary for fraud classes (this is the existing Component 2 protocol above):**
62
+ - Only source that guarantees: domain match to real collector phone conditions, controlled multi-angle capture, and clean separation between `forcibly_desoldered_pad`, `factory_unpopulated_pad`, and `occluded_region` at capture time (know the ground truth because you staged it, rather than inferring it after the fact from a forum photo).
63
+ - Remains the dataset of record for Phase 4 evaluation thresholds; Tier 1/2 data is for pretraining and augmentation only, not held-out test data.
64
+
65
+ #### Component 3: Annotation & QA
66
+ - [NEW] Bounding-box annotation via CVAT or Label Studio, exported in COCO/YOLO format.
67
+ - [NEW] `qa_annotation_review.py` — inter-annotator agreement check (min. 2 annotators per image, flag disagreement >10% of boxes for adjudication).
68
+ - Target: minimum 300 images per class, with at least 30% deliberately-stripped/burnt negative examples, before first training run.
69
+
70
+ ### Phase 2: Form-Factor Baseline Definitions
71
+
72
+ #### Component 4: Dynamic Board Profiles (`baselines/board_profiles.json`)
73
+ - [NEW] Defines expected component counts/area ratios per board class **and form factor**:
74
+ - `desktop_atx`, `desktop_micro_atx`, `desktop_itx`
75
+ - `server_1u_2u`, `server_blade_4u`
76
+ - `gpu_pcb_high_end`, `gpu_pcb_budget`
77
+ - `ram_dimm_desktop`, `ram_so_dimm_laptop`
78
+ - Sourced from recycling domain experts — consumed downstream by `purity_assay.py`.
79
+
80
+ ### Phase 3: Model Training
81
+
82
+ #### Component 5: Training Pipeline (`training/train.py`)
83
+ - [NEW] YOLOv8n/s fine-tuning with multi-scale training (`imgsz=960` or `1280`) and custom anchor ratios for elongated `gold_finger` boxes ($>4:1$).
84
+ - Heavy augmentations for field realities: specular glare on gold fingers, lighting variance, dirt noise, and angle tilt.
85
+ - [NEW] `train_config.yaml` — Focal loss & elevated class weights for `forcibly_desoldered_pad` vs `factory_unpopulated_pad`.
86
+
87
+ #### Component 6: Auxiliary Desoldered Pad Classifier Head
88
+ - [NEW] Secondary classification head specifically trained to distinguish desoldered blowtorch pads from factory empty pads.
89
+
90
+ #### Component 7: Export & Quantization (`export/export_tflite.py`)
91
+ - [NEW] Export to TFLite INT8 quantized, target size <15MB, target inference <1s on low-end Android hardware.
92
+ - [NEW] `model_contract.md` — freezes input/output tensor schema.
93
+
94
+ ### Phase 4: Evaluation
95
+
96
+ #### Component 8: Model Evaluation (`eval/evaluate.py`)
97
+ - [NEW] Per-class mAP, plus dedicated fraud recall on `forcibly_desoldered_pad` and false-positive rate on `factory_unpopulated_pad`.
98
+ - Thresholds: $\ge 90\%$ recall on intact classes, $\ge 85\%$ recall on desoldered pad classes, and $\le 5\%$ false positive rate on factory unpopulated pads.
99
+
100
+ ---
101
+
102
+ ## Track B: Integration into Kabadiwala Connect
103
+
104
+ ### Component 9: Purity Engine & Memory-Conscious Orchestrator (`purity_engine/`)
105
+
106
+ - [NEW] `purity_engine/model_client.py` — wrapper supporting `MockModelClient` and `TFLiteModelClient` with explicit tensor memory management (`model.dispose()` between Stage 1 and Stage 2).
107
+ - [NEW] `purity_engine/purity_assay.py` — implements `calculate_board_integrity_score(detected_components, form_factor)`:
108
+ - Dynamic price formula:
109
+ $$\text{Adjusted Price} = \text{Base Price} \times \left( \text{Floor}_{\text{category}} + (1 - \text{Floor}_{\text{category}}) \times \frac{\text{BIS}}{100} \right)$$
110
+ - Scrap Grade Floors: Server/GPU = 15%, Desktop = 30%, Low-grade Power = 60%.
111
+ - [NEW] `purity_engine/pcb_analyzer.py` — single entry point for Collector Lite & Recycler Portal.
112
+
113
+ ### Component 10: Vernacular Voice Alerts with Audio Fallback (`purity_engine/vernacular_voice.py`)
114
+
115
+ - [NEW] Extends Collector Lite's 8-language Web Speech API audio system with Service Worker pre-recorded `.opus` audio fallbacks for offline devices lacking regional voice packs.
116
+ - Message templates parameterized by BIS band (Pristine $\ge 85\%$, Partial $50\text{--}84\%$, Severe $<50\%$).
117
+
118
+ ### Component 11: Collector Lite Multi-Angle UI Integration (`mobile/kabadiwala-lite.html`)
119
+
120
+ - Extend Step 1 of Collector Lite: Stage 1 21-class classifier detects `PCB` $\rightarrow$ prompts guided Front/Back photo capture $\rightarrow$ triggers `pcb_analyzer`.
121
+ - Displays BIS score, missing-component breakdown, and transparent price adjustment in Step 3.
122
+ - Persists assay JSON into IndexedDB with the scrap slip.
123
+
124
+ ### Component 12: QR Handover Payload Enrichment (`mobile/dealer.html`, backend)
125
+
126
+ - QR payload includes collector BIS score, form factor, and assay report hash.
127
+
128
+ ### Component 13: Recycler Portal BIS-Delta View (`recycler-dashboard-frontend/`)
129
+
130
+ - Re-scan intake lot via `pcb_analyzer`.
131
+ - Tolerance Bands:
132
+ - $< 12\%$ BIS Drop $\rightarrow$ Normal capture variance (Pass).
133
+ - $12\text{--}25\%$ BIS Drop $\rightarrow$ Discrepancy Flagged.
134
+ - $> 25\%$ BIS Drop $\rightarrow$ Critical Fraud Alert & CPCB Form 6 PDF Audit Log Entry.
135
+
136
+ ### Component 14: Backend API Changes (`backend/`)
137
+
138
+ - [NEW] `POST /api/lots/{lot_id}/assay` & `GET /api/lots/{lot_id}/bis-delta`.
139
+
140
+ ---
141
+
142
+ ## Sequencing Summary
143
+
144
+ | | Track A (Model & Dataset) | Track B (App Integration) |
145
+ |---|---|---|
146
+ | Now | Tier 1: bootstrap from open datasets. Tier 3: harvest dirty/stripped/unpopulated boards; annotate fine-grained taxonomy. Tier 2 (mined web sources) blocked pending licensing decision | Build multi-angle UI & pricing engine against `MockModelClient` |
147
+ | Parallel | Multi-scale YOLOv8 training with focal loss & TFLite INT8 quantization | Collector Lite, audio fallbacks, Recycler Portal BIS-delta tolerance UI |
148
+ | Hand-off | Ship model clearing Phase 4 thresholds | Swap `TFLiteModelClient` in with zero code changes |
manifest.db ADDED
File without changes
pipeline/__init__.py ADDED
File without changes
pipeline/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (148 Bytes). View file
 
pipeline/__pycache__/config.cpython-312.pyc ADDED
Binary file (6.3 kB). View file
 
pipeline/__pycache__/crawler.cpython-312.pyc ADDED
Binary file (13.2 kB). View file
 
pipeline/__pycache__/dedup.cpython-312.pyc ADDED
Binary file (18.2 kB). View file
 
pipeline/__pycache__/manifest.cpython-312.pyc ADDED
Binary file (24.7 kB). View file
 
pipeline/__pycache__/processor.cpython-312.pyc ADDED
Binary file (9.71 kB). View file
 
pipeline/__pycache__/queries.cpython-312.pyc ADDED
Binary file (5.19 kB). View file
 
pipeline/__pycache__/splitter.cpython-312.pyc ADDED
Binary file (5.6 kB). View file
 
pipeline/__pycache__/validator.cpython-312.pyc ADDED
Binary file (9.79 kB). View file
 
pipeline/auto_annotate.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Automated Zero-Shot Auto-Annotation Pipeline using YOLO-World (Ultra-Lightweight / Resumable Mode).
2
+
3
+ Auto-labels images in `data/images/` using the updated 7-class taxonomy:
4
+ 0: cpu_socket
5
+ 1: gold_finger
6
+ 2: ic_chip
7
+ 3: tantalum_capacitor
8
+ 4: forcibly_desoldered_pad
9
+ 5: factory_unpopulated_pad
10
+ 6: occluded_region
11
+
12
+ Features:
13
+ - Resumable (`skip_existing=True`): Skips already auto-labeled non-empty `.txt` files.
14
+ - Ultra-Low Memory (<500 MB RAM): Standard single-pass inference + per-image `gc.collect()`.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import gc
19
+ import json
20
+ import logging
21
+ import os
22
+ import shutil
23
+ from pathlib import Path
24
+
25
+ import torch
26
+ import yaml
27
+ from PIL import Image
28
+ from tqdm import tqdm
29
+
30
+ cache_dir = Path("data/cache").resolve()
31
+ cache_dir.mkdir(parents=True, exist_ok=True)
32
+ os.environ["TORCH_HOME"] = str(cache_dir)
33
+ os.environ["HF_HOME"] = str(cache_dir)
34
+
35
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
36
+ log = logging.getLogger(__name__)
37
+
38
+ CLASS_NAMES = [
39
+ "cpu_socket",
40
+ "gold_finger",
41
+ "ic_chip",
42
+ "tantalum_capacitor",
43
+ "forcibly_desoldered_pad",
44
+ "factory_unpopulated_pad",
45
+ "occluded_region",
46
+ ]
47
+
48
+ CLASS_PROMPTS = [
49
+ "CPU socket square slot",
50
+ "gold edge connector pins",
51
+ "black IC microchip",
52
+ "yellow SMD capacitor",
53
+ "desoldered solder pad footprint",
54
+ "empty unpopulated solder pad",
55
+ "metal heatsink shield cover",
56
+ ]
57
+
58
+
59
+ def run_auto_annotation(
60
+ data_dir: str | Path = "data",
61
+ output_dir: str | Path = "data/annotated_auto",
62
+ conf_threshold: float = 0.015,
63
+ max_images: int | None = None,
64
+ skip_existing: bool = True,
65
+ ) -> dict:
66
+ torch.set_num_threads(1)
67
+
68
+ data_dir = Path(data_dir)
69
+ output_dir = Path(output_dir)
70
+ images_in_dir = data_dir / "images"
71
+
72
+ images_out_dir = output_dir / "images"
73
+ labels_out_dir = output_dir / "labels"
74
+ images_out_dir.mkdir(parents=True, exist_ok=True)
75
+ labels_out_dir.mkdir(parents=True, exist_ok=True)
76
+
77
+ log.info("Loading YOLO-World model (Resumable Low-Memory Mode)...")
78
+ from ultralytics import YOLOWorld
79
+
80
+ model = YOLOWorld("yolov8s-worldv2.pt")
81
+ model.set_classes(CLASS_PROMPTS)
82
+
83
+ image_files = sorted(list(images_in_dir.glob("*.jpg")) + list(images_in_dir.glob("*.png")))
84
+ if max_images:
85
+ image_files = image_files[:max_images]
86
+
87
+ log.info("Starting Resumable Auto-Annotation across %d images...", len(image_files))
88
+
89
+ class_detection_counts = {name: 0 for name in CLASS_NAMES}
90
+ total_images_processed = 0
91
+ total_boxes_generated = 0
92
+ skipped_count = 0
93
+
94
+ for img_path in tqdm(image_files, desc="Resumable Auto-Annotating", unit="img"):
95
+ img_name = img_path.name
96
+ stem = img_path.stem
97
+
98
+ label_file = labels_out_dir / f"{stem}.txt"
99
+ dst_path = images_out_dir / img_name
100
+
101
+ if not dst_path.exists():
102
+ try:
103
+ shutil.copy2(img_path, dst_path)
104
+ except Exception as e:
105
+ log.warning("Could not copy %s: %s", img_name, e)
106
+
107
+ # Skip if label file exists and is non-empty
108
+ if skip_existing and label_file.exists() and label_file.stat().st_size > 0:
109
+ lines = label_file.read_text(encoding="utf-8").strip().splitlines()
110
+ for l in lines:
111
+ if not l: continue
112
+ parts = l.split()
113
+ cls_id = int(parts[0])
114
+ if 0 <= cls_id < len(CLASS_NAMES):
115
+ class_detection_counts[CLASS_NAMES[cls_id]] += 1
116
+ total_boxes_generated += 1
117
+ total_images_processed += 1
118
+ skipped_count += 1
119
+ continue
120
+
121
+ # Standard single-pass inference (lightweight)
122
+ results = model.predict(str(img_path), conf=conf_threshold, verbose=False)
123
+
124
+ lines = []
125
+ if results and len(results) > 0:
126
+ boxes = results[0].boxes
127
+ if boxes is not None and len(boxes) > 0:
128
+ xywhn = boxes.xywhn.cpu().numpy()
129
+ cls_ids = boxes.cls.cpu().numpy().astype(int)
130
+
131
+ for (x, y, w, h), cls_id in zip(xywhn, cls_ids):
132
+ if 0 <= cls_id < len(CLASS_NAMES):
133
+ lines.append(f"{cls_id} {x:.6f} {y:.6f} {w:.6f} {h:.6f}")
134
+ class_name = CLASS_NAMES[cls_id]
135
+ class_detection_counts[class_name] += 1
136
+ total_boxes_generated += 1
137
+
138
+ label_file.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
139
+ total_images_processed += 1
140
+
141
+ del results
142
+ gc.collect()
143
+
144
+ dataset_yaml = {
145
+ "path": str(output_dir.resolve()),
146
+ "train": "images",
147
+ "val": "images",
148
+ "names": {i: name for i, name in enumerate(CLASS_NAMES)},
149
+ }
150
+ yaml_path = output_dir / "data.yaml"
151
+ with open(yaml_path, "w", encoding="utf-8") as f:
152
+ yaml.dump(dataset_yaml, f, default_flow_style=False)
153
+
154
+ summary = {
155
+ "total_images_processed": total_images_processed,
156
+ "total_boxes_generated": total_boxes_generated,
157
+ "skipped_already_annotated": skipped_count,
158
+ "conf_threshold": conf_threshold,
159
+ "class_detection_counts": class_detection_counts,
160
+ "output_directory": str(output_dir.resolve()),
161
+ "data_yaml": str(yaml_path.resolve()),
162
+ }
163
+
164
+ summary_path = output_dir / "auto_annotation_summary.json"
165
+ with open(summary_path, "w", encoding="utf-8") as f:
166
+ json.dump(summary, f, indent=2)
167
+
168
+ log.info("Auto-annotation complete! Summary saved to %s", summary_path)
169
+ return summary
170
+
171
+
172
+ if __name__ == "__main__":
173
+ import sys
174
+ max_imgs = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else None
175
+ conf_val = float(sys.argv[2]) if len(sys.argv) > 2 else 0.015
176
+ run_auto_annotation(conf_threshold=conf_val, max_images=max_imgs)
pipeline/config.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration loading, filesystem layout and logging setup."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import logging
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import yaml
12
+
13
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
14
+
15
+
16
+ def load_yaml(path: Path) -> dict[str, Any]:
17
+ with open(path, "r", encoding="utf-8") as fh:
18
+ return yaml.safe_load(fh) or {}
19
+
20
+
21
+ def deep_update(base: dict, override: dict) -> dict:
22
+ """Recursively merge ``override`` into ``base`` (in place) and return it."""
23
+ for key, value in override.items():
24
+ if isinstance(value, dict) and isinstance(base.get(key), dict):
25
+ deep_update(base[key], value)
26
+ else:
27
+ base[key] = copy.deepcopy(value)
28
+ return base
29
+
30
+
31
+ def load_config(path: str | Path | None = None, overrides: dict | None = None) -> dict[str, Any]:
32
+ cfg_path = Path(path) if path else PROJECT_ROOT / "config" / "config.yaml"
33
+ cfg = load_yaml(cfg_path)
34
+ cfg["_config_dir"] = str(cfg_path.resolve().parent)
35
+ if overrides:
36
+ deep_update(cfg, overrides)
37
+ return cfg
38
+
39
+
40
+ def load_taxonomy(cfg: dict) -> dict[str, Any]:
41
+ return load_yaml(Path(cfg["_config_dir"]) / "taxonomy.yaml")
42
+
43
+
44
+ def load_queries(cfg: dict) -> dict[str, Any]:
45
+ return load_yaml(Path(cfg["_config_dir"]) / "queries.yaml")
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Paths:
50
+ """Filesystem layout. Manifest paths are stored relative to ``data``."""
51
+
52
+ base: Path
53
+ data: Path
54
+ originals: Path
55
+ images: Path
56
+ review: Path
57
+ realworld: Path
58
+ reports: Path
59
+ splits: Path
60
+ manifest_db: Path
61
+ manifest_jsonl: Path
62
+
63
+ def abs(self, rel: str | Path) -> Path:
64
+ return self.data / rel
65
+
66
+ def rel(self, path: str | Path) -> str:
67
+ return str(Path(path).resolve().relative_to(self.data.resolve()))
68
+
69
+ def ensure(self) -> None:
70
+ for p in (self.data, self.originals, self.images, self.review, self.realworld,
71
+ self.reports, self.splits):
72
+ p.mkdir(parents=True, exist_ok=True)
73
+
74
+
75
+ def get_paths(cfg: dict, base: str | Path | None = None) -> Paths:
76
+ base_dir = Path(base).resolve() if base else PROJECT_ROOT
77
+ pcfg = cfg.get("paths", {})
78
+ data = base_dir / pcfg.get("data_dir", "data")
79
+ return Paths(
80
+ base=base_dir,
81
+ data=data,
82
+ originals=data / "originals",
83
+ images=data / "images",
84
+ review=data / "review",
85
+ realworld=data / "realworld",
86
+ reports=base_dir / pcfg.get("reports_dir", "reports"),
87
+ splits=base_dir / pcfg.get("splits_dir", "splits"),
88
+ manifest_db=data / "manifest.db",
89
+ manifest_jsonl=data / "manifest.jsonl",
90
+ )
91
+
92
+
93
+ def setup_logging(verbose: bool = False) -> None:
94
+ """Configure logging *before* icrawler is imported.
95
+
96
+ icrawler calls ``logging.basicConfig`` when a crawler is constructed; that is a
97
+ no-op once the root logger already has handlers, so configuring first keeps our
98
+ format and level in charge.
99
+ """
100
+ level = logging.DEBUG if verbose else logging.INFO
101
+ root = logging.getLogger()
102
+ if not root.handlers:
103
+ handler = logging.StreamHandler(sys.stderr)
104
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-7s %(name)s: %(message)s",
105
+ datefmt="%H:%M:%S"))
106
+ root.addHandler(handler)
107
+ root.setLevel(level)
108
+ logging.getLogger("urllib3").setLevel(logging.WARNING)
109
+ logging.getLogger("PIL").setLevel(logging.WARNING)
pipeline/crawler.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harvesting engine: query search engines (icrawler / HTTP fallback) and download raw image binaries.
2
+
3
+ Flow:
4
+ 1. Build query list from queries.yaml matrix.
5
+ 2. For each query and engine:
6
+ - Skip if `harvest_runs` records the run as done.
7
+ - Surface image URLs and store in `sources` and `hits` tables via `manifest.add_hit`.
8
+ - Record completed run in `harvest_runs`.
9
+ 3. Download pending URLs into `data/originals/`, computing SHA-256 ID.
10
+ 4. Register downloaded files in `images` table with status 'downloaded'.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import logging
16
+ import mimetypes
17
+ import urllib.request
18
+ import urllib.error
19
+ from concurrent.futures import ThreadPoolExecutor, as_completed
20
+ from pathlib import Path
21
+ from typing import Sequence
22
+
23
+ from tqdm import tqdm
24
+
25
+ from .manifest import Manifest, normalize_url
26
+ from .queries import QuerySpec, build_queries
27
+
28
+ log = logging.getLogger(__name__)
29
+
30
+ HEADERS = {
31
+ "User-Agent": (
32
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
33
+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
34
+ ),
35
+ "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
36
+ }
37
+
38
+ EXT_MAP = {
39
+ "image/jpeg": ".jpg",
40
+ "image/jpg": ".jpg",
41
+ "image/png": ".png",
42
+ "image/webp": ".webp",
43
+ "image/gif": ".gif",
44
+ "image/bmp": ".bmp",
45
+ "image/tiff": ".tif",
46
+ "image/heic": ".heic",
47
+ "image/heif": ".heif",
48
+ }
49
+
50
+
51
+ def download_single_url(
52
+ source: dict, originals_dir: Path, timeout: float = 10.0
53
+ ) -> tuple[dict, str | None, str | None, int | None, str | None]:
54
+ """Download raw binary for one URL.
55
+
56
+ Returns (source, image_id, filepath, http_status, error_message).
57
+ """
58
+ url = source["url"]
59
+ url_norm = source["url_norm"]
60
+ req = urllib.request.Request(url, headers=HEADERS)
61
+
62
+ try:
63
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
64
+ content_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower()
65
+ data = resp.read()
66
+ http_status = resp.status
67
+ except urllib.error.HTTPError as exc:
68
+ return source, None, None, exc.code, f"HTTPError: {exc.code}"
69
+ except Exception as exc:
70
+ return source, None, None, None, f"{type(exc).__name__}: {exc}"
71
+
72
+ if len(data) < 500:
73
+ return source, None, None, http_status, "file_too_small_raw"
74
+
75
+ sha = hashlib.sha256(data).hexdigest()
76
+ image_id = sha[:16]
77
+
78
+ ext = EXT_MAP.get(content_type) or Path(url).suffix.lower()
79
+ if not ext or len(ext) > 5 or ext not in (".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".tif", ".heic"):
80
+ ext = ".jpg"
81
+
82
+ dst = originals_dir / f"{image_id}{ext}"
83
+ if not dst.exists():
84
+ originals_dir.mkdir(parents=True, exist_ok=True)
85
+ tmp = dst.with_name(dst.name + f".tmp")
86
+ tmp.write_bytes(data)
87
+ tmp.replace(dst)
88
+
89
+ return source, image_id, str(dst), http_status, None
90
+
91
+
92
+ def download_pending_sources(
93
+ manifest: Manifest, originals_dir: Path, data_dir: Path, cfg: dict
94
+ ) -> dict[str, int]:
95
+ """Download pending URLs from manifest into `originals_dir`."""
96
+ ccfg = cfg.get("crawler", {})
97
+ workers = int(ccfg.get("threads", 4))
98
+ timeout = float(ccfg.get("timeout", 10.0))
99
+
100
+ pending = manifest.pending_sources()
101
+ stats = {"downloaded": 0, "download_failed": 0}
102
+ if not pending:
103
+ log.info("crawler: no pending sources to download")
104
+ return stats
105
+
106
+ log.info("crawler: downloading %d pending URL(s)", len(pending))
107
+
108
+ def work(src: dict):
109
+ return download_single_url(src, originals_dir, timeout=timeout)
110
+
111
+ with ThreadPoolExecutor(max_workers=workers) as ex:
112
+ futures = [ex.submit(work, s) for s in pending]
113
+ with manifest.transaction():
114
+ for fut in tqdm(as_completed(futures), total=len(futures), desc="download", unit="url"):
115
+ src, image_id, dst_path, http_status, err = fut.result()
116
+ if err is None and image_id and dst_path:
117
+ data_file = Path(dst_path)
118
+ data = data_file.read_bytes()
119
+ sha = hashlib.sha256(data).hexdigest()
120
+ rel_path = str(data_file.relative_to(data_dir))
121
+
122
+ manifest.add_image(
123
+ image_id=image_id,
124
+ sha256=sha,
125
+ origin="web",
126
+ source_ref=src["url"],
127
+ orig_path=rel_path,
128
+ orig_format=data_file.suffix.lstrip(".").lower(),
129
+ filesize=len(data),
130
+ status="downloaded",
131
+ )
132
+ manifest.mark_source(
133
+ src["url_norm"],
134
+ status="downloaded",
135
+ http_status=http_status,
136
+ image_id=image_id,
137
+ attempts=1,
138
+ )
139
+ stats["downloaded"] += 1
140
+ else:
141
+ manifest.mark_source(
142
+ src["url_norm"],
143
+ status="failed",
144
+ http_status=http_status,
145
+ error=err,
146
+ attempts=1,
147
+ )
148
+ stats["download_failed"] += 1
149
+
150
+ log.info("crawler download stats: %s", stats)
151
+ return stats
152
+
153
+
154
+ def run_icrawler_harvest(
155
+ manifest: Manifest,
156
+ queries: Sequence[QuerySpec],
157
+ data_dir: Path,
158
+ engine_name: str = "bing",
159
+ max_num: int = 50,
160
+ force: bool = False,
161
+ filter_classes: set[str] | Sequence[str] | None = None,
162
+ ) -> dict[str, int]:
163
+ """Harvest image binaries using icrawler, save to data/originals, and register in manifest."""
164
+ stats = {"runs": 0, "urls_found": 0, "urls_new": 0, "images_harvested": 0}
165
+ try:
166
+ if engine_name.lower() == "bing":
167
+ from icrawler.builtin import BingImageCrawler as CrawlerEngine
168
+ elif engine_name.lower() == "flickr":
169
+ from icrawler.builtin import FlickrImageCrawler as CrawlerEngine
170
+ elif engine_name.lower() == "baidu":
171
+ from icrawler.builtin import BaiduImageCrawler as CrawlerEngine
172
+ else:
173
+ log.warning("Unknown engine '%s', defaulting to Bing", engine_name)
174
+ from icrawler.builtin import BingImageCrawler as CrawlerEngine
175
+ except ImportError:
176
+ log.warning("icrawler is not installed; skipping search engine crawling")
177
+ return stats
178
+
179
+ import tempfile
180
+ import shutil
181
+
182
+ originals_dir = data_dir / "originals"
183
+ originals_dir.mkdir(parents=True, exist_ok=True)
184
+
185
+ filter_set = set(filter_classes) if filter_classes else None
186
+
187
+ for qspec in queries:
188
+ if filter_set and qspec.class_hint not in filter_set:
189
+ continue
190
+ if not force and manifest.run_done(engine_name, qspec.query):
191
+ log.debug("Skip harvest done run: %s / %s", engine_name, qspec.query)
192
+ continue
193
+
194
+ tmp_dir = Path(tempfile.mkdtemp(prefix="icrawler_"))
195
+ try:
196
+ crawler = CrawlerEngine(
197
+ downloader_threads=2,
198
+ storage={"root_dir": str(tmp_dir)},
199
+ log_level=logging.WARNING,
200
+ )
201
+ crawler.crawl(keyword=qspec.query, max_num=max_num)
202
+
203
+ found_count = 0
204
+ new_count = 0
205
+ with manifest.transaction():
206
+ for img_file in tmp_dir.glob("*"):
207
+ if img_file.is_file() and img_file.stat().st_size > 500:
208
+ found_count += 1
209
+ data = img_file.read_bytes()
210
+ sha = hashlib.sha256(data).hexdigest()
211
+ image_id = sha[:16]
212
+ ext = img_file.suffix.lower()
213
+ if not ext or len(ext) > 5 or ext not in (".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"):
214
+ ext = ".jpg"
215
+
216
+ dst_file = originals_dir / f"{image_id}{ext}"
217
+ if not dst_file.exists():
218
+ dst_file.write_bytes(data)
219
+
220
+ source_url = f"icrawler://{engine_name}/{qspec.class_hint}/{image_id}"
221
+ is_new = manifest.add_hit(
222
+ source_url, engine_name, qspec.query, class_hint=qspec.class_hint, lang=qspec.lang
223
+ )
224
+ if is_new:
225
+ new_count += 1
226
+
227
+ rel_path = str(dst_file.relative_to(data_dir))
228
+ manifest.add_image(
229
+ image_id=image_id,
230
+ sha256=sha,
231
+ origin="web",
232
+ source_ref=source_url,
233
+ orig_path=rel_path,
234
+ orig_format=ext.lstrip("."),
235
+ filesize=len(data),
236
+ status="downloaded",
237
+ )
238
+ manifest.mark_source(
239
+ source_url,
240
+ status="downloaded",
241
+ image_id=image_id,
242
+ )
243
+ stats["images_harvested"] += 1
244
+
245
+ manifest.record_run(
246
+ engine_name, qspec.query, qspec.class_hint, max_num, found_count, new_count
247
+ )
248
+ stats["runs"] += 1
249
+ stats["urls_found"] += found_count
250
+ stats["urls_new"] += new_count
251
+ except Exception as exc:
252
+ log.error("icrawler harvest failed for %s (%s): %s", qspec.query, engine_name, exc)
253
+ finally:
254
+ shutil.rmtree(tmp_dir, ignore_errors=True)
255
+
256
+ log.info("harvest stats (%s): %s", engine_name, stats)
257
+ return stats
258
+
259
+
260
+ def run(
261
+ manifest: Manifest, cfg: dict, data_dir: Path, engine: str = "bing", max_num: int = 50, force: bool = False, filter_classes: set[str] | Sequence[str] | None = None
262
+ ) -> dict[str, int]:
263
+ """Full crawler workflow: harvest queries and download raw images."""
264
+ qcfg = cfg.get("queries") or {}
265
+ if not qcfg:
266
+ from .config import load_queries
267
+ qcfg = load_queries(cfg)
268
+
269
+ queries = build_queries(qcfg)
270
+ harvest_stats = run_icrawler_harvest(manifest, queries, data_dir, engine_name=engine, max_num=max_num, force=force, filter_classes=filter_classes)
271
+
272
+ originals_dir = data_dir / "originals"
273
+ download_stats = download_pending_sources(manifest, originals_dir, data_dir, cfg)
274
+
275
+ return {**harvest_stats, **download_stats}
pipeline/dedup.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deduplication engine (global across all classes and queries).
2
+
3
+ Layer 1 exact SHA-256 of the original bytes (already the image_id, so identical downloads
4
+ collapse at download time) + SHA-256 of the decoded normalized pixels.
5
+ Layer 2 near-dup pHash AND dHash (64-bit each) within a Hamming-distance budget. Every image
6
+ also stores the hashes of its horizontally FLIPPED version, and a pair counts
7
+ as a duplicate if it matches in either orientation (mirror copies).
8
+ Layer 3 semantic CLIP-embedding cosine clustering. This layer never deletes anything; it only
9
+ merges cluster ids so the splitter keeps "same board, different angle" together.
10
+
11
+ Layers 1-2 remove images: within a duplicate group the keeper is chosen by
12
+ (already-processed before new) > (real-world before web) > higher resolution > larger file > id
13
+ so re-running the pipeline never swaps out an image that was already kept or annotated.
14
+ Duplicate groups are connected components (union-find), so chains A~B~C collapse into one group.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from collections import defaultdict
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
21
+ from pathlib import Path
22
+ from typing import Sequence
23
+
24
+ import imagehash
25
+ import numpy as np
26
+ from PIL import Image, ImageOps
27
+ from tqdm import tqdm
28
+
29
+ from .manifest import Manifest
30
+
31
+ log = logging.getLogger(__name__)
32
+
33
+ # Statuses whose images are candidates for duplicate comparison (hashes present).
34
+ _PROCESSED = ("deduped", "kept", "review")
35
+ _CANDIDATES = ("normalized",) + _PROCESSED
36
+
37
+ _POP8 = np.array([bin(i).count("1") for i in range(256)], dtype=np.uint8)
38
+
39
+
40
+ # ------------------------------------------------------------------------------------ hashing
41
+ def compute_hashes(path: str | Path) -> dict[str, str]:
42
+ """pHash/dHash (8x8 => 64 bit, hex) for an image and for its horizontal mirror."""
43
+ with Image.open(path) as im:
44
+ im.draft("RGB", (512, 512)) # cheap JPEG downscale on decode; same procedure for all images
45
+ im = ImageOps.exif_transpose(im).convert("RGB")
46
+ flipped = ImageOps.mirror(im)
47
+ return {
48
+ "phash": str(imagehash.phash(im, hash_size=8)),
49
+ "dhash": str(imagehash.dhash(im, hash_size=8)),
50
+ "phash_flip": str(imagehash.phash(flipped, hash_size=8)),
51
+ "dhash_flip": str(imagehash.dhash(flipped, hash_size=8)),
52
+ }
53
+
54
+
55
+ def hex_to_u64(values: Sequence[str]) -> np.ndarray:
56
+ return np.array([int(v, 16) for v in values], dtype=np.uint64)
57
+
58
+
59
+ def popcount64(x: np.ndarray) -> np.ndarray:
60
+ """Per-element population count of a uint64 array."""
61
+ if hasattr(np, "bitwise_count"): # numpy >= 2.0
62
+ return np.bitwise_count(x)
63
+ x = np.ascontiguousarray(x)
64
+ return _POP8[x.view(np.uint8).reshape(*x.shape, 8)].sum(axis=-1)
65
+
66
+
67
+ # --------------------------------------------------------------------------------- union-find
68
+ class UnionFind:
69
+ def __init__(self, n: int):
70
+ self.parent = list(range(n))
71
+
72
+ def find(self, a: int) -> int:
73
+ while self.parent[a] != a:
74
+ self.parent[a] = self.parent[self.parent[a]]
75
+ a = self.parent[a]
76
+ return a
77
+
78
+ def union(self, a: int, b: int) -> None:
79
+ ra, rb = self.find(a), self.find(b)
80
+ if ra != rb:
81
+ self.parent[max(ra, rb)] = min(ra, rb)
82
+
83
+ def groups(self) -> list[list[int]]:
84
+ out: dict[int, list[int]] = defaultdict(list)
85
+ for i in range(len(self.parent)):
86
+ out[self.find(i)].append(i)
87
+ return [g for g in out.values() if len(g) > 1]
88
+
89
+
90
+ def near_duplicate_pairs(ph: np.ndarray, dh: np.ndarray, phf: np.ndarray, dhf: np.ndarray,
91
+ phash_max: int, dhash_max: int, block_cells: int = 4_000_000):
92
+ """Yield (i, j), i < j, whose pHash *and* dHash are within budget in the same orientation
93
+ (direct, or with j mirrored). Vectorized in row blocks to bound memory."""
94
+ n = len(ph)
95
+ if n < 2:
96
+ return
97
+ block = max(1, block_cells // n)
98
+ cols = np.arange(n)
99
+ for a in range(0, n, block):
100
+ b = min(n, a + block)
101
+ upper = cols[None, :] > np.arange(a, b)[:, None]
102
+ direct = (popcount64(ph[a:b, None] ^ ph[None, :]) <= phash_max) & \
103
+ (popcount64(dh[a:b, None] ^ dh[None, :]) <= dhash_max)
104
+ mirrored = (popcount64(ph[a:b, None] ^ phf[None, :]) <= phash_max) & \
105
+ (popcount64(dh[a:b, None] ^ dhf[None, :]) <= dhash_max)
106
+ ii, jj = np.nonzero((direct | mirrored) & upper)
107
+ for i, j in zip(ii + a, jj):
108
+ yield int(i), int(j)
109
+
110
+
111
+ def find_duplicate_groups(rows: list[dict], phash_max: int, dhash_max: int) -> list[list[int]]:
112
+ """Group row indices by exact pixel hash + near-duplicate hashes (connected components)."""
113
+ n = len(rows)
114
+ uf = UnionFind(n)
115
+ by_pixels: dict[str, int] = {}
116
+ for i, r in enumerate(rows):
117
+ px = r.get("pixel_sha256")
118
+ if px:
119
+ if px in by_pixels:
120
+ uf.union(by_pixels[px], i)
121
+ else:
122
+ by_pixels[px] = i
123
+ if n >= 2:
124
+ ph = hex_to_u64([r["phash"] for r in rows])
125
+ dh = hex_to_u64([r["dhash"] for r in rows])
126
+ phf = hex_to_u64([r["phash_flip"] for r in rows])
127
+ dhf = hex_to_u64([r["dhash_flip"] for r in rows])
128
+ for i, j in near_duplicate_pairs(ph, dh, phf, dhf, phash_max, dhash_max):
129
+ uf.union(i, j)
130
+ return uf.groups()
131
+
132
+
133
+ def keeper_rank(row: dict) -> tuple:
134
+ """Lower sorts first = preferred keeper."""
135
+ processed = 0 if row["status"] in _PROCESSED else 1
136
+ realworld = 0 if row.get("origin") == "realworld" else 1
137
+ pixels = (row.get("norm_width") or row.get("width") or 0) * (row.get("norm_height") or row.get("height") or 0)
138
+ return (processed, realworld, -pixels, -(row.get("filesize") or 0), row["image_id"])
139
+
140
+
141
+ # ------------------------------------------------------------------------------------- stage
142
+ def run(manifest: Manifest, cfg: dict, data_dir: Path) -> dict[str, int]:
143
+ """Hash new images, then discard exact/near duplicates across the whole candidate pool."""
144
+ dcfg = cfg["dedup"]
145
+ stats = {"hashed": 0, "exact_duplicate": 0, "near_duplicate": 0, "deduped": 0, "hash_failed": 0}
146
+
147
+ # 1. hashes for images that do not have them yet
148
+ fresh = [r for r in manifest.images(statuses=["normalized"]) if not r["phash"]]
149
+ if fresh:
150
+ def work(r: dict):
151
+ try:
152
+ return r, compute_hashes(data_dir / r["norm_path"]), None
153
+ except Exception as exc: # noqa: BLE001
154
+ return r, None, exc
155
+
156
+ with ThreadPoolExecutor(max_workers=int(dcfg.get("hash_workers", 4))) as ex:
157
+ futures = [ex.submit(work, r) for r in fresh]
158
+ with manifest.transaction():
159
+ for fut in tqdm(as_completed(futures), total=len(futures), desc="hash", unit="img"):
160
+ r, hashes, err = fut.result()
161
+ if err is not None:
162
+ log.warning("hashing failed for %s: %s", r["image_id"], err)
163
+ manifest.discard(r["image_id"], "hash_failed")
164
+ stats["hash_failed"] += 1
165
+ else:
166
+ manifest.update_image(r["image_id"], **hashes)
167
+ stats["hashed"] += 1
168
+
169
+ # 2. group duplicates over the full candidate pool (new + previously processed)
170
+ rows = [r for r in manifest.images(statuses=_CANDIDATES) if r["phash"]]
171
+ groups = find_duplicate_groups(rows, int(dcfg["phash_max_dist"]), int(dcfg["dhash_max_dist"]))
172
+ log.info("dedup: %d candidates, %d duplicate group(s)", len(rows), len(groups))
173
+
174
+ discarded: set[str] = set()
175
+ cluster_of: dict[str, str] = {} # cluster ids assigned during this run
176
+ with manifest.transaction():
177
+ for group in groups:
178
+ members = sorted((rows[i] for i in group), key=keeper_rank)
179
+ keeper, losers = members[0], members[1:]
180
+ # Reuse the keeper's existing cluster id: a previous semantic merge may have
181
+ # renamed it, and a rerun must never undo that.
182
+ cid = keeper["cluster_id"] or keeper["image_id"]
183
+ for member in members:
184
+ cluster_of[member["image_id"]] = cid
185
+ manifest.update_image(member["image_id"], cluster_id=cid)
186
+ for loser in losers:
187
+ exact = bool(loser["pixel_sha256"]) and loser["pixel_sha256"] == keeper["pixel_sha256"]
188
+ reason = "exact_duplicate" if exact else "near_duplicate"
189
+ if loser["status"] == "normalized":
190
+ manifest.discard(loser["image_id"], reason, dup_of=keeper["image_id"])
191
+ discarded.add(loser["image_id"])
192
+ stats[reason] += 1
193
+ else:
194
+ # An already-processed image is never removed retroactively (it may already
195
+ # be annotated); it only joins the cluster so splits stay leak-free.
196
+ log.warning("kept %s although it duplicates %s (already processed)",
197
+ loser["image_id"], keeper["image_id"])
198
+ # Survivors advance; singletons get their own cluster id.
199
+ for r in rows:
200
+ if r["status"] != "normalized" or r["image_id"] in discarded:
201
+ continue
202
+ updates = {"status": "deduped"}
203
+ if not cluster_of.get(r["image_id"]) and not r["cluster_id"]:
204
+ updates["cluster_id"] = r["image_id"]
205
+ manifest.update_image(r["image_id"], **updates)
206
+ stats["deduped"] += 1
207
+ log.info("dedup: %s", stats)
208
+ return stats
209
+
210
+
211
+ # ------------------------------------------------------------------------- semantic clustering
212
+ def semantic_clusters(ids: list[str], emb: np.ndarray, threshold: float,
213
+ existing: dict[str, str] | None = None, block_cells: int = 4_000_000) -> dict[str, str]:
214
+ """Merge images into clusters by embedding cosine >= threshold (and by existing cluster ids).
215
+
216
+ Returns image_id -> cluster id (the smallest image_id in the component, deterministic).
217
+ Assumes rows of ``emb`` are L2-normalized.
218
+ """
219
+ n = len(ids)
220
+ uf = UnionFind(n)
221
+ if existing:
222
+ first_seen: dict[str, int] = {}
223
+ for i, image_id in enumerate(ids):
224
+ cid = existing.get(image_id)
225
+ if cid:
226
+ if cid in first_seen:
227
+ uf.union(first_seen[cid], i)
228
+ else:
229
+ first_seen[cid] = i
230
+ if n >= 2:
231
+ block = max(1, block_cells // n)
232
+ cols = np.arange(n)
233
+ for a in range(0, n, block):
234
+ b = min(n, a + block)
235
+ sim = emb[a:b] @ emb.T
236
+ ii, jj = np.nonzero((sim >= threshold) & (cols[None, :] > np.arange(a, b)[:, None]))
237
+ for i, j in zip(ii + a, jj):
238
+ uf.union(int(i), int(j))
239
+ comp: dict[int, list[str]] = defaultdict(list)
240
+ for i, image_id in enumerate(ids):
241
+ comp[uf.find(i)].append(image_id)
242
+ return {image_id: min(members) for members in comp.values() for image_id in members}
243
+
244
+
245
+ def run_semantic(manifest: Manifest, cfg: dict) -> dict[str, int]:
246
+ """Layer 3: merge cluster ids using stored CLIP embeddings (labels only, deletes nothing)."""
247
+ rows = manifest.images(statuses=["kept", "review"])
248
+ ids, emb = manifest.load_embeddings([r["image_id"] for r in rows])
249
+ if not ids:
250
+ log.warning("cluster: no embeddings found (run `filter` with CLIP first); skipping")
251
+ return {"clustered": 0, "merged_clusters": 0}
252
+ existing = {r["image_id"]: r["cluster_id"] or r["image_id"] for r in rows}
253
+ norms = np.linalg.norm(emb, axis=1, keepdims=True)
254
+ emb = emb / np.clip(norms, 1e-9, None)
255
+ new_ids = semantic_clusters(ids, emb, float(cfg["dedup"]["semantic_cosine"]), existing)
256
+
257
+ remap: dict[str, str] = {}
258
+ for image_id, new in new_ids.items():
259
+ old = existing[image_id]
260
+ if old != new:
261
+ remap[old] = new
262
+ with manifest.transaction():
263
+ # Update *all* rows (incl. discarded duplicates) that carry a merged cluster id.
264
+ for old, new in remap.items():
265
+ manifest.execute("UPDATE images SET cluster_id=? WHERE cluster_id=?", (new, old))
266
+ for image_id, new in new_ids.items():
267
+ if image_id not in remap and existing[image_id] != new:
268
+ manifest.update_image(image_id, cluster_id=new)
269
+ stats = {"clustered": len(ids), "merged_clusters": len(remap)}
270
+ log.info("cluster: %s", stats)
271
+ return stats
pipeline/manifest.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SQLite manifest: the single source of truth for provenance and pipeline state.
2
+
3
+ Tables
4
+ ------
5
+ sources one row per (normalized) URL; download state
6
+ hits every (url, engine, query) that surfaced a URL -> class hints and provenance
7
+ harvest_runs completed (engine, query) harvests so reruns skip them
8
+ images one row per unique image (sha256 of original bytes) with all pipeline state
9
+ embeddings optional CLIP embeddings (float16 blobs)
10
+
11
+ Image status flow
12
+ -----------------
13
+ downloaded -> validated -> normalized -> deduped -> kept | review | discarded
14
+ Every stage only touches rows in its own input status, so all stages are idempotent
15
+ and a rerun after an interruption never repeats finished work.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import sqlite3
21
+ import threading
22
+ from contextlib import contextmanager
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+ from typing import Any, Iterable, Iterator
26
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
27
+
28
+ import numpy as np
29
+
30
+ STATUSES = ("downloaded", "validated", "normalized", "deduped", "kept", "review", "discarded")
31
+
32
+ SCHEMA = """
33
+ PRAGMA journal_mode=WAL;
34
+ PRAGMA synchronous=NORMAL;
35
+
36
+ CREATE TABLE IF NOT EXISTS sources (
37
+ url_norm TEXT PRIMARY KEY,
38
+ url TEXT NOT NULL,
39
+ status TEXT NOT NULL DEFAULT 'pending',
40
+ attempts INTEGER NOT NULL DEFAULT 0,
41
+ http_status INTEGER,
42
+ error TEXT,
43
+ image_id TEXT,
44
+ harvested_at TEXT,
45
+ downloaded_at TEXT
46
+ );
47
+ CREATE INDEX IF NOT EXISTS idx_sources_status ON sources(status);
48
+ CREATE INDEX IF NOT EXISTS idx_sources_image ON sources(image_id);
49
+
50
+ CREATE TABLE IF NOT EXISTS hits (
51
+ url_norm TEXT NOT NULL,
52
+ engine TEXT NOT NULL,
53
+ query TEXT NOT NULL,
54
+ class_hint TEXT,
55
+ lang TEXT,
56
+ harvested_at TEXT,
57
+ PRIMARY KEY (url_norm, engine, query)
58
+ );
59
+
60
+ CREATE TABLE IF NOT EXISTS harvest_runs (
61
+ engine TEXT NOT NULL,
62
+ query TEXT NOT NULL,
63
+ class_hint TEXT,
64
+ max_num INTEGER,
65
+ urls_found INTEGER,
66
+ urls_new INTEGER,
67
+ finished_at TEXT,
68
+ PRIMARY KEY (engine, query)
69
+ );
70
+
71
+ CREATE TABLE IF NOT EXISTS images (
72
+ image_id TEXT PRIMARY KEY,
73
+ sha256 TEXT NOT NULL,
74
+ origin TEXT NOT NULL DEFAULT 'web',
75
+ source_ref TEXT,
76
+ orig_path TEXT,
77
+ orig_format TEXT,
78
+ filesize INTEGER,
79
+ width INTEGER,
80
+ height INTEGER,
81
+ aspect_ratio REAL,
82
+ norm_path TEXT,
83
+ norm_width INTEGER,
84
+ norm_height INTEGER,
85
+ pixel_sha256 TEXT,
86
+ phash TEXT,
87
+ dhash TEXT,
88
+ phash_flip TEXT,
89
+ dhash_flip TEXT,
90
+ flags TEXT NOT NULL DEFAULT '[]',
91
+ status TEXT NOT NULL,
92
+ discard_reason TEXT,
93
+ dup_of TEXT,
94
+ cluster_id TEXT,
95
+ clip_score REAL,
96
+ relevance_bucket TEXT,
97
+ board_type TEXT,
98
+ condition TEXT,
99
+ source_type TEXT,
100
+ review_status TEXT,
101
+ reviewer TEXT,
102
+ reviewed_at TEXT,
103
+ split TEXT,
104
+ session_id TEXT,
105
+ board_id TEXT,
106
+ created_at TEXT,
107
+ updated_at TEXT
108
+ );
109
+ CREATE INDEX IF NOT EXISTS idx_images_status ON images(status);
110
+ CREATE INDEX IF NOT EXISTS idx_images_cluster ON images(cluster_id);
111
+ CREATE INDEX IF NOT EXISTS idx_images_dup_of ON images(dup_of);
112
+
113
+ CREATE TABLE IF NOT EXISTS embeddings (
114
+ image_id TEXT PRIMARY KEY,
115
+ dim INTEGER NOT NULL,
116
+ vec BLOB NOT NULL
117
+ );
118
+ """
119
+
120
+ IMAGE_COLUMNS = {
121
+ "image_id", "sha256", "origin", "source_ref", "orig_path", "orig_format", "filesize", "width",
122
+ "height", "aspect_ratio", "norm_path", "norm_width", "norm_height", "pixel_sha256", "phash",
123
+ "dhash", "phash_flip", "dhash_flip", "flags", "status", "discard_reason", "dup_of", "cluster_id",
124
+ "clip_score", "relevance_bucket", "board_type", "condition", "source_type", "review_status",
125
+ "reviewer", "reviewed_at", "split", "session_id", "board_id", "created_at", "updated_at",
126
+ }
127
+
128
+ _TRACKING_PARAMS = {"fbclid", "gclid", "msclkid", "yclid"}
129
+ _DEFAULT_PORTS = {"http": 80, "https": 443}
130
+
131
+
132
+ def utcnow() -> str:
133
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
134
+
135
+
136
+ def normalize_url(url: str) -> str:
137
+ """Canonical form used as the dedup key for URLs (case, default ports, fragment, tracking)."""
138
+ parts = urlsplit(url.strip())
139
+ scheme = parts.scheme.lower()
140
+ host = (parts.hostname or "").lower()
141
+ try:
142
+ port = parts.port
143
+ except ValueError:
144
+ port = None
145
+ netloc = host
146
+ if port and port != _DEFAULT_PORTS.get(scheme):
147
+ netloc = f"{host}:{port}"
148
+ query = sorted(
149
+ (k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
150
+ if not k.lower().startswith("utm_") and k.lower() not in _TRACKING_PARAMS
151
+ )
152
+ return urlunsplit((scheme, netloc, parts.path or "/", urlencode(query), ""))
153
+
154
+
155
+ def _check_columns(fields: Iterable[str]) -> None:
156
+ bad = set(fields) - IMAGE_COLUMNS
157
+ if bad:
158
+ raise KeyError(f"unknown image column(s): {sorted(bad)}")
159
+
160
+
161
+ class Manifest:
162
+ """Thread-safe SQLite wrapper (one connection, serialized by an RLock)."""
163
+
164
+ def __init__(self, db_path: str | Path):
165
+ self.db_path = Path(db_path)
166
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
167
+ self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False,
168
+ isolation_level=None, timeout=60)
169
+ self._conn.row_factory = sqlite3.Row
170
+ self._lock = threading.RLock()
171
+ self._tx_depth = 0
172
+ with self._lock:
173
+ self._conn.executescript(SCHEMA)
174
+
175
+ # -- infrastructure -----------------------------------------------------------------
176
+ def close(self) -> None:
177
+ with self._lock:
178
+ self._conn.close()
179
+
180
+ def __enter__(self) -> "Manifest":
181
+ return self
182
+
183
+ def __exit__(self, *exc) -> None:
184
+ self.close()
185
+
186
+ @contextmanager
187
+ def transaction(self) -> Iterator[None]:
188
+ """Group many writes into one commit (re-entrant)."""
189
+ with self._lock:
190
+ outer = self._tx_depth == 0
191
+ if outer:
192
+ self._conn.execute("BEGIN")
193
+ self._tx_depth += 1
194
+ try:
195
+ yield
196
+ except BaseException:
197
+ self._tx_depth -= 1
198
+ if outer:
199
+ self._conn.execute("ROLLBACK")
200
+ raise
201
+ else:
202
+ self._tx_depth -= 1
203
+ if outer:
204
+ self._conn.execute("COMMIT")
205
+
206
+ def execute(self, sql: str, params: Iterable[Any] = ()) -> sqlite3.Cursor:
207
+ with self._lock:
208
+ return self._conn.execute(sql, tuple(params))
209
+
210
+ def query(self, sql: str, params: Iterable[Any] = ()) -> list[sqlite3.Row]:
211
+ with self._lock:
212
+ return self._conn.execute(sql, tuple(params)).fetchall()
213
+
214
+ # -- sources / hits -------------------------------------------------------------------
215
+ def add_hit(self, url: str, engine: str, query: str, class_hint: str | None = None,
216
+ lang: str | None = None) -> bool:
217
+ """Record a harvested URL. Returns True if the URL was new."""
218
+ url_norm = normalize_url(url)
219
+ now = utcnow()
220
+ with self._lock:
221
+ cur = self._conn.execute(
222
+ "INSERT OR IGNORE INTO sources(url_norm, url, status, harvested_at) "
223
+ "VALUES (?, ?, 'pending', ?)", (url_norm, url, now))
224
+ is_new = cur.rowcount == 1
225
+ self._conn.execute(
226
+ "INSERT OR IGNORE INTO hits(url_norm, engine, query, class_hint, lang, harvested_at) "
227
+ "VALUES (?, ?, ?, ?, ?, ?)", (url_norm, engine, query, class_hint, lang, now))
228
+ return is_new
229
+
230
+ def pending_sources(self, limit: int | None = None, include_transient: bool = False) -> list[dict]:
231
+ statuses = ("pending", "failed_transient") if include_transient else ("pending",)
232
+ sql = f"SELECT * FROM sources WHERE status IN ({','.join('?' * len(statuses))}) ORDER BY harvested_at, url_norm"
233
+ params: list[Any] = list(statuses)
234
+ if limit:
235
+ sql += " LIMIT ?"
236
+ params.append(limit)
237
+ return [dict(r) for r in self.query(sql, params)]
238
+
239
+ def mark_source(self, url_norm: str, status: str, http_status: int | None = None,
240
+ error: str | None = None, image_id: str | None = None, attempts: int = 0) -> None:
241
+ self.execute(
242
+ "UPDATE sources SET status=?, http_status=?, error=?, image_id=?, "
243
+ "attempts=attempts+?, downloaded_at=? WHERE url_norm=?",
244
+ (status, http_status, error, image_id, attempts, utcnow(), url_norm))
245
+
246
+ # -- harvest runs ---------------------------------------------------------------------
247
+ def run_done(self, engine: str, query: str) -> bool:
248
+ return bool(self.query("SELECT 1 FROM harvest_runs WHERE engine=? AND query=?", (engine, query)))
249
+
250
+ def record_run(self, engine: str, query: str, class_hint: str | None, max_num: int,
251
+ found: int, new: int) -> None:
252
+ self.execute(
253
+ "INSERT OR REPLACE INTO harvest_runs VALUES (?, ?, ?, ?, ?, ?, ?)",
254
+ (engine, query, class_hint, max_num, found, new, utcnow()))
255
+
256
+ # -- images ----------------------------------------------------------------------------
257
+ def add_image(self, **fields: Any) -> bool:
258
+ """Insert an image row if its image_id is new. Returns True if inserted."""
259
+ _check_columns(fields)
260
+ fields.setdefault("origin", "web")
261
+ now = utcnow()
262
+ fields.setdefault("created_at", now)
263
+ fields.setdefault("updated_at", now)
264
+ if isinstance(fields.get("flags"), (list, tuple, set)):
265
+ fields["flags"] = json.dumps(sorted(fields["flags"]))
266
+ cols = list(fields)
267
+ cur = self.execute(
268
+ f"INSERT OR IGNORE INTO images({','.join(cols)}) VALUES ({','.join('?' * len(cols))})",
269
+ [fields[c] for c in cols])
270
+ return cur.rowcount == 1
271
+
272
+ @staticmethod
273
+ def _row(row: sqlite3.Row | None) -> dict | None:
274
+ if row is None:
275
+ return None
276
+ d = dict(row)
277
+ d["flags"] = json.loads(d.get("flags") or "[]")
278
+ return d
279
+
280
+ def get_image(self, image_id: str) -> dict | None:
281
+ rows = self.query("SELECT * FROM images WHERE image_id=?", (image_id,))
282
+ return self._row(rows[0]) if rows else None
283
+
284
+ def images(self, statuses: Iterable[str] | None = None, origin: str | None = None,
285
+ where: str | None = None, params: Iterable[Any] = ()) -> list[dict]:
286
+ clauses, args = [], []
287
+ if statuses:
288
+ statuses = tuple(statuses)
289
+ clauses.append(f"status IN ({','.join('?' * len(statuses))})")
290
+ args += list(statuses)
291
+ if origin:
292
+ clauses.append("origin=?")
293
+ args.append(origin)
294
+ if where:
295
+ clauses.append(f"({where})")
296
+ args += list(params)
297
+ sql = "SELECT * FROM images" + (" WHERE " + " AND ".join(clauses) if clauses else "")
298
+ sql += " ORDER BY image_id"
299
+ return [self._row(r) for r in self.query(sql, args)]
300
+
301
+ def update_image(self, image_id: str, **fields: Any) -> None:
302
+ _check_columns(fields)
303
+ if not fields:
304
+ return
305
+ if isinstance(fields.get("flags"), (list, tuple, set)):
306
+ fields["flags"] = json.dumps(sorted(fields["flags"]))
307
+ fields["updated_at"] = utcnow()
308
+ sets = ", ".join(f"{c}=?" for c in fields)
309
+ self.execute(f"UPDATE images SET {sets} WHERE image_id=?", [*fields.values(), image_id])
310
+
311
+ def add_flags(self, image_id: str, *new_flags: str) -> None:
312
+ img = self.get_image(image_id)
313
+ if img is None:
314
+ return
315
+ merged = sorted(set(img["flags"]) | set(new_flags))
316
+ self.update_image(image_id, flags=merged)
317
+
318
+ def discard(self, image_id: str, reason: str, dup_of: str | None = None) -> None:
319
+ self.update_image(image_id, status="discarded", discard_reason=reason, dup_of=dup_of)
320
+
321
+ def count_by(self, column: str, where: str = "1=1", params: Iterable[Any] = ()) -> dict[str, int]:
322
+ _check_columns([column])
323
+ rows = self.query(
324
+ f"SELECT {column} AS k, COUNT(*) AS n FROM images WHERE {where} GROUP BY {column}", params)
325
+ return {(r["k"] if r["k"] is not None else "none"): r["n"] for r in rows}
326
+
327
+ # -- provenance ----------------------------------------------------------------------
328
+ def class_hints_by_image(self) -> dict[str, set[str]]:
329
+ """image_id -> class hints, folding duplicates (dup_of) into their keeper."""
330
+ rows = self.query(
331
+ "SELECT s.image_id AS image_id, h.class_hint AS class_hint "
332
+ "FROM sources s JOIN hits h ON h.url_norm = s.url_norm "
333
+ "WHERE s.image_id IS NOT NULL AND h.class_hint IS NOT NULL")
334
+ direct: dict[str, set[str]] = {}
335
+ for r in rows:
336
+ direct.setdefault(r["image_id"], set()).add(r["class_hint"])
337
+ result = {k: set(v) for k, v in direct.items()}
338
+ for r in self.query("SELECT image_id, dup_of FROM images WHERE dup_of IS NOT NULL"):
339
+ if r["image_id"] in direct:
340
+ result.setdefault(r["dup_of"], set()).update(direct[r["image_id"]])
341
+ return result
342
+
343
+ def provenance(self, image_id: str) -> dict[str, list[str]]:
344
+ """Source URLs, queries, engines and class hints for an image incl. its duplicates."""
345
+ rows = self.query(
346
+ "SELECT s.url AS url, h.engine AS engine, h.query AS query, h.class_hint AS class_hint "
347
+ "FROM sources s LEFT JOIN hits h ON h.url_norm = s.url_norm "
348
+ "WHERE s.image_id IN (SELECT ? UNION SELECT image_id FROM images WHERE dup_of = ?)",
349
+ (image_id, image_id))
350
+ out: dict[str, set[str]] = {"source_urls": set(), "engines": set(), "queries": set(),
351
+ "class_hints": set()}
352
+ for r in rows:
353
+ out["source_urls"].add(r["url"])
354
+ if r["engine"]:
355
+ out["engines"].add(r["engine"])
356
+ if r["query"]:
357
+ out["queries"].add(r["query"])
358
+ if r["class_hint"]:
359
+ out["class_hints"].add(r["class_hint"])
360
+ return {k: sorted(v) for k, v in out.items()}
361
+
362
+ def valid_counts_by_class(self, valid_statuses: Iterable[str] = ("deduped", "kept", "validated", "normalized")) -> dict[str, int]:
363
+ """Return a mapping of class_hint -> count of valid (non-discarded) images."""
364
+ statuses = tuple(valid_statuses)
365
+ sql = f"""
366
+ SELECT h.class_hint, COUNT(DISTINCT i.image_id)
367
+ FROM images i
368
+ JOIN sources s ON i.source_ref = s.url_norm OR i.image_id = s.image_id
369
+ JOIN hits h ON s.url_norm = h.url_norm
370
+ WHERE i.status IN ({','.join('?' * len(statuses))})
371
+ GROUP BY h.class_hint
372
+ """
373
+ rows = self.query(sql, statuses)
374
+ return {r[0]: r[1] for r in rows if r[0]}
375
+
376
+ def export_jsonl(self, path: str | Path) -> int:
377
+ path = Path(path)
378
+ path.parent.mkdir(parents=True, exist_ok=True)
379
+ n = 0
380
+ with open(path, "w", encoding="utf-8") as fh:
381
+ for img in self.images():
382
+ img.update(self.provenance(img["image_id"]))
383
+ fh.write(json.dumps(img, ensure_ascii=False) + "\n")
384
+ n += 1
385
+ return n
386
+
387
+ # -- embeddings ----------------------------------------------------------------------
388
+ def save_embeddings(self, vectors: dict[str, np.ndarray]) -> None:
389
+ with self.transaction():
390
+ for image_id, vec in vectors.items():
391
+ arr = np.asarray(vec, dtype=np.float16)
392
+ self.execute("INSERT OR REPLACE INTO embeddings VALUES (?, ?, ?)",
393
+ (image_id, int(arr.shape[0]), arr.tobytes()))
394
+
395
+ def load_embeddings(self, image_ids: Iterable[str] | None = None) -> tuple[list[str], np.ndarray]:
396
+ rows = self.query("SELECT image_id, dim, vec FROM embeddings ORDER BY image_id")
397
+ if image_ids is not None:
398
+ wanted = set(image_ids)
399
+ rows = [r for r in rows if r["image_id"] in wanted]
400
+ if not rows:
401
+ return [], np.zeros((0, 0), dtype=np.float32)
402
+ ids = [r["image_id"] for r in rows]
403
+ mat = np.stack([np.frombuffer(r["vec"], dtype=np.float16).astype(np.float32) for r in rows])
404
+ return ids, mat
pipeline/processor.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Normalization engine: turn any validated original into a standard RGB JPEG.
2
+
3
+ Order matters and follows the plan:
4
+
5
+ 1. EXIF transpose first (phone photos would otherwise end up rotated).
6
+ 2. Colour handling to RGB:
7
+ - RGBA / LA / PA / palette-with-transparency -> composited on WHITE
8
+ (a naive convert("RGB") turns transparent pixels black)
9
+ - CMYK -> sRGB through the embedded ICC profile when there is one
10
+ - RGB with a non-sRGB ICC profile -> converted to sRGB when possible
11
+ - grayscale / 1-bit / 16-bit -> RGB
12
+ 3. Downscale (never upscale) if the long side exceeds ``max_long_side`` (LANCZOS).
13
+ 4. Encode as JPEG q95, 4:4:4 chroma (subsampling=0), optimized, metadata stripped.
14
+
15
+ Originals are never modified; this only ever writes a derived copy.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import io
21
+ import logging
22
+ import os
23
+ from concurrent.futures import ThreadPoolExecutor, as_completed
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ from PIL import Image, ImageCms, ImageOps
29
+ from tqdm import tqdm
30
+
31
+ from .manifest import Manifest
32
+ from .validator import register_heif
33
+
34
+ log = logging.getLogger(__name__)
35
+ register_heif()
36
+
37
+ Image.MAX_IMAGE_PIXELS = None # size is already policed by the validator
38
+
39
+
40
+ @dataclass
41
+ class NormalizeResult:
42
+ width: int
43
+ height: int
44
+ pixel_sha256: str
45
+
46
+
47
+ def _icc_to_srgb(img: Image.Image) -> Image.Image:
48
+ """Convert to sRGB via the embedded ICC profile; fall back to a plain convert."""
49
+ icc = img.info.get("icc_profile")
50
+ if not icc:
51
+ return img.convert("RGB")
52
+ try:
53
+ src = ImageCms.ImageCmsProfile(io.BytesIO(icc))
54
+ if img.mode == "RGB" and "srgb" in ImageCms.getProfileDescription(src).lower():
55
+ return img
56
+ dst = ImageCms.createProfile("sRGB")
57
+ return ImageCms.profileToProfile(img, src, dst, outputMode="RGB")
58
+ except Exception:
59
+ return img.convert("RGB")
60
+
61
+
62
+ def _wide_mode_to_rgb(img: Image.Image) -> Image.Image:
63
+ """16-bit / int / float single-channel images -> 8-bit RGB with min/max scaling."""
64
+ arr = np.asarray(img, dtype=np.float64)
65
+ lo, hi = float(arr.min()), float(arr.max())
66
+ scaled = np.zeros_like(arr) if hi <= lo else (arr - lo) / (hi - lo) * 255.0
67
+ return Image.fromarray(scaled.astype(np.uint8), mode="L").convert("RGB")
68
+
69
+
70
+ def to_rgb(img: Image.Image) -> Image.Image:
71
+ mode = img.mode
72
+ if mode in ("RGBA", "LA", "PA", "RGBa", "La") or (mode == "P" and "transparency" in img.info):
73
+ rgba = img.convert("RGBA")
74
+ background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
75
+ return Image.alpha_composite(background, rgba).convert("RGB")
76
+ if mode == "CMYK":
77
+ return _icc_to_srgb(img)
78
+ if mode in ("I", "I;16", "I;16L", "I;16B", "F"):
79
+ return _wide_mode_to_rgb(img)
80
+ if mode == "RGB":
81
+ return _icc_to_srgb(img) if img.info.get("icc_profile") else img
82
+ return img.convert("RGB") # L, 1, P (opaque), YCbCr, LAB, HSV, ...
83
+
84
+
85
+ def normalize_image(src: str | Path, dst: str | Path, pcfg: dict) -> NormalizeResult:
86
+ src, dst = Path(src), Path(dst)
87
+ with Image.open(src) as opened:
88
+ opened.seek(0) # first frame of animated files
89
+ img = ImageOps.exif_transpose(opened)
90
+ img.load()
91
+ img = to_rgb(img)
92
+
93
+ max_long = int(pcfg.get("max_long_side", 2560))
94
+ long_side = max(img.size)
95
+ if max_long and long_side > max_long:
96
+ scale = max_long / long_side
97
+ new_size = (max(1, round(img.width * scale)), max(1, round(img.height * scale)))
98
+ img = img.resize(new_size, Image.Resampling.LANCZOS)
99
+
100
+ digest = hashlib.sha256(f"{img.width}x{img.height}".encode() + img.tobytes()).hexdigest()
101
+
102
+ dst.parent.mkdir(parents=True, exist_ok=True)
103
+ tmp = dst.with_name(dst.name + f".{os.getpid()}.tmp")
104
+ try:
105
+ img.save(tmp, format="JPEG", quality=int(pcfg.get("jpeg_quality", 95)),
106
+ subsampling=int(pcfg.get("jpeg_subsampling", 0)), optimize=True)
107
+ os.replace(tmp, dst) # atomic: a crash never leaves a half-written JPEG
108
+ finally:
109
+ if tmp.exists():
110
+ tmp.unlink()
111
+ return NormalizeResult(img.width, img.height, digest)
112
+
113
+
114
+ def run(manifest: Manifest, cfg: dict, data_dir: Path, images_dir: Path) -> dict[str, int]:
115
+ """Normalize every image in status 'validated'."""
116
+ pcfg = cfg["process"]
117
+ todo = manifest.images(statuses=["validated"])
118
+ stats = {"normalized": 0, "normalize_failed": 0}
119
+ if not todo:
120
+ log.info("process: nothing to do")
121
+ return stats
122
+
123
+ def work(img: dict):
124
+ dst = images_dir / f"{img['image_id']}.jpg"
125
+ try:
126
+ return img, normalize_image(data_dir / img["orig_path"], dst, pcfg), dst, None
127
+ except Exception as exc: # noqa: BLE001 - any decode/encode failure discards the image
128
+ return img, None, dst, exc
129
+
130
+ with ThreadPoolExecutor(max_workers=int(pcfg.get("workers", 4))) as ex:
131
+ futures = [ex.submit(work, img) for img in todo]
132
+ with manifest.transaction():
133
+ for fut in tqdm(as_completed(futures), total=len(futures), desc="process", unit="img"):
134
+ img, res, dst, err = fut.result()
135
+ if err is None and res is not None:
136
+ manifest.update_image(
137
+ img["image_id"], status="normalized", norm_path=str(dst.relative_to(data_dir)),
138
+ norm_width=res.width, norm_height=res.height, pixel_sha256=res.pixel_sha256)
139
+ stats["normalized"] += 1
140
+ else:
141
+ log.warning("normalize failed for %s: %s", img["image_id"], err)
142
+ manifest.discard(img["image_id"], "normalize_failed")
143
+ stats["normalize_failed"] += 1
144
+ log.info("process: %s", stats)
145
+ return stats
pipeline/queries.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Query registry: expand seed terms along diversity axes (deterministically)."""
2
+ from __future__ import annotations
3
+
4
+ import random
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class QuerySpec:
10
+ class_hint: str
11
+ query: str
12
+ lang: str = "en"
13
+ kind: str = "seed" # seed | expanded | lang
14
+
15
+
16
+ def _overlap(phrase: str, words: set[str]) -> float:
17
+ toks = phrase.lower().split()
18
+ return sum(t in words for t in toks) / len(toks) if toks else 1.0
19
+
20
+
21
+ def build_queries(
22
+ qcfg: dict,
23
+ classes: list[str] | None = None,
24
+ langs: list[str] | None = None,
25
+ ) -> list[QuerySpec]:
26
+ """Build the full query list.
27
+
28
+ For every seed term: the seed itself plus up to ``max_variants_per_seed`` variants that
29
+ append one or two randomly chosen axis values (board type, condition, view/setting).
30
+ A class may override any axis (e.g. ``desoldered_zone`` never pairs with "intact").
31
+ Multilingual terms are hand-written per class and appended as-is.
32
+
33
+ Output order and content are fully determined by ``expansion.seed``.
34
+ """
35
+ exp = qcfg.get("expansion", {}) or {}
36
+ rng = random.Random(exp.get("seed", 7))
37
+ per_seed = int(exp.get("max_variants_per_seed", 8))
38
+ global_axes = qcfg.get("axes", {}) or {}
39
+
40
+ out: list[QuerySpec] = []
41
+ seen: set[tuple[str, str]] = set()
42
+
43
+ def add(spec: QuerySpec) -> None:
44
+ key = (spec.class_hint, spec.query.strip().lower())
45
+ if key not in seen and spec.query.strip():
46
+ seen.add(key)
47
+ out.append(spec)
48
+
49
+ for cls, body in (qcfg.get("classes") or {}).items():
50
+ if classes and cls not in classes:
51
+ continue
52
+ body = body or {}
53
+ axes = {**global_axes, **(body.get("axes") or {})}
54
+ axis_names = sorted(a for a, vals in axes.items() if vals)
55
+
56
+ for seed in body.get("seeds", []) or []:
57
+ add(QuerySpec(cls, seed, "en", "seed"))
58
+ seed_words = set(seed.lower().split())
59
+ variants: set[str] = set()
60
+ attempts = 0
61
+ while axis_names and len(variants) < per_seed and attempts < per_seed * 10:
62
+ attempts += 1
63
+ chosen = rng.sample(axis_names, min(rng.choice([1, 2]), len(axis_names)))
64
+ parts = [rng.choice(axes[a]) for a in sorted(chosen)]
65
+ # Skip axis values the seed already (mostly) says, e.g. "close up" + "close up macro".
66
+ parts = [p for p in parts if _overlap(p, seed_words) < 0.5]
67
+ if parts:
68
+ variants.add(f"{seed} {' '.join(parts)}")
69
+ for v in sorted(variants):
70
+ add(QuerySpec(cls, v, "en", "expanded"))
71
+
72
+ for lang, terms in (body.get("multilingual") or {}).items():
73
+ if langs and lang not in langs:
74
+ continue
75
+ for term in terms or []:
76
+ add(QuerySpec(cls, term, lang, "lang"))
77
+ return out
pipeline/splitter.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dataset Splitter Engine.
2
+
3
+ Stratified, cluster-aware train / val / test dataset partitioning:
4
+ - Prevents data leakage by ensuring all images in the same visual `cluster_id`
5
+ are assigned to the SAME split (train, val, or test).
6
+ - Maintains balanced class distributions across splits according to target ratios (e.g. 70 / 15 / 15).
7
+ - Exports organized image & label directories under `data/splits/` for YOLOv8 model training.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import random
13
+ import shutil
14
+ from collections import defaultdict
15
+ from pathlib import Path
16
+ from typing import Sequence
17
+
18
+ from .manifest import Manifest
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+
23
+ def create_cluster_splits(
24
+ manifest: Manifest,
25
+ train_ratio: float = 0.70,
26
+ val_ratio: float = 0.15,
27
+ test_ratio: float = 0.15,
28
+ seed: int = 42,
29
+ ) -> dict[str, list[dict]]:
30
+ """Partition valid images into cluster-isolated train/val/test splits."""
31
+ random.seed(seed)
32
+
33
+ rows = manifest.images(statuses=["deduped", "kept", "validated", "normalized"])
34
+ if not rows:
35
+ log.warning("splitter: no valid images found to split")
36
+ return {"train": [], "val": [], "test": []}
37
+
38
+ clusters: dict[str, list[dict]] = defaultdict(list)
39
+ for r in rows:
40
+ cid = r["cluster_id"] or r["image_id"]
41
+ clusters[cid].append(r)
42
+
43
+ cluster_items = list(clusters.items())
44
+ random.shuffle(cluster_items)
45
+
46
+ total_count = len(rows)
47
+ target_train = int(total_count * train_ratio)
48
+ target_val = int(total_count * val_ratio)
49
+
50
+ splits: dict[str, list[dict]] = {"train": [], "val": [], "test": []}
51
+
52
+ current_train = 0
53
+ current_val = 0
54
+
55
+ for cid, members in cluster_items:
56
+ mem_len = len(members)
57
+ if current_train < target_train:
58
+ splits["train"].extend(members)
59
+ current_train += mem_len
60
+ elif current_val < target_val:
61
+ splits["val"].extend(members)
62
+ current_val += mem_len
63
+ else:
64
+ splits["test"].extend(members)
65
+
66
+ return splits
67
+
68
+
69
+ def run(
70
+ manifest: Manifest,
71
+ cfg: dict,
72
+ data_dir: Path,
73
+ splits_dir: Path,
74
+ train_ratio: float = 0.70,
75
+ val_ratio: float = 0.15,
76
+ test_ratio: float = 0.15,
77
+ copy_files: bool = True,
78
+ seed: int = 42,
79
+ ) -> dict[str, int]:
80
+ """Execute cluster-isolated dataset split and write image & label files to splits directory."""
81
+ splits = create_cluster_splits(
82
+ manifest, train_ratio=train_ratio, val_ratio=val_ratio, test_ratio=test_ratio, seed=seed
83
+ )
84
+
85
+ stats = {
86
+ "train": len(splits["train"]),
87
+ "val": len(splits["val"]),
88
+ "test": len(splits["test"]),
89
+ "total_split": sum(len(s) for s in splits.values()),
90
+ }
91
+
92
+ if not stats["total_split"]:
93
+ log.warning("splitter: 0 images split")
94
+ return stats
95
+
96
+ with manifest.transaction():
97
+ for split_name, members in splits.items():
98
+ for m in members:
99
+ manifest.update_image(m["image_id"], split=split_name)
100
+
101
+ auto_labels_dir = data_dir / "annotated_auto" / "labels"
102
+
103
+ if copy_files:
104
+ for split_name, members in splits.items():
105
+ dst_img_dir = splits_dir / split_name / "images"
106
+ dst_lbl_dir = splits_dir / split_name / "labels"
107
+ dst_img_dir.mkdir(parents=True, exist_ok=True)
108
+ dst_lbl_dir.mkdir(parents=True, exist_ok=True)
109
+
110
+ for m in members:
111
+ src_rel = m.get("norm_path") or m.get("orig_path")
112
+ if not src_rel:
113
+ continue
114
+ src_path = data_dir / src_rel
115
+ if src_path.exists():
116
+ dst_path = dst_img_dir / src_path.name
117
+ if not dst_path.exists():
118
+ shutil.copy2(src_path, dst_path)
119
+
120
+ # Copy matching label file if available
121
+ label_name = f"{src_path.stem}.txt"
122
+ src_label = auto_labels_dir / label_name
123
+ if src_label.exists():
124
+ dst_label = dst_lbl_dir / label_name
125
+ if not dst_label.exists():
126
+ shutil.copy2(src_label, dst_label)
127
+
128
+ log.info("splitter split summary: %s", stats)
129
+ return stats
pipeline/validator.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validation engine.
2
+
3
+ Checks run cheapest-first so most bad files fail early:
4
+
5
+ 1. file size < min_file_bytes -> discard too_small_file
6
+ 2. integrity open -> verify() -> reopen -> load() -> discard corrupt
7
+ 3. animated multi-frame GIF/WEBP/APNG -> flag animated (first frame used)
8
+ 4. resolution short/long side below minimum -> discard low_resolution
9
+ 5. aspect (hard) > hard_aspect : 1 -> discard extreme_aspect_hard
10
+ 6. aspect (soft) > flag_aspect : 1 -> flag extreme_aspect (goes to review)
11
+
12
+ `verify()` alone does not detect truncated JPEGs, so the file is reopened and fully decoded
13
+ with `load()` (verify() invalidates the image object, hence the reopen).
14
+ The soft aspect limit is a *flag*, not a discard: RAM modules and edge-finger strips are
15
+ naturally ~4.5-5:1 and must survive.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+
24
+ from PIL import Image, ImageFile
25
+ from tqdm import tqdm
26
+
27
+ from .manifest import Manifest
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+ ImageFile.LOAD_TRUNCATED_IMAGES = False # never silently accept truncated files
32
+ # Pillow's own bomb check works through process-global warnings (not thread-safe), so it is
33
+ # disabled and replaced by an explicit header-size check in validate_image().
34
+ Image.MAX_IMAGE_PIXELS = None
35
+
36
+ ALLOWED_FORMATS = {"JPEG", "MPO", "PNG", "WEBP", "GIF", "BMP", "TIFF"}
37
+
38
+
39
+ def register_heif() -> bool:
40
+ """Enable iPhone HEIC/HEIF photos if the optional `pillow-heif` package is installed."""
41
+ try:
42
+ import pillow_heif # type: ignore
43
+
44
+ pillow_heif.register_heif_opener()
45
+ ALLOWED_FORMATS.add("HEIF")
46
+ return True
47
+ except Exception: # pragma: no cover - optional dependency
48
+ return False
49
+
50
+
51
+ register_heif()
52
+
53
+
54
+ @dataclass
55
+ class ValidationResult:
56
+ ok: bool
57
+ reason: str | None = None
58
+ flags: list[str] = field(default_factory=list)
59
+ width: int | None = None
60
+ height: int | None = None
61
+ fmt: str | None = None
62
+ aspect: float | None = None
63
+
64
+
65
+ DEFAULT_AI_KEYWORDS = {
66
+ "midjourney", "stable diffusion", "dall-e", "dalle", "comfyui",
67
+ "novelai", "c2pa", "firefly", "bing image creator", "flux.1",
68
+ "fooocus", "automatic1111", "ai_generated", "generated by"
69
+ }
70
+
71
+
72
+ def check_ai_metadata(img: Image.Image, custom_keywords: list[str] | set[str] | None = None) -> bool:
73
+ """Return True if image metadata contains AI generator signatures."""
74
+ keywords = set(custom_keywords) if custom_keywords else DEFAULT_AI_KEYWORDS
75
+ info = getattr(img, "info", {})
76
+ if not isinstance(info, dict):
77
+ return False
78
+ raw_str = " ".join(f"{k} {v}" for k, v in info.items()).lower()
79
+ return any(kw.lower() in raw_str for kw in keywords)
80
+
81
+
82
+ def validate_image(path: str | Path, vcfg: dict) -> ValidationResult:
83
+ path = Path(path)
84
+ try:
85
+ size = path.stat().st_size
86
+ except OSError:
87
+ return ValidationResult(False, "missing_file")
88
+ if size < int(vcfg["min_file_bytes"]):
89
+ return ValidationResult(False, "too_small_file")
90
+
91
+ max_pixels = int(vcfg.get("max_pixels", 120_000_000))
92
+ flags: list[str] = []
93
+ try:
94
+ with Image.open(path) as img: # lazy: reads the header only
95
+ if img.width * img.height > max_pixels:
96
+ return ValidationResult(False, "decompression_bomb", width=img.width, height=img.height)
97
+ img.verify()
98
+ with Image.open(path) as img: # reopen: verify() leaves the object unusable
99
+ fmt = img.format
100
+ if fmt not in ALLOWED_FORMATS:
101
+ return ValidationResult(False, "unsupported_format", fmt=fmt)
102
+ animated = bool(getattr(img, "is_animated", False))
103
+ img.load() # full decode -> catches truncation that verify() misses
104
+ width, height = img.size
105
+
106
+ if check_ai_metadata(img, vcfg.get("ai_keywords")):
107
+ return ValidationResult(False, "ai_generated_metadata", width=width, height=height, fmt=fmt)
108
+ except Exception: # OSError, SyntaxError, ValueError, struct errors, ...
109
+ return ValidationResult(False, "corrupt")
110
+
111
+ if animated:
112
+ flags.append("animated")
113
+
114
+ short, long_ = min(width, height), max(width, height)
115
+ if short < int(vcfg["min_short_side"]) or long_ < int(vcfg["min_long_side"]):
116
+ return ValidationResult(False, "low_resolution", flags, width, height, fmt)
117
+
118
+ aspect = long_ / short if short else float("inf")
119
+ if aspect > float(vcfg["hard_aspect"]):
120
+ return ValidationResult(False, "extreme_aspect_hard", flags, width, height, fmt, aspect)
121
+ if aspect > float(vcfg["flag_aspect"]):
122
+ flags.append("extreme_aspect")
123
+
124
+ return ValidationResult(True, None, flags, width, height, fmt, round(aspect, 4))
125
+
126
+
127
+ def run(manifest: Manifest, cfg: dict, data_dir: Path, force: bool = False) -> dict[str, int]:
128
+ """Validate images. If force=True, re-checks previously validated/normalized images for AI metadata."""
129
+ vcfg = cfg["validate"]
130
+ statuses = ["downloaded", "validated", "normalized", "kept"] if force else ["downloaded"]
131
+ todo = manifest.images(statuses=statuses)
132
+ stats: dict[str, int] = {"validated": 0}
133
+ if not todo:
134
+ log.info("validate: nothing to do")
135
+ return stats
136
+
137
+ def work(img: dict) -> tuple[dict, ValidationResult]:
138
+ return img, validate_image(data_dir / img["orig_path"], vcfg)
139
+
140
+ workers = int(vcfg.get("workers", 4))
141
+ with ThreadPoolExecutor(max_workers=workers) as ex:
142
+ futures = [ex.submit(work, img) for img in todo]
143
+ with manifest.transaction():
144
+ for fut in tqdm(as_completed(futures), total=len(futures), desc="validate", unit="img"):
145
+ img, res = fut.result()
146
+ if res.ok:
147
+ flags = sorted(set(img["flags"]) | set(res.flags))
148
+ manifest.update_image(
149
+ img["image_id"], status="validated", width=res.width, height=res.height,
150
+ aspect_ratio=res.aspect, orig_format=(res.fmt or "").lower(), flags=flags)
151
+ stats["validated"] += 1
152
+ else:
153
+ manifest.update_image(
154
+ img["image_id"], status="discarded", discard_reason=res.reason,
155
+ width=res.width, height=res.height, aspect_ratio=res.aspect,
156
+ flags=sorted(set(img["flags"]) | set(res.flags)))
157
+ stats[res.reason or "discarded"] = stats.get(res.reason or "discarded", 0) + 1
158
+ log.info("validate: %s", stats)
159
+ return stats
purity_engine/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Purity Engine Package for Edge PCB Component Purity & Cannibalization Index."""
2
+
3
+ from .model_client import BaseModelClient, MockModelClient, Detection
4
+ from .purity_assay import calculate_board_integrity_score, calculate_adjusted_scrap_price, AssayedBoard
5
+ from .vernacular_voice import generate_vernacular_voice_alert
6
+ from .pcb_analyzer import PCBAnalyzer
7
+
8
+ __all__ = [
9
+ "BaseModelClient",
10
+ "MockModelClient",
11
+ "Detection",
12
+ "calculate_board_integrity_score",
13
+ "calculate_adjusted_scrap_price",
14
+ "AssayedBoard",
15
+ "generate_vernacular_voice_alert",
16
+ "PCBAnalyzer",
17
+ ]
purity_engine/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (675 Bytes). View file
 
purity_engine/__pycache__/model_client.cpython-312.pyc ADDED
Binary file (4.9 kB). View file
 
purity_engine/__pycache__/pcb_analyzer.cpython-312.pyc ADDED
Binary file (3.63 kB). View file
 
purity_engine/__pycache__/purity_assay.cpython-312.pyc ADDED
Binary file (6.08 kB). View file
 
purity_engine/__pycache__/vernacular_voice.cpython-312.pyc ADDED
Binary file (5.34 kB). View file