Skip to content

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

move camera page to file

roryclear9378624d3986
diff --git a/cameraview.html b/cameraview.html
new file mode 100644
index 0000000..eb393b8
--- /dev/null
+++ b/cameraview.html
@@ -0,0 +1,1422 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
+ <link href="https://fonts.googleapis.com/css2?family=Inter&display=swap" rel="stylesheet">
+ <style>
+ .polygon-point {
+ transition: all 0.2s ease;
+ }
+
+ .polygon-point:hover {
+ transform: scale(1.2);
+ box-shadow: 0 0 5px rgba(0,0,0,0.5);
+ }
+
+ .polygon-line path {
+ transition: all 0.2s ease;
+ }
+
+ body {
+ font-family: 'Inter', sans-serif;
+ margin: 0;
+ padding: 0;
+ background-color: #f9f9f9;
+ color: #333;
+ }
+
+ .checkbox-container {
+ display: grid;
+ grid-template-columns: auto auto;
+ gap: 8px 16px;
+ max-height: 200px;
+ overflow-y: auto;
+ margin: 0 auto;
+ padding: 8px;
+ justify-content: center;
+ }
+
+ .checkbox-container input[type="checkbox"] {
+ margin: 0;
+ width: 16px;
+ height: 16px;
+ }
+
+ .checkbox-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-left: 10px;
+ }
+
+ .checkbox-item input[type="checkbox"] {
+ margin: 0;
+ transform: scale(1.2);
+ }
+
+ .container {
+ max-width: 900px;
+ margin: 0 auto;
+ padding: 20px;
+ }
+
+ video {
+ width: 100%;
+ border-radius: 12px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ margin-bottom: 20px;
+ }
+
+ .date-picker-container {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ gap: 10px;
+ margin: 20px 0;
+ flex-wrap: wrap;
+ }
+
+ .date-picker-container input[type="date"],
+ .date-picker-container button {
+ height: 40px;
+ font-size: 0.95rem;
+ padding: 6px 12px;
+ border-radius: 6px;
+ border: 1px solid #ccc;
+ box-sizing: border-box;
+ }
+
+ .counts-wrapper {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ gap: 20px;
+ margin: 20px 0;
+ }
+
+ .controls {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16px;
+ align-items: flex-end;
+ justify-content: center;
+ margin-bottom: 20px;
+ }
+
+ .controls label {
+ font-size: 0.9rem;
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 auto;
+ min-width: 120px;
+ }
+
+ input[type="date"],
+ input[type="time"] {
+ padding: 6px 10px;
+ border-radius: 8px;
+ border: 1px solid #ccc;
+ font-size: 1rem;
+ }
+
+ button {
+ background-color: #f0f0f0;
+ color: #1a73e8;
+ padding: 10px 24px;
+ border: none;
+ border-radius: 6px;
+ font-size: 1rem;
+ cursor: pointer;
+ transition: all 0.3s ease;
+ min-width: 100px;
+ text-align: center;
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
+ }
+
+ button:hover {
+ background-color: #e0e0e0;
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
+ }
+
+ .form-actions button {
+ min-width: 80px;
+ }
+
+ #alertsContainer table button {
+ padding: 6px 12px;
+ min-width: 90px;
+ text-align: center;
+ font-size: 0.9rem;
+ }
+
+ h3 {
+ font-size: 1.2rem;
+ margin: 20px 0 10px;
+ }
+
+ #eventImagesContainer {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 14px;
+ }
+
+ #eventImagesContainer img {
+ width: 220px;
+ height: auto;
+ border-radius: 10px;
+ border: 1px solid #ccc;
+ transition: transform 0.2s;
+ }
+
+ #eventImagesContainer img:hover {
+ transform: scale(1.05);
+ }
+
+ /* Modal styles */
+ .modal {
+ display: none;
+ position: fixed;
+ z-index: 999;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ background-color: rgba(0, 0, 0, 0.4);
+ justify-content: center;
+ align-items: center;
+ overflow: auto;
+ }
+
+ .form-group.checkbox-group {
+ flex: 1;
+ min-height: 0; /* Important for flex children */
+ }
+
+ .modal-content {
+ background-color: #fefefe;
+ padding: 20px;
+ border-radius: 8px;
+ width: 90%;
+ max-width: 500px;
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
+ }
+
+ .modal-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 15px;
+ }
+
+ .modal-header h3 {
+ margin: 0;
+ }
+
+ .close {
+ color: #aaa;
+ font-size: 28px;
+ font-weight: bold;
+ cursor: pointer;
+ }
+
+ .close:hover {
+ color: black;
+ }
+
+ .form-group {
+ margin-bottom: 15px;
+ }
+
+ .form-group label {
+ display: block;
+ margin-bottom: 5px;
+ font-weight: 500;
+ }
+
+ .form-group input {
+ width: 100%;
+ padding: 8px;
+ border: 1px solid #ddd;
+ border-radius: 4px;
+ box-sizing: border-box;
+ }
+
+ .form-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 10px;
+ margin-top: 20px;
+ }
+
+ @media (max-width: 600px) {
+ button {
+ padding: 8px 16px;
+ font-size: 0.9rem;
+ min-width: 80px;
+ }
+
+ .form-actions button {
+ min-width: 70px;
+ }
+
+ input[type="date"] {
+ width: 100%;
+ max-width: 200px;
+ padding: 6px 8px;
+ font-size: 0.9rem;
+ }
+
+ input[type="time"] {
+ width: 100px;
+ padding: 6px 8px;
+ font-size: 0.9rem;
+ }
+
+ .modal-content {
+ width: 95%;
+ padding: 15px;
+ }
+
+ .form-group input {
+ padding: 6px 8px;
+ font-size: 0.9rem;
+ }
+
+ #alertsContainer table {
+ font-size: 0.9rem;
+ }
+
+ #alertsContainer table button {
+ min-width: 80px;
+ padding: 5px 10px;
+ font-size: 0.8rem;
+ }
+
+ .controls label {
+ min-width: auto;
+ width: 100%;
+ }
+
+ .counts-wrapper {
+ flex-direction: column;
+ gap: 10px;
+ }
+
+ .date-picker-container {
+ flex-wrap: nowrap;
+ }
+
+ .date-picker-container input[type="date"],
+ .date-picker-container button {
+ height: 36px;
+ font-size: 0.85rem;
+ padding: 6px 10px;
+ }
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <video id="video" controls></video>
+ <div class="date-picker-container">
+ <input type="date" id="folderPicker" value="{selected_dir}">
+ <label style="display: flex; align-items: center; gap: 6px; margin-left: 10px;">
+ <input type="checkbox" id="showDetections" {show_detections_checked}> Show detections
+ </label>
+ </div>
+ <h3>Active Alerts</h3>
+ <div id="alertsContainer">
+ <p>Loading alerts...</p>
+ <div style="display: flex; gap: 10px; justify-content: flex-start; margin-top: 10px;">
+ <button onclick="openSettingsEditor()">Settings</button>
+ <button onclick="openAlertModal()">Add Alert</button>
+ </div>
+ </div>
+
+ <!-- The Modal -->
+ <div id="alertModal" class="modal">
+ <div class="modal-content" style="max-width: 400px;">
+ <div class="modal-header">
+ <h3>Add New Alert</h3>
+ <span class="close" onclick="closeAlertModal()">&times;</span>
+ </div>
+ <form id="alertForm" onsubmit="addAlert(event)" style="display: flex; flex-direction: column; align-items: center;">
+ <div class="form-group" style="width: 90%; text-align: center;">
+ <label for="maxCount">Trigger if there are more than</label>
+ <input type="number" id="maxCount" name="max" min="1" value="1" required
+ style="width: 80px; margin: 0 6px; text-align: center; display: inline-block;">
+ <span>objects detected</span>
+ </div>
+ <div class="form-group checkbox-group" style="width: 90%; text-align: center;">
+ <label>of class(es)</label>
+ <div id="checkboxContainer" class="checkbox-container"></div>
+ </div>
+ <div class="form-group" style="width: 90%; text-align: center;">
+ <label for="windowMinutes">within this time window</label>
+ <input type="number" id="windowMinutes" name="window" min="1" value="1" required
+ style="width: 80px; margin: 0 6px; text-align: center; display: inline-block;">
+ <span>minutes</span>
+ </div>
+
+ <div class="form-group" style="width: 90%; text-align: center;">
+ <label>Schedule (optional)</label>
+ <div style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;">
+ <div>
+ <label for="scheduleFrom">From</label><br>
+ <input type="time" id="scheduleFrom" name="schedule_from" step="60" style="text-align: center;">
+ </div>
+ <div>
+ <label for="scheduleTo">To</label><br>
+ <input type="time" id="scheduleTo" name="schedule_to" step="60" style="text-align: center;">
+ </div>
+ </div>
+ </div>
+ <div class="form-group" style="width: 90%; text-align: center;">
+ <div style="display: flex; flex-direction: column; align-items: center; gap: 5px; margin-top: 5px;">
+ <label><input type="checkbox" name="days" value="0" checked> Mon</label>
+ <label><input type="checkbox" name="days" value="1" checked> Tue</label>
+ <label><input type="checkbox" name="days" value="2" checked> Wed</label>
+ <label><input type="checkbox" name="days" value="3" checked> Thu</label>
+ <label><input type="checkbox" name="days" value="4" checked> Fri</label>
+ <label><input type="checkbox" name="days" value="5" checked> Sat</label>
+ <label><input type="checkbox" name="days" value="6" checked> Sun</label>
+ </div>
+ </div>
+
+ <div class="form-actions" style="display: flex; justify-content: center; gap: 10px; margin-top: 20px; width: 100%;">
+ <button type="button" onclick="closeAlertModal()">Cancel</button>
+ <button type="submit">Save Alert</button>
+ </div>
+ </form>
+ </div>
+ </div>
+
+
+ <div id="zoneModal" class="modal">
+ <div class="modal-content" style="max-width: 600px;">
+ <div class="modal-header">
+ <h3>Edit Zone</h3>
+ <span class="close" onclick="closeZoneModal()">&times;</span>
+ </div>
+ <div style="position: relative; display: inline-block; max-width: 100%;">
+ <img id="zonePreview" src="/{cam_name}/preview.png"
+ style="width: 100%; max-height: 400px; object-fit: contain; border: 1px solid #ccc; border-radius: 6px; user-select: none; -webkit-user-drag: none; cursor: crosshair;">
+ <div id="polygonOverlay" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;"></div>
+ </div>
+ <div style="margin: 10px 0; text-align: center; color: #666; font-size: 0.9rem;">
+ Click on the image to add points. Right-click to remove points. Click on the first point (blue) to complete the polygon.
+ </div>
+ <div class="form-actions" style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center; width: 100%;">
+ <div style="display: flex; flex-direction: column; gap: 10px;">
+ <label style="display: flex; align-items: center; gap: 6px;">
+ <input type="checkbox" id="zoneEnabledCheckbox" checked> Enable Zone
+ </label>
+ <label style="display: flex; align-items: center; gap: 6px;">
+ <input type="checkbox" id="outsideZoneCheckbox"> Detect outside of zone
+ </label>
+ <label style="display: flex; align-items: center; gap: 6px;">
+ Detection Threshold:
+ <input type="number" id="zoneThreshold" value="50" min="0" max="100" step="1" style="width: 60px;"> %
+ </label>
+ </div>
+ <div style="display: flex; gap: 10px;">
+ <button type="button" onclick="clearPolygon()">Clear</button>
+ <button type="button" onclick="closeZoneModal()">Cancel</button>
+ <button type="button" onclick="saveZone()">Save</button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+
+ <div class="counts-wrapper">
+ <table id="objectCounts" style="font-size: 1rem; border-collapse: collapse;">
+ <tbody></tbody>
+ </table>
+ <button onclick="resetCounts()">Reset</button>
+ </div>
+
+ <h3>Detected Events</h3>
+ <div id="eventImagesContainer">
+ {image_links}
+ </div>
+ <div id="imagePreviewModal" class="modal">
+ <span class="close" onclick="closeImagePreview()">&times;</span>
+ <img id="previewImage" src="" alt="Preview">
+ </div>
+ </div>
+
+ <script>
+ const classLabels = {class_labels};
+ const alertModal = document.getElementById("alertModal");
+ const folderPicker = document.getElementById("folderPicker");
+ const video = document.getElementById("video");
+ const startTime = {start_time};
+ const cameraName = "{cam_name}";
+
+
+ window.onload = function () {
+ const container = document.getElementById('checkboxContainer');
+ container.innerHTML = '';
+
+ for (let i = 0; i < 80; i++) {
+ const checkbox = document.createElement('input');
+ checkbox.type = 'checkbox';
+ checkbox.value = i;
+ checkbox.name = 'class_ids';
+ checkbox.id = 'class_' + i;
+
+ const label = document.createElement('label');
+ label.htmlFor = 'class_' + i;
+ label.textContent = (classLabels[i] !== undefined) ? `${classLabels[i]}` : `${i}`;
+
+ container.appendChild(checkbox);
+ container.appendChild(label);
+ }
+ };
+
+ function viewImage(imageSrc) {
+ const previewModal = document.getElementById("imagePreviewModal");
+ const previewImage = document.getElementById("previewImage");
+ previewImage.src = imageSrc;
+
+ // Force reasonable size
+ previewImage.style.maxWidth = '70%';
+ previewImage.style.maxHeight = '70%';
+ previewImage.style.width = 'auto';
+ previewImage.style.height = 'auto';
+
+ previewModal.style.display = "flex";
+ }
+
+ function closeImagePreview() {
+ document.getElementById("imagePreviewModal").style.display = "none";
+ }
+
+ function playVideoAtTime(timestamp) {
+ const params = new URLSearchParams(window.location.search);
+ params.set('start', timestamp);
+ window.location.search = params.toString();
+ }
+ window.addEventListener("click", function(event) {
+ const modal = document.getElementById("imagePreviewModal");
+ if (event.target === modal) {
+ closeImagePreview();
+ }
+ });
+ document.addEventListener('keydown', function(event) {
+ if (event.key === 'Escape') {
+ closeImagePreview();
+ }
+ });
+
+ const zoneModal = document.getElementById("zoneModal");
+ const zoneRect = document.getElementById("zoneRect");
+ let isDragging = false;
+ let isResizing = false;
+ let resizeHandle = null;
+ let startX, startY;
+ let startWidth, startHeight;
+ let startLeft, startTop;
+
+function closeZoneModal() {
+ zoneModal.style.display = "none";
+}
+
+ // Global variables for polygon editing
+ // Global variables for polygon editing
+ let polygonSvg = null;
+ let polygonPath = null;
+ let firstPoint = null;
+ let isPolygonComplete = false;
+
+ function openSettingsEditor() {
+ zoneModal.style.display = "flex";
+
+ // Initialize the zone editor first
+ initZoneEditor();
+
+ // Then load the settings
+ fetch(`/get_settings?cam=${encodeURIComponent(cameraName)}`)
+ .then(res => res.json())
+ .then(data => {
+ console.log("Received settings data:", data);
+ const previewEl = document.getElementById("zonePreview");
+
+ if (data && data.coords) {
+ console.log("Loading coords:", data.coords);
+ // Load existing polygon coordinates
+ loadPolygon(data.coords, previewEl);
+ }
+
+ const zoneEnabledCheckbox = document.getElementById("zoneEnabledCheckbox");
+ if (data.is_on !== undefined) {
+ zoneEnabledCheckbox.checked = data.is_on;
+ } else if (data.length && data[0] && data[0].is_on !== undefined) {
+ zoneEnabledCheckbox.checked = data[0].is_on;
+ } else {
+ zoneEnabledCheckbox.checked = false;
+ }
+
+ const outsideZoneCheckbox = document.getElementById("outsideZoneCheckbox");
+ if (data.outside !== undefined) {
+ outsideZoneCheckbox.checked = data.outside;
+ } else if (data.length && data[0] && data[0].outside !== undefined) {
+ outsideZoneCheckbox.checked = data[0].outside;
+ } else {
+ outsideZoneCheckbox.checked = false;
+ }
+
+ const thresholdInput = document.getElementById("zoneThreshold");
+ let rawThreshold = undefined;
+ if (data.threshold !== undefined) {
+ rawThreshold = data.threshold;
+ } else if (data.length && data[0] && data[0].threshold !== undefined) {
+ rawThreshold = data[0].threshold;
+ }
+ if (rawThreshold !== undefined) {
+ if (rawThreshold <= 1) {
+ thresholdInput.value = (rawThreshold * 100).toFixed(0);
+ } else {
+ thresholdInput.value = rawThreshold.toFixed(0);
+ }
+ }
+ })
+ .catch(err => {
+ console.error("Failed to load zone:", err);
+ });
+ }
+
+ function closeZoneModal() {
+ zoneModal.style.display = "none";
+ }
+
+ function saveZone() {
+ const previewEl = document.getElementById("zonePreview");
+ const points = Array.from(document.querySelectorAll('.polygon-point'));
+
+ let coords = null;
+ if (points.length >= 3) {
+ const videoWidth = 1280;
+ const videoHeight = 720;
+ const previewRect = previewEl.getBoundingClientRect();
+
+ coords = points.map(point => {
+ const pointRect = point.getBoundingClientRect();
+ const centerX = pointRect.left + pointRect.width / 2;
+ const centerY = pointRect.top + pointRect.height / 2;
+
+ const x = ((centerX - previewRect.left) / previewRect.width) * videoWidth;
+ const y = ((centerY - previewRect.top) / previewRect.height) * videoHeight;
+
+ return [x, y];
+ });
+ }
+
+ const is_on = document.getElementById("zoneEnabledCheckbox").checked;
+ const outside = document.getElementById("outsideZoneCheckbox").checked;
+
+ const thresholdPercent = parseFloat(document.getElementById("zoneThreshold").value) || 50;
+ const threshold = thresholdPercent / 100;
+
+ const params = new URLSearchParams({
+ cam: cameraName,
+ is_on: is_on,
+ threshold: threshold.toFixed(2),
+ outside: outside
+ });
+
+ if (coords) {
+ params.set('coords', JSON.stringify(coords));
+ }
+
+ fetch(`/edit_settings?${params.toString()}`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to save settings");
+ console.log("Settings saved successfully");
+ closeZoneModal();
+ })
+ .catch(err => {
+ console.error("Save settings failed:", err);
+ alert("Failed to save settings.");
+ });
+ }
+
+ function initZoneEditor() {
+ const previewEl = document.getElementById("zonePreview");
+
+ // Clear any existing polygon
+ clearPolygon();
+
+ // Initialize SVG overlay
+ initPolygonOverlay();
+
+ // Add click event listener for adding points
+ previewEl.addEventListener('click', handlePreviewClick);
+ }
+
+ function initPolygonOverlay() {
+ const overlay = document.getElementById("polygonOverlay");
+ overlay.innerHTML = '';
+
+ // Create SVG element
+ polygonSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ polygonSvg.style.width = '100%';
+ polygonSvg.style.height = '100%';
+ polygonSvg.style.position = 'absolute';
+ polygonSvg.style.top = '0';
+ polygonSvg.style.left = '0';
+ polygonSvg.style.pointerEvents = 'none';
+
+ polygonPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
+ polygonPath.setAttribute('fill', 'none');
+ polygonPath.setAttribute('stroke', '#ff0000');
+ polygonPath.setAttribute('stroke-width', '2');
+ polygonPath.setAttribute('stroke-linejoin', 'round');
+
+ polygonSvg.appendChild(polygonPath);
+ overlay.appendChild(polygonSvg);
+ }
+
+ function handlePreviewClick(e) {
+ const previewEl = document.getElementById("zonePreview");
+ const rect = previewEl.getBoundingClientRect();
+
+ // Calculate position relative to preview element
+ const x = e.clientX - rect.left;
+ const y = e.clientY - rect.top;
+
+ // Check if we're clicking on the first point (to close polygon)
+ if (firstPoint && isClickOnPoint(firstPoint, x, y)) {
+ // Complete the polygon
+ completePolygon();
+ return;
+ }
+
+ // Create a new point
+ createPoint(x, y);
+
+ // Update the polygon visualization
+ updatePolygonLine();
+ }
+
+ function isClickOnPoint(point, clickX, clickY) {
+ const pointRect = point.getBoundingClientRect();
+ const previewRect = document.getElementById("zonePreview").getBoundingClientRect();
+ const pointX = parseInt(point.style.left) + 6; // Center of point
+ const pointY = parseInt(point.style.top) + 6;
+
+ // Check if click is within the point's area
+ const distance = Math.sqrt(Math.pow(clickX - pointX, 2) + Math.pow(clickY - pointY, 2));
+ return distance <= 10; // Increased tolerance for easier clicking
+ }
+
+ function completePolygon() {
+ console.log("Completing polygon"); // Debug log
+ polygonPath.setAttribute('fill', 'rgba(0, 255, 0, 0.3)');
+ polygonPath.setAttribute('stroke', '#00ff00');
+ const previewEl = document.getElementById("zonePreview");
+ previewEl.removeEventListener('click', handlePreviewClick);
+ enablePointDragging();
+ isPolygonComplete = true;
+ updatePolygonLine();
+ }
+
+ function createPoint(x, y) {
+ const overlay = document.getElementById("polygonOverlay");
+ const point = document.createElement('div');
+ point.className = 'polygon-point';
+ point.style.position = 'absolute';
+ point.style.left = (x - 6) + 'px';
+ point.style.top = (y - 6) + 'px';
+ point.style.width = '12px';
+ point.style.height = '12px';
+ point.style.backgroundColor = '#ff0000';
+ point.style.borderRadius = '50%';
+ point.style.cursor = 'crosshair';
+ point.style.zIndex = '20';
+ point.style.border = '2px solid #ffffff';
+ point.style.boxShadow = '0 0 3px rgba(0,0,0,0.5)';
+ point.style.pointerEvents = 'auto';
+
+ // Store first point reference
+ if (!firstPoint) {
+ firstPoint = point;
+ // Make first point visually distinct
+ point.style.backgroundColor = '#0000ff';
+ point.style.border = '2px solid #ffffff';
+ point.style.cursor = 'pointer'; // Make first point more clickable
+ }
+
+ // Add click listener to first point for completion
+ if (firstPoint === point) {
+ point.addEventListener('click', function(e) {
+ e.stopPropagation();
+ if (!isPolygonComplete) {
+ completePolygon();
+ }
+ });
+ }
+
+ // Add delete on right-click (always available)
+ point.addEventListener('contextmenu', (e) => {
+ e.preventDefault();
+ removePoint(point);
+ });
+
+ overlay.appendChild(point);
+ return point;
+ }
+
+ function enablePointDragging() {
+ const points = Array.from(document.querySelectorAll('.polygon-point'));
+ points.forEach(point => {
+ makePointDraggable(point);
+ point.style.cursor = 'move';
+ });
+ }
+
+ function removePoint(point) {
+ // If removing the first point, update the firstPoint reference
+ if (point === firstPoint) {
+ const points = Array.from(document.querySelectorAll('.polygon-point'));
+ if (points.length > 1) {
+ firstPoint = points[1]; // Second point becomes first
+ firstPoint.style.backgroundColor = '#0000ff';
+ } else {
+ firstPoint = null;
+ }
+ }
+
+ point.remove();
+ updatePolygonLine();
+
+ // If polygon was complete, re-enable editing
+ if (isPolygonComplete) {
+ isPolygonComplete = false;
+ const previewEl = document.getElementById("zonePreview");
+ previewEl.addEventListener('click', handlePreviewClick);
+
+ // Reset visual style
+ if (polygonPath) {
+ polygonPath.setAttribute('fill', 'none');
+ polygonPath.setAttribute('stroke', '#ff0000');
+ }
+
+ // Disable dragging on remaining points
+ const remainingPoints = Array.from(document.querySelectorAll('.polygon-point'));
+ remainingPoints.forEach(p => {
+ p.style.cursor = 'crosshair';
+ // Remove existing drag listeners
+ p.replaceWith(p.cloneNode(true));
+ });
+ }
+
+ // Reset instruction text
+ const instruction = document.querySelector('#zoneModal .modal-content div:nth-child(3)');
+ if (instruction) {
+ instruction.innerHTML = 'Click on the image to add points. Right-click to remove points. Click on the first point (blue) to complete the polygon.';
+ }
+ }
+
+ function makePointDraggable(point) {
+ let isDragging = false;
+ let startX, startY, startLeft, startTop;
+
+ function dragPoint(e) {
+ if (!isDragging) return;
+
+ const previewEl = document.getElementById("zonePreview");
+ const previewRect = previewEl.getBoundingClientRect();
+
+ const deltaX = e.clientX - startX;
+ const deltaY = e.clientY - startY;
+
+ let newLeft = startLeft + deltaX;
+ let newTop = startTop + deltaY;
+
+ // Constrain to preview area
+ newLeft = Math.max(0, Math.min(newLeft, previewRect.width - 12));
+ newTop = Math.max(0, Math.min(newTop, previewRect.height - 12));
+
+ point.style.left = newLeft + 'px';
+ point.style.top = newTop + 'px';
+
+ // Force synchronous layout update before updating polygon line
+ point.offsetHeight; // This triggers a reflow
+
+ updatePolygonLine();
+ }
+
+ function stopDragPoint() {
+ isDragging = false;
+ document.removeEventListener('mousemove', dragPoint);
+ document.removeEventListener('mouseup', stopDragPoint);
+ document.removeEventListener('mouseleave', stopDragPoint);
+ }
+
+ point.addEventListener('mousedown', (e) => {
+ // Only allow dragging if polygon is complete
+ if (!isPolygonComplete) return;
+
+ e.preventDefault();
+ e.stopPropagation();
+ isDragging = true;
+ startX = e.clientX;
+ startY = e.clientY;
+
+ const style = window.getComputedStyle(point);
+ startLeft = parseInt(style.left);
+ startTop = parseInt(style.top);
+
+ document.addEventListener('mousemove', dragPoint);
+ document.addEventListener('mouseup', stopDragPoint);
+ document.addEventListener('mouseleave', stopDragPoint);
+ });
+ }
+
+ function updatePolygonLine() {
+ const previewEl = document.getElementById("zonePreview");
+ const points = Array.from(document.querySelectorAll('.polygon-point'));
+
+ if (points.length === 0) {
+ polygonPath.setAttribute('d', '');
+ firstPoint = null;
+ isPolygonComplete = false;
+ return;
+ }
+
+ // Create SVG path for the polygon - just draw lines between points, don't close automatically
+ const pathData = points.map((point, index) => {
+ const rect = point.getBoundingClientRect();
+ const previewRect = previewEl.getBoundingClientRect();
+ const x = rect.left - previewRect.left + 6; // Center of point
+ const y = rect.top - previewRect.top + 6;
+ return `${index === 0 ? 'M' : 'L'} ${x} ${y}`;
+ }).join(' ');
+
+ // Only close the path if polygon is complete
+ if (isPolygonComplete) {
+ polygonPath.setAttribute('d', pathData + ' Z');
+ } else {
+ polygonPath.setAttribute('d', pathData);
+ }
+ }
+
+ function loadPolygon(coords, previewEl) {
+ const videoWidth = 1280;
+ const videoHeight = 720;
+
+ // Wait for the image to load to get actual dimensions
+ const img = document.getElementById("zonePreview");
+ if (img.complete) {
+ drawPolygonCoords(coords, img, previewEl);
+ } else {
+ img.addEventListener('load', function() {
+ drawPolygonCoords(coords, img, previewEl);
+ });
+ }
+ }
+
+ function drawPolygonCoords(coords, img, previewEl) {
+ const videoWidth = 1280;
+ const videoHeight = 720;
+
+ // Get the actual displayed dimensions of the image
+ const displayedWidth = img.clientWidth;
+ const displayedHeight = img.clientHeight;
+
+ console.log("Loading polygon coords:", coords);
+ console.log("Image dimensions:", displayedWidth, displayedHeight);
+
+ coords.forEach(coord => {
+ const x = (coord[0] / videoWidth) * displayedWidth;
+ const y = (coord[1] / videoHeight) * displayedHeight;
+ console.log("Creating point at:", x, y, "from coord:", coord);
+ createPoint(x, y);
+ });
+
+ updatePolygonLine();
+
+ // If loading an existing polygon, mark it as complete
+ if (coords.length >= 3) {
+ completePolygon();
+ }
+ }
+
+ function clearPolygon() {
+ const overlay = document.getElementById("polygonOverlay");
+ const points = overlay.querySelectorAll('.polygon-point');
+ points.forEach(point => point.remove());
+
+ firstPoint = null;
+ isPolygonComplete = false;
+
+ if (polygonPath) {
+ polygonPath.setAttribute('d', '');
+ polygonPath.setAttribute('fill', 'none');
+ polygonPath.setAttribute('stroke', '#ff0000');
+ }
+
+ // Re-enable clicking
+ const previewEl = document.getElementById("zonePreview");
+ previewEl.addEventListener('click', handlePreviewClick);
+
+ // Reset instruction text
+ const instruction = document.querySelector('#zoneModal .modal-content div:nth-child(3)');
+ if (instruction) {
+ instruction.innerHTML = 'Click on the image to add points. Right-click to remove points. Click on the first point (blue) to complete the polygon.';
+ }
+ }
+
+ // Add some CSS styles for the polygon editor
+ const polygonStyles = `
+ .polygon-point:hover {
+ transform: scale(1.2);
+ box-shadow: 0 0 5px rgba(0,0,0,0.5);
+ }
+ .polygon-line path {
+ transition: all 0.2s ease;
+ }
+ `;
+
+ const styleSheet = document.createElement("style");
+ styleSheet.textContent = polygonStyles;
+ document.head.appendChild(styleSheet);
+
+
+ function openAlertModal() {
+ alertModal.style.display = "flex";
+ }
+
+ function closeAlertModal() {
+ alertModal.style.display = "none";
+ }
+
+ window.addEventListener("click", function(event) {
+ if (event.target === alertModal) closeAlertModal();
+ });
+
+ document.getElementById("showDetections").addEventListener("change", function() {
+ const currentTime = video.currentTime;
+ const params = new URLSearchParams(window.location.search);
+ params.set('show_detections', this.checked);
+ params.set('start', currentTime);
+ window.location.search = params.toString();
+ });
+
+ function initDetectionSettings() {
+ const urlParams = new URLSearchParams(window.location.search);
+ const showDetections = urlParams.get('show_detections') === 'true';
+
+ if (showDetections) {
+ // Send initial request
+ fetch(`/edit_settings?cam=${encodeURIComponent(cameraName)}&show_dets=1`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to update detection settings");
+ console.log("Detection settings updated successfully");
+ })
+ .catch(err => {
+ console.error("Failed to update detection settings:", err);
+ });
+
+ // Set up interval to send request every 30 seconds
+ window.detectionInterval = setInterval(() => {
+ fetch(`/edit_settings?cam=${encodeURIComponent(cameraName)}&show_dets=1`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to refresh detection settings");
+ console.log("Detection settings refreshed");
+ })
+ .catch(err => {
+ console.error("Failed to refresh detection settings:", err);
+ });
+ }, 30000); // 30 seconds
+ }
+}
+
+document.getElementById("showDetections").addEventListener("change", function() {
+ const currentTime = video.currentTime;
+ const params = new URLSearchParams(window.location.search);
+ params.set('show_detections', this.checked);
+ window.location.search = params.toString();
+});
+
+window.addEventListener('beforeunload', function() {
+ if (window.detectionInterval) {
+ clearInterval(window.detectionInterval);
+ }
+});
+
+initDetectionSettings();
+
+ function loadStream(folder) {
+ const showDetections = document.getElementById("showDetections").checked;
+ const streamSuffix = showDetections ? "" : "_raw";
+ const url = `${cameraName}${streamSuffix}/streams/${folder}/stream.m3u8`;
+
+ async function waitForManifest(maxRetries = 30, delay = 2000) {
+ for (let i = 0; i < maxRetries; i++) {
+ try {
+ const res = await fetch(url, { cache: "no-store" });
+ if (res.ok) {
+ const text = await res.text();
+ if (text.includes("#EXTINF")) {
+ return true; // playlist has segments
+ }
+ }
+ } catch (err) {
+ console.warn("Stream not ready yet:", err);
+ }
+ await new Promise(r => setTimeout(r, delay));
+ }
+ return false;
+ }
+
+ (async () => {
+ const ready = await waitForManifest();
+ if (!ready) {
+ console.error("Stream never became available.");
+ return;
+ }
+
+ if (Hls.isSupported()) {
+ const hls = new Hls({
+ manifestLoadingTimeOut: 20000,
+ manifestLoadingMaxRetry: Infinity,
+ manifestLoadingRetryDelay: 2000,
+ });
+
+ hls.loadSource(url);
+ hls.attachMedia(video);
+
+ hls.on(Hls.Events.MANIFEST_PARSED, function () {
+ if (startTime !== null) video.currentTime = startTime;
+ video.play();
+ });
+
+ hls.on(Hls.Events.ERROR, function (event, data) {
+ if (data.fatal) {
+ switch (data.type) {
+ case Hls.ErrorTypes.NETWORK_ERROR:
+ console.warn("Network error, retrying...");
+ hls.startLoad(-1);
+ break;
+ case Hls.ErrorTypes.MEDIA_ERROR:
+ console.warn("Media error, recovering...");
+ hls.recoverMediaError();
+ break;
+ default:
+ console.error("Fatal error, destroying HLS instance.");
+ hls.destroy();
+ break;
+ }
+ }
+ });
+ } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
+ video.src = url;
+ video.addEventListener('loadedmetadata', function () {
+ if (startTime !== null) video.currentTime = startTime;
+ video.play();
+ });
+ }
+ })();
+ }
+
+
+ function loadEventImages(folder) {
+ fetch(`/event_thumbs?cam=${cameraName}&folder=${folder}`)
+ .then(res => res.text())
+ .then(html => {
+ const container = document.getElementById("eventImagesContainer");
+
+ // Create a temporary div to parse incoming HTML
+ const temp = document.createElement("div");
+ temp.innerHTML = html.trim();
+
+ // Compare child count and content
+ const isSameLength = container.children.length === temp.children.length;
+ let isSame = isSameLength;
+
+ if (isSameLength) {
+ for (let i = 0; i < container.children.length; i++) {
+ if (
+ container.children[i].outerHTML.trim() !==
+ temp.children[i].outerHTML.trim()
+ ) {
+ isSame = false;
+ break;
+ }
+ }
+ }
+
+ if (!isSame) {
+ container.innerHTML = html;
+ }
+ })
+ .catch(err => {
+ console.error("Failed to load images:", err);
+ const container = document.getElementById("eventImagesContainer");
+ container.innerHTML = "<p>No event images found.</p>";
+ });
+ }
+
+ function fetchCounts() {
+ fetch(`/get_counts?cam=${encodeURIComponent(cameraName)}`)
+ .then(res => res.json())
+ .then(data => {
+ const tbody = document.querySelector("#objectCounts tbody");
+ tbody.innerHTML = "";
+
+ const entries = Object.entries(data).sort((a, b) => b[1] - a[1]);
+ if (!entries.length) {
+ tbody.innerHTML = "<tr><td colspan='2'>No detections.</td></tr>";
+ return;
+ }
+
+ for (const [label, count] of entries) {
+ tbody.innerHTML += `
+ <tr>
+ <td style="padding:6px 12px; border-bottom:1px solid #eee;">${label}</td>
+ <td style="padding:6px 12px; border-bottom:1px solid #eee;">${count}</td>
+ </tr>`;
+ }
+ })
+ .catch(err => {
+ console.error("Failed to fetch counts:", err);
+ document.querySelector("#objectCounts tbody").innerHTML = "<tr><td colspan='2'>Error fetching counts.</td></tr>";
+ });
+ }
+
+ function resetCounts() {
+ if (!confirm("Are you sure you want to reset the counts for this camera?")) return;
+ fetch(`/reset_counts?cam=${encodeURIComponent(cameraName)}`)
+ .then(res => res.json())
+ .then(() => {
+ console.log("Counts reset");
+ fetchCounts();
+ })
+ .catch(err => {
+ console.error("Failed to reset counts:", err);
+ alert("Failed to reset counts.");
+ });
+ }
+
+ function fetchAlerts() {
+ fetch(`/get_alerts?cam=${encodeURIComponent(cameraName)}`)
+ .then(res => res.json())
+ .then(alerts => {
+ const container = document.getElementById("alertsContainer");
+ if (!alerts.length) {
+ container.innerHTML = `
+ <p>No alerts configured.</p>
+ <div style="display: flex; gap: 10px; justify-content: center; margin-top: 10px;">
+ <button onclick="openSettingsEditor()">Settings</button>
+ <button onclick="openAlertModal()">Add Alert</button>
+ </div>`;
+ return;
+ }
+
+ let html = `<table style="width:100%; border-collapse:collapse; font-size:0.95rem;">
+ <thead>
+ <tr>
+ <th style="text-align:center; padding:6px; border-bottom:1px solid #ccc;"></th>
+ <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Occurrences of</th>
+ <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Within</th>
+ <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Schedule</th>
+ <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;"></th>
+ </tr>
+ </thead><tbody>`;
+
+ for (const alert of alerts) {
+ const classNames = alert.classes.map(id => classLabels[id] ?? id).join(", ");
+ const h = Math.floor(alert.window / 3600);
+ const m = Math.floor((alert.window % 3600) / 60);
+ const s = alert.window % 60;
+ const windowStr = `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
+ const fromH = Math.floor(alert.sched[0][0] / 3600);
+ const fromM = Math.floor((alert.sched[0][0] % 3600) / 60);
+ let toSec = alert.sched[0][1];
+ if (toSec % 60 !== 0) {
+ toSec += 60 - (toSec % 60);
+ }
+ if (toSec >= 86400) {
+ toSec = 0;
+ }
+ const toH = Math.floor(toSec / 3600);
+ const toM = Math.floor((toSec % 3600) / 60);
+ const timeRange = `${String(fromH).padStart(2,'0')}:${String(fromM).padStart(2,'0')} to ${String(toH).padStart(2,'0')}:${String(toM).padStart(2,'0')}`;
+
+ const daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
+ const activeDays = alert.sched.slice(1).map((on, idx) => on ? daysOfWeek[idx] : null).filter(Boolean);
+ let daysStr;
+ if (activeDays.length === 7) {
+ daysStr = "Daily";
+ } else {
+ // compress consecutive ranges (Mon–Fri)
+ const indices = alert.sched.slice(1).map((on, i) => on ? i : -1).filter(i => i >= 0);
+ let ranges = [];
+ let start = null;
+ let prev = null;
+ for (const idx of indices) {
+ if (start === null) {
+ start = idx;
+ prev = idx;
+ } else if (idx === prev + 1) {
+ prev = idx;
+ } else {
+ ranges.push([start, prev]);
+ start = idx;
+ prev = idx;
+ }
+ }
+ if (start !== null) {
+ ranges.push([start, prev]);
+ }
+ daysStr = ranges.map(([a, b]) => {
+ if (a === b) return daysOfWeek[a];
+ else return `${daysOfWeek[a]}-${daysOfWeek[b]}`;
+ }).join(", ");
+ }
+ const schedStr = `${timeRange} (${daysStr})`;
+ const isOn = alert.hasOwnProperty("is_on") ? alert.is_on : true;
+ const checkedAttr = isOn ? "checked" : "";
+ html += `<tr>
+ <td style="padding:6px; border-bottom:1px solid #eee;">${alert.max}</td>
+ <td style="padding:6px; border-bottom:1px solid #eee;">${classNames}</td>
+ <td style="padding:6px; border-bottom:1px solid #eee;">${windowStr}</td>
+ <td style="padding:6px; border-bottom:1px solid #eee;">${schedStr}</td>
+ <td style="padding:6px; border-bottom:1px solid #eee; display:flex; justify-content:center; align-items:center;">
+ <input type="checkbox" data-alert-id="${alert.id}" ${checkedAttr}
+ onchange="toggleAlert('${alert.id}', this.checked)"
+ style="transform:scale(1.2); cursor:pointer;">
+ </td>
+ <td style="padding:6px; border-bottom:1px solid #eee; text-align:center;">
+ <button onclick="deleteAlert('${alert.id}')" style="padding:4px 8px;">Delete</button>
+ </td>
+ </tr>`;
+ }
+
+
+ html += `</tbody></table>
+ <div style="margin-top:10px; display:flex; gap:10px; justify-content:center;">
+ <button onclick="openSettingsEditor()">Settings</button>
+ <button onclick="openAlertModal()">Add Alert</button>
+ </div>`;
+ container.innerHTML = html;
+ })
+ .catch(err => {
+ console.error("Failed to fetch alerts:", err);
+ document.getElementById("alertsContainer").innerHTML = "<p>Error loading alerts.</p>";
+ });
+ }
+
+ function toggleAlert(alertId, isOn) {
+ fetch(`/edit_alert?cam=${encodeURIComponent(cameraName)}&id=${alertId}&is_on=${isOn}`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to toggle alert");
+ console.log(`Alert ${alertId} ${isOn ? 'enabled' : 'disabled'}`);
+ })
+ .catch(err => {
+ console.error("Toggle alert failed:", err);
+ alert("Failed to toggle alert status.");
+ fetchAlerts();
+ });
+ }
+
+ function deleteAlert(alertId) {
+ fetch(`/edit_alert?cam=${encodeURIComponent(cameraName)}&id=${alertId}`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to delete alert");
+ fetchAlerts();
+ })
+ .catch(err => {
+ console.error("Delete failed:", err);
+ alert("Failed to delete alert.");
+ });
+ }
+
+ function addAlert(event) {
+ event.preventDefault();
+ const form = event.target;
+ const formData = new FormData(form);
+
+ const windowMinutes = parseFloat(formData.get('window'));
+ const windowSeconds = Math.round(windowMinutes * 60);
+
+ const checked = form.querySelectorAll('input[name="class_ids"]:checked');
+ const classIds = Array.from(checked).map(cb => cb.value).join(',');
+
+ const scheduleFrom = formData.get("schedule_from") || "00:00:00";
+ const scheduleTo = formData.get("schedule_to") || "23:59:59";
+
+ const toSeconds = (hhmmss) => {
+ const parts = hhmmss.split(":").map(Number);
+ const [h = 0, m = 0, s = 0] = parts;
+ return h * 3600 + m * 60 + s;
+ };
+
+ const fromSec = toSeconds(scheduleFrom);
+ const toSec = toSeconds(scheduleTo);
+ const dayChecks = form.querySelectorAll('input[name="days"]');
+ const dayBools = Array.from(dayChecks).map(cb => cb.checked);
+ const schedArray = [[fromSec, toSec], ...dayBools];
+
+ const params = new URLSearchParams({
+ cam: cameraName,
+ window: windowSeconds,
+ max: formData.get('max'),
+ class_ids: classIds,
+ sched: JSON.stringify(schedArray),
+ });
+
+ fetch(`/edit_alert?${params.toString()}`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to add alert");
+ return res.json();
+ })
+ .then(() => {
+ closeAlertModal();
+ form.reset();
+ fetchAlerts();
+ })
+ .catch(err => {
+ console.error("Add alert failed:", err);
+ alert("Failed to add alert.");
+ });
+ }
+
+
+ folderPicker.addEventListener("change", () => {
+ const folder = folderPicker.value;
+ const params = new URLSearchParams(window.location.search);
+ params.set('date', folder);
+ window.location.search = params.toString();
+ });
+
+ function getCurrentDate() {
+ const params = new URLSearchParams(window.location.search);
+ return params.get('date') || folderPicker.value;
+ }
+
+
+ function getQueryParam(name) {
+ const urlParams = new URLSearchParams(window.location.search);
+ return urlParams.get(name);
+ }
+
+ const initialDate = getQueryParam('date') || "{selected_dir}";
+ folderPicker.value = initialDate;
+
+
+ loadStream(getCurrentDate());
+ loadEventImages(getCurrentDate());
+ fetchAlerts();
+ fetchCounts();
+ setInterval(fetchCounts, 5000);
+ setInterval(() => loadEventImages(getCurrentDate()), 5000);
+</script>
+</body>
+</html>
\ No newline at end of file
diff --git a/clearcam.py b/clearcam.py
index 4f0c163..c7f0fd4 100644
--- a/clearcam.py
+++ b/clearcam.py
@@ -1620,1430 +1620,16 @@ class HLSRequestHandler(BaseHTTPRequestHandler):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
- html = f"""
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
- <link href="https://fonts.googleapis.com/css2?family=Inter&display=swap" rel="stylesheet">
- <style>
- .polygon-point {{
- transition: all 0.2s ease;
- }}
-
- .polygon-point:hover {{
- transform: scale(1.2);
- box-shadow: 0 0 5px rgba(0,0,0,0.5);
- }}
-
- .polygon-line path {{
- transition: all 0.2s ease;
- }}
-
- body {{
- font-family: 'Inter', sans-serif;
- margin: 0;
- padding: 0;
- background-color: #f9f9f9;
- color: #333;
- }}
-
- .checkbox-container {{
- display: grid;
- grid-template-columns: auto auto;
- gap: 8px 16px;
- max-height: 200px;
- overflow-y: auto;
- margin: 0 auto;
- padding: 8px;
- justify-content: center;
- }}
-
- .checkbox-container input[type="checkbox"] {{
- margin: 0;
- width: 16px;
- height: 16px;
- }}
-
- .checkbox-item {{
- display: flex;
- align-items: center;
- gap: 8px;
- margin-left: 10px;
- }}
-
- .checkbox-item input[type="checkbox"] {{
- margin: 0;
- transform: scale(1.2);
- }}
-
- .container {{
- max-width: 900px;
- margin: 0 auto;
- padding: 20px;
- }}
-
- video {{
- width: 100%;
- border-radius: 12px;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
- margin-bottom: 20px;
- }}
-
- .date-picker-container {{
- display: flex;
- justify-content: center;
- align-items: center;
- gap: 10px;
- margin: 20px 0;
- flex-wrap: wrap;
- }}
-
- .date-picker-container input[type="date"],
- .date-picker-container button {{
- height: 40px;
- font-size: 0.95rem;
- padding: 6px 12px;
- border-radius: 6px;
- border: 1px solid #ccc;
- box-sizing: border-box;
- }}
-
- .counts-wrapper {{
- display: flex;
- flex-wrap: wrap;
- justify-content: center;
- align-items: center;
- gap: 20px;
- margin: 20px 0;
- }}
-
- .controls {{
- display: flex;
- flex-wrap: wrap;
- gap: 16px;
- align-items: flex-end;
- justify-content: center;
- margin-bottom: 20px;
- }}
-
- .controls label {{
- font-size: 0.9rem;
- display: flex;
- flex-direction: column;
- flex: 1 1 auto;
- min-width: 120px;
- }}
-
- input[type="date"],
- input[type="time"] {{
- padding: 6px 10px;
- border-radius: 8px;
- border: 1px solid #ccc;
- font-size: 1rem;
- }}
-
- button {{
- background-color: #f0f0f0;
- color: #1a73e8;
- padding: 10px 24px;
- border: none;
- border-radius: 6px;
- font-size: 1rem;
- cursor: pointer;
- transition: all 0.3s ease;
- min-width: 100px;
- text-align: center;
- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
- }}
-
- button:hover {{
- background-color: #e0e0e0;
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
- }}
-
- .form-actions button {{
- min-width: 80px;
- }}
-
- #alertsContainer table button {{
- padding: 6px 12px;
- min-width: 90px;
- text-align: center;
- font-size: 0.9rem;
- }}
-
- h3 {{
- font-size: 1.2rem;
- margin: 20px 0 10px;
- }}
-
- #eventImagesContainer {{
- display: flex;
- flex-wrap: wrap;
- justify-content: center;
- gap: 14px;
- }}
-
- #eventImagesContainer img {{
- width: 220px;
- height: auto;
- border-radius: 10px;
- border: 1px solid #ccc;
- transition: transform 0.2s;
- }}
-
- #eventImagesContainer img:hover {{
- transform: scale(1.05);
- }}
-
- /* Modal styles */
- .modal {{
- display: none;
- position: fixed;
- z-index: 999;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(0, 0, 0, 0.4);
- justify-content: center;
- align-items: center;
- overflow: auto;
- }}
-
- .form-group.checkbox-group {{
- flex: 1;
- min-height: 0; /* Important for flex children */
- }}
-
- .modal-content {{
- background-color: #fefefe;
- padding: 20px;
- border-radius: 8px;
- width: 90%;
- max-width: 500px;
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
- }}
-
- .modal-header {{
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 15px;
- }}
-
- .modal-header h3 {{
- margin: 0;
- }}
-
- .close {{
- color: #aaa;
- font-size: 28px;
- font-weight: bold;
- cursor: pointer;
- }}
-
- .close:hover {{
- color: black;
- }}
-
- .form-group {{
- margin-bottom: 15px;
- }}
-
- .form-group label {{
- display: block;
- margin-bottom: 5px;
- font-weight: 500;
- }}
-
- .form-group input {{
- width: 100%;
- padding: 8px;
- border: 1px solid #ddd;
- border-radius: 4px;
- box-sizing: border-box;
- }}
-
- .form-actions {{
- display: flex;
- justify-content: flex-end;
- gap: 10px;
- margin-top: 20px;
- }}
-
- @media (max-width: 600px) {{
- button {{
- padding: 8px 16px;
- font-size: 0.9rem;
- min-width: 80px;
- }}
-
- .form-actions button {{
- min-width: 70px;
- }}
-
- input[type="date"] {{
- width: 100%;
- max-width: 200px;
- padding: 6px 8px;
- font-size: 0.9rem;
- }}
-
- input[type="time"] {{
- width: 100px;
- padding: 6px 8px;
- font-size: 0.9rem;
- }}
-
- .modal-content {{
- width: 95%;
- padding: 15px;
- }}
-
- .form-group input {{
- padding: 6px 8px;
- font-size: 0.9rem;
- }}
-
- #alertsContainer table {{
- font-size: 0.9rem;
- }}
-
- #alertsContainer table button {{
- min-width: 80px;
- padding: 5px 10px;
- font-size: 0.8rem;
- }}
-
- .controls label {{
- min-width: auto;
- width: 100%;
- }}
-
- .counts-wrapper {{
- flex-direction: column;
- gap: 10px;
- }}
-
- .date-picker-container {{
- flex-wrap: nowrap;
- }}
-
- .date-picker-container input[type="date"],
- .date-picker-container button {{
- height: 36px;
- font-size: 0.85rem;
- padding: 6px 10px;
- }}
- }}
- </style>
- </head>
- <body>
- <div class="container">
- <video id="video" controls></video>
- <div class="date-picker-container">
- <input type="date" id="folderPicker" value="{selected_dir}">
- <label style="display: flex; align-items: center; gap: 6px; margin-left: 10px;">
- <input type="checkbox" id="showDetections" {show_detections_checked}> Show detections
- </label>
- </div>
- <h3>Active Alerts</h3>
- <div id="alertsContainer">
- <p>Loading alerts...</p>
- <div style="display: flex; gap: 10px; justify-content: flex-start; margin-top: 10px;">
- <button onclick="openSettingsEditor()">Settings</button>
- <button onclick="openAlertModal()">Add Alert</button>
- </div>
- </div>
-
- <!-- The Modal -->
- <div id="alertModal" class="modal">
- <div class="modal-content" style="max-width: 400px;">
- <div class="modal-header">
- <h3>Add New Alert</h3>
- <span class="close" onclick="closeAlertModal()">&times;</span>
- </div>
- <form id="alertForm" onsubmit="addAlert(event)" style="display: flex; flex-direction: column; align-items: center;">
- <div class="form-group" style="width: 90%; text-align: center;">
- <label for="maxCount">Trigger if there are more than</label>
- <input type="number" id="maxCount" name="max" min="1" value="1" required
- style="width: 80px; margin: 0 6px; text-align: center; display: inline-block;">
- <span>objects detected</span>
- </div>
- <div class="form-group checkbox-group" style="width: 90%; text-align: center;">
- <label>of class(es)</label>
- <div id="checkboxContainer" class="checkbox-container"></div>
- </div>
- <div class="form-group" style="width: 90%; text-align: center;">
- <label for="windowMinutes">within this time window</label>
- <input type="number" id="windowMinutes" name="window" min="1" value="1" required
- style="width: 80px; margin: 0 6px; text-align: center; display: inline-block;">
- <span>minutes</span>
- </div>
-
- <div class="form-group" style="width: 90%; text-align: center;">
- <label>Schedule (optional)</label>
- <div style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;">
- <div>
- <label for="scheduleFrom">From</label><br>
- <input type="time" id="scheduleFrom" name="schedule_from" step="60" style="text-align: center;">
- </div>
- <div>
- <label for="scheduleTo">To</label><br>
- <input type="time" id="scheduleTo" name="schedule_to" step="60" style="text-align: center;">
- </div>
- </div>
- </div>
- <div class="form-group" style="width: 90%; text-align: center;">
- <div style="display: flex; flex-direction: column; align-items: center; gap: 5px; margin-top: 5px;">
- <label><input type="checkbox" name="days" value="0" checked> Mon</label>
- <label><input type="checkbox" name="days" value="1" checked> Tue</label>
- <label><input type="checkbox" name="days" value="2" checked> Wed</label>
- <label><input type="checkbox" name="days" value="3" checked> Thu</label>
- <label><input type="checkbox" name="days" value="4" checked> Fri</label>
- <label><input type="checkbox" name="days" value="5" checked> Sat</label>
- <label><input type="checkbox" name="days" value="6" checked> Sun</label>
- </div>
- </div>
-
- <div class="form-actions" style="display: flex; justify-content: center; gap: 10px; margin-top: 20px; width: 100%;">
- <button type="button" onclick="closeAlertModal()">Cancel</button>
- <button type="submit">Save Alert</button>
- </div>
- </form>
- </div>
- </div>
-
-
- <div id="zoneModal" class="modal">
- <div class="modal-content" style="max-width: 600px;">
- <div class="modal-header">
- <h3>Edit Zone</h3>
- <span class="close" onclick="closeZoneModal()">&times;</span>
- </div>
- <div style="position: relative; display: inline-block; max-width: 100%;">
- <img id="zonePreview" src="/{cam_name}/preview.png"
- style="width: 100%; max-height: 400px; object-fit: contain; border: 1px solid #ccc; border-radius: 6px; user-select: none; -webkit-user-drag: none; cursor: crosshair;">
- <div id="polygonOverlay" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;"></div>
- </div>
- <div style="margin: 10px 0; text-align: center; color: #666; font-size: 0.9rem;">
- Click on the image to add points. Right-click to remove points. Click on the first point (blue) to complete the polygon.
- </div>
- <div class="form-actions" style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center; width: 100%;">
- <div style="display: flex; flex-direction: column; gap: 10px;">
- <label style="display: flex; align-items: center; gap: 6px;">
- <input type="checkbox" id="zoneEnabledCheckbox" checked> Enable Zone
- </label>
- <label style="display: flex; align-items: center; gap: 6px;">
- <input type="checkbox" id="outsideZoneCheckbox"> Detect outside of zone
- </label>
- <label style="display: flex; align-items: center; gap: 6px;">
- Detection Threshold:
- <input type="number" id="zoneThreshold" value="50" min="0" max="100" step="1" style="width: 60px;"> %
- </label>
- </div>
- <div style="display: flex; gap: 10px;">
- <button type="button" onclick="clearPolygon()">Clear</button>
- <button type="button" onclick="closeZoneModal()">Cancel</button>
- <button type="button" onclick="saveZone()">Save</button>
- </div>
- </div>
- </div>
- </div>
-
-
- <div class="counts-wrapper">
- <table id="objectCounts" style="font-size: 1rem; border-collapse: collapse;">
- <tbody></tbody>
- </table>
- <button onclick="resetCounts()">Reset</button>
- </div>
-
- <h3>Detected Events</h3>
- <div id="eventImagesContainer">
- {image_links}
- </div>
- <div id="imagePreviewModal" class="modal">
- <span class="close" onclick="closeImagePreview()">&times;</span>
- <img id="previewImage" src="" alt="Preview">
- </div>
- </div>
-
- <script>
- const classLabels = {class_labels};
- const alertModal = document.getElementById("alertModal");
- const folderPicker = document.getElementById("folderPicker");
- const video = document.getElementById("video");
- const startTime = {start_time if start_time is not None else 'null'};
- const cameraName = "{cam_name}";
-
-
- window.onload = function () {{
- const container = document.getElementById('checkboxContainer');
- container.innerHTML = '';
-
- for (let i = 0; i < 80; i++) {{
- const checkbox = document.createElement('input');
- checkbox.type = 'checkbox';
- checkbox.value = i;
- checkbox.name = 'class_ids';
- checkbox.id = 'class_' + i;
-
- const label = document.createElement('label');
- label.htmlFor = 'class_' + i;
- label.textContent = (classLabels[i] !== undefined) ? `${{classLabels[i]}}` : `${{i}}`;
-
- container.appendChild(checkbox);
- container.appendChild(label);
- }}
- }};
-
- function viewImage(imageSrc) {{
- const previewModal = document.getElementById("imagePreviewModal");
- const previewImage = document.getElementById("previewImage");
- previewImage.src = imageSrc;
-
- // Force reasonable size
- previewImage.style.maxWidth = '70%';
- previewImage.style.maxHeight = '70%';
- previewImage.style.width = 'auto';
- previewImage.style.height = 'auto';
-
- previewModal.style.display = "flex";
- }}
-
- function closeImagePreview() {{
- document.getElementById("imagePreviewModal").style.display = "none";
- }}
-
- function playVideoAtTime(timestamp) {{
- const params = new URLSearchParams(window.location.search);
- params.set('start', timestamp);
- window.location.search = params.toString();
- }}
- window.addEventListener("click", function(event) {{
- const modal = document.getElementById("imagePreviewModal");
- if (event.target === modal) {{
- closeImagePreview();
- }}
- }});
- document.addEventListener('keydown', function(event) {{
- if (event.key === 'Escape') {{
- closeImagePreview();
- }}
- }});
-
- const zoneModal = document.getElementById("zoneModal");
- const zoneRect = document.getElementById("zoneRect");
- let isDragging = false;
- let isResizing = false;
- let resizeHandle = null;
- let startX, startY;
- let startWidth, startHeight;
- let startLeft, startTop;
-
- function closeZoneModal() {{
- zoneModal.style.display = "none";
- }}
-
- // Global variables for polygon editing
- // Global variables for polygon editing
- let polygonSvg = null;
- let polygonPath = null;
- let firstPoint = null;
- let isPolygonComplete = false;
-
- function openSettingsEditor() {{
- zoneModal.style.display = "flex";
-
- // Initialize the zone editor first
- initZoneEditor();
-
- // Then load the settings
- fetch(`/get_settings?cam=${{encodeURIComponent(cameraName)}}`)
- .then(res => res.json())
- .then(data => {{
- console.log("Received settings data:", data);
- const previewEl = document.getElementById("zonePreview");
-
- if (data && data.coords) {{
- console.log("Loading coords:", data.coords);
- // Load existing polygon coordinates
- loadPolygon(data.coords, previewEl);
- }}
-
- const zoneEnabledCheckbox = document.getElementById("zoneEnabledCheckbox");
- if (data.is_on !== undefined) {{
- zoneEnabledCheckbox.checked = data.is_on;
- }} else if (data.length && data[0] && data[0].is_on !== undefined) {{
- zoneEnabledCheckbox.checked = data[0].is_on;
- }} else {{
- zoneEnabledCheckbox.checked = false;
- }}
-
- const outsideZoneCheckbox = document.getElementById("outsideZoneCheckbox");
- if (data.outside !== undefined) {{
- outsideZoneCheckbox.checked = data.outside;
- }} else if (data.length && data[0] && data[0].outside !== undefined) {{
- outsideZoneCheckbox.checked = data[0].outside;
- }} else {{
- outsideZoneCheckbox.checked = false;
- }}
-
- const thresholdInput = document.getElementById("zoneThreshold");
- let rawThreshold = undefined;
- if (data.threshold !== undefined) {{
- rawThreshold = data.threshold;
- }} else if (data.length && data[0] && data[0].threshold !== undefined) {{
- rawThreshold = data[0].threshold;
- }}
- if (rawThreshold !== undefined) {{
- if (rawThreshold <= 1) {{
- thresholdInput.value = (rawThreshold * 100).toFixed(0);
- }} else {{
- thresholdInput.value = rawThreshold.toFixed(0);
- }}
- }}
- }})
- .catch(err => {{
- console.error("Failed to load zone:", err);
- }});
- }}
-
- function closeZoneModal() {{
- zoneModal.style.display = "none";
- }}
-
- function saveZone() {{
- const previewEl = document.getElementById("zonePreview");
- const points = Array.from(document.querySelectorAll('.polygon-point'));
-
- let coords = null;
- if (points.length >= 3) {{
- const videoWidth = 1280;
- const videoHeight = 720;
- const previewRect = previewEl.getBoundingClientRect();
-
- coords = points.map(point => {{
- const pointRect = point.getBoundingClientRect();
- const centerX = pointRect.left + pointRect.width / 2;
- const centerY = pointRect.top + pointRect.height / 2;
-
- const x = ((centerX - previewRect.left) / previewRect.width) * videoWidth;
- const y = ((centerY - previewRect.top) / previewRect.height) * videoHeight;
-
- return [x, y];
- }});
- }}
-
- const is_on = document.getElementById("zoneEnabledCheckbox").checked;
- const outside = document.getElementById("outsideZoneCheckbox").checked;
-
- const thresholdPercent = parseFloat(document.getElementById("zoneThreshold").value) || 50;
- const threshold = thresholdPercent / 100;
-
- const params = new URLSearchParams({{
- cam: cameraName,
- is_on: is_on,
- threshold: threshold.toFixed(2),
- outside: outside
- }});
-
- if (coords) {{
- params.set('coords', JSON.stringify(coords));
- }}
-
- fetch(`/edit_settings?${{params.toString()}}`)
- .then(res => {{
- if (!res.ok) throw new Error("Failed to save settings");
- console.log("Settings saved successfully");
- closeZoneModal();
- }})
- .catch(err => {{
- console.error("Save settings failed:", err);
- alert("Failed to save settings.");
- }});
- }}
-
- function initZoneEditor() {{
- const previewEl = document.getElementById("zonePreview");
-
- // Clear any existing polygon
- clearPolygon();
-
- // Initialize SVG overlay
- initPolygonOverlay();
-
- // Add click event listener for adding points
- previewEl.addEventListener('click', handlePreviewClick);
- }}
-
- function initPolygonOverlay() {{
- const overlay = document.getElementById("polygonOverlay");
- overlay.innerHTML = '';
-
- // Create SVG element
- polygonSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- polygonSvg.style.width = '100%';
- polygonSvg.style.height = '100%';
- polygonSvg.style.position = 'absolute';
- polygonSvg.style.top = '0';
- polygonSvg.style.left = '0';
- polygonSvg.style.pointerEvents = 'none';
-
- polygonPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- polygonPath.setAttribute('fill', 'none');
- polygonPath.setAttribute('stroke', '#ff0000');
- polygonPath.setAttribute('stroke-width', '2');
- polygonPath.setAttribute('stroke-linejoin', 'round');
-
- polygonSvg.appendChild(polygonPath);
- overlay.appendChild(polygonSvg);
- }}
-
- function handlePreviewClick(e) {{
- const previewEl = document.getElementById("zonePreview");
- const rect = previewEl.getBoundingClientRect();
-
- // Calculate position relative to preview element
- const x = e.clientX - rect.left;
- const y = e.clientY - rect.top;
-
- // Check if we're clicking on the first point (to close polygon)
- if (firstPoint && isClickOnPoint(firstPoint, x, y)) {{
- // Complete the polygon
- completePolygon();
- return;
- }}
-
- // Create a new point
- createPoint(x, y);
-
- // Update the polygon visualization
- updatePolygonLine();
- }}
-
- function isClickOnPoint(point, clickX, clickY) {{
- const pointRect = point.getBoundingClientRect();
- const previewRect = document.getElementById("zonePreview").getBoundingClientRect();
- const pointX = parseInt(point.style.left) + 6; // Center of point
- const pointY = parseInt(point.style.top) + 6;
-
- // Check if click is within the point's area
- const distance = Math.sqrt(Math.pow(clickX - pointX, 2) + Math.pow(clickY - pointY, 2));
- return distance <= 10; // Increased tolerance for easier clicking
- }}
-
- function completePolygon() {{
- console.log("Completing polygon"); // Debug log
- polygonPath.setAttribute('fill', 'rgba(0, 255, 0, 0.3)');
- polygonPath.setAttribute('stroke', '#00ff00');
- const previewEl = document.getElementById("zonePreview");
- previewEl.removeEventListener('click', handlePreviewClick);
- enablePointDragging();
- isPolygonComplete = true;
- updatePolygonLine();
- }}
-
- function createPoint(x, y) {{
- const overlay = document.getElementById("polygonOverlay");
- const point = document.createElement('div');
- point.className = 'polygon-point';
- point.style.position = 'absolute';
- point.style.left = (x - 6) + 'px';
- point.style.top = (y - 6) + 'px';
- point.style.width = '12px';
- point.style.height = '12px';
- point.style.backgroundColor = '#ff0000';
- point.style.borderRadius = '50%';
- point.style.cursor = 'crosshair';
- point.style.zIndex = '20';
- point.style.border = '2px solid #ffffff';
- point.style.boxShadow = '0 0 3px rgba(0,0,0,0.5)';
- point.style.pointerEvents = 'auto';
-
- // Store first point reference
- if (!firstPoint) {{
- firstPoint = point;
- // Make first point visually distinct
- point.style.backgroundColor = '#0000ff';
- point.style.border = '2px solid #ffffff';
- point.style.cursor = 'pointer'; // Make first point more clickable
- }}
-
- // Add click listener to first point for completion
- if (firstPoint === point) {{
- point.addEventListener('click', function(e) {{
- e.stopPropagation();
- if (!isPolygonComplete) {{
- completePolygon();
- }}
- }});
- }}
-
- // Add delete on right-click (always available)
- point.addEventListener('contextmenu', (e) => {{
- e.preventDefault();
- removePoint(point);
- }});
-
- overlay.appendChild(point);
- return point;
- }}
-
- function enablePointDragging() {{
- const points = Array.from(document.querySelectorAll('.polygon-point'));
- points.forEach(point => {{
- makePointDraggable(point);
- point.style.cursor = 'move';
- }});
- }}
-
- function removePoint(point) {{
- // If removing the first point, update the firstPoint reference
- if (point === firstPoint) {{
- const points = Array.from(document.querySelectorAll('.polygon-point'));
- if (points.length > 1) {{
- firstPoint = points[1]; // Second point becomes first
- firstPoint.style.backgroundColor = '#0000ff';
- }} else {{
- firstPoint = null;
- }}
- }}
-
- point.remove();
- updatePolygonLine();
-
- // If polygon was complete, re-enable editing
- if (isPolygonComplete) {{
- isPolygonComplete = false;
- const previewEl = document.getElementById("zonePreview");
- previewEl.addEventListener('click', handlePreviewClick);
-
- // Reset visual style
- if (polygonPath) {{
- polygonPath.setAttribute('fill', 'none');
- polygonPath.setAttribute('stroke', '#ff0000');
- }}
-
- // Disable dragging on remaining points
- const remainingPoints = Array.from(document.querySelectorAll('.polygon-point'));
- remainingPoints.forEach(p => {{
- p.style.cursor = 'crosshair';
- // Remove existing drag listeners
- p.replaceWith(p.cloneNode(true));
- }});
- }}
-
- // Reset instruction text
- const instruction = document.querySelector('#zoneModal .modal-content div:nth-child(3)');
- if (instruction) {{
- instruction.innerHTML = 'Click on the image to add points. Right-click to remove points. Click on the first point (blue) to complete the polygon.';
- }}
- }}
-
- function makePointDraggable(point) {{
- let isDragging = false;
- let startX, startY, startLeft, startTop;
-
- function dragPoint(e) {{
- if (!isDragging) return;
-
- const previewEl = document.getElementById("zonePreview");
- const previewRect = previewEl.getBoundingClientRect();
-
- const deltaX = e.clientX - startX;
- const deltaY = e.clientY - startY;
-
- let newLeft = startLeft + deltaX;
- let newTop = startTop + deltaY;
-
- // Constrain to preview area
- newLeft = Math.max(0, Math.min(newLeft, previewRect.width - 12));
- newTop = Math.max(0, Math.min(newTop, previewRect.height - 12));
-
- point.style.left = newLeft + 'px';
- point.style.top = newTop + 'px';
-
- // Force synchronous layout update before updating polygon line
- point.offsetHeight; // This triggers a reflow
-
- updatePolygonLine();
- }}
-
- function stopDragPoint() {{
- isDragging = false;
- document.removeEventListener('mousemove', dragPoint);
- document.removeEventListener('mouseup', stopDragPoint);
- document.removeEventListener('mouseleave', stopDragPoint);
- }}
-
- point.addEventListener('mousedown', (e) => {{
- // Only allow dragging if polygon is complete
- if (!isPolygonComplete) return;
-
- e.preventDefault();
- e.stopPropagation();
- isDragging = true;
- startX = e.clientX;
- startY = e.clientY;
-
- const style = window.getComputedStyle(point);
- startLeft = parseInt(style.left);
- startTop = parseInt(style.top);
-
- document.addEventListener('mousemove', dragPoint);
- document.addEventListener('mouseup', stopDragPoint);
- document.addEventListener('mouseleave', stopDragPoint);
- }});
- }}
-
- function updatePolygonLine() {{
- const previewEl = document.getElementById("zonePreview");
- const points = Array.from(document.querySelectorAll('.polygon-point'));
-
- if (points.length === 0) {{
- polygonPath.setAttribute('d', '');
- firstPoint = null;
- isPolygonComplete = false;
- return;
- }}
-
- // Create SVG path for the polygon - just draw lines between points, don't close automatically
- const pathData = points.map((point, index) => {{
- const rect = point.getBoundingClientRect();
- const previewRect = previewEl.getBoundingClientRect();
- const x = rect.left - previewRect.left + 6; // Center of point
- const y = rect.top - previewRect.top + 6;
- return `${{index === 0 ? 'M' : 'L'}} ${{x}} ${{y}}`;
- }}).join(' ');
-
- // Only close the path if polygon is complete
- if (isPolygonComplete) {{
- polygonPath.setAttribute('d', pathData + ' Z');
- }} else {{
- polygonPath.setAttribute('d', pathData);
- }}
- }}
-
- function loadPolygon(coords, previewEl) {{
- const videoWidth = 1280;
- const videoHeight = 720;
-
- // Wait for the image to load to get actual dimensions
- const img = document.getElementById("zonePreview");
- if (img.complete) {{
- drawPolygonCoords(coords, img, previewEl);
- }} else {{
- img.addEventListener('load', function() {{
- drawPolygonCoords(coords, img, previewEl);
- }});
- }}
- }}
-
- function drawPolygonCoords(coords, img, previewEl) {{
- const videoWidth = 1280;
- const videoHeight = 720;
-
- // Get the actual displayed dimensions of the image
- const displayedWidth = img.clientWidth;
- const displayedHeight = img.clientHeight;
-
- console.log("Loading polygon coords:", coords);
- console.log("Image dimensions:", displayedWidth, displayedHeight);
-
- coords.forEach(coord => {{
- const x = (coord[0] / videoWidth) * displayedWidth;
- const y = (coord[1] / videoHeight) * displayedHeight;
- console.log("Creating point at:", x, y, "from coord:", coord);
- createPoint(x, y);
- }});
-
- updatePolygonLine();
-
- // If loading an existing polygon, mark it as complete
- if (coords.length >= 3) {{
- completePolygon();
- }}
- }}
-
- function clearPolygon() {{
- const overlay = document.getElementById("polygonOverlay");
- const points = overlay.querySelectorAll('.polygon-point');
- points.forEach(point => point.remove());
-
- firstPoint = null;
- isPolygonComplete = false;
-
- if (polygonPath) {{
- polygonPath.setAttribute('d', '');
- polygonPath.setAttribute('fill', 'none');
- polygonPath.setAttribute('stroke', '#ff0000');
- }}
-
- // Re-enable clicking
- const previewEl = document.getElementById("zonePreview");
- previewEl.addEventListener('click', handlePreviewClick);
-
- // Reset instruction text
- const instruction = document.querySelector('#zoneModal .modal-content div:nth-child(3)');
- if (instruction) {{
- instruction.innerHTML = 'Click on the image to add points. Right-click to remove points. Click on the first point (blue) to complete the polygon.';
- }}
- }}
-
- // Add some CSS styles for the polygon editor
- const polygonStyles = `
- .polygon-point:hover {{
- transform: scale(1.2);
- box-shadow: 0 0 5px rgba(0,0,0,0.5);
- }}
- .polygon-line path {{
- transition: all 0.2s ease;
- }}
- `;
-
- const styleSheet = document.createElement("style");
- styleSheet.textContent = polygonStyles;
- document.head.appendChild(styleSheet);
-
-
- function openAlertModal() {{
- alertModal.style.display = "flex";
- }}
-
- function closeAlertModal() {{
- alertModal.style.display = "none";
- }}
-
- window.addEventListener("click", function(event) {{
- if (event.target === alertModal) closeAlertModal();
- }});
-
- document.getElementById("showDetections").addEventListener("change", function() {{
- const currentTime = video.currentTime;
- const params = new URLSearchParams(window.location.search);
- params.set('show_detections', this.checked);
- params.set('start', currentTime);
- window.location.search = params.toString();
- }});
-
- function initDetectionSettings() {{
- const urlParams = new URLSearchParams(window.location.search);
- const showDetections = urlParams.get('show_detections') === 'true';
-
- if (showDetections) {{
- // Send initial request
- fetch(`/edit_settings?cam=${{encodeURIComponent(cameraName)}}&show_dets=1`)
- .then(res => {{
- if (!res.ok) throw new Error("Failed to update detection settings");
- console.log("Detection settings updated successfully");
- }})
- .catch(err => {{
- console.error("Failed to update detection settings:", err);
- }});
-
- // Set up interval to send request every 30 seconds
- window.detectionInterval = setInterval(() => {{
- fetch(`/edit_settings?cam=${{encodeURIComponent(cameraName)}}&show_dets=1`)
- .then(res => {{
- if (!res.ok) throw new Error("Failed to refresh detection settings");
- console.log("Detection settings refreshed");
- }})
- .catch(err => {{
- console.error("Failed to refresh detection settings:", err);
- }});
- }}, 30000); // 30 seconds
- }}
- }}
-
- document.getElementById("showDetections").addEventListener("change", function() {{
- const currentTime = video.currentTime;
- const params = new URLSearchParams(window.location.search);
- params.set('show_detections', this.checked);
- window.location.search = params.toString();
- }});
-
- window.addEventListener('beforeunload', function() {{
- if (window.detectionInterval) {{
- clearInterval(window.detectionInterval);
- }}
- }});
-
- initDetectionSettings();
-
- function loadStream(folder) {{
- const showDetections = document.getElementById("showDetections").checked;
- const streamSuffix = showDetections ? "" : "_raw";
- const url = `${{cameraName}}${{streamSuffix}}/streams/${{folder}}/stream.m3u8`;
-
- async function waitForManifest(maxRetries = 30, delay = 2000) {{
- for (let i = 0; i < maxRetries; i++) {{
- try {{
- const res = await fetch(url, {{ cache: "no-store" }});
- if (res.ok) {{
- const text = await res.text();
- if (text.includes("#EXTINF")) {{
- return true; // playlist has segments
- }}
- }}
- }} catch (err) {{
- console.warn("Stream not ready yet:", err);
- }}
- await new Promise(r => setTimeout(r, delay));
- }}
- return false;
- }}
-
- (async () => {{
- const ready = await waitForManifest();
- if (!ready) {{
- console.error("Stream never became available.");
- return;
- }}
-
- if (Hls.isSupported()) {{
- const hls = new Hls({{
- manifestLoadingTimeOut: 20000,
- manifestLoadingMaxRetry: Infinity,
- manifestLoadingRetryDelay: 2000,
- }});
-
- hls.loadSource(url);
- hls.attachMedia(video);
-
- hls.on(Hls.Events.MANIFEST_PARSED, function () {{
- if (startTime !== null) video.currentTime = startTime;
- video.play();
- }});
-
- hls.on(Hls.Events.ERROR, function (event, data) {{
- if (data.fatal) {{
- switch (data.type) {{
- case Hls.ErrorTypes.NETWORK_ERROR:
- console.warn("Network error, retrying...");
- hls.startLoad(-1);
- break;
- case Hls.ErrorTypes.MEDIA_ERROR:
- console.warn("Media error, recovering...");
- hls.recoverMediaError();
- break;
- default:
- console.error("Fatal error, destroying HLS instance.");
- hls.destroy();
- break;
- }}
- }}
- }});
- }} else if (video.canPlayType('application/vnd.apple.mpegurl')) {{
- video.src = url;
- video.addEventListener('loadedmetadata', function () {{
- if (startTime !== null) video.currentTime = startTime;
- video.play();
- }});
- }}
- }})();
- }}
-
-
- function loadEventImages(folder) {{
- fetch(`/event_thumbs?cam=${{cameraName}}&folder=${{folder}}`)
- .then(res => res.text())
- .then(html => {{
- const container = document.getElementById("eventImagesContainer");
-
- // Create a temporary div to parse incoming HTML
- const temp = document.createElement("div");
- temp.innerHTML = html.trim();
-
- // Compare child count and content
- const isSameLength = container.children.length === temp.children.length;
- let isSame = isSameLength;
-
- if (isSameLength) {{
- for (let i = 0; i < container.children.length; i++) {{
- if (
- container.children[i].outerHTML.trim() !==
- temp.children[i].outerHTML.trim()
- ) {{
- isSame = false;
- break;
- }}
- }}
- }}
-
- if (!isSame) {{
- container.innerHTML = html;
- }}
- }})
- .catch(err => {{
- console.error("Failed to load images:", err);
- const container = document.getElementById("eventImagesContainer");
- container.innerHTML = "<p>No event images found.</p>";
- }});
- }}
-
- function fetchCounts() {{
- fetch(`/get_counts?cam=${{encodeURIComponent(cameraName)}}`)
- .then(res => res.json())
- .then(data => {{
- const tbody = document.querySelector("#objectCounts tbody");
- tbody.innerHTML = "";
-
- const entries = Object.entries(data).sort((a, b) => b[1] - a[1]);
- if (!entries.length) {{
- tbody.innerHTML = "<tr><td colspan='2'>No detections.</td></tr>";
- return;
- }}
-
- for (const [label, count] of entries) {{
- tbody.innerHTML += `
- <tr>
- <td style="padding:6px 12px; border-bottom:1px solid #eee;">${{label}}</td>
- <td style="padding:6px 12px; border-bottom:1px solid #eee;">${{count}}</td>
- </tr>`;
- }}
- }})
- .catch(err => {{
- console.error("Failed to fetch counts:", err);
- document.querySelector("#objectCounts tbody").innerHTML = "<tr><td colspan='2'>Error fetching counts.</td></tr>";
- }});
- }}
-
- function resetCounts() {{
- if (!confirm("Are you sure you want to reset the counts for this camera?")) return;
- fetch(`/reset_counts?cam=${{encodeURIComponent(cameraName)}}`)
- .then(res => res.json())
- .then(() => {{
- console.log("Counts reset");
- fetchCounts();
- }})
- .catch(err => {{
- console.error("Failed to reset counts:", err);
- alert("Failed to reset counts.");
- }});
- }}
-
- function fetchAlerts() {{
- fetch(`/get_alerts?cam=${{encodeURIComponent(cameraName)}}`)
- .then(res => res.json())
- .then(alerts => {{
- const container = document.getElementById("alertsContainer");
- if (!alerts.length) {{
- container.innerHTML = `
- <p>No alerts configured.</p>
- <div style="display: flex; gap: 10px; justify-content: center; margin-top: 10px;">
- <button onclick="openSettingsEditor()">Settings</button>
- <button onclick="openAlertModal()">Add Alert</button>
- </div>`;
- return;
- }}
-
- let html = `<table style="width:100%; border-collapse:collapse; font-size:0.95rem;">
- <thead>
- <tr>
- <th style="text-align:center; padding:6px; border-bottom:1px solid #ccc;"></th>
- <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Occurrences of</th>
- <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Within</th>
- <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Schedule</th>
- <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;"></th>
- </tr>
- </thead><tbody>`;
-
- for (const alert of alerts) {{
- const classNames = alert.classes.map(id => classLabels[id] ?? id).join(", ");
- const h = Math.floor(alert.window / 3600);
- const m = Math.floor((alert.window % 3600) / 60);
- const s = alert.window % 60;
- const windowStr = `${{String(h).padStart(2,'0')}}:${{String(m).padStart(2,'0')}}:${{String(s).padStart(2,'0')}}`;
- const fromH = Math.floor(alert.sched[0][0] / 3600);
- const fromM = Math.floor((alert.sched[0][0] % 3600) / 60);
- let toSec = alert.sched[0][1];
- if (toSec % 60 !== 0) {{
- toSec += 60 - (toSec % 60);
- }}
- if (toSec >= 86400) {{
- toSec = 0;
- }}
- const toH = Math.floor(toSec / 3600);
- const toM = Math.floor((toSec % 3600) / 60);
- const timeRange = `${{String(fromH).padStart(2,'0')}}:${{String(fromM).padStart(2,'0')}} to ${{String(toH).padStart(2,'0')}}:${{String(toM).padStart(2,'0')}}`;
-
- const daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
- const activeDays = alert.sched.slice(1).map((on, idx) => on ? daysOfWeek[idx] : null).filter(Boolean);
- let daysStr;
- if (activeDays.length === 7) {{
- daysStr = "Daily";
- }} else {{
- // compress consecutive ranges (Mon–Fri)
- const indices = alert.sched.slice(1).map((on, i) => on ? i : -1).filter(i => i >= 0);
- let ranges = [];
- let start = null;
- let prev = null;
- for (const idx of indices) {{
- if (start === null) {{
- start = idx;
- prev = idx;
- }} else if (idx === prev + 1) {{
- prev = idx;
- }} else {{
- ranges.push([start, prev]);
- start = idx;
- prev = idx;
- }}
- }}
- if (start !== null) {{
- ranges.push([start, prev]);
- }}
- daysStr = ranges.map(([a, b]) => {{
- if (a === b) return daysOfWeek[a];
- else return `${{daysOfWeek[a]}}-${{daysOfWeek[b]}}`;
- }}).join(", ");
- }}
- const schedStr = `${{timeRange}} (${{daysStr}})`;
- const isOn = alert.hasOwnProperty("is_on") ? alert.is_on : true;
- const checkedAttr = isOn ? "checked" : "";
- html += `<tr>
- <td style="padding:6px; border-bottom:1px solid #eee;">${{alert.max}}</td>
- <td style="padding:6px; border-bottom:1px solid #eee;">${{classNames}}</td>
- <td style="padding:6px; border-bottom:1px solid #eee;">${{windowStr}}</td>
- <td style="padding:6px; border-bottom:1px solid #eee;">${{schedStr}}</td>
- <td style="padding:6px; border-bottom:1px solid #eee; display:flex; justify-content:center; align-items:center;">
- <input type="checkbox" data-alert-id="${{alert.id}}" ${{checkedAttr}}
- onchange="toggleAlert('${{alert.id}}', this.checked)"
- style="transform:scale(1.2); cursor:pointer;">
- </td>
- <td style="padding:6px; border-bottom:1px solid #eee; text-align:center;">
- <button onclick="deleteAlert('${{alert.id}}')" style="padding:4px 8px;">Delete</button>
- </td>
- </tr>`;
- }}
-
-
- html += `</tbody></table>
- <div style="margin-top:10px; display:flex; gap:10px; justify-content:center;">
- <button onclick="openSettingsEditor()">Settings</button>
- <button onclick="openAlertModal()">Add Alert</button>
- </div>`;
- container.innerHTML = html;
- }})
- .catch(err => {{
- console.error("Failed to fetch alerts:", err);
- document.getElementById("alertsContainer").innerHTML = "<p>Error loading alerts.</p>";
- }});
- }}
-
- function toggleAlert(alertId, isOn) {{
- fetch(`/edit_alert?cam=${{encodeURIComponent(cameraName)}}&id=${{alertId}}&is_on=${{isOn}}`)
- .then(res => {{
- if (!res.ok) throw new Error("Failed to toggle alert");
- console.log(`Alert ${{alertId}} ${{isOn ? 'enabled' : 'disabled'}}`);
- }})
- .catch(err => {{
- console.error("Toggle alert failed:", err);
- alert("Failed to toggle alert status.");
- fetchAlerts();
- }});
- }}
-
- function deleteAlert(alertId) {{
- fetch(`/edit_alert?cam=${{encodeURIComponent(cameraName)}}&id=${{alertId}}`)
- .then(res => {{
- if (!res.ok) throw new Error("Failed to delete alert");
- fetchAlerts();
- }})
- .catch(err => {{
- console.error("Delete failed:", err);
- alert("Failed to delete alert.");
- }});
- }}
-
- function addAlert(event) {{
- event.preventDefault();
- const form = event.target;
- const formData = new FormData(form);
-
- const windowMinutes = parseFloat(formData.get('window'));
- const windowSeconds = Math.round(windowMinutes * 60);
-
- const checked = form.querySelectorAll('input[name="class_ids"]:checked');
- const classIds = Array.from(checked).map(cb => cb.value).join(',');
-
- const scheduleFrom = formData.get("schedule_from") || "00:00:00";
- const scheduleTo = formData.get("schedule_to") || "23:59:59";
-
- const toSeconds = (hhmmss) => {{
- const parts = hhmmss.split(":").map(Number);
- const [h = 0, m = 0, s = 0] = parts;
- return h * 3600 + m * 60 + s;
- }};
-
- const fromSec = toSeconds(scheduleFrom);
- const toSec = toSeconds(scheduleTo);
- const dayChecks = form.querySelectorAll('input[name="days"]');
- const dayBools = Array.from(dayChecks).map(cb => cb.checked);
- const schedArray = [[fromSec, toSec], ...dayBools];
-
- const params = new URLSearchParams({{
- cam: cameraName,
- window: windowSeconds,
- max: formData.get('max'),
- class_ids: classIds,
- sched: JSON.stringify(schedArray),
- }});
-
- fetch(`/edit_alert?${{params.toString()}}`)
- .then(res => {{
- if (!res.ok) throw new Error("Failed to add alert");
- return res.json();
- }})
- .then(() => {{
- closeAlertModal();
- form.reset();
- fetchAlerts();
- }})
- .catch(err => {{
- console.error("Add alert failed:", err);
- alert("Failed to add alert.");
- }});
- }}
-
-
- folderPicker.addEventListener("change", () => {{
- const folder = folderPicker.value;
- const params = new URLSearchParams(window.location.search);
- params.set('date', folder);
- window.location.search = params.toString();
- }});
-
- function getCurrentDate() {{
- const params = new URLSearchParams(window.location.search);
- return params.get('date') || folderPicker.value;
- }}
-
-
- function getQueryParam(name) {{
- const urlParams = new URLSearchParams(window.location.search);
- return urlParams.get(name);
- }}
-
- const initialDate = getQueryParam('date') || "{selected_dir}";
- folderPicker.value = initialDate;
-
-
- loadStream(getCurrentDate());
- loadEventImages(getCurrentDate());
- fetchAlerts();
- fetchCounts();
- setInterval(fetchCounts, 5000);
- setInterval(() => loadEventImages(getCurrentDate()), 5000);
- </script>
- </body>
- </html>
- """
+ with open('cameraview.html', 'r', encoding='utf-8') as f: html = f.read()
+ replacements = {
+ '{selected_dir}': selected_dir,
+ '{show_detections_checked}': 'checked' if show_detections else '',
+ '{image_links}': image_links,
+ '{class_labels}': json.dumps(class_labels),
+ '{start_time}': start_time if start_time is not None else 'null',
+ '{cam_name}': cam_name
+ }
+ for placeholder, value in replacements.items(): html = html.replace(placeholder, value)
self.wfile.write(html.encode("utf-8"))
return