File size: 6,386 Bytes
ab46ed9 | 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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | #!/usr/bin/env python3
"""
Local smoke test for `Miner` without Chutes or `sv`.
Vehicle detection (subnet cls_id 0–3: bus, car, truck, motorcycle):
python test_local.py --smoke-vehicle
python test_local.py --image ../imgs/bus.jpg
Other:
python test_local.py
python test_local.py --dummy-n 4
Requires `yolo11n.pt` in the same directory as `miner.py`.
"""
from __future__ import annotations
import argparse
import logging
import sys
from pathlib import Path
import numpy as np
# Same directory as this script = HF repo root for local testing
REPO_ROOT = Path(__file__).resolve().parent
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
from miner import Miner, subnet_vehicle_label # noqa: E402
# Default repo sample images (turbovision/imgs/) for --smoke-vehicle
VEHICLE_SMOKE_IMAGES: tuple[tuple[str, str], ...] = (
("bus.jpg", "subnet cls 0 = bus"),
("car.jpg", "subnet cls 1 = car"),
("truck.jpg", "subnet cls 2 = truck"),
("motor.jpg", "subnet cls 3 = motorcycle"),
)
def _load_images(args: argparse.Namespace) -> list[np.ndarray]:
if args.image:
try:
import cv2
except ImportError as e:
raise SystemExit(
"OpenCV is required to load images. Install with: pip install opencv-python-headless"
) from e
out: list[np.ndarray] = []
for p in args.image:
path = Path(p).expanduser().resolve()
if not path.is_file():
raise SystemExit(f"Not a file: {path}")
bgr = cv2.imread(str(path))
if bgr is None:
raise SystemExit(f"Failed to read image: {path}")
out.append(bgr)
return out
h, w = args.dummy_h, args.dummy_w
return [
np.zeros((h, w, 3), dtype=np.uint8) for _ in range(args.dummy_n)
]
def main() -> None:
parser = argparse.ArgumentParser(description="Local Miner smoke test (no Chutes).")
parser.add_argument(
"--n-keypoints",
type=int,
default=32,
help="Must match challenge metadata (default: 32).",
)
parser.add_argument(
"--offset",
type=int,
default=0,
help="Frame index offset for the first image in the batch.",
)
parser.add_argument(
"--dummy-n",
type=int,
default=2,
help="Number of blank frames when not using --image.",
)
parser.add_argument(
"--dummy-h",
type=int,
default=480,
help="Height of synthetic blank frames.",
)
parser.add_argument(
"--dummy-w",
type=int,
default=640,
help="Width of synthetic blank frames.",
)
parser.add_argument(
"--image",
nargs="*",
default=None,
help="One or more image paths (BGR). If omitted, uses blank frames.",
)
parser.add_argument(
"--verbose",
"-v",
action="store_true",
help="Print every detection (subnet cls_id + label).",
)
parser.add_argument(
"--smoke-vehicle",
action="store_true",
help=(
"Run one inference per turbovision/imgs sample (bus, car, truck, motor) "
"if present; checks COCO→subnet remapping for vehicle element."
),
)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
if args.smoke_vehicle:
if args.image:
raise SystemExit("Use either --smoke-vehicle or --image, not both.")
_run_vehicle_smoke(args)
return
batch_images = _load_images(args)
print(f"Loaded {len(batch_images)} frame(s); repo_root={REPO_ROOT}")
miner = Miner(REPO_ROOT)
results = miner.predict_batch(
batch_images=batch_images,
offset=args.offset,
n_keypoints=args.n_keypoints,
)
_print_results(results, args.verbose)
print("OK")
def _print_results(results, verbose: bool) -> None:
for r in results:
print(
f" frame_id={r.frame_id} boxes={len(r.boxes)} "
f"keypoints={len(r.keypoints)}"
)
if not r.boxes:
continue
show = r.boxes if verbose else r.boxes[:1]
for j, b in enumerate(show):
lab = subnet_vehicle_label(b.cls_id)
tag = f"[{j}] " if verbose else ""
print(
f" box: {tag}cls_id={b.cls_id} ({lab}) conf={b.conf:.3f} "
f"xyxy=({b.x1},{b.y1})-({b.x2},{b.y2})"
)
if not verbose and len(r.boxes) > 1:
print(f" ... and {len(r.boxes) - 1} more box(es); use --verbose")
def _run_vehicle_smoke(args: argparse.Namespace) -> None:
try:
import cv2
except ImportError as e:
raise SystemExit(
"OpenCV is required. Install with: pip install opencv-python-headless"
) from e
imgs_dir = REPO_ROOT.parent / "imgs"
print(f"Vehicle smoke test (repo_root={REPO_ROOT}, imgs_dir={imgs_dir})")
miner = Miner(REPO_ROOT)
ok = True
for fname, hint in VEHICLE_SMOKE_IMAGES:
path = imgs_dir / fname
if not path.is_file():
print(f" skip {fname} — not found ({hint})")
continue
bgr = cv2.imread(str(path))
if bgr is None:
print(f" FAIL {fname}: could not decode")
ok = False
continue
results = miner.predict_batch(
batch_images=[bgr],
offset=0,
n_keypoints=args.n_keypoints,
)
r = results[0]
print(f" {fname} ({hint})")
if not r.boxes:
print(" no vehicle COCO detections after remapping (empty)")
ok = False
continue
show = r.boxes if args.verbose else r.boxes[:1]
for j, b in enumerate(show):
lab = subnet_vehicle_label(b.cls_id)
tag = f"[{j}] " if args.verbose else ""
print(
f" box: {tag}cls_id={b.cls_id} ({lab}) conf={b.conf:.3f} "
f"xyxy=({b.x1},{b.y1})-({b.x2},{b.y2})"
)
if not args.verbose and len(r.boxes) > 1:
print(f" ... +{len(r.boxes) - 1} more; use --verbose")
print("OK" if ok else "DONE (some images missing or no detections)")
if __name__ == "__main__":
main()
|