File size: 3,321 Bytes
50a3c34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Minimal inference for the WorkSight activity model.

    pip install torch torchvision safetensors opencv-python huggingface_hub
    python inference.py clip.mp4            # whole frame
    python inference.py clip.mp4 --person   # crop around the largest person (needs ultralytics)

Input: a ~3 second clip. Output: activity label and class probabilities.
"""
import argparse
import json
from pathlib import Path

import cv2
import numpy as np
import torch
from safetensors.torch import load_file
from torchvision.models.video import mvit_v2_s

HERE = Path(__file__).parent


def load_model(repo_dir=HERE, device="cpu"):
    cfg = json.loads((Path(repo_dir) / "config.json").read_text())
    model = mvit_v2_s(weights=None)
    model.head[1] = torch.nn.Linear(model.head[1].in_features, cfg["num_classes"])
    model.load_state_dict(load_file(str(Path(repo_dir) / "model.safetensors")))
    return model.eval().to(device), cfg


def read_clip(path, n=16, size=224, person=False):
    cap = cv2.VideoCapture(str(path))
    frames = []
    while True:
        ok, f = cap.read()
        if not ok:
            break
        frames.append(f)
    cap.release()
    if not frames:
        raise ValueError(f"cannot read {path}")
    idx = np.linspace(0, len(frames) - 1, n).round().astype(int)
    frames = [frames[i] for i in idx]
    if person:   # same crop as the WorkSight live monitor: largest person, 18% margin, squashed to 224x224
        from ultralytics import YOLO
        boxes = YOLO("yolo11s.pt").predict(frames[n // 2], classes=[0], verbose=False)[0].boxes.xyxy.numpy()
        if len(boxes):
            x1, y1, x2, y2 = boxes[np.prod(boxes[:, 2:] - boxes[:, :2], axis=1).argmax()].astype(int)
            dx, dy = int((x2 - x1) * 0.18), int((y2 - y1) * 0.18)
            h, w = frames[0].shape[:2]
            frames = [f[max(0, y1 - dy):min(h, y2 + dy), max(0, x1 - dx):min(w, x2 + dx)] for f in frames]
            return np.stack([cv2.cvtColor(cv2.resize(f, (size, size)), cv2.COLOR_BGR2RGB) for f in frames])
    out = []
    for f in frames:   # resize short side to 256, centre crop 224
        h, w = f.shape[:2]
        s = 256 / min(h, w)
        f = cv2.resize(f, (round(w * s), round(h * s)))
        y, x = (f.shape[0] - size) // 2, (f.shape[1] - size) // 2
        out.append(cv2.cvtColor(f[y:y + size, x:x + size], cv2.COLOR_BGR2RGB))
    return np.stack(out)


@torch.no_grad()
def predict(model, cfg, clip, device="cpu"):
    x = torch.from_numpy(clip).permute(3, 0, 1, 2)[None].float().div(255).to(device)   # 1,C,T,H,W
    x = (x - cfg["mean"][0]) / cfg["std"][0]
    p = (model(x).softmax(1) + model(x.flip(-1)).softmax(1)) / 2                      # flip averaging
    p = p[0].cpu().numpy()
    labels = [cfg["id2label"][str(i)] for i in range(cfg["num_classes"])]
    label = labels[p.argmax()] if p.max() >= cfg["uncertain_threshold"] else "uncertain"
    return label, {k: round(float(v), 3) for k, v in zip(labels, p)}


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("video")
    ap.add_argument("--person", action="store_true")
    args = ap.parse_args()
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model, cfg = load_model(device=device)
    print(*predict(model, cfg, read_clip(args.video, person=args.person), device))