File size: 4,001 Bytes
a63439d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Custom YOLOv8 Training & Export Script for E-Waste Cannibalization Index."""
from __future__ import annotations

import json
import logging
import os
from pathlib import Path

import yaml
from ultralytics import YOLO

# Enforce all cache and runs directories to reside strictly within workspace
workspace_dir = Path(__file__).resolve().parent.parent
cache_dir = (workspace_dir / "data" / "cache").resolve()
cache_dir.mkdir(parents=True, exist_ok=True)
runs_dir = (workspace_dir / "data" / "runs").resolve()
runs_dir.mkdir(parents=True, exist_ok=True)

os.environ["TORCH_HOME"] = str(cache_dir)
os.environ["HF_HOME"] = str(cache_dir)
os.environ["ULTRALYTICS_CONFIG_DIR"] = str(cache_dir)

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

CONFIG_PATH = workspace_dir / "training" / "train_config.yaml"


def load_train_config(config_file: Path = CONFIG_PATH) -> dict:
    if config_file.exists():
        with open(config_file, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)
    return {
        "data": "data/splits/data.yaml",
        "model": "yolov8n.pt",
        "imgsz": 960,
        "epochs": 50,
        "batch": 8,
        "copy_paste": 0.8,
        "cls": 2.5,
    }


def run_training(config_override: dict | None = None) -> dict:
    cfg = load_train_config()
    if config_override:
        cfg.update(config_override)

    log.info("Loaded training configuration: %s", cfg)

    model_name = cfg.get("model", "yolov8n.pt")
    data_yaml = str((workspace_dir / cfg.get("data", "data/splits/data.yaml")).resolve())
    epochs = int(cfg.get("epochs", 50))
    imgsz = int(cfg.get("imgsz", 960))
    batch_size = int(cfg.get("batch", 8))

    log.info("Initializing YOLO model backbone: %s", model_name)
    model = YOLO(model_name)

    # Train model with Copy-Paste augmentation and elevated class loss gain
    log.info("Starting YOLOv8 fine-tuning on %s (%d epochs, imgsz=%d)...", data_yaml, epochs, imgsz)
    results = model.train(
        data=data_yaml,
        epochs=epochs,
        imgsz=imgsz,
        batch=batch_size,
        copy_paste=float(cfg.get("copy_paste", 0.8)),
        mosaic=float(cfg.get("mosaic", 1.0)),
        mixup=float(cfg.get("mixup", 0.15)),
        box=float(cfg.get("box", 7.5)),
        cls=float(cfg.get("cls", 2.5)),
        dfl=float(cfg.get("dfl", 1.5)),
        project=str(runs_dir),
        name="ewaste_purity_v1",
        exist_ok=True,
        verbose=True,
    )

    # Validate trained model on test split
    log.info("Validating trained model on test split...")
    metrics = model.val(data=data_yaml, split="test", imgsz=imgsz)

    maps_per_class = metrics.box.maps.tolist() if hasattr(metrics.box, "maps") else []
    mp = float(metrics.box.mp) if hasattr(metrics.box, "mp") else 0.0
    mr = float(metrics.box.mr) if hasattr(metrics.box, "mr") else 0.0
    map50 = float(metrics.box.map50) if hasattr(metrics.box, "map50") else 0.0
    map95 = float(metrics.box.map) if hasattr(metrics.box, "map") else 0.0

    eval_summary = {
        "mean_precision": round(mp, 4),
        "mean_recall": round(mr, 4),
        "mAP_50": round(map50, 4),
        "mAP_50_95": round(map95, 4),
        "maps_per_class": maps_per_class,
    }

    eval_file = workspace_dir / "reports" / "model_eval_summary.json"
    eval_file.parent.mkdir(parents=True, exist_ok=True)
    eval_file.write_text(json.dumps(eval_summary, indent=2), encoding="utf-8")
    log.info("Saved evaluation summary to %s", eval_file)

    try:
        log.info("Exporting trained model to TFLite format...")
        model.export(format="tflite", int8=True, imgsz=imgsz)
        log.info("TFLite export successful!")
    except Exception as exc:
        log.warning("TFLite export deferred: %s", exc)

    return eval_summary


if __name__ == "__main__":
    import sys
    ep = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 5
    run_training({"epochs": ep})