Micro_component_dataset / pipeline /auto_annotate.py
FaustDerLegende's picture
Upload folder using huggingface_hub (part 84)
693bf28 verified
Raw History Blame Contribute Delete
5.86 kB
"""Automated Zero-Shot Auto-Annotation Pipeline using YOLO-World (Ultra-Lightweight / Resumable Mode).
Auto-labels images in `data/images/` using the updated 7-class taxonomy:
0: cpu_socket
1: gold_finger
2: ic_chip
3: tantalum_capacitor
4: forcibly_desoldered_pad
5: factory_unpopulated_pad
6: occluded_region
Features:
- Resumable (`skip_existing=True`): Skips already auto-labeled non-empty `.txt` files.
- Ultra-Low Memory (<500 MB RAM): Standard single-pass inference + per-image `gc.collect()`.
"""
from __future__ import annotations
import gc
import json
import logging
import os
import shutil
from pathlib import Path
import torch
import yaml
from PIL import Image
from tqdm import tqdm
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",
]
CLASS_PROMPTS = [
"CPU socket square slot",
"gold edge connector pins",
"black IC microchip",
"yellow SMD capacitor",
"desoldered solder pad footprint",
"empty unpopulated solder pad",
"metal heatsink shield cover",
]
def run_auto_annotation(
data_dir: str | Path = "data",
output_dir: str | Path = "data/annotated_auto",
conf_threshold: float = 0.015,
max_images: int | None = None,
skip_existing: bool = True,
) -> dict:
torch.set_num_threads(1)
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 model (Resumable Low-Memory Mode)...")
from ultralytics import YOLOWorld
model = YOLOWorld("yolov8s-worldv2.pt")
model.set_classes(CLASS_PROMPTS)
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("Starting Resumable Auto-Annotation across %d images...", len(image_files))
class_detection_counts = {name: 0 for name in CLASS_NAMES}
total_images_processed = 0
total_boxes_generated = 0
skipped_count = 0
for img_path in tqdm(image_files, desc="Resumable Auto-Annotating", unit="img"):
img_name = img_path.name
stem = img_path.stem
label_file = labels_out_dir / f"{stem}.txt"
dst_path = images_out_dir / img_name
if not dst_path.exists():
try:
shutil.copy2(img_path, dst_path)
except Exception as e:
log.warning("Could not copy %s: %s", img_name, e)
# Skip if label file exists and is non-empty
if skip_existing and label_file.exists() and label_file.stat().st_size > 0:
lines = label_file.read_text(encoding="utf-8").strip().splitlines()
for l in lines:
if not l: continue
parts = l.split()
cls_id = int(parts[0])
if 0 <= cls_id < len(CLASS_NAMES):
class_detection_counts[CLASS_NAMES[cls_id]] += 1
total_boxes_generated += 1
total_images_processed += 1
skipped_count += 1
continue
# Standard single-pass inference (lightweight)
results = model.predict(str(img_path), conf=conf_threshold, verbose=False)
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
label_file.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
total_images_processed += 1
del results
gc.collect()
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,
"skipped_already_annotated": skipped_count,
"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.015
run_auto_annotation(conf_threshold=conf_val, max_images=max_imgs)