# Implementation Plan: Edge "Component Purity & Cannibalization Index" (Updated) 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. 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. --- ## User Review Required > [!IMPORTANT] > - **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. > - **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. > - **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). > - **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. > - **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. > - **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. > - **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. --- ## Track A: Micro-Component Detection Model ### Phase 1: Data Collection & Labeling (Updated Guidelines) #### Component 1: Refined Labeling Taxonomy (`taxonomy/component_classes.yaml`) - [NEW] Defines fine-grained class states to eliminate false positives: - `bga_cpu_socket_intact`, `bga_cpu_socket_missing` - `gold_edge_finger_intact`, `gold_edge_finger_stripped` - `tantalum_cap_intact`, `tantalum_cap_missing` - `ram_dimm_slot_intact`, `ram_dimm_slot_stripped` - `forcibly_desoldered_pad` (jagged solder, torn traces, blowtorch/burnt flux residue — primary fraud signal) - `factory_unpopulated_pad` (clean silkscreen outline, smooth solder dots — unpopulated from factory, NOT fraud) - `occluded_region` (heatsinks, metal shields, heavy dirt/dust covering component pads) #### Component 2: Data Collection & Sourcing Protocol (`data_collection/`) - [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. - [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). - Sourcing requirements: Must harvest dirty, corroded, dusty, and factory-unpopulated boards alongside pristine and stripped examples to match field scrap yard conditions. #### Component 2a: Data Sourcing Strategy — Open Datasets, Mined Web Sources, and Field Photography (`data_collection/sourcing_strategy.md`) Research into publicly available data confirms a **three-tier sourcing strategy**, since scraping alone cannot cover the fraud-specific classes: **Tier 1 — Open datasets, for bootstrapping `*_intact` classes (use directly, no scraping needed):** - 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. - 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). - HuggingFace `pcb-object-detection-dataset` — 21-class YOLO set including heatsinks and connectors. - Roboflow Universe community PCB datasets (component-level bounding boxes, CC BY 4.0). - **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. **Tier 2 — Mined web sources, as a supplemental seed set for `forcibly_desoldered_pad` only (not a primary source):** - 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. - 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. - **Known limitations, by design not treated as a primary source**: - Low volume per source and inconsistent photo quality/angle — doesn't match the phone-camera, scrap-yard conditions defined in `capture_protocol.md`. - No existing bounding boxes — still requires full manual annotation, same as field photos. - 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. - **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. **Tier 3 — Deliberately staged field photography, mandatory and primary for fraud classes (this is the existing Component 2 protocol above):** - 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). - 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. #### Component 3: Annotation & QA - [NEW] Bounding-box annotation via CVAT or Label Studio, exported in COCO/YOLO format. - [NEW] `qa_annotation_review.py` — inter-annotator agreement check (min. 2 annotators per image, flag disagreement >10% of boxes for adjudication). - Target: minimum 300 images per class, with at least 30% deliberately-stripped/burnt negative examples, before first training run. ### Phase 2: Form-Factor Baseline Definitions #### Component 4: Dynamic Board Profiles (`baselines/board_profiles.json`) - [NEW] Defines expected component counts/area ratios per board class **and form factor**: - `desktop_atx`, `desktop_micro_atx`, `desktop_itx` - `server_1u_2u`, `server_blade_4u` - `gpu_pcb_high_end`, `gpu_pcb_budget` - `ram_dimm_desktop`, `ram_so_dimm_laptop` - Sourced from recycling domain experts — consumed downstream by `purity_assay.py`. ### Phase 3: Model Training #### Component 5: Training Pipeline (`training/train.py`) - [NEW] YOLOv8n/s fine-tuning with multi-scale training (`imgsz=960` or `1280`) and custom anchor ratios for elongated `gold_finger` boxes ($>4:1$). - Heavy augmentations for field realities: specular glare on gold fingers, lighting variance, dirt noise, and angle tilt. - [NEW] `train_config.yaml` — Focal loss & elevated class weights for `forcibly_desoldered_pad` vs `factory_unpopulated_pad`. #### Component 6: Auxiliary Desoldered Pad Classifier Head - [NEW] Secondary classification head specifically trained to distinguish desoldered blowtorch pads from factory empty pads. #### Component 7: Export & Quantization (`export/export_tflite.py`) - [NEW] Export to TFLite INT8 quantized, target size <15MB, target inference <1s on low-end Android hardware. - [NEW] `model_contract.md` — freezes input/output tensor schema. ### Phase 4: Evaluation #### Component 8: Model Evaluation (`eval/evaluate.py`) - [NEW] Per-class mAP, plus dedicated fraud recall on `forcibly_desoldered_pad` and false-positive rate on `factory_unpopulated_pad`. - Thresholds: $\ge 90\%$ recall on intact classes, $\ge 85\%$ recall on desoldered pad classes, and $\le 5\%$ false positive rate on factory unpopulated pads. --- ## Track B: Integration into Kabadiwala Connect ### Component 9: Purity Engine & Memory-Conscious Orchestrator (`purity_engine/`) - [NEW] `purity_engine/model_client.py` — wrapper supporting `MockModelClient` and `TFLiteModelClient` with explicit tensor memory management (`model.dispose()` between Stage 1 and Stage 2). - [NEW] `purity_engine/purity_assay.py` — implements `calculate_board_integrity_score(detected_components, form_factor)`: - Dynamic price formula: $$\text{Adjusted Price} = \text{Base Price} \times \left( \text{Floor}_{\text{category}} + (1 - \text{Floor}_{\text{category}}) \times \frac{\text{BIS}}{100} \right)$$ - Scrap Grade Floors: Server/GPU = 15%, Desktop = 30%, Low-grade Power = 60%. - [NEW] `purity_engine/pcb_analyzer.py` — single entry point for Collector Lite & Recycler Portal. ### Component 10: Vernacular Voice Alerts with Audio Fallback (`purity_engine/vernacular_voice.py`) - [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. - Message templates parameterized by BIS band (Pristine $\ge 85\%$, Partial $50\text{--}84\%$, Severe $<50\%$). ### Component 11: Collector Lite Multi-Angle UI Integration (`mobile/kabadiwala-lite.html`) - Extend Step 1 of Collector Lite: Stage 1 21-class classifier detects `PCB` $\rightarrow$ prompts guided Front/Back photo capture $\rightarrow$ triggers `pcb_analyzer`. - Displays BIS score, missing-component breakdown, and transparent price adjustment in Step 3. - Persists assay JSON into IndexedDB with the scrap slip. ### Component 12: QR Handover Payload Enrichment (`mobile/dealer.html`, backend) - QR payload includes collector BIS score, form factor, and assay report hash. ### Component 13: Recycler Portal BIS-Delta View (`recycler-dashboard-frontend/`) - Re-scan intake lot via `pcb_analyzer`. - Tolerance Bands: - $< 12\%$ BIS Drop $\rightarrow$ Normal capture variance (Pass). - $12\text{--}25\%$ BIS Drop $\rightarrow$ Discrepancy Flagged. - $> 25\%$ BIS Drop $\rightarrow$ Critical Fraud Alert & CPCB Form 6 PDF Audit Log Entry. ### Component 14: Backend API Changes (`backend/`) - [NEW] `POST /api/lots/{lot_id}/assay` & `GET /api/lots/{lot_id}/bis-delta`. --- ## Sequencing Summary | | Track A (Model & Dataset) | Track B (App Integration) | |---|---|---| | 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` | | Parallel | Multi-scale YOLOv8 training with focal loss & TFLite INT8 quantization | Collector Lite, audio fallbacks, Recycler Portal BIS-delta tolerance UI | | Hand-off | Ship model clearing Phase 4 thresholds | Swap `TFLiteModelClient` in with zero code changes |