Download code/benchmark_precision.py from DIMPU1516/merged_csv: direct link, hf CLI and curl.
- Browser
- Download file 7.87 kB
-
https://huggingface.co/datasets/DIMPU1516/merged_csv/resolve/main/code/benchmark_precision.py
- Command line
-
hf download hf://datasets/DIMPU1516/merged_csv/code/benchmark_precision.py
-
curl -L -o benchmark_precision.py https://huggingface.co/datasets/DIMPU1516/merged_csv/resolve/main/code/benchmark_precision.py
7.87 kB
| """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)) | |
| 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 | |