File size: 5,140 Bytes
11a414e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
"""Automated Zero-Shot Auto-Annotation Pipeline using YOLO-World.

Auto-labels all images in `data/images/` using the updated taxonomy:
  0: cpu_socket
  1: gold_finger
  2: ic_chip
  3: tantalum_capacitor
  4: forcibly_desoldered_pad
  5: factory_unpopulated_pad
  6: occluded_region

Generates YOLO format bounding box label files (.txt) and data.yaml in `data/annotated_auto/`.
"""
from __future__ import annotations

import json
import logging
import os
import shutil
from pathlib import Path

import yaml
from PIL import Image
from tqdm import tqdm

# Ensure cache directories reside within workspace
cache_dir = Path("data/cache").resolve()
cache_dir.mkdir(parents=True, exist_ok=True)
os.environ["TORCH_HOME"] = str(cache_dir)
os.environ["HF_HOME"] = str(cache_dir)

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger(__name__)

CLASS_NAMES = [
    "cpu_socket",
    "gold_finger",
    "ic_chip",
    "tantalum_capacitor",
    "forcibly_desoldered_pad",
    "factory_unpopulated_pad",
    "occluded_region",
]

# Prompts tuned for zero-shot YOLO-World detector
CLASS_PROMPTS = [
    "CPU socket",
    "gold finger edge connector",
    "microchip",
    "tantalum capacitor",
    "desoldered solder pad",
    "unpopulated solder pad",
    "heatsink shield",
]


def run_auto_annotation(
    data_dir: str | Path = "data",
    output_dir: str | Path = "data/annotated_auto",
    conf_threshold: float = 0.02,
    max_images: int | None = None,
) -> dict:
    data_dir = Path(data_dir)
    output_dir = Path(output_dir)
    images_in_dir = data_dir / "images"
    
    images_out_dir = output_dir / "images"
    labels_out_dir = output_dir / "labels"
    images_out_dir.mkdir(parents=True, exist_ok=True)
    labels_out_dir.mkdir(parents=True, exist_ok=True)

    log.info("Loading YOLO-World zero-shot model...")
    from ultralytics import YOLOWorld

    model = YOLOWorld("yolov8s-worldv2.pt")
    model.set_classes(CLASS_PROMPTS)
    log.info("YOLO-World model configured with %d classes (conf threshold: %.3f).", len(CLASS_PROMPTS), conf_threshold)

    image_files = sorted(list(images_in_dir.glob("*.jpg")) + list(images_in_dir.glob("*.png")))
    if max_images:
        image_files = image_files[:max_images]

    log.info("Found %d images to auto-annotate.", len(image_files))

    class_detection_counts = {name: 0 for name in CLASS_NAMES}
    total_images_processed = 0
    total_boxes_generated = 0

    for img_path in tqdm(image_files, desc="Auto-annotating images", unit="img"):
        img_name = img_path.name
        stem = img_path.stem

        # Copy image to output directory
        target_img_path = images_out_dir / img_name
        if not target_img_path.exists():
            try:
                shutil.copy2(img_path, target_img_path)
            except Exception as e:
                log.warning("Could not copy %s: %s", img_name, e)

        # Run inference
        results = model.predict(str(img_path), conf=conf_threshold, verbose=False)
        label_file = labels_out_dir / f"{stem}.txt"

        lines = []
        if results and len(results) > 0:
            boxes = results[0].boxes
            if boxes is not None and len(boxes) > 0:
                xywhn = boxes.xywhn.cpu().numpy()
                cls_ids = boxes.cls.cpu().numpy().astype(int)

                for (x, y, w, h), cls_id in zip(xywhn, cls_ids):
                    if 0 <= cls_id < len(CLASS_NAMES):
                        lines.append(f"{cls_id} {x:.6f} {y:.6f} {w:.6f} {h:.6f}")
                        class_name = CLASS_NAMES[cls_id]
                        class_detection_counts[class_name] += 1
                        total_boxes_generated += 1

        with open(label_file, "w", encoding="utf-8") as f:
            f.write("\n".join(lines) + ("\n" if lines else ""))

        total_images_processed += 1

    # Create dataset yaml specification
    dataset_yaml = {
        "path": str(output_dir.resolve()),
        "train": "images",
        "val": "images",
        "names": {i: name for i, name in enumerate(CLASS_NAMES)},
    }
    yaml_path = output_dir / "data.yaml"
    with open(yaml_path, "w", encoding="utf-8") as f:
        yaml.dump(dataset_yaml, f, default_flow_style=False)

    summary = {
        "total_images_processed": total_images_processed,
        "total_boxes_generated": total_boxes_generated,
        "conf_threshold": conf_threshold,
        "class_detection_counts": class_detection_counts,
        "output_directory": str(output_dir.resolve()),
        "data_yaml": str(yaml_path.resolve()),
    }

    summary_path = output_dir / "auto_annotation_summary.json"
    with open(summary_path, "w", encoding="utf-8") as f:
        json.dump(summary, f, indent=2)

    log.info("Auto-annotation complete! Summary saved to %s", summary_path)
    return summary


if __name__ == "__main__":
    import sys
    max_imgs = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else None
    conf_val = float(sys.argv[2]) if len(sys.argv) > 2 else 0.02
    run_auto_annotation(conf_threshold=conf_val, max_images=max_imgs)