ScoreVision / test_local.py
EliasCarter's picture
scorevision: push artifact
ab46ed9 verified
Raw History Blame Contribute Delete
6.39 kB
#!/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()