File size: 3,500 Bytes
dac3297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Train YOLOv8 on 2-class HVAC unit detection.

Classes:
  0 = ceiling_ducted
  1 = wall_mounted

Dataset: 1 image (cellar page), 12 annotated units
Strategy: Train with heavy augmentation (rotation, scale, mosaic) to compensate for small dataset.
"""
from pathlib import Path
import shutil
import yaml
import sys

ROOT = Path(__file__).resolve().parent
V2_DIR = ROOT / "yolo_v2_data"
EXTRACT_DIR = V2_DIR / "extracted"
RAW_DIR = V2_DIR / "raw"
DATASET_DIR = V2_DIR / "dataset"
LOG_FILE = V2_DIR / "train_log.txt"

log_lines = []
def log(msg):
    log_lines.append(str(msg))
    print(msg)

def save_log():
    LOG_FILE.write_text("\n".join(log_lines), encoding="utf-8")

try:
    # Find image and label
    image_files = list(RAW_DIR.glob("*.jpg")) + list(RAW_DIR.glob("*.png"))
    label_files = [f for f in EXTRACT_DIR.rglob("*.txt") if f.name != "classes.txt"]

    if not image_files:
        log("ERROR: No image file found in raw/")
        save_log()
        sys.exit(1)
    if not label_files:
        log("ERROR: No label file found in extracted/")
        save_log()
        sys.exit(1)

    image_path = image_files[0]
    label_path = label_files[0]
    log(f"Image: {image_path.name}")
    log(f"Label: {label_path.name}")

    # Build YOLO dataset structure
    train_img_dir = DATASET_DIR / "images" / "train"
    train_lbl_dir = DATASET_DIR / "labels" / "train"
    val_img_dir = DATASET_DIR / "images" / "val"
    val_lbl_dir = DATASET_DIR / "labels" / "val"

    for d in [train_img_dir, train_lbl_dir, val_img_dir, val_lbl_dir]:
        d.mkdir(parents=True, exist_ok=True)

    # Use simple name for image/label
    target_name = "cellar"
    shutil.copy(image_path, train_img_dir / f"{target_name}{image_path.suffix}")
    shutil.copy(label_path, train_lbl_dir / f"{target_name}.txt")
    # Same image as val (we only have 1 image)
    shutil.copy(image_path, val_img_dir / f"{target_name}{image_path.suffix}")
    shutil.copy(label_path, val_lbl_dir / f"{target_name}.txt")

    log(f"Dataset built at: {DATASET_DIR}")

    # Write data.yaml
    data_yaml = {
        "path": str(DATASET_DIR).replace("\\", "/"),
        "train": "images/train",
        "val": "images/val",
        "nc": 2,
        "names": {0: "ceiling_ducted", 1: "wall_mounted"}
    }
    yaml_path = DATASET_DIR / "data.yaml"
    with open(yaml_path, "w") as f:
        yaml.dump(data_yaml, f, sort_keys=False)
    log(f"data.yaml written: {yaml_path}")

    # Train
    log("\n=== Training YOLOv8n ===")
    from ultralytics import YOLO
    import torch

    device = 0 if torch.cuda.is_available() else "cpu"
    log(f"Device: {device}")

    model = YOLO("yolov8n.pt")
    results = model.train(
        data=str(yaml_path),
        epochs=100,
        imgsz=1280,        # Larger image size for small objects (boxes ~2% of image)
        batch=2,
        device=device,
        patience=30,
        # Heavy augmentation for small dataset
        degrees=15,        # rotation
        translate=0.1,
        scale=0.3,
        shear=2.0,
        flipud=0.0,
        fliplr=0.5,
        mosaic=1.0,
        mixup=0.1,
        copy_paste=0.1,
        project=str(V2_DIR / "runs"),
        name="yolov8n_2class",
        verbose=True,
    )

    log("\n=== Training done ===")
    log(f"Best weights: {V2_DIR / 'runs' / 'yolov8n_2class' / 'weights' / 'best.pt'}")
    save_log()
except Exception as e:
    import traceback
    log(f"ERROR: {e}")
    log(traceback.format_exc())
    save_log()
    raise