Add object detection, tracking, mobile notifications, and search to any security camera.
Faces (#142)
Rory Clear405ebc2514d2
diff --git a/adaface.py b/adaface.pynew file mode 100644index 0000000..e4acf51--- /dev/null+++ b/adaface.py@@ -0,0 +1,95 @@+from tinygrad import Tensor, nn+from tinygrad.nn.state import safe_save, safe_load, get_state_dict, load_state_dict+from tinygrad.helpers import fetch+class MaxPool2d:+ def __init__(self, kernel_size=2, stride=None, padding=0):+ self.kernel_size = kernel_size+ self.stride = stride if stride is not None else kernel_size+ self.padding = padding++ def __call__(self, x): return x.pad((self.padding, self.padding, self.padding, self.padding)).max_pool2d(kernel_size=self.kernel_size, stride=self.stride)++class Seq():+ def __init__(self, size=0):+ super().__init__()+ self.list = [None] * size+ def __len__(self): return len(self.list)+ def __setitem__(self, key, value): self.list[key] = value+ def __getitem__(self, idx): return self.list[idx]+ def __delitem__(self, idx): del self.list[idx]+ def __call__(self, x):+ for y in self.list: x = y(x)+ return x++class BasicBlockIR_tiny():+ def __init__(self, in_channel, depth, stride):+ self.in_channel = in_channel+ self.depth = depth+ self.stride = stride++ self.res_layer0 = nn.BatchNorm2d(self.in_channel)+ self.conv_layer0 = nn.Conv2d(self.in_channel, self.depth, (3, 3), (1, 1), 1, bias=False)+ self.res_layer1 = nn.BatchNorm2d(self.depth)+ self.prelu_weight = Tensor.empty(self.depth)+ self.conv_layer1 = nn.Conv2d(self.depth, self.depth, (3, 3), self.stride, 1, bias=False)+ self.res_layer2 = nn.BatchNorm2d(self.depth)++ if self.depth == self.in_channel:+ self.shortcut_layer = MaxPool2d(1, self.stride)+ else:+ self.shortcut_layer0 = nn.Conv2d(self.in_channel, self.depth, (1, 1), self.stride, bias=False)+ self.shortcut_layer1 = nn.BatchNorm2d(self.depth)++++ def __call__(self, x):+ if self.depth == self.in_channel:+ shortcut = self.shortcut_layer(x)+ else:+ shortcut = self.shortcut_layer0(x)+ shortcut = self.shortcut_layer1(shortcut)+ x = self.res_layer0(x)+ x = self.conv_layer0(x)+ x = self.res_layer1(x)+ x = Tensor.where(x > 0, x, self.prelu_weight.view(1, -1, 1, 1) * x)+ x = self.conv_layer1(x)+ x = self.res_layer2(x)+ return x + shortcut++++sizes = [[64, 64, 2], [64, 64, 1], [64, 64, 1], [64, 128, 2], [128, 128, 1], [128, 128, 1], [128, 128, 1], [128, 256, 2], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 256, 1], [256, 512, 2], [512, 512, 1], [512, 512, 1]]++class ADAFACE():+ def __init__(self):++ self.linear = nn.Linear(512 * 7 * 7, 512)+ self.bn = nn.BatchNorm2d(512)++ self.bn2 = nn.BatchNorm(512, affine=False)+ self.prelu_weight = Tensor.empty(64)+ self.conv0 = nn.Conv2d(3, 64, (3, 3), 1, 1, bias=False)+ self.bn0 = nn.BatchNorm2d(64)++ self.body = Seq(size=24)+ for i in range(len(self.body)): self.body[i] = BasicBlockIR_tiny(sizes[i][0], sizes[i][1], sizes[i][2])+ state_dict = safe_load(fetch("https://huggingface.co/roryclear/AdaFace/resolve/main/adaface_ir50_ms1mv2.safetensors"))+ load_state_dict(self, state_dict)+++ def __call__(self, x):+ x = ((x[:,:,::-1] / 255.) - 0.5) / 0.5+ x = x.permute(2,0,1).unsqueeze(0)++ x = self.conv0(x)+ x = self.bn0(x)+ x = Tensor.where(x > 0, x, self.prelu_weight.view(1, -1, 1, 1) * x)++ for module in self.body: x = module(x)+ x = self.bn(x)+ x = x.view(x.size(0), -1)+ x = self.linear(x)+ x = self.bn2(x)+ norm = Tensor.sqrt(Tensor.sum(x * x, keepdim=True))+ output = x / norm+ return output, norm\ No newline at end of filediff --git a/blazeface.py b/blazeface.pynew file mode 100644index 0000000..ad829ad--- /dev/null+++ b/blazeface.py@@ -0,0 +1,261 @@+from tinygrad import Tensor, nn+from tinygrad.nn.state import safe_save, safe_load, get_state_dict, load_state_dict++class BlazeBlock():+ def __init__(self, c=None, channel_pad=0):+ if c is not None:+ self.stride = c.stride+ self.channel_pad = c.channel_pad+ self.conv0_tiny = c.conv0_tiny+ self.conv1_tiny = c.conv1_tiny+ return++ self.channel_pad = channel_pad++ def __call__(self, x):+ if self.stride == 2:+ h = x.pad(((0, 0), (0, 0), (0, 2), (0, 2)))+ x = x.max_pool2d(self.stride, self.stride)+ else:+ h = x++ if self.channel_pad > 0:+ x = x.pad(((0, 0), (0, self.channel_pad), (0, 0), (0, 0)))+++ h = self.conv0_tiny(h)+ h = self.conv1_tiny(h)+ x += h+ x = x.relu()+ return x++class Seq():+ def __init__(self, size=0):+ super().__init__()+ self.list = [None] * size+ def __len__(self): return len(self.list)+ def __setitem__(self, key, value): self.list[key] = value+ def __getitem__(self, idx): return self.list[idx]+ def __call__(self, x):+ for y in self.list: x = y(x)+ return x++class FinalBlazeBlock():+ def __init__(self, f=None):+ if f is not None:+ self.act = f.act+ self.convs = f.convs+ self.conv0_tiny = f.conv0_tiny+ self.conv1_tiny = f.conv1_tiny+ return++ self.conv0_tiny = nn.Conv2d(96, 96, kernel_size=3, stride=2, padding=0, groups=96, bias=True)+ self.conv1_tiny = nn.Conv2d(96, 96, kernel_size=1, stride=1, padding=0, bias=True)++ def __call__(self, x):+ x = x.pad(((0, 0), (0, 0), (0, 2), (0, 2)))+ x = self.conv0_tiny(x)+ x = self.conv1_tiny(x)+ x = x.relu()+ return x++class BlazeFace():+ def __init__(self, m=None):+ if m is not None:+ self.backbone_tiny = m.backbone_tiny+ self.conv_tiny = m.conv_tiny+ self.classifier_8 = m.classifier_8+ self.classifier_16 = m.classifier_16+ self.regressor_8 = m.regressor_8+ self.regressor_16 = m.regressor_16+ self.anchors = m.anchors+ self.x_scale = m.x_scale+ self.y_scale = m.y_scale+ self.w_scale = m.w_scale+ self.h_scale = m.h_scale+ self.score_clipping_thresh = m.score_clipping_thresh+ self.min_score_thresh = m.min_score_thresh+ self.min_suppression_threshold = m.min_suppression_threshold+ self.final = m.final+ return++ self.conv_tiny = nn.Conv2d(in_channels=3, out_channels=24, kernel_size=5, stride=2, padding=0, bias=True)+ self.classifier_8_tiny = nn.Conv2d(in_channels=96, out_channels=2, kernel_size=1, groups=1, bias=True)+ self.classifier_16_tiny = nn.Conv2d(in_channels=96, out_channels=6, kernel_size=1, groups=1, bias=True)+ self.regressor_8_tiny = nn.Conv2d(in_channels=96, out_channels=32, kernel_size=1, groups=1, bias=True)+ self.regressor_16_tiny = nn.Conv2d(in_channels=96, out_channels=96, kernel_size=1, groups=1, bias=True)++ self.final = FinalBlazeBlock()+ self.backbone_tiny = Seq(31)+ for i in range(7):+ self.backbone_tiny[i] = BlazeBlock()+ self.backbone_tiny[i].conv0_tiny = nn.Conv2d(24, 24, kernel_size=3, stride=1, padding=1, groups=24, bias=True)+ self.backbone_tiny[i].conv1_tiny = nn.Conv2d(24, 24, kernel_size=1, stride=1, padding=0, groups=1, bias=True)+ self.backbone_tiny[i].stride = 1+ self.backbone_tiny[7] = BlazeBlock()+ self.backbone_tiny[7].conv0_tiny = nn.Conv2d(24, 24, kernel_size=3, stride=2, padding=0, groups=24, bias=True)+ self.backbone_tiny[7].conv1_tiny = nn.Conv2d(24, 24, kernel_size=1, stride=1, padding=0, groups=1, bias=True)+ self.backbone_tiny[7].stride = 2+ for i in range(8, 15):+ self.backbone_tiny[i] = BlazeBlock()+ self.backbone_tiny[i].conv0_tiny = nn.Conv2d(24, 24, kernel_size=3, stride=1, padding=1, groups=24, bias=True)+ self.backbone_tiny[i].conv1_tiny = nn.Conv2d(24, 24, kernel_size=1, stride=1, padding=0, groups=1, bias=True)+ self.backbone_tiny[i].stride = 1+ self.backbone_tiny[15] = BlazeBlock(channel_pad=24)+ self.backbone_tiny[15].conv0_tiny = nn.Conv2d(24, 24, kernel_size=3, stride=2, padding=0, groups=24, bias=True)+ self.backbone_tiny[15].conv1_tiny = nn.Conv2d(24, 48, kernel_size=1, stride=1, padding=0, groups=1, bias=True)+ self.backbone_tiny[15].stride = 2+ for i in range(16, 23):+ self.backbone_tiny[i] = BlazeBlock()+ self.backbone_tiny[i].conv0_tiny = nn.Conv2d(48, 48, kernel_size=3, stride=1, padding=1, groups=48, bias=True)+ self.backbone_tiny[i].conv1_tiny = nn.Conv2d(48, 48, kernel_size=1, stride=1, padding=0, groups=1, bias=True)+ self.backbone_tiny[i].stride = 1+ self.backbone_tiny[23] = BlazeBlock(channel_pad=48)+ self.backbone_tiny[23].conv0_tiny = nn.Conv2d(48, 48, kernel_size=3, stride=2, padding=0, groups=48, bias=True)+ self.backbone_tiny[23].conv1_tiny = nn.Conv2d(48, 96, kernel_size=1, stride=1, padding=0, groups=1, bias=True)+ self.backbone_tiny[23].stride = 2+ for i in range(24, 31):+ self.backbone_tiny[i] = BlazeBlock()+ self.backbone_tiny[i].conv0_tiny = nn.Conv2d(96, 96, kernel_size=3, stride=1, padding=1, groups=96, bias=True)+ self.backbone_tiny[i].conv1_tiny = nn.Conv2d(96, 96, kernel_size=1, stride=1, padding=0, groups=1, bias=True)+ self.backbone_tiny[i].stride = 1++ self.anchors = Tensor.empty(896, 4)+ self.num_classes = 1+ self.num_anchors = 896+ self.num_coords = 16+ self.score_clipping_thresh = 100.0++ self.x_scale = 256.0+ self.y_scale = 256.0+ self.h_scale = 256.0+ self.w_scale = 256.0+ self.min_score_thresh = 0.85+ self.min_suppression_threshold = 0.3++ load_state_dict(self, safe_load("blazeface.safetensors"))+++ def forward(self, x):+ x = x.pad(((0, 0), (0, 0), (1, 2), (1, 2)))+ b = x.shape[0] # batch size, needed for reshaping later+ x = self.conv_tiny(x)+ x = x.relu()+ x = self.backbone_tiny(x) # (b, 16, 16, 96)+ h = self.final(x) # (b, 8, 8, 96)+ c1 = self.classifier_8_tiny(x) # (b, 2, 16, 16)+ c1 = c1.permute(0, 2, 3, 1) # (b, 16, 16, 2)+ c1 = c1.reshape(b, -1, 1) # (b, 512, 1)++ c2 = self.classifier_16_tiny(h) # (b, 6, 8, 8)+ c2 = c2.permute(0, 2, 3, 1) # (b, 8, 8, 6)+ c2 = c2.reshape(b, -1, 1) # (b, 384, 1)++ c = Tensor.cat(c1, c2, dim=1)+ r1 = self.regressor_8_tiny(x) # (b, 32, 16, 16)+ r1 = r1.permute(0, 2, 3, 1) # (b, 16, 16, 32)+ r1 = r1.reshape(b, -1, 16) # (b, 512, 16)++ r2 = self.regressor_16_tiny(h) # (b, 96, 8, 8)+ r2 = r2.permute(0, 2, 3, 1) # (b, 8, 8, 96)+ r2 = r2.reshape(b, -1, 16) # (b, 384, 16)++ r = Tensor.cat(r1, r2, dim=1)+ return [r, c]++ def __call__(self, img):+ h0, w0 = img.shape[:2]++ scale = min(256/w0, 256/h0)+ new_w, new_h = int(w0*scale), int(h0*scale)+ img = resize(img, [new_w, new_h])+ pad_top = (256 - new_h) // 2+ pad_bottom = 256 - new_h - pad_top+ pad_left = (256 - new_w) // 2+ pad_right = 256 - new_w - pad_left+ x = img.pad(((pad_top, pad_bottom), (pad_left, pad_right), (0,0)), value=0)+ x = x.permute((2, 0, 1))+ x = x.unsqueeze(0)+ x = x / 127.5 - 1.0+ out = self.forward(x)++ detections = self._tensors_to_detections(out[0], out[1], self.anchors)++ detections = Tensor.cat(detections[:, :4], detections[:, 16:17], dim=1)++ detections = self.postprocess(detections)[0]++ detections = detections * 256+ detections[:, [0, 2]] -= pad_top # ymin, ymax+ detections[:, [1, 3]] -= pad_left # xmin, xmax+ detections /= scale+ return detections[:, :5]++ def _tensors_to_detections(self, raw_box_tensor, raw_score_tensor, anchors):+ detection_boxes = self._decode_boxes(raw_box_tensor, anchors) # (B, N, 16)+ thresh = self.score_clipping_thresh+ scores = raw_score_tensor.clip(-thresh, thresh).sigmoid().squeeze(-1)+ mask = scores >= self.min_score_thresh # (B, N)+ scores = scores.unsqueeze(-1) # (B, N, 1)+ detections = Tensor.cat(detection_boxes, scores, dim=-1) # (B, N, 17)+ detections *= mask.unsqueeze(-1)+ return detections[0]++ def _decode_boxes(self, raw_boxes, anchors):+ boxes = Tensor.zeros_like(raw_boxes).contiguous()+ ax = anchors[:, 0]+ ay = anchors[:, 1]+ aw = anchors[:, 2]+ ah = anchors[:, 3]+ x_center = raw_boxes[..., 0] / self.x_scale * aw + ax+ y_center = raw_boxes[..., 1] / self.y_scale * ah + ay+ w = raw_boxes[..., 2] / self.w_scale * aw+ h = raw_boxes[..., 3] / self.h_scale * ah+ boxes[..., 0] = y_center - h / 2. # ymin+ boxes[..., 1] = x_center - w / 2. # xmin+ boxes[..., 2] = y_center + h / 2. # ymax+ boxes[..., 3] = x_center + w / 2. # xmax+ keypoints = raw_boxes[..., 4:].view(*raw_boxes.shape[:-1], 6, 2)+ kp_x = keypoints[..., 0] / self.x_scale * aw.unsqueeze(0).unsqueeze(-1) + ax.unsqueeze(0).unsqueeze(-1)+ kp_y = keypoints[..., 1] / self.y_scale * ah.unsqueeze(0).unsqueeze(-1) + ay.unsqueeze(0).unsqueeze(-1)+ keypoints_decoded = Tensor.stack((kp_x, kp_y), dim=-1) # (B, N, 6, 2)+ boxes[..., 4:] = keypoints_decoded.view(*raw_boxes.shape[:-1], -1)+ return boxes++ def postprocess(self, boxes):+ boxes = boxes.unsqueeze(0)+ max_det = 896+ iou_threshold = 0.3+ probs = boxes[:, :, 4]+ order_all = Tensor.topk(probs, min(max_det, probs.shape[1]))[1]+ batch_idx = Tensor.arange(order_all.shape[0]).reshape(-1, 1)+ boxes = boxes[batch_idx, order_all]+ ious = compute_iou_matrix(boxes[:, :, :4])+ ious = Tensor.triu(ious, diagonal=1)+ high_iou_mask = (ious > iou_threshold)+ no_overlap_mask = high_iou_mask.sum(axis=1) == 0+ conf_mask = (boxes[:, :, 4] >= self.min_score_thresh)+ final_mask = no_overlap_mask * conf_mask+ return boxes * final_mask.unsqueeze(-1)++def compute_iou_matrix(boxes):+ x1s = boxes[:, :, 0]+ y1s = boxes[:, :, 1]+ x2s = boxes[:, :, 2]+ y2s = boxes[:, :, 3]+ areas = (x2s - x1s) * (y2s - y1s)+ x1 = Tensor.maximum(x1s[:, :, None], x1s[:, None, :])+ y1 = Tensor.maximum(y1s[:, :, None], y1s[:, None, :])+ x2 = Tensor.minimum(x2s[:, :, None], x2s[:, None, :])+ y2 = Tensor.minimum(y2s[:, :, None], y2s[:, None, :])+ w = Tensor.maximum(Tensor(0), x2 - x1)+ h = Tensor.maximum(Tensor(0), y2 - y1)+ intersection = w * h+ union = areas[:, :, None] + areas[:, None, :] - intersection+ return intersection / union++def resize(img, new_size):+ img = img.permute(2,0,1)+ img = Tensor.interpolate(img, size=(new_size[1], new_size[0]), mode='linear', align_corners=False)+ img = img.permute(1, 2, 0)+ return img\ No newline at end of filediff --git a/blazeface.safetensors b/blazeface.safetensorsnew file mode 100755index 0000000..ee229b8Binary files /dev/null and b/blazeface.safetensors differdiff --git a/clearcam.py b/clearcam.pyindex f48ff5e..9e81b93 100644--- a/clearcam.py+++ b/clearcam.py@@ -283,6 +283,7 @@ class VideoCapture:timestamp = "video" if self.vod else datetime.now().strftime("%Y-%m-%d")filepath = BASE_DIR / "cameras" / f"{self.cam_name}/objects/{timestamp}"filepath.mkdir(parents=True, exist_ok=True)+ (BASE_DIR / "cameras" / f"{self.cam_name}/faces/{timestamp}").mkdir(parents=True, exist_ok=True)object_filename = filepath / f"{ts}_{int(p[6])}_{int(p[5])}.jpg"x1, y1, x2, y2 = map(int, (p[0], p[1], p[2], p[3]))cx = (x1 + x2) // 2@@ -449,6 +450,7 @@ class VideoCapture:def reset_vod(self):self.cap = cv2.VideoCapture(self.src) # reset video on settings changeshutil.rmtree(BASE_DIR / "cameras" / self.cam_name / "objects", ignore_errors=True)+ shutil.rmtree(BASE_DIR / "cameras" / self.cam_name / "faces", ignore_errors=True)shutil.rmtree(BASE_DIR / "cameras" / self.cam_name / "event_images", ignore_errors=True)def inference_loop(self):@@ -643,9 +645,13 @@ def run_search(return_q, searcher, image_text, top_k, cam_name, selected_dir):res = searcher.search(image_text, top_k, cam_name, selected_dir)return_q.put(res)-def run_clip(return_q, clip, searcher, im, top_k, cam_name, selected_dir):- embedding = clip.precompute_embedding_bs1_np(im)- res = searcher.search(None, top_k, cam_name, selected_dir, embedding)+def run_clip(return_q, clip, searcher, im, top_k, cam_name, selected_dir, is_face):+ im = clip.preprocess_face(im) if is_face else clip.preprocess_clip(im)+ if im is not None:+ embedding = clip.precompute_face_embedding_bs1_np(im) if is_face else clip.precompute_embedding_bs1_np(im)+ res = searcher.search(None, top_k, cam_name, selected_dir, embedding, is_face)+ else:+ res = []return_q.put(res)class HLSRequestHandler(BaseHTTPRequestHandler):@@ -1045,6 +1051,7 @@ class HLSRequestHandler(BaseHTTPRequestHandler):similar_img = data.get("similar_img")start = data.get("start")count = data.get("count")+ is_face = data.get("is_face") or Falseif start is None: start, count = 0, 100uploaded_image = data.get("uploaded_image")if uploaded_image:@@ -1068,15 +1075,16 @@ class HLSRequestHandler(BaseHTTPRequestHandler):})selected_dirs.append("video")- if (image_text or similar_img) and use_clip: self.searcher._load_all_embeddings()-+ if image_text and use_clip: self.searcher._load_all_embeddings()+ if (uploaded_image or similar_img) and use_clip: self.searcher._load_all_embeddings(face=is_face)+if uploaded_image and use_clip:- results = self.server.process_with_clip_lock(run_clip, self.clip, self.searcher, uploaded_image, start+count, cam_name, selected_dir)+ results = self.server.process_with_clip_lock(run_clip, self.clip, self.searcher, uploaded_image, start+count, cam_name, selected_dir, is_face)self.send_results(results, start, count)return-+if similar_img and use_clip:- results = self.server.process_with_clip_lock(run_clip, self.clip, self.searcher, similar_img, start+count, cam_name, selected_dir)+ results = self.server.process_with_clip_lock(run_clip, self.clip, self.searcher, similar_img, start+count, cam_name, selected_dir, is_face) # todo one with aboveself.send_results(results, start, count)return@@ -1348,9 +1356,11 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):shutil.rmtree(oldest_recording)event_images_dir = largest_cam.with_name(largest_cam.name) / Path("event_images") / Path(oldest_recording.name)object_images_dir = largest_cam.with_name(largest_cam.name) / Path("objects") / Path(oldest_recording.name)+ face_images_dir = largest_cam.with_name(largest_cam.name) / Path("objects") / Path(oldest_recording.name)#dets_dir = largest_cam.with_name(largest_cam.name) / Path("dets") / Path(oldest_recording.name)if event_images_dir.exists(): shutil.rmtree(event_images_dir)if object_images_dir.exists(): shutil.rmtree(object_images_dir)+ if face_images_dir.exists(): shutil.rmtree(face_images_dir)#if dets_dir.exists(): shutil.rmtree(dets_dir)print(f"Deleted oldest recording: {oldest_recording}")diff --git a/clip.py b/clip.pyindex de63fac..8eb6681 100644--- a/clip.py+++ b/clip.py@@ -8,74 +8,55 @@ import numpy as npimport cv2import timefrom utils.helpers import send_notif, export_and_upload, BASE_DIR+from blazeface import BlazeFace+from adaface import ADAFACE+from tinygrad.nn.state import safe_save, safe_load, get_state_dict, load_state_dict-class Model: pass+class Blank: pass--class CachedCLIPSearch:- def __init__(self, model_name="ViT-L-14", pretrained_name="laion2b_s32b_b82k", prewarm=True):- self.image_embeddings = {}- self.image_paths = {}-- self.model = Model()- device = Device.DEFAULT- # convert- weights = nn.state.safe_load(fetch("http://huggingface.co/laion/CLIP-ViT-L-14-laion2B-s32B-b82K/resolve/main/open_clip_pytorch_model.safetensors"))-- self.model.visual_conv1 = nn.Conv2d(3, 1024, (14, 14), (14, 14), (0, 0), (1, 1), 1, bias=False)- self.model.visual_conv1.weight = weights["visual.conv1.weight"].to(device)-- self.model.class_embedding = weights["visual.class_embedding"].to(device)- self.model.positional_embedding = weights["visual.positional_embedding"].to(device)-+class OpenCLIP:+ def __init__(self):+ self.visual_conv1 = nn.Conv2d(3, 1024, (14, 14), (14, 14), (0, 0), (1, 1), 1, bias=False)+ self.class_embedding = Tensor.empty(1024)+ self.positional_embedding = Tensor.empty(257, 1024)- self.model.ln_pre = nn.LayerNorm(1024)- self.model.ln_pre.weight = weights["visual.ln_pre.weight"].to(device)- self.model.ln_pre.bias = weights["visual.ln_pre.bias"].to(device)--- self.model.ln_post = nn.LayerNorm(1024)- self.model.ln_post.weight = weights["visual.ln_post.weight"].to(device)- self.model.ln_post.bias = weights["visual.ln_post.bias"].to(device)-- self.model.proj = weights["visual.proj"].to(device)-- self.model.resblocks = []+ self.ln_pre = nn.LayerNorm(1024)+ self.ln_post = nn.LayerNorm(1024)+ self.proj = Tensor.empty(1024, 768)+ self.resblocks = []for i in range(24):- resblock = Model()-+ resblock = Blank()resblock.ln_1 = nn.LayerNorm(1024, 1e-05, elementwise_affine=True)- resblock.ln_1.weight = weights[f"visual.transformer.resblocks.{i}.ln_1.weight"].to(device)- resblock.ln_1.bias = weights[f"visual.transformer.resblocks.{i}.ln_1.bias"].to(device)-resblock.ln_2 = nn.LayerNorm(1024, 1e-05, elementwise_affine=True)- resblock.ln_2.weight = weights[f"visual.transformer.resblocks.{i}.ln_2.weight"].to(device)- resblock.ln_2.bias = weights[f"visual.transformer.resblocks.{i}.ln_2.bias"].to(device)-- resblock.in_proj_weight = weights[f"visual.transformer.resblocks.{i}.attn.in_proj_weight"].to(device)- resblock.in_proj_bias = weights[f"visual.transformer.resblocks.{i}.attn.in_proj_bias"].to(device)-- resblock.out_proj_weight = weights[f"visual.transformer.resblocks.{i}.attn.out_proj.weight"].to(device)- resblock.out_proj_bias = weights[f"visual.transformer.resblocks.{i}.attn.out_proj.bias"].to(device)--- resblock.mlp_c_fc = nn.Linear(4096, 1024)- resblock.mlp_c_fc.weight = weights[f"visual.transformer.resblocks.{i}.mlp.c_fc.weight"].to(device)- resblock.mlp_c_fc.bias = weights[f"visual.transformer.resblocks.{i}.mlp.c_fc.bias"].to(device)-- resblock.mlp_c_proj = nn.Linear(1024, 4096)- resblock.mlp_c_proj.weight = weights[f"visual.transformer.resblocks.{i}.mlp.c_proj.weight"].to(device)- resblock.mlp_c_proj.bias = weights[f"visual.transformer.resblocks.{i}.mlp.c_proj.bias"].to(device)+ resblock.in_proj_weight = Tensor.empty(3072, 1024)+ resblock.in_proj_bias = Tensor.empty(3072)+ resblock.out_proj_weight = Tensor.empty(1024, 1024)+ resblock.out_proj_bias = Tensor.empty(1024)+ resblock.mlp_c_fc = nn.Linear(1024, 4096)+ resblock.mlp_c_proj = nn.Linear(4096, 1024)+ self.resblocks.append(resblock)++ state_dict = safe_load(fetch("https://huggingface.co/roryclear/CLIP-ViT-L-14-laion2B-s32B-b82K/resolve/main/CLIP-ViT-L-14-laion2B-s32B-b82K.safetensors"))+ load_state_dict(self, state_dict)- self.model.resblocks.append(resblock)+class CachedCLIPSearch:+ def __init__(self, prewarm=True):+ self.image_embeddings = {}+ self.image_paths = {}++ self.model = OpenCLIP()- weights = None+ self.blazeface = BlazeFace()+ self.adaface = ADAFACE()- # for BEAM+ # prewarmif prewarm:- precompute_embeddings_jit(self.model, Tensor.rand((1, 3, 224, 224), dtype=dtypes.float32))- precompute_embeddings_jit(self.model, Tensor.rand((16, 3, 224, 224), dtype=dtypes.float32))+ blazeface_jit(self.blazeface, Tensor.rand((640, 640, 3)).cast(dtype=dtypes.uchar))+ adaface_jit(self.adaface, Tensor.rand((112, 112, 3)).cast(dtype=dtypes.uchar))+ precompute_embeddings_jit(self.model, Tensor.rand((1, 3, 224, 224), dtype=dtypes.float32))+ precompute_embeddings_jit(self.model, Tensor.rand((16, 3, 224, 224), dtype=dtypes.float32))+def find_object_folders(self, base_path="data/cameras"):object_folders = []@@ -92,14 +73,8 @@ class CachedCLIPSearch:return object_folders# db for progressdef precompute_embeddings(self, folder_path, batch_size=16, vod=False, database=None, cam_name=None, userID=None, key=None):- cache_file = os.path.join(folder_path, "embeddings.pkl")- folder_embeddings = {}- folder_paths = {}- if os.path.exists(cache_file):- with open(cache_file, "rb") as f:- cache = pickle.load(f)- folder_embeddings = cache.get("embeddings", {})- folder_paths = cache.get("paths", {})+ folder_embeddings, folder_paths = get_embeddings(folder_path, "embeddings.pkl")+ folder_embeddings_face, folder_paths_face = get_embeddings(folder_path.replace("objects", "faces"), "embeddings.pkl")current_images = {os.path.join(folder_path, f)@@ -115,12 +90,16 @@ class CachedCLIPSearch:folder_embeddings.pop(img, None)folder_paths.pop(img, None)- if not new_images:- os.makedirs(os.path.dirname(cache_file), exist_ok=True)- with open(cache_file, "wb") as f:- pickle.dump({"embeddings": folder_embeddings, "paths": folder_paths}, f)- return [], []+ if not new_images: return [], []new_image_list = list(new_images)+ ''' todo add back for faces+ self.process_faces(new_image_list)+ face_paths, face_embeddings = self.process_faces(new_image_list)+ for path, emb in zip(face_paths, face_embeddings):+ folder_embeddings_face[path] = emb+ folder_paths_face[path] = path+ save_embeddings(folder_path.replace("objects", "faces"), "embeddings.pkl", folder_embeddings_face, folder_paths_face)+ '''emb_ret = []path_ret = []for i in range(0, len(new_image_list), batch_size):@@ -142,8 +121,8 @@ class CachedCLIPSearch:else:embeddings = []for j in range(len(batch_np)):- emb = precompute_embedding_jit_bs1(self.model, Tensor(batch_np[j:j+1])).numpy()- embeddings.append(emb)+ emb = precompute_embedding_jit_bs1(self.model, Tensor(batch_np[j:j+1])).numpy()+ embeddings.append(emb)emb_ret.extend(embeddings)path_ret.extend(batch_paths)for path, embedding in zip(batch_paths, embeddings):@@ -151,27 +130,113 @@ class CachedCLIPSearch:folder_paths[path] = pathprint(f"Processed {min(i + batch_size, len(new_image_list))}/{len(new_image_list)} new images...")if vod: database.run_put("analysis_prog", cam_name, {"Processing":(min(i + batch_size, len(new_image_list))/len(new_image_list))*100})- os.makedirs(os.path.dirname(cache_file), exist_ok=True)- with open(cache_file, "wb") as f: pickle.dump({"embeddings": folder_embeddings, "paths": folder_paths}, f)+ save_embeddings(folder_path, "embeddings.pkl", folder_embeddings, folder_paths)return emb_ret, path_ret++ def precompute_embedding_bs1_np(self, img): return precompute_embedding_jit_bs1(self.model, Tensor(img)).numpy() # todo remove++ def precompute_face_embedding_bs1_np(self, img): return adaface_jit(self.adaface, Tensor(img))[0].numpy() # todo remove++ def preprocess_clip(self, img):+ if type(img) == bytes:+ img = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_COLOR)+ else:+ img = f"data/cameras{img}"+ img = cv2.imread(img)+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)+ return [preprocess(img)]- def precompute_embedding_bs1_np(self, img):- if type(img) == bytes: # todo, another level up?+ def preprocess_face(self, img):+ if type(img) == bytes: # todo dup of aboveimg = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_COLOR)else:img = f"data/cameras{img}"img = cv2.imread(img)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)- img = [preprocess(img)]- ret = precompute_embedding_jit_bs1(self.model, Tensor(img)).numpy()- return ret-+ if img.shape != (112, 112, 3): img = self.img_to_face(img)+ return img++ def img_to_face(self, orig):+ h, w = orig.shape[:2]+ scale = 640 / max(h, w)+ resized = cv2.resize(orig, (int(w*scale), int(h*scale)))+ delta_w, delta_h = 640 - resized.shape[1], 640 - resized.shape[0]+ top, bottom = delta_h // 2, delta_h - (delta_h // 2)+ left, right = delta_w // 2, delta_w - (delta_w // 2)+ orig = cv2.copyMakeBorder(resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0,0,0])+ detections = blazeface_jit(self.blazeface, Tensor(orig)).numpy()+ detections = detections[detections[:, 4] != 0]+ # one face per person for now+ if detections.shape[0] > 0:+ x1, y1, x2, y2 = detections[0][:4]+ if (x2 - x1) < 60: return # min size of 60 for now?+ # 1.5x bigger+ cx = (x1 + x2) / 2+ cy = (y1 + y2) / 2+ w = x2 - x1+ h = y2 - y1+ scale = 1.5+ new_w = w * scale+ new_h = h * scale+ new_x1 = int(cx - new_w / 2)+ new_y1 = int(cy - new_h / 2)+ new_x2 = int(cx + new_w / 2)+ new_y2 = int(cy + new_h / 2)+ H, W = orig.shape[:2]+ new_x1 = max(0, new_x1)+ new_y1 = max(0, new_y1)+ new_x2 = min(W, new_x2)+ new_y2 = min(H, new_y2)++ cropped = orig[int(new_x1):int(new_x2), int(new_y1):int(new_y2)]+ face_img = cv2.resize(cropped, (112, 112))+ face_img = cv2.cvtColor(face_img, cv2.COLOR_RGB2BGR)+ return face_img++ def process_faces(self, paths):+ ret_paths = []+ ret_embeddings = []+ for path in paths:+ if path.endswith("_0.jpg"): # person+ orig = cv2.imread(path)+ orig = cv2.cvtColor(orig, cv2.COLOR_BGR2RGB)+ face_img = self.img_to_face(orig)+ if face_img is None: continue+ cv2.imwrite(path.replace("objects","faces"), face_img)+ embeddings = adaface_jit(self.adaface, Tensor(face_img))[0].numpy()+ ret_embeddings.append(embeddings)+ ret_paths.append(path)++ return ret_paths, ret_embeddings++def get_embeddings(path, filename):+ cache_file = os.path.join(path, filename)+ folder_embeddings = {}+ folder_paths = {}+ if os.path.exists(cache_file):+ with open(cache_file, "rb") as f:+ cache = pickle.load(f)+ folder_embeddings = cache.get("embeddings", {})+ folder_paths = cache.get("paths", {})+ return folder_embeddings, folder_paths++def save_embeddings(folder_path, file_name, folder_embeddings, folder_paths):+ cache_file = os.path.join(folder_path, file_name)+ os.makedirs(os.path.dirname(cache_file), exist_ok=True)+ with open(cache_file, "wb") as f: pickle.dump({"embeddings": folder_embeddings, "paths": folder_paths}, f)+@TinyJitdef precompute_embeddings_jit(model, x): return precompute_embedding(model, x)@TinyJitdef precompute_embedding_jit_bs1(model, x): return precompute_embedding(model, x)+@TinyJit+def blazeface_jit(model, x): return model(x)++@TinyJit+def adaface_jit(model, x): return model(x)+def precompute_embedding(model, x):x = model.visual_conv1(x)x = x.reshape(x.shape[0], x.shape[1], -1)diff --git a/clip_search.py b/clip_search.pyindex d1ba6a2..da0cf88 100644--- a/clip_search.py+++ b/clip_search.py@@ -6,74 +6,42 @@ from clearcam import event_img_infofrom utils.clip_tokenizer import SimpleTokenizerimport numpy as npimport math+from tinygrad.nn.state import safe_save, safe_load, get_state_dict, load_state_dict-class Model:- pass+class Blank: passclass CLIPSearch:def __init__(self, base_path="data/cameras"):self.base_path = base_pathself.image_embeddings = {}+ self.face_embeddings = {}self.image_paths = {}+ self.face_paths = {}self.tokenizer = SimpleTokenizer()+ self.text_projection = Tensor.empty(768, 768)+ self.positional_embedding = Tensor.empty(77, 768)+ self.token_embedding = nn.Embedding(49408, 768)- device = Device.DEFAULT--- self.model = Model()-- weights = nn.state.safe_load(fetch("http://huggingface.co/laion/CLIP-ViT-L-14-laion2B-s32B-b82K/resolve/main/open_clip_pytorch_model.safetensors"))-- self.model.text_projection = weights["text_projection"].to(device)- self.model.positional_embedding = weights["positional_embedding"].to(device)-- self.model.token_embedding = nn.Embedding(49408, 768) # todo unhardcode- self.model.token_embedding.weight = weights["token_embedding.weight"].to(device)-- self.model.ln_final = nn.LayerNorm(768, eps=1e-5, elementwise_affine=True)- self.model.ln_final.weight = weights["ln_final.weight"].to(device)- self.model.ln_final.bias = weights["ln_final.bias"].to(device)-- self.model.attn_mask = Tensor.ones(77, 77).tril().where(0.0, -math.inf).cast("float32")- self.model.resblocks = []+ self.ln_final = nn.LayerNorm(768, eps=1e-5, elementwise_affine=True)+ self.attn_mask = Tensor.ones(77, 77).tril().where(0.0, -math.inf).cast("float32")+ self.resblocks = []for i in range(12):- resblock = Model()- layernorm = nn.LayerNorm(768, 1e-5, elementwise_affine=True)- layernorm.weight = weights[f"transformer.resblocks.{i}.ln_1.weight"].to(device)- layernorm.bias = weights[f"transformer.resblocks.{i}.ln_1.bias"].to(device)- resblock.ln_1 = layernorm-- layernorm = nn.LayerNorm(768, 1e-5, elementwise_affine=True)- layernorm.weight = weights[f"transformer.resblocks.{i}.ln_2.weight"].to(device)- layernorm.bias = weights[f"transformer.resblocks.{i}.ln_2.bias"].to(device)- resblock.ln_2 = layernorm-- weight = weights[f"transformer.resblocks.{i}.attn.out_proj.weight"].to(device)- resblock.attn_out_proj_weight = weight-- bias = weights[f"transformer.resblocks.{i}.attn.out_proj.bias"].to(device)- resblock.attn_out_proj_bias = bias-- mlpcfc = nn.Linear(3072, 768)- mlpcfc.weight = weights[f"transformer.resblocks.{i}.mlp.c_fc.weight"].to(device)- mlpcfc.bias = weights[f"transformer.resblocks.{i}.mlp.c_fc.bias"].to(device)- resblock.mlp_c_fc = mlpcfc+ resblock = Blank()+ resblock.ln_1 = nn.LayerNorm(768, 1e-5, elementwise_affine=True)+ resblock.ln_2 = nn.LayerNorm(768, 1e-5, elementwise_affine=True)+ resblock.attn_out_proj_weight = Tensor.empty(768, 768)+ resblock.attn_out_proj_bias = Tensor.empty(768)+ resblock.mlp_c_fc = nn.Linear(768, 3072)+ resblock.mlp_c_proj = nn.Linear(3072, 768)+ resblock.in_proj_weight = Tensor.empty(2304, 768)+ resblock.in_proj_bias = Tensor.empty(2304)+ self.resblocks.append(resblock)- mlpcp = nn.Linear(768, 3072)- mlpcp.weight = weights[f"transformer.resblocks.{i}.mlp.c_proj.weight"].to(device)- mlpcp.bias = weights[f"transformer.resblocks.{i}.mlp.c_proj.bias"].to(device)- resblock.mlp_c_proj = mlpcp+ state_dict = safe_load(fetch("https://huggingface.co/roryclear/CLIP-ViT-L-14-laion2B-s32B-b82K/resolve/main/CLIP-ViT-L-14-laion2B-s32B-b82K_2.safetensors"))+ load_state_dict(self, state_dict)- weight = weights[f"transformer.resblocks.{i}.attn.in_proj_weight"].to(device)- resblock.in_proj_weight = weight- bias = weights[f"transformer.resblocks.{i}.attn.in_proj_bias"].to(device)- resblock.in_proj_bias = bias-- self.model.resblocks.append(resblock)-- weights = Nonedef _load_single_embeddings_file(self, cache_file):try:@@ -94,35 +62,42 @@ class CLIPSearch:print(f"Error loading {cache_file}: {e}")return 0- def _load_all_embeddings(self):+ def _load_all_embeddings(self, face=False):total_loaded = 0valid_paths = set()- if not os.path.exists(self.base_path): return- for camera_folder in os.listdir(self.base_path):- camera_path = os.path.join(self.base_path, camera_folder)- if not os.path.isdir(camera_path): continue-- objects_path = os.path.join(camera_path, "objects")- if not os.path.isdir(objects_path): continue- for date_folder in os.listdir(objects_path):- date_path = os.path.join(objects_path, date_folder)- if not os.path.isdir(date_path): continue- cache_file = os.path.join(date_path, "embeddings.pkl")- if not os.path.exists(cache_file): continue- with open(cache_file, "rb") as f: cache = pickle.load(f)- folder_embeddings = cache.get("embeddings", {})- folder_paths = cache.get("paths", {})- valid_paths.update(folder_embeddings.keys())- self.image_embeddings.update(folder_embeddings)- self.image_paths.update(folder_paths)- total_loaded += len(folder_embeddings)+ cache_filename = "embeddings.pkl"+ target_embeddings = self.face_embeddings if face else self.image_embeddings+ target_paths = self.face_paths if face else self.image_paths- stale_keys = set(self.image_embeddings.keys()) - valid_paths+ for camera_folder in os.listdir(self.base_path):+ camera_path = os.path.join(self.base_path, camera_folder)+ if not os.path.isdir(camera_path): continue+ objects_path = os.path.join(camera_path, "faces" if face else "objects")+ if not os.path.isdir(objects_path): continue+ for date_folder in os.listdir(objects_path):+ date_path = os.path.join(objects_path, date_folder)+ if not os.path.isdir(date_path): continue+ cache_file = os.path.join(date_path, cache_filename)+ if not os.path.exists(cache_file): continue+ with open(cache_file, "rb") as f:+ cache = pickle.load(f)+ folder_embeddings = cache.get("embeddings", {})+ folder_paths = cache.get("paths", {})+ valid_paths.update(folder_embeddings.keys())+ target_embeddings.update(folder_embeddings)+ target_paths.update(folder_paths)+ total_loaded += len(folder_embeddings)+ stale_keys = set(target_embeddings.keys()) - valid_pathsfor k in stale_keys:- del self.image_embeddings[k]- self.image_paths.pop(k, None)+ del target_embeddings[k]+ target_paths.pop(k, None)++ if face:+ self.face_embeddings = target_embeddings+ else:+ self.image_embeddings = target_embeddings- print(f"\nTotal images loaded: {total_loaded}")+ print(f"\nTotal {'face' if face else 'image'} embeddings loaded: {total_loaded}")def _encode_text(self, query, realize=False):tokens = [49406]@@ -130,19 +105,20 @@ class CLIPSearch:tokens.append(49407)if len(tokens) < 77: tokens += [0] * (77 - len(tokens))tokens = Tensor([tokens])- text_emb = encode_text(self.model, tokens)+ text_emb = encode_text(self, tokens)if realize: return text_emb.numpy()return text_emb- def search(self, query=None, top_k=10, cam_name=None, timestamp=None, text_embedding=None):- if not self.image_embeddings:+ def search(self, query=None, top_k=10, cam_name=None, timestamp=None, text_embedding=None, is_face=False):+ embeddings = self.face_embeddings if is_face else self.image_embeddings+ if not embeddings:print("No embeddings available.")return []if text_embedding is None:text_embedding = self._encode_text(query)text_embedding = text_embedding.numpy()all_similarities = []- for path, img_embedding in self.image_embeddings.items():+ for path, img_embedding in embeddings.items():normalized_path = path.replace("\\", "/")if cam_name and f"/cameras/{cam_name}/" not in normalized_path:continuediff --git a/mainview.html b/mainview.htmlindex e1b05cb..8c46e42 100644--- a/mainview.html+++ b/mainview.html@@ -1360,9 +1360,18 @@<polyline points="21 15 16 10 5 21"></polyline></svg></label>+ <!-- todo add back for face+ <label for="faceUpload" style="cursor: pointer; padding: 6px 12px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); display: flex; align-items: center; justify-content: center;" title="Search by face">+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">+ <circle cx="12" cy="8" r="4"></circle>+ <path d="M6 20c0-4 3-6 6-6s6 2 6 6"></path>+ </svg>+ </label>+ -->+ <input type="file" id="faceUpload" accept="image/*" style="display: none;"><span class="tooltip"><span class="tooltip-icon">?</span>- <span class="tooltiptext">Use an image to find similar objects in your footage.</span>+ <span class="tooltiptext">Upload an image to find similar objects in your footage.</span></span><input type="file" id="imageUpload" accept="image/*" style="display: none;"></div>@@ -1603,7 +1612,7 @@<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script><script>-+ let is_face = false;let autoRefreshInterval = null;let dontRefresh = false;@@ -3020,32 +3029,41 @@loadEventImages(false);}- document.getElementById('imageUpload').addEventListener('change', function(event) {+ function handleImageUpload(event, face=false) {+ is_face = faceconst file = event.target.files[0];if (!file) return;+const reader = new FileReader();reader.onload = function(e) {const fullDataUrl = e.target.result;uploadedImageData = fullDataUrl.split(',')[1];-+document.getElementById('imageSearchInput').value = '';currentSimilarImage = null;+const searchText = document.getElementById('searchText');const searchSpinner = document.getElementById('searchSpinner');-+searchText.textContent = 'Searching';searchSpinner.style.display = 'block';document.getElementById('searchButton').disabled = true;-- loadEventImages(false).finally(() => {++ loadEventImages(false, is_face).finally(() => {searchText.textContent = 'Search';searchSpinner.style.display = 'none';document.getElementById('searchButton').disabled = false;});};-+reader.readAsDataURL(file);- });+ }++ document.getElementById('imageUpload')+ .addEventListener('change', (e) => handleImageUpload(e, face=false));++ document.getElementById('faceUpload')+ .addEventListener('change', (e) => handleImageUpload(e, face=true));document.getElementById('imageSearchInput').addEventListener('keypress', function(event) {if (event.key === 'Enter') {@@ -3061,7 +3079,9 @@let previousEventImages = null;- async function loadEventImages(append = false) {+ async function loadEventImages(append=false, face=null) {+ if(face != null) is_face = face;+ dontRefresh = true;if (!append) {eventStart = 0;hasMoreEvents = true;@@ -3073,7 +3093,8 @@name_contains: alertsOnlyFilter ? "_notif" : null,image_text: null,similar_img: null,- uploaded_image: null+ uploaded_image: null,+ is_face: false, // todo use is_face when ready};payload.start = eventStart;payload.count = EVENT_PAGE_SIZE;@@ -3084,9 +3105,9 @@payload.similar_img = `/${currentSimilarImage}`;currentSimilarImage = null;} else if (currentImageSearchText) {+ is_face = false;payload.image_text = currentImageSearchText;}-const res = await fetch("/event_thumbs", {method: "POST",headers: {@@ -3188,7 +3209,6 @@container.innerHTML ='<p style="text-align:center; color:#666; width:100%;">No events detected yet.</p>';}-} catch (err) {console.error("Failed to load event images:", err);document.getElementById("eventImagesContainer").innerHTML =@@ -3309,7 +3329,7 @@currentSimilarImage = match[1];document.getElementById('imageSearchInput').value = '';- loadEventImages(false).finally(() => {+ loadEventImages(false, is_face).finally(() => {searchText.textContent = 'Search';searchSpinner.style.display = 'none';searchButton.disabled = false;diff --git a/test/test_clip.py b/test/test_clip.pyindex 9ca04ac..80eeba5 100644--- a/test/test_clip.py+++ b/test/test_clip.py@@ -5,7 +5,7 @@ import osdef setup_clip_test():if os.path.exists("test/clip_images/embeddings.pkl"): os.remove("test/clip_images/embeddings.pkl")- scanner = CachedCLIPSearch()+ scanner = CachedCLIPSearch(prewarm=False)scanner.precompute_embeddings("test/clip_images")def test_clip_search():