Add object detection, tracking, mobile notifications, and search to any security camera.
Twoframes (#162)
Rory Clear55e71ec78ec1
diff --git a/clearcam.py b/clearcam.pyindex 9ae204a..8558229 100644--- a/clearcam.py+++ b/clearcam.py@@ -182,8 +182,7 @@ class VideoCapture:self.raw_frame = {}self.last_preds = {}- self.last_frame = {}- self.lock = {}+ self.last_frames = {}self.settings = {}self.count = {}@@ -209,7 +208,7 @@ class VideoCapture:def init_cam(self, cam_name, src):self.counter[cam_name] = RollingClassCounter(cam_name=cam_name, window_seconds=float('inf'))self.src[cam_name] = src # todo- self.last_frame[cam_name] = None+ self.last_frames[cam_name] = deque(maxlen=2)self.vod[cam_name] = src.endswith(('.mp4', '.avi', '.mov', '.mkv', '.webm'))self.frame_num[cam_name] = -1self.last_frame_num[cam_name] = -1@@ -230,8 +229,6 @@ class VideoCapture:self.alert_counters[cam_name][id] = alert_counterdatabase.run_put("alerts", cam_name, alert_counter, id=id)- self.lock[cam_name] = threading.Lock()-self.last_det[cam_name] = -1self.last_live_check[cam_name] = time.time()self.last_live_seg[cam_name] = time.time()@@ -388,13 +385,13 @@ class VideoCapture:x2_new = cx + hwy1_new = cy - hhy2_new = cy + hh- H, W = self.last_frame[cam_name].shape[:2]+ H, W = self.last_frames[cam_name][-1].shape[:2]x1_new = max(0, min(x1_new, W))x2_new = max(0, min(x2_new, W))y1_new = max(0, min(y1_new, H))y2_new = max(0, min(y2_new, H))if (y2_new - y1_new) < 100 or (x2_new - x1_new) < 100: return # too small- crop = self.last_frame[cam_name][y1_new:y2_new, x1_new:x2_new]+ crop = self.last_frames[cam_name][-1][y1_new:y2_new, x1_new:x2_new]cv2.imwrite(str(object_filename), crop)if use_clip or use_face: object_queue.append(object_filename)@@ -413,9 +410,8 @@ class VideoCapture:time.sleep(0.5)else:fail_count = 0- with self.lock[cam_name]:- self.raw_frame[cam_name] = np.frombuffer(raw_bytes, np.uint8).reshape((self.height[cam_name], self.width[cam_name], 3))- self.frame_num[cam_name] += 1+ self.raw_frame[cam_name] = np.frombuffer(raw_bytes, np.uint8).reshape((self.height[cam_name], self.width[cam_name], 3))+ self.frame_num[cam_name] += 1time.sleep(1 / 100)except Exception as e:print("Error in frame_loop:", e, cam_name)@@ -430,7 +426,7 @@ class VideoCapture:self.cap[cam_name].grab() # skip for max fpsret, frame = self.cap[cam_name].read()- self.last_frame[cam_name] = frame #todo+ self.last_frames[cam_name].append(frame)if not ret or cam_name not in database.run_get("links", None):self.running[cam_name] = Falseif "Processing" not in database.run_get("analysis_prog", cam_name): database.run_put("analysis_prog", cam_name, {"Tracking":100}) # todo stop when done?@@ -438,31 +434,28 @@ class VideoCapture:self.last_preds[cam_name], _ = self.run_inference(frame, cam_name=cam_name)database.run_put("analysis_prog", cam_name, {"Tracking":self.cap[cam_name].get(cv2.CAP_PROP_POS_FRAMES)/self.cap[cam_name].get(cv2.CAP_PROP_FRAME_COUNT)*100})else:- with self.lock[cam_name]:- frame_num = self.frame_num[cam_name]- last_frame_num = self.last_frame_num[cam_name]- if self.raw_frame[cam_name] is None: return- frame = self.raw_frame[cam_name].copy()+ frame_num = self.frame_num[cam_name]+ last_frame_num = self.last_frame_num[cam_name]+ if self.raw_frame[cam_name] is None: return+ frame = self.raw_frame[cam_name].copy()if frame_num == last_frame_num: return- if not any(counter.is_active() for _, counter in self.alert_counters[cam_name].items()): # don't run inference when no active scheds- with self.lock[cam_name]: self.last_preds[cam_name] = [] # to remove annotation when no alerts active+ # don't run inference when no active scheds+ if not any(counter.is_active() for _, counter in self.alert_counters[cam_name].items()): self.last_preds[cam_name] = [] # to remove annotation when no alerts activeelse:if not userID or alerts_on[cam_name]:preds, frame = self.run_inference(frame, cam_name=cam_name)- with self.lock[cam_name]:- self.last_preds[cam_name] = preds.copy()- self.last_frame[cam_name] = frame.numpy().copy()- self.last_frame_num[cam_name] = self.frame_num[cam_name]+ self.last_frames[cam_name].append(frame.numpy().copy())+ self.last_preds[cam_name] = preds.copy()+ self.last_frame_num[cam_name] = self.frame_num[cam_name]curr_time = time.time()fps = 1 / (curr_time - self.prev_time[cam_name])self.prev_time[cam_name] = curr_timeprint(f"\rFPS: {fps:.2f}", end="", flush=True)else:- with self.lock[cam_name]:- self.last_frame_num[cam_name] = self.frame_num[cam_name]- self.last_preds = []+ self.last_frame_num[cam_name] = self.frame_num[cam_name]+ self.last_preds = []filtered_preds = self.last_preds[cam_name]@@ -482,7 +475,7 @@ class VideoCapture:timestamp = "video" if self.vod[cam_name] else datetime.now().strftime("%Y-%m-%d")filepath = BASE_DIR / "cameras" / f"{cam_name}/event_images/{timestamp}"filepath.mkdir(parents=True, exist_ok=True)- annotated_frame = draw_predictions(self.last_frame[cam_name].copy(), filtered_preds, color_dict)+ annotated_frame = draw_predictions(self.last_frames[cam_name][-1].copy(), filtered_preds, color_dict)# todo alerts can be sent with the wrong thumbnail if two happen quickly, use mapts = int(self.cap[cam_name].get(cv2.CAP_PROP_POS_FRAMES) / self.src_fps[cam_name]) - 5 if self.vod[cam_name] else int(time.time() - self.start_time[cam_name] - 5)self.filename[cam_name] = filepath / f"{ts}_notif.jpg" if alert.is_notif else filepath / f"{ts}.jpg"@@ -494,7 +487,9 @@ class VideoCapture:title = f"Event Detected ({cam_name})"threading.Thread(target=send_notif, args=(userID,title,None), daemon=True).start()if use_qwen: # extra notif if qwen- text = qwen.generate(prompt=qwen_prompt, image=cv2.cvtColor(cv2.imread(self.filename[cam_name]), cv2.COLOR_BGR2RGB), reset=True) # must reset or run out of context+ # use frames before last, only one reset needed, must convert to RGB+ for i in range(len(self.last_frames[cam_name])-1): qwen.generate(image=cv2.cvtColor(self.last_frames[cam_name][i], cv2.COLOR_BGR2RGB), reset=True if i==0 else False)+ text = qwen.generate(prompt=qwen_prompt, image=cv2.cvtColor(cv2.imread(self.filename[cam_name]), cv2.COLOR_BGR2RGB), reset=False) # must reset or run out of contextthreading.Thread(target=send_notif, args=(userID,f"AI Summary ({cam_name}):",text), daemon=True).start()threading.Thread(target=export_and_upload, kwargs={"cam_name": cam_name, "thumbnail": self.filename[cam_name], "userID": userID, "key": key, "start": ts, "wait":True}, daemon=True).start()self.last_det[cam_name] = time.time()diff --git a/llm/qwen3vl.py b/llm/qwen3vl.pyindex 46c5eae..24ac6cf 100644--- a/llm/qwen3vl.py+++ b/llm/qwen3vl.py@@ -89,20 +89,11 @@ class SimpleTokenizer:return ([] if self.bos_id is None else [self.bos_id]) + (self.encode("<sop>") if self.preset == 'glm4' else [])def is_end(self, token_id:int) -> bool: return token_id in (self.eos_id, self.eot_id)-#https://github.com/huggingface/transformers/blob/1316cd76c0ce328228e08d55dc257484961b074c/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py#L129-def rotate_half(x):- x1 = x[..., : x.shape[-1] // 2]- x2 = x[..., x.shape[-1] // 2 :]- ret = Tensor.cat(-x2, x1, dim=-1)- return ret--def apply_rotary_pos_emb_vision(query, key, cos, sin): return (query * cos) + (rotate_half(query) * sin), (key * cos) + (rotate_half(key) * sin)-class Qwen3VL():def __init__(self, size="2B", res=(640, 640)): # (height, width) resself.res = resself.max_context = 2000- self.vis = Qwen3VLVis(size=size)+ self.vis = Qwen3VLVis(size=size, res=res)self.lang, kv = Transformer.from_gguf(fetch(f"https://huggingface.co/Qwen/Qwen3-VL-{size}-Instruct-GGUF/resolve/main/Qwen3VL-{size}-Instruct-F16.gguf"), self.max_context) # max contextself.tok = SimpleTokenizer.from_gguf_kv(kv)self.start_pos = 0@@ -117,7 +108,7 @@ class Qwen3VL():def generate(self, prompt=None, image=None, reset=False):if reset: self.start_pos = 0if image is not None:- prefill_img(vis=self.vis, lang=self.lang, image=image, start_pos=Variable("pos",0,self.max_context).bind(self.start_pos), res=self.res)+ prefill_img(vis=self.vis, lang=self.lang, image=image, start_pos=Variable("pos",0,self.max_context).bind(self.start_pos))self.start_pos += ((self.res[0] * self.res[1]) // (32*32)) + 8 # todo unhardcodeif prompt is None: returnprompt = "<|im_start|>user\n" + prompt + "<|im_end|>\n<|im_start|>assistant\n"@@ -146,10 +137,18 @@ class Qwen3VL():print("\b" * len(tok_s), end="", flush=True)print("\n")return self.tok.decode(toks_out)+#https://github.com/huggingface/transformers/blob/1316cd76c0ce328228e08d55dc257484961b074c/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py#L129+def rotate_half(x):+ x1 = x[..., : x.shape[-1] // 2]+ x2 = x[..., x.shape[-1] // 2 :]+ ret = Tensor.cat(-x2, x1, dim=-1)+ return ret++def apply_rotary_pos_emb_vision(query, key, cos, sin): return (query * cos) + (rotate_half(query) * sin), (key * cos) + (rotate_half(key) * sin)-def prefill_img(vis, lang, image, start_pos, res=(640, 640)):- if image.shape[:2] != res:- target_h, target_w = res[:2]+def prefill_img(vis, lang, image, start_pos):+ if image.shape[:2] != vis.res:+ target_h, target_w = vis.res[:2]s = min(target_w / image.shape[1], target_h / image.shape[0])r = cv2.resize(image, (int(image.shape[1] * s), int(image.shape[0] * s)))image = cv2.copyMakeBorder(r, (target_h - r.shape[0]) // 2, target_h - r.shape[0] - (target_h - r.shape[0]) // 2, (target_w - r.shape[1]) // 2, target_w - r.shape[1] - (target_w - r.shape[1]) // 2, cv2.BORDER_CONSTANT, value=0)@@ -163,12 +162,11 @@ def prefill(vis, lang, image, start_pos):image = image.interpolate(size=(height, width))resized_height, resized_width = image.shape[-2:]patches = (image - 127.5) / 127.5 # todo use mean and std- batch_size, channel = 1, 3+ channels = 3# https://github.com/huggingface/transformers/blob/4ae05b0fba41860adaaeb708774fc1f48c92c049/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py#L195grid_h, grid_w = resized_height // vis.patch_size, resized_width // vis.patch_sizepatches = patches.reshape(- batch_size,- channel,+ channels,grid_h // vis.merge_size,vis.merge_size,vis.patch_size,@@ -176,21 +174,20 @@ def prefill(vis, lang, image, start_pos):vis.merge_size,vis.patch_size,)- patches = patches.permute(0, 2, 5, 3, 6, 1, 4, 7)+ patches = patches.permute(1, 4, 2, 5, 0, 3, 6)pixel_values = (- patches.unsqueeze(6)- .expand(-1, -1, -1, -1, -1, -1, vis.merge_size, -1, -1)+ patches.unsqueeze(5)+ .expand(-1, -1, -1, -1, -1, vis.merge_size, -1, -1).reshape(- batch_size,grid_h * grid_w,- channel * vis.merge_size * vis.patch_size * vis.patch_size,+ channels * vis.merge_size * vis.patch_size * vis.patch_size,)- )[0]+ )pixel_values = pixel_values.cast(dtypes.bfloat16)# f"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>\n<|im_end|>\n" fill size of img with image token# <|im_end|>\n<|im_start|>assistant\n- num_image_tokens = int((grid_h*grid_w) / 4)+ num_image_tokens = int((grid_h*grid_w) / 4) # todo cleaninput_ids = Tensor.cat(Tensor([151644, 872, 198, 151652]), Tensor.zeros(num_image_tokens), Tensor([151653, 198, 151645, 198])).unsqueeze(0).cast(dtypes.int)image_embeds, hidden_states, deepstack_feature_lists = vis(pixel_values, [grid_h, grid_w])@@ -259,10 +256,13 @@ def get_vision_position_ids(h: int, w:int, merge_size: int):return pos_idsclass Qwen3VLVis():- def __init__(self, size="2B"):+ def __init__(self, size="2B", res=[640, 640]):+ self.res = res+ self.toks_per_img = (self.res[0] * self.res[1]) // (32*32) # 32x32 tokens per pixel https://www.alibabacloud.com/help/en/model-studio/visionkv, state_dict = gguf_load(fetch(f"https://huggingface.co/Qwen/Qwen3-VL-{size}-Instruct-GGUF/resolve/main/mmproj-Qwen3VL-{size}-Instruct-F16.gguf"))self.merge_size = kv["clip.vision.spatial_merge_size"]self.patch_size = kv["clip.vision.patch_size"]+ self.feed_forward_length = kv["clip.vision.feed_forward_length"]self.v = Qwen3VisBlocks(kv=kv, weights=state_dict)self.mm = [nn.Linear(*state_dict["mm.0.weight"].shape[::-1], bias=True), None, nn.Linear(*state_dict["mm.2.weight"].shape[::-1], bias=True)]state_dict["v.patch_embd.weight1"] = state_dict["v.patch_embd.weight.1"]@@ -296,7 +296,7 @@ class Qwen3VLVis():if i in self.v.deepstack_idx: deepstack_feature_lists.append(self.v.deepstack[i](hidden_states))image_embeds = self.v.post_ln(hidden_states)- image_embeds = image_embeds.view(-1, 4096)+ image_embeds = image_embeds.view(-1, self.feed_forward_length)image_embeds = self.mm[0](image_embeds)image_embeds = Tensor.gelu(image_embeds)image_embeds = self.mm[2](image_embeds)