File size: 5,980 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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""
End-to-end pipeline: YOLO detection + OCR label reading.

Steps:
1. Run trained YOLOv8 on cellar image (tiled, since image is large)
2. For each detection, crop the box + a small margin
3. Run PaddleOCR on the crop to extract the unit label text (AC-P, AC-T, etc.)
4. Save annotated output image and JSON results
"""
from pathlib import Path
import json
import sys

ROOT = Path(__file__).resolve().parent
V2_DIR = ROOT / "yolo_v2_data"
RAW_DIR = V2_DIR / "raw"
OUT_DIR = V2_DIR / "output"
OUT_DIR.mkdir(exist_ok=True)
LOG_FILE = V2_DIR / "detect_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:
    from PIL import Image, ImageDraw, ImageFont
    from ultralytics import YOLO

    # Find the trained model
    runs_dir = V2_DIR / "runs"
    best_weights = list(runs_dir.rglob("best.pt"))
    if not best_weights:
        log("ERROR: No trained model found. Run train_yolo_v2.py first.")
        save_log()
        sys.exit(1)

    weights_path = best_weights[0]
    log(f"Using model: {weights_path}")

    # Find image
    image_files = list(RAW_DIR.glob("*.jpg")) + list(RAW_DIR.glob("*.png"))
    img_path = image_files[0]
    log(f"Image: {img_path.name}")

    img = Image.open(img_path).convert("RGB")
    W, H = img.size
    log(f"Image size: {W} x {H}")

    # Load model and run inference
    model = YOLO(str(weights_path))

    # For large images, tile to handle small objects better
    TILE_SIZE = 1280
    OVERLAP = 256

    log("\n=== Running detection (tiled) ===")
    all_dets = []
    seen = set()  # for dedup

    y = 0
    while y < H:
        x = 0
        while x < W:
            x2 = min(x + TILE_SIZE, W)
            y2 = min(y + TILE_SIZE, H)
            tile = img.crop((x, y, x2, y2))
            results = model(tile, conf=0.05, iou=0.4, verbose=False)
            for result in results:
                if result.boxes is None:
                    continue
                for box in result.boxes:
                    bx1, by1, bx2, by2 = box.xyxy[0].cpu().numpy()
                    cls = int(box.cls[0].cpu().numpy())
                    conf = float(box.conf[0].cpu().numpy())
                    # Convert to page coords
                    px1 = int(bx1) + x
                    py1 = int(by1) + y
                    px2 = int(bx2) + x
                    py2 = int(by2) + y
                    # Simple dedup by rounded center
                    key = (round((px1+px2)/2/30), round((py1+py2)/2/30), cls)
                    if key in seen:
                        continue
                    seen.add(key)
                    all_dets.append({
                        "x1": px1, "y1": py1, "x2": px2, "y2": py2,
                        "class": cls,
                        "class_name": "ceiling_ducted" if cls == 0 else "wall_mounted",
                        "confidence": round(conf, 3),
                    })
            x += TILE_SIZE - OVERLAP
        y += TILE_SIZE - OVERLAP

    log(f"Total detections: {len(all_dets)}")
    log(f"  ceiling_ducted: {sum(1 for d in all_dets if d['class']==0)}")
    log(f"  wall_mounted:   {sum(1 for d in all_dets if d['class']==1)}")

    # Run OCR on each detection
    log("\n=== Running OCR on each detection ===")
    try:
        from paddleocr import PaddleOCR
        ocr_engine = PaddleOCR(use_angle_cls=True, lang='en', show_log=False)
        ocr_available = True
    except Exception as e:
        log(f"PaddleOCR not available: {e}")
        log("Install with: pip install paddlepaddle paddleocr")
        ocr_available = False

    if ocr_available:
        MARGIN = 30  # pixels around box to capture label text nearby
        for det in all_dets:
            cx1 = max(0, det["x1"] - MARGIN)
            cy1 = max(0, det["y1"] - MARGIN)
            cx2 = min(W, det["x2"] + MARGIN)
            cy2 = min(H, det["y2"] + MARGIN)
            crop = img.crop((cx1, cy1, cx2, cy2))
            import numpy as np
            crop_np = np.array(crop)
            try:
                result = ocr_engine.ocr(crop_np, cls=True)
                texts = []
                if result and result[0]:
                    for line in result[0]:
                        text = line[1][0]
                        conf = line[1][1]
                        texts.append({"text": text, "confidence": round(conf, 3)})
                det["ocr_texts"] = texts
                # Heuristic: find AC-* or similar pattern
                import re
                labels = []
                for t in texts:
                    matches = re.findall(r'[A-Z]{2,4}-?[A-Z0-9]+', t["text"].upper())
                    labels.extend(matches)
                det["unit_label"] = labels[0] if labels else None
            except Exception as e:
                det["ocr_error"] = str(e)
                det["unit_label"] = None

    # Save JSON
    json_path = OUT_DIR / "detections.json"
    with open(json_path, "w") as f:
        json.dump(all_dets, f, indent=2)
    log(f"\nDetections saved: {json_path}")

    # Annotate image
    log("\n=== Annotating image ===")
    overlay = img.copy()
    draw = ImageDraw.Draw(overlay)
    try:
        font = ImageFont.truetype("arial.ttf", 16)
    except:
        font = ImageFont.load_default()

    colors = {0: (0, 255, 0), 1: (255, 100, 0)}
    for idx, det in enumerate(all_dets, 1):
        color = colors[det["class"]]
        draw.rectangle([det["x1"], det["y1"], det["x2"], det["y2"]], outline=color, width=3)
        label = det.get("unit_label") or det["class_name"][:3]
        draw.text((det["x1"], det["y1"] - 18), f"{idx}.{label}", fill=color, font=font)

    out_img = OUT_DIR / "detection_result.jpg"
    overlay.save(out_img, quality=85)
    log(f"Annotated image: {out_img}")

    save_log()
except Exception as e:
    import traceback
    log(f"ERROR: {e}")
    log(traceback.format_exc())
    save_log()
    raise