File size: 7,874 Bytes
8578684
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared helpers for the air-writing pipeline: labels, video loading, dataset,
model builder, calibration metrics and the terminal decision rule."""
import math
import random
import re

import cv2
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset

LETTERS = [chr(c) for c in range(ord("A"), ord("Z") + 1)]
DIGITS = [str(d) for d in range(10)]
MEAN, STD = 0.45, 0.225          # same normalisation as the original script

# Pairs that the literature reports as easy to confuse (seed paper + AirLetters paper)
CONFUSABLE = [("1", "I"), ("5", "S"), ("0", "O"), ("8", "B"), ("2", "Z"),
              ("3", "B"), ("P", "D"), ("O", "Q"), ("1", "7")]
REJECT_CLASSES = {"OTHER", "NOTHING", "OTHER_THINGS"}


# ------------------------------------------------------------------ labels
def class_names(separate_contrast=False):
    """37 classes (26 letters + 10 digits + OTHER) or 38 with two contrast classes."""
    extra = ["NOTHING", "OTHER_THINGS"] if separate_contrast else ["OTHER"]
    return LETTERS + DIGITS + extra


def parse_label(text, separate_contrast=False):
    """'Drawing the letter A in the air' -> 'A'; 'Doing nothing' -> 'OTHER' (or 'NOTHING').
    Fails loudly on a label that mentions letter/digit but cannot be parsed."""
    t = str(text).strip().lower()
    m = re.search(r"letter\s+([a-z])\b", t)
    if m:
        return m.group(1).upper()
    m = re.search(r"digit\s+(\d)\b", t)
    if m:
        return m.group(1)
    if "letter" in t or "digit" in t:
        raise ValueError(f"Cannot parse label: {text!r}")
    if separate_contrast:
        return "NOTHING" if "nothing" in t else "OTHER_THINGS"
    return "OTHER"


# ------------------------------------------------------------------ video
def sample_indices(total, n, train):
    """One frame per equal time segment: random inside the segment (train) or centre (eval)."""
    edges = np.linspace(0, total, n + 1)
    idx = []
    for i in range(n):
        lo, hi = edges[i], max(edges[i] + 1e-6, edges[i + 1] - 1e-6)
        idx.append(int(random.uniform(lo, hi)) if train else int((edges[i] + edges[i + 1]) / 2))
    return [min(max(i, 0), total - 1) for i in idx]


def read_frames(path, n, train):
    cap = cv2.VideoCapture(path)
    if not cap.isOpened():
        raise IOError(f"cannot open video: {path}")
    total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    if total <= 0:
        cap.release()
        raise IOError(f"video reports 0 frames: {path}")
    indices = sample_indices(total, n, train)
    wanted, got, pos = set(indices), {}, 0
    last = max(indices)
    while pos <= last:
        if not cap.grab():
            break
        if pos in wanted:
            ok, fr = cap.retrieve()
            if ok:
                got[pos] = fr
        pos += 1
    cap.release()
    if not got:
        raise IOError(f"no decodable frames: {path}")
    keys = sorted(got)
    return [got[min(keys, key=lambda k: abs(k - i))] for i in indices]  # nearest decoded frame


def preprocess(frames_bgr, size, train):
    """Returns a float tensor C x T x H x W (e.g. 3 x 16 x 224 x 224)."""
    h, w = frames_bgr[0].shape[:2]
    y0, x0, ch, cw = 0, 0, h, w
    if train:                                   # random resized crop, scale (0.7, 1.0), same box for all frames
        s = random.uniform(0.7, 1.0)
        ch, cw = int(h * math.sqrt(s)), int(w * math.sqrt(s))
        y0, x0 = random.randint(0, h - ch), random.randint(0, w - cw)
    out = []
    for f in frames_bgr:
        f = cv2.resize(f[y0:y0 + ch, x0:x0 + cw], (size, size), interpolation=cv2.INTER_AREA)
        out.append(cv2.cvtColor(f, cv2.COLOR_BGR2RGB))
    x = torch.from_numpy(np.stack(out)).float().div_(255.0)          # T,H,W,3
    if train:                                   # brightness / contrast jitter. NO flips, NO rotations.
        b, c = random.uniform(0.8, 1.2), random.uniform(0.8, 1.2)
        x = (((x - 0.5) * c + 0.5) * b).clamp_(0, 1)
    x = (x - MEAN) / STD
    return x.permute(3, 0, 1, 2).contiguous()


class AirDataset(Dataset):
    def __init__(self, csv_path, video_dir, num_frames=16, size=224, train=False,
                 separate_contrast=False, on_error="raise", max_samples=None):
        df = pd.read_csv(csv_path)
        df.columns = df.columns.str.strip()
        if max_samples:
            df = df.sample(n=min(max_samples, len(df)), random_state=0).reset_index(drop=True)
        self.names = class_names(separate_contrast)
        cid = {n: i for i, n in enumerate(self.names)}
        self.files = df["filename"].tolist()
        self.paths = [f"{video_dir.rstrip('/')}/{f}" for f in self.files]
        self.y = [cid[parse_label(l, separate_contrast)] for l in df["label"]]
        self.num_frames, self.size, self.train, self.on_error = num_frames, size, train, on_error

    def __len__(self):
        return len(self.paths)

    def __getitem__(self, i):
        for attempt in range(10):
            try:
                x = preprocess(read_frames(self.paths[i], self.num_frames, self.train), self.size, self.train)
                return x, self.y[i]
            except Exception as e:
                if self.on_error == "raise":
                    raise
                print(f"[WARN] skipping unreadable video ({e})")
                i = random.randint(0, len(self.paths) - 1)
        raise RuntimeError("Too many unreadable videos.")


# ------------------------------------------------------------------ model
def build_model(num_classes, depth=101, frames=16, size=224):
    import torch.nn as nn
    from pytorchvideo.models.resnet import create_resnet
    assert size % 32 == 0, "size must be a multiple of 32"
    return create_resnet(input_channel=3, model_num_class=num_classes, model_depth=depth,
                         norm=nn.BatchNorm3d, activation=nn.ReLU,
                         head_pool_kernel_size=(min(4, frames), size // 32, size // 32))


@torch.no_grad()
def collect_logits(model, loader, device, use_amp=False):
    model.eval()
    logits, labels = [], []
    for x, y in loader:
        with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=use_amp):
            out = model(x.to(device, non_blocking=True))
        logits.append(out.float().cpu())
        labels.append(y)
    return torch.cat(logits).numpy(), torch.cat(labels).numpy()


# ------------------------------------------------------------------ calibration / decision
def softmax(z, T=1.0):
    z = z / T
    z = z - z.max(axis=1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=1, keepdims=True)


def ece(probs, labels, bins=15):
    conf, pred = probs.max(1), probs.argmax(1)
    acc = (pred == labels).astype(float)
    edges, total = np.linspace(0, 1, bins + 1), 0.0
    for lo, hi in zip(edges[:-1], edges[1:]):
        m = (conf > lo) & (conf <= hi)
        if m.any():
            total += m.mean() * abs(acc[m].mean() - conf[m].mean())
    return float(total)


def nll(probs, labels):
    return float(-np.log(np.clip(probs[np.arange(len(labels)), labels], 1e-12, 1)).mean())


def fit_temperature(logits, labels):
    """Temperature scaling: pick T that minimises NLL on VALIDATION logits only."""
    grid = np.exp(np.linspace(np.log(0.3), np.log(10), 300))
    return float(min(grid, key=lambda T: nll(softmax(logits, T), labels)))


def decide(probs, names, conf_thr=0.80, margin=0.20, pairs=CONFUSABLE):
    """Terminal rule: ACCEPT / RETRY (ask the user to write again) / REJECT (not a character)."""
    order = np.argsort(probs)[::-1]
    p1, p2 = float(probs[order[0]]), float(probs[order[1]])
    c1, c2 = names[order[0]], names[order[1]]
    if c1 in REJECT_CLASSES:
        return "REJECT", c1, p1
    if p1 < conf_thr:
        return "RETRY", c1, p1
    if {c1, c2} in [set(p) for p in pairs] and (p1 - p2) < margin:
        return "RETRY", c1, p1
    return "ACCEPT", c1, p1