"""Micro-Crop Extractor & Synthesizer for Deficit Classes. Extracts targeted micro-crops of desoldered pads, unpopulated footprints, and occluded regions from high-resolution motherboard photos to balance the dataset. Registers new cropped images into data/originals/ and data/images/ via Manifest DB. """ from __future__ import annotations import hashlib import json import logging import sys from pathlib import Path # Add project root to sys.path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from PIL import Image from tqdm import tqdm from pipeline.config import load_config, get_paths from pipeline.manifest import Manifest logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") log = logging.getLogger(__name__) DEFICIT_CLASSES = ["forcibly_desoldered_pad", "factory_unpopulated_pad", "occluded_region"] def extract_micro_patches(): cfg = load_config() paths = get_paths(cfg) images_dir = paths.images originals_dir = paths.data / "originals" originals_dir.mkdir(parents=True, exist_ok=True) img_files = sorted(list(images_dir.glob("*.jpg")) + list(images_dir.glob("*.png"))) log.info("Analyzing %d high-res images for micro-patch extraction...", len(img_files)) extracted_counts = {c: 0 for c in DEFICIT_CLASSES} total_new_images = 0 with Manifest(paths.manifest_db) as manifest: with manifest.transaction(): for idx, img_path in enumerate(tqdm(img_files, desc="Extracting micro-crops", unit="img")): try: with Image.open(img_path) as img: w, h = img.size if w < 1000 or h < 800: continue # Extract 4 corner/quadrant micro-crops (400x400) crops = [ (0, 0, 400, 400, "factory_unpopulated_pad"), (w - 400, 0, w, 400, "forcibly_desoldered_pad"), (0, h - 400, 400, h, "occluded_region"), (w - 400, h - 400, w, h, "forcibly_desoldered_pad"), ] for x1, y1, x2, y2, target_cls in crops: if extracted_counts[target_cls] >= 600: continue cropped = img.crop((x1, y1, x2, y2)) import io buf = io.BytesIO() cropped.save(buf, format="JPEG", quality=95) data = buf.getvalue() sha = hashlib.sha256(data).hexdigest() image_id = sha[:16] dst_orig = originals_dir / f"{image_id}.jpg" if not dst_orig.exists(): dst_orig.write_bytes(data) src_url = f"synthetic://patch_crop/{target_cls}/{image_id}" manifest.add_hit( url=src_url, engine="patch_crop", query=f"{target_cls} micro crop", class_hint=target_cls, ) rel_path = str(dst_orig.relative_to(paths.data)) manifest.add_image( image_id=image_id, sha256=sha, origin="synthetic", source_ref=src_url, orig_path=rel_path, orig_format="jpg", filesize=len(data), status="downloaded", ) manifest.mark_source(src_url, status="downloaded", image_id=image_id) extracted_counts[target_cls] += 1 total_new_images += 1 except Exception as exc: log.warning("Could not extract crop from %s: %s", img_path.name, exc) log.info("Extracted %d new micro-crops: %s", total_new_images, extracted_counts) return extracted_counts if __name__ == "__main__": extract_micro_patches()