Skip to content

Add object detection, tracking, mobile notifications, and search to any security camera.

Search with file3 (#116)

Rory Cleard1b7dd3e810c
diff --git a/clearcam.py b/clearcam.py
index bb3d81f..6f72430 100644
--- a/clearcam.py
+++ b/clearcam.py
@@ -25,6 +25,7 @@ import zlib
from utils.db import db
import multiprocessing
import re
+import base64
def resize(img, new_size):
img = img.permute(2,0,1)
@@ -771,6 +772,21 @@ class HLSRequestHandler(BaseHTTPRequestHandler):
self.show_dets = None
super().__init__(*args, **kwargs)
+
+ def process_with_clip_lock(self, func, *args):
+ if not self.server.clip_lock.acquire(timeout=30):
+ self.send_error(429, "CLIP processor busy, try again later")
+ return None
+ try:
+ return_q = multiprocessing.Queue()
+ p = multiprocessing.Process(target=func, args=(return_q, *args))
+ p.start()
+ results = return_q.get(timeout=3600)
+ p.join()
+ return results
+ finally:
+ self.server.clip_lock.release()
+
def send_results(self, results):
image_data = []
for path_str, score in results:
@@ -1116,6 +1132,10 @@ class HLSRequestHandler(BaseHTTPRequestHandler):
name_contains = data.get("name_contains")
image_text = data.get("image_text")
similar_img = data.get("similar_img")
+ uploaded_image = data.get("uploaded_image")
+ if uploaded_image:
+ if ',' in uploaded_image: uploaded_image = uploaded_image.split(',')[1]
+ uploaded_image = base64.b64decode(uploaded_image)
if cam_name:
camera_dirs = [self.base_dir / cam_name]
@@ -1135,21 +1155,18 @@ class HLSRequestHandler(BaseHTTPRequestHandler):
if (image_text or similar_img) and use_clip: self.searcher._load_all_embeddings()
+ if uploaded_image and use_clip:
+ results = self.process_with_clip_lock(run_clip, self.clip, self.searcher, uploaded_image, 100, cam_name, selected_dir)
+ self.send_results(results)
+ return
+
if similar_img and use_clip:
- return_q = multiprocessing.Queue()
- p = multiprocessing.Process(target=run_clip, args=(return_q, self.clip, self.searcher, similar_img, 100, cam_name, selected_dir,))
- p.start()
- results = return_q.get(timeout=3600)
- p.join()
+ results = self.process_with_clip_lock(run_clip, self.clip, self.searcher, similar_img, 100, cam_name, selected_dir)
self.send_results(results)
return
if image_text and use_clip:
- return_q = multiprocessing.Queue()
- p = multiprocessing.Process(target=run_search, args=(return_q, self.searcher, image_text, 100, cam_name, selected_dir,))
- p.start()
- results = return_q.get(timeout=3600)
- p.join()
+ results = self.process_with_clip_lock(run_search, self.searcher, image_text, 100, cam_name, selected_dir)
self.send_results(results)
return
@@ -1450,6 +1467,7 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
self.clip_stop_event = threading.Event()
self.clip_thread = None
self._setup_cleanup_and_clip_thread()
+ self.clip_lock = threading.Lock()
def finish_request(self, request, client_address):
self.RequestHandlerClass(request, client_address, self, clip_instance=self.clip, searcher_instance=self.searcher)
diff --git a/clip.py b/clip.py
index cbfb471..41df563 100644
--- a/clip.py
+++ b/clip.py
@@ -168,8 +168,11 @@ class CachedCLIPSearch:
print(f"{datetime.now()}: Updated cache for {folder_path}. Total images stored: {len(folder_embeddings)}")
def precompute_embedding_bs1_np(self, img):
- img = f"data/cameras{img}" # todo base path?
- img = cv2.imread(img)
+ if type(img) == bytes: # todo, another level up?
+ 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)
img = [preprocess(img)]
ret = precompute_embedding_bs1(self.model, Tensor(img)).numpy()
diff --git a/mainview.html b/mainview.html
index b78d94f..4009dbe 100644
--- a/mainview.html
+++ b/mainview.html
@@ -63,6 +63,7 @@
}
.tooltip {
+ margin-left: 4px;
position: relative;
display: inline-flex;
align-items: center;
@@ -742,6 +743,7 @@
flex-wrap: wrap;
gap: 14px;
justify-content: flex-start;
+ width: 100%;
}
.event-image-item {
@@ -1329,18 +1331,34 @@
Alerts Only
</label>
- <div style="display: flex; align-items: center; gap: 6px; margin-left: 10px;">
- <input type="text" id="imageSearchInput" placeholder="Search text..." style="padding: 6px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); color: var(--text-primary);">
- <button onclick="searchEventImages()" id="searchButton" style="padding: 6px 12px; background: var(--accent-primary); color: white; border: none; border-radius: 4px; cursor: pointer; display: flex; align-items: center; gap: 4px;">
- <span id="searchText">Search</span>
- <div id="searchSpinner" class="spinner" style="display: none;"></div>
- </button>
- <button onclick="clearSearch()" style="padding: 6px 12px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.2s;">Clear</button>
- </div>
- </div>
- <div id="eventImagesContainer">
- <p style="text-align:center; color:#666; width:100%;">No events detected yet.</p>
+ <div style="display: flex; align-items: center; gap: 6px; margin-left: 10px;">
+ <div style="position: relative; display: flex; align-items: center;">
+ <label for="imageUpload" 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 image">
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
+ <circle cx="8.5" cy="8.5" r="1.5"></circle>
+ <polyline points="21 15 16 10 5 21"></polyline>
+ </svg>
+ </label>
+ <span class="tooltip">
+ <span class="tooltip-icon">?</span>
+ <span class="tooltiptext">Use an image to find similar objects in your footage.</span>
+ </span>
+ <input type="file" id="imageUpload" accept="image/*" style="display: none;">
</div>
+
+ <input type="text" id="imageSearchInput" placeholder="Search text..." style="padding: 6px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); color: var(--text-primary);">
+
+ <button onclick="searchEventImages()" id="searchButton" style="padding: 6px 12px; background: var(--accent-primary); color: white; border: none; border-radius: 4px; cursor: pointer; display: flex; align-items: center; gap: 4px;">
+ <span id="searchText">Search</span>
+ <div id="searchSpinner" class="spinner" style="display: none;"></div>
+ </button>
+
+ <button onclick="clearSearch()" style="padding: 6px 12px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.2s;">Clear</button>
+ </div>
+ <div id="eventImagesContainer">
+ <p style="text-align:center; color:#666; width:100%;">No events detected yet.</p>
+ </div>
</div>
<div id="multiView"></div>
@@ -1534,7 +1552,7 @@
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
-
+ let uploadedImageData = null;
const classLabels = {
0: 'person',
1: 'bicycle',
@@ -1958,7 +1976,7 @@
loadEventImages();
setInterval(() => {
- if (!currentImageSearchText) {
+ if (!currentImageSearchText && !currentSimilarImage && !uploadedImageData) {
loadEventImages();
}
}, 5000);
@@ -2829,6 +2847,9 @@
const searchText = document.getElementById('searchText');
const searchSpinner = document.getElementById('searchSpinner');
const magnifyButtons = document.querySelectorAll('.event-image-actions button[title="Search Similar"]');
+
+ uploadedImageData = null;
+ document.getElementById('imageUpload').value = '';
currentImageSearchText = searchInput.value.trim();
searchText.textContent = 'Searching';
@@ -2856,11 +2877,42 @@
magnifyButtons.forEach(btn => btn.disabled = false);
document.getElementById('imageSearchInput').value = '';
+ document.getElementById('imageUpload').value = '';
+
currentImageSearchText = '';
currentSimilarImage = null;
+ uploadedImageData = null;
+
loadEventImages();
}
+ document.getElementById('imageUpload').addEventListener('change', function(event) {
+ const 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().finally(() => {
+ searchText.textContent = 'Search';
+ searchSpinner.style.display = 'none';
+ document.getElementById('searchButton').disabled = false;
+ });
+ };
+
+ reader.readAsDataURL(file);
+ });
+
document.getElementById('imageSearchInput').addEventListener('keypress', function(event) {
if (event.key === 'Enter') {
event.preventDefault();
@@ -2868,7 +2920,12 @@
}
});
+ document.querySelector('label[for="imageUpload"]').addEventListener('click', function(e) {
+ e.preventDefault();
+ document.getElementById('imageUpload').click();
+ });
+
let previousEventImages = null;
async function loadEventImages() {
try {
@@ -2878,9 +2935,12 @@
name_contains: alertsOnlyFilter ? "_notif" : null,
image_text: null,
similar_img: null,
+ uploaded_image: null
};
- if (currentSimilarImage) {
+ if (uploadedImageData) {
+ payload.uploaded_image = uploadedImageData;
+ } else if (currentSimilarImage) {
payload.similar_img = `/${currentSimilarImage}`;
currentSimilarImage = null;
} else if (currentImageSearchText) {
@@ -2989,6 +3049,9 @@
searchButton.disabled = true;
magnifyButtons.forEach(btn => btn.disabled = true);
+ uploadedImageData = null;
+ document.getElementById('imageUpload').value = '';
+
currentSimilarImage = match[1];
document.getElementById('imageSearchInput').value = '';