Add object detection, tracking, mobile notifications, and search to any security camera.
no extra libs for clip
rorycleard4b54f9a26ae
diff --git a/clip.py b/clip.pyindex 5441936..76b262c 100644--- a/clip.py+++ b/clip.py@@ -1,15 +1,15 @@import torch-from PIL import Imageimport open_clipimport osimport pickle-import timefrom datetime import datetime+import cv2+import numpy as npclass CachedCLIPSearch:def __init__(self, model_name="ViT-L-14", pretrained_name="laion2b_s32b_b82k"):print(f"Loading OpenCLIP model: {model_name} ({pretrained_name})")- self.model, _, self.preprocess = open_clip.create_model_and_transforms(+ self.model, _, _ = open_clip.create_model_and_transforms(model_name,pretrained=pretrained_name)@@ -79,23 +79,25 @@ class CachedCLIPSearch:for i in range(0, len(new_image_list), batch_size):batch_paths = new_image_list[i:i + batch_size]- batch_images = []+ batch_np_images = []for img_path in batch_paths:try:- with Image.open(img_path) as img:- if img.mode != "RGB":- img = img.convert("RGB")- batch_images.append(img.copy())+ img = cv2.imread(img_path)+ if img is None:+ print(f"Failed to load {img_path}")+ continue++ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)+ batch_np_images.append(img)+except Exception as e:print(f"Error loading {img_path}: {e}")continue- if batch_images:+ if batch_np_images:with torch.no_grad():- batch_tensors = torch.stack(- [self.preprocess(img) for img in batch_images]- )+ batch_tensors = torch.stack([preprocess(img) for img in batch_np_images])embeddings = self.model.encode_image(batch_tensors)embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True)@@ -105,9 +107,6 @@ class CachedCLIPSearch:print(f"Processed {min(i + batch_size, len(new_image_list))}/{len(new_image_list)} new images...")- for img in batch_images:- img.close()-# Save updated cacheos.makedirs(os.path.dirname(cache_file), exist_ok=True)with open(cache_file, "wb") as f:@@ -115,6 +114,15 @@ class CachedCLIPSearch:print(f"{datetime.now()}: Updated cache for {folder_path}. Total images stored: {len(folder_embeddings)}")++def preprocess(image):+ image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_CUBIC)+ image = image.astype(np.float32) / 255.0+ image = (image - 0.5) / 0.5+ image = np.transpose(image, (0, 1, 2))+ tensor = torch.from_numpy(image).permute(2, 0, 1) # CHW+ return tensor+'''if __name__ == "__main__":searcher = CachedCLIPSearch(diff --git a/clip_requirements.txt b/clip_requirements.txtdeleted file mode 100644index 7b319ce..0000000--- a/clip_requirements.txt+++ /dev/null@@ -1,15 +0,0 @@-filelock==3.20.0-fsspec==2025.10.0-Jinja2==3.1.6-MarkupSafe==3.0.3-mpmath==1.3.0-networkx==3.6-numpy==2.0.0-opencv-python-headless==4.10.0.84-pillow==12.0.0-scipy==1.14.1-sympy==1.14.0-tinygrad @ git+https://github.com/roryclear/tinygrad.git@2b13c3de65fb00f28597eae9266d512792f74f44-torch==2.9.1-torchvision==0.24.1-typing_extensions==4.15.0diff --git a/test/test_clip.py b/test/test_clip.pyindex e3bf2e6..8dbcba7 100644--- a/test/test_clip.py+++ b/test/test_clip.py@@ -14,13 +14,13 @@ def test_clip_search():searcher = tiny_ClipSearch()searcher._load_single_embeddings_file("test/clip_images/embeddings.pkl")res = searcher.search("ferrari f40")- np.testing.assert_allclose(res[0][1], 0.33788394927978516, rtol=1e-03)- np.testing.assert_allclose(res[1][1], 0.07776700705289841, rtol=1e-02) # careful now+ np.testing.assert_allclose(res[0][1], 0.3566271960735321, rtol=1e-03)+ np.testing.assert_allclose(res[1][1], 0.0718243420124054, rtol=1e-02) # careful nowassert res[0][0] == "test/clip_images/f40.jpg"assert res[1][0] == "test/clip_images/micra.jpg"res = searcher.search("nissan micra")- np.testing.assert_allclose(res[0][1], 0.3227463960647583, rtol=1e-03)- np.testing.assert_allclose(res[1][1], 0.04420311748981476, rtol=1e-02)+ np.testing.assert_allclose(res[0][1], 0.3218580484390259, rtol=1e-03)+ np.testing.assert_allclose(res[1][1], 0.07153752446174622, rtol=1e-02)assert res[1][0] == "test/clip_images/f40.jpg"assert res[0][0] == "test/clip_images/micra.jpg"@@ -28,13 +28,13 @@ def test_clip_search_jit():searcher = tiny_ClipSearch()searcher._load_single_embeddings_file("test/clip_images/embeddings.pkl")for _ in range(5): res = searcher.search("ferrari f40")- np.testing.assert_allclose(res[0][1], 0.33788394927978516, rtol=1e-03)- np.testing.assert_allclose(res[1][1], 0.07776700705289841, rtol=1e-02) # careful now+ np.testing.assert_allclose(res[0][1], 0.3566271960735321, rtol=1e-03)+ np.testing.assert_allclose(res[1][1], 0.0718243420124054, rtol=1e-02) # careful nowassert res[0][0] == "test/clip_images/f40.jpg"assert res[1][0] == "test/clip_images/micra.jpg"for _ in range(5): res = searcher.search("nissan micra")- np.testing.assert_allclose(res[0][1], 0.3227463960647583, rtol=1e-03)- np.testing.assert_allclose(res[1][1], 0.04420311748981476, rtol=1e-02)+ np.testing.assert_allclose(res[0][1], 0.3218580484390259, rtol=1e-03)+ np.testing.assert_allclose(res[1][1], 0.07153752446174622, rtol=1e-02)assert res[1][0] == "test/clip_images/f40.jpg"assert res[0][0] == "test/clip_images/micra.jpg"diff --git a/tiny_clip.py b/tiny_clip.pyindex c1c3ecd..fb05c03 100644--- a/tiny_clip.py+++ b/tiny_clip.py@@ -1,12 +1,11 @@-from PIL import Imageimport osimport picklefrom datetime import datetimefrom tinygrad import nn, Tensor, TinyJit, Devicefrom tinygrad.helpers import fetch-from torchvision.transforms import functional as Ffrom tinygrad.dtype import dtypesimport numpy as np+import cv2class TinyModel: pass@@ -132,32 +131,28 @@ class CachedCLIPSearch:new_image_list = list(new_images)+for i in range(0, len(new_image_list), batch_size):batch_paths = new_image_list[i:i + batch_size]- batch_images = []+ batch_np = []for img_path in batch_paths:- try:- with Image.open(img_path) as img:- if img.mode != "RGB":- img = img.convert("RGB")- batch_images.append(img.copy())- except Exception as e:- print(f"Error loading {img_path}: {e}")- continue-- batch_tensors = np.stack([inline_preprocess(img) for img in batch_images])- if len(batch_images) == batch_size:- x = Tensor(batch_tensors)- embeddings = tiny_precompute_embeddings(self.tiny_model, x)- embeddings = embeddings.numpy()+ img = cv2.imread(img_path)+ if img is None: continue+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)+ img = preprocess(img)+ batch_np.append(img)++ if not batch_np: continue+ batch_np = np.stack(batch_np)++ if len(batch_np) == batch_size:+ embeddings = tiny_precompute_embeddings(self.tiny_model, Tensor(batch_np)).numpy()else:embeddings = []- for i in range(len(batch_images)): # one by one if not batch_size- single_x = Tensor(batch_tensors[i:i+1])- single_embedding = tiny_precompute_embedding(self.tiny_model, single_x)- single_embedding_torch = single_embedding.numpy()- embeddings.append(single_embedding_torch)+ for j in range(len(batch_np)):+ emb = tiny_precompute_embedding(self.tiny_model, Tensor(batch_np[j:j+1])).numpy()+ embeddings.append(emb)for path, embedding in zip(batch_paths, embeddings):folder_embeddings[path] = embedding@@ -165,9 +160,6 @@ class CachedCLIPSearch:print(f"Processed {min(i + batch_size, len(new_image_list))}/{len(new_image_list)} new images...")- for img in batch_images:- img.close()-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)@@ -218,15 +210,12 @@ def tiny_precompute_embedding(tiny_model, x):embeddings = embeddings / (embeddings.pow(2).sum(axis=-1, keepdim=True).sqrt() + 1e-8)return embeddings-def inline_preprocess(image):- image = F.resize(image, size=224, interpolation=F.InterpolationMode.BICUBIC, antialias=True)- image = F.center_crop(image, output_size=(224, 224))- if image.mode != 'RGB':- image = image.convert('RGB')- image = F.to_tensor(image)- image = F.normalize(image, mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))-- return image+def preprocess(img):+ img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC)+ img = img.astype(np.float32) / 255.0+ img = (img - 0.5) / 0.5+ img = np.transpose(img, (2, 0, 1))+ return img'''if __name__ == "__main__":