Compare commits

..
Author SHA1 Message Date
Josh Hawkins 84c678d03e restore model bindings in media sync test, add test module docstrings 2026-11-23 19:02:13 -06:00
Josh Hawkins 61acbb2dcd fix media auth for trigger thumbnails and sub-stream recordings, fix trigger notification image
- Restricted roles got a 403 on their own cameras' trigger thumbnails and sub-stream recordings because /clips/triggers/{camera} had no classifier branch and {camera}@sub folders resolved to a camera name no allow-list contains. Trigger thumbnails now resolve like thumbs and previews, and the @sub suffix is stripped from the recording camera.
- Trigger push notifications pointed at a trigger thumbnail named after the triggering event, but those files are named after the trigger's reference event, so the image never loaded. The notification now uses the triggering event's thumbnail through the event thumbnail API.
- Media sync only scanned .jpg export thumbnails, so orphaned .webp thumbnails from current exports were never reclaimed. It now scans both.
2026-11-23 18:55:34 -06:00
16 changed files with 268 additions and 207 deletions
-2
View File
@@ -9630,8 +9630,6 @@ components:
title: Condition
max_duration_minutes:
type: integer
maximum: 1440.0
minimum: 1.0
title: Max Duration Minutes
default: 60
labels:
+2 -8
View File
@@ -14,7 +14,7 @@ import cv2
import numpy as np
from fastapi import APIRouter, Body, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from pydantic import BaseModel
from frigate.api.auth import (
allow_any_authenticated,
@@ -56,7 +56,6 @@ from frigate.genai.utils import (
)
from frigate.jobs.export import ExportQueueFullError, start_export_job
from frigate.jobs.vlm_watch import (
MAX_WATCH_MINUTES,
VLMWatchJob,
get_vlm_watch_job,
start_vlm_watch_job,
@@ -89,7 +88,7 @@ class VLMMonitorRequest(BaseModel):
camera: str
condition: str
max_duration_minutes: int = Field(default=60, ge=1, le=MAX_WATCH_MINUTES)
max_duration_minutes: int = 60
labels: list[str] = []
zones: list[str] = []
@@ -1031,17 +1030,12 @@ async def _execute_start_camera_watch(
camera = arguments.get("camera", "").strip()
condition = arguments.get("condition", "").strip()
max_duration_minutes = int(arguments.get("max_duration_minutes", 60))
max_duration_minutes = max(1, min(MAX_WATCH_MINUTES, max_duration_minutes))
labels = arguments.get("labels") or []
zones = arguments.get("zones") or []
if not camera or not condition:
return {"error": "camera and condition are required."}
for value in (labels, zones):
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
return {"error": "labels and zones must be lists of strings."}
config = request.app.frigate_config
if camera not in config.cameras:
return {"error": f"Camera '{camera}' not found."}
+19 -24
View File
@@ -216,28 +216,26 @@ def train_face(request: Request, name: str, body: dict = None):
status_code=404,
)
attributes = (event.data or {}).get("attributes") or []
snapshot = get_event_snapshot(event) if attributes else None
success = False
snapshot = get_event_snapshot(event)
face_box = event.data["attributes"][0]["box"]
detect_config: DetectConfig = request.app.frigate_config.cameras[
event.camera
].detect
if snapshot is not None:
face_box = attributes[0]["box"]
detect_config: DetectConfig = request.app.frigate_config.cameras[
event.camera
].detect
# crop onto the face box minus the bounding box itself
x1 = int(face_box[0] * detect_config.width) + 2
y1 = int(face_box[1] * detect_config.height) + 2
x2 = x1 + int(face_box[2] * detect_config.width) - 4
y2 = y1 + int(face_box[3] * detect_config.height) - 4
face = snapshot[y1:y2, x1:x2]
success = True
# crop onto the face box minus the bounding box itself
x1 = int(face_box[0] * detect_config.width) + 2
y1 = int(face_box[1] * detect_config.height) + 2
x2 = x1 + int(face_box[2] * detect_config.width) - 4
y2 = y1 + int(face_box[3] * detect_config.height) - 4
face = snapshot[y1:y2, x1:x2]
if face.size > 0:
try:
success = cv2.imwrite(os.path.join(new_file_folder, new_name), face)
except cv2.error:
logger.exception("Failed to save face image for %s", event_id)
if face.size > 0:
try:
cv2.imwrite(os.path.join(new_file_folder, new_name), face)
success = True
except Exception:
pass
if not success:
return JSONResponse(
@@ -1275,10 +1273,7 @@ async def generate_state_examples(request: Request, body: GenerateStateExamplesB
if camera_name in request.app.frigate_config.cameras
}
async with example_collection_lock:
await asyncio.to_thread(
collect_state_classification_examples, model_name, cameras_normalized
)
collect_state_classification_examples(model_name, cameras_normalized)
return JSONResponse(
content={"success": True, "message": "Example generation completed"},
+5 -3
View File
@@ -20,7 +20,7 @@ from urllib.parse import unquote
from peewee import DoesNotExist, Field
from frigate.config import FrigateConfig
from frigate.const import CLIPS_DIR, EXPORT_DIR
from frigate.const import CLIPS_DIR, EXPORT_DIR, SUB_CACHE_TAG
from frigate.models import Export, User
logger = logging.getLogger(__name__)
@@ -137,11 +137,12 @@ def _resolve_recording(
# /recordings/{date} → neutral
# /recordings/{date}/{hour} → multi-camera listing
# /recordings/{date}/{hour}/{cam}/... → camera
# /recordings/{date}/{hour}/{cam}@sub/... → camera (sub stream)
if len(parts) <= 2:
return MediaAuthResolution.LISTING_NEUTRAL, None
if len(parts) == 3:
return MediaAuthResolution.LISTING_MULTI_CAMERA, None
return MediaAuthResolution.CAMERA, parts[3]
return MediaAuthResolution.CAMERA, parts[3].removesuffix(SUB_CACHE_TAG)
def _resolve_clip(
@@ -150,6 +151,7 @@ def _resolve_clip(
# /clips → multi-camera listing
# /clips/thumbs/{cam}/... → camera
# /clips/previews/{cam}/... → camera
# /clips/triggers/{cam}/... → camera
# /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed)
# /clips/export/{export_id}.{ext} → camera (DB lookup)
# /clips/faces/... → admin-only
@@ -163,7 +165,7 @@ def _resolve_clip(
second = parts[1]
if second in ("thumbs", "previews"):
if second in ("thumbs", "previews", "triggers"):
if len(parts) == 2:
return MediaAuthResolution.LISTING_MULTI_CAMERA, None
return MediaAuthResolution.CAMERA, parts[2]
+1 -1
View File
@@ -685,7 +685,7 @@ class WebPushClient(Communicator):
title = f"{name.replace('_', ' ')} triggered on {camera_name}"
message = f"{titlecase(trigger_type)} trigger fired for {camera_name} with score {score:.2f}"
image = f"clips/triggers/{camera}/{event_id}.webp"
image = f"api/events/{event_id}/thumbnail.webp"
direct_url = f"/explore?event_id={event_id}"
ttl = 0
+12 -9
View File
@@ -110,13 +110,6 @@ class LlamaCppClient(GenAIClient):
"""POST with the configured auth headers injected."""
return requests.post(url, headers=self._auth_headers(), **kwargs)
def _server_url(self) -> str | None:
"""Return the configured base_url without a trailing slash or /v1."""
if not self.genai_config.base_url:
return None
return self.genai_config.base_url.rstrip("/").removesuffix("/v1")
def _fetch_llama_props(self, base_url: str, model: str) -> dict[str, Any]:
"""Fetch /props from a llama.cpp server, with llama-swap fallback.
@@ -150,10 +143,16 @@ class LlamaCppClient(GenAIClient):
self._supports_tools = False
self._supports_reasoning = False
base_url = self._server_url()
base_url = (
self.genai_config.base_url.rstrip("/")
if self.genai_config.base_url
else None
)
if base_url is None:
return None
else:
base_url = base_url.replace("/v1", "") # Strip /v1 if included in base_url
if not self.validate_model:
# Probe path
@@ -507,7 +506,11 @@ class LlamaCppClient(GenAIClient):
def _fetch_models_data(self) -> list[dict[str, Any]]:
"""Return the raw /v1/models entries, or an empty list if unreachable."""
base_url = self.provider or self._server_url()
base_url = self.provider or (
self.genai_config.base_url.rstrip("/")
if self.genai_config.base_url
else None
)
if base_url is None:
return []
+16 -5
View File
@@ -8,7 +8,7 @@ from collections.abc import AsyncGenerator
from typing import Any
import numpy as np
from httpx import HTTPError
from httpx import RemoteProtocolError, TimeoutException
from ollama import AsyncClient as OllamaAsyncClient
from ollama import Client as ApiClient
from ollama import ResponseError
@@ -282,7 +282,12 @@ class OllamaClient(GenAIClient):
try:
response = self.provider.chat(**request_params)
except (HTTPError, ResponseError, ConnectionError) as e:
except (
TimeoutException,
ResponseError,
RemoteProtocolError,
ConnectionError,
) as e:
logger.warning("Ollama returned an error: %s", str(e))
return None
@@ -401,7 +406,13 @@ class OllamaClient(GenAIClient):
# image items have to bypass it and post the JSON directly.
response = self.provider._request_raw("POST", "/api/embed", json=payload)
body = response.json()
except (HTTPError, ResponseError, ConnectionError, ValueError) as e:
except (
TimeoutException,
ResponseError,
RemoteProtocolError,
ConnectionError,
ValueError,
) as e:
logger.warning("Ollama embeddings error: %s", str(e))
return []
@@ -542,7 +553,7 @@ class OllamaClient(GenAIClient):
)
response = self.provider.chat(**request_params)
return self._message_from_response(response)
except (HTTPError, ResponseError, ConnectionError) as e:
except (TimeoutException, ResponseError, ConnectionError) as e:
logger.warning("Ollama returned an error: %s", str(e))
return {
"content": None,
@@ -674,7 +685,7 @@ class OllamaClient(GenAIClient):
"finish_reason": "stop",
},
)
except (HTTPError, ResponseError, ConnectionError) as e:
except (TimeoutException, ResponseError, ConnectionError) as e:
logger.warning("Ollama streaming error: %s", str(e))
yield (
"message",
+17 -27
View File
@@ -28,8 +28,6 @@ _MAX_INTERVAL = 300
# Minimum seconds between VLM iterations when woken by detections (no zone filter)
_DETECTION_COOLDOWN_WITHOUT_ZONE = 10
MAX_WATCH_MINUTES = 1440
# Max user/assistant turn pairs to keep in conversation history
_MAX_HISTORY = 10
@@ -77,17 +75,15 @@ class VLMWatchRunner(threading.Thread):
self.conversation: list[dict[str, Any]] = []
def run(self) -> None:
self.job.status = JobStatusTypesEnum.running
self.job.start_time = time.time()
self._broadcast_status()
self.conversation = [{"role": "system", "content": self._build_system_prompt()}]
# monotonic so a wall clock step can't end the job early or let it overrun
max_end_time = time.monotonic() + self.job.max_duration_minutes * 60
try:
self.job.status = JobStatusTypesEnum.running
self.job.start_time = time.time()
self._broadcast_status()
self.conversation = [
{"role": "system", "content": self._build_system_prompt()}
]
# monotonic so a wall clock step can't end the job early or let it overrun
max_end_time = time.monotonic() + self.job.max_duration_minutes * 60
while not self.cancel_event.is_set():
if time.monotonic() > max_end_time:
logger.debug(
@@ -208,13 +204,7 @@ class VLMWatchRunner(threading.Thread):
)
reasoning = str(parsed.get("reasoning", ""))
notification_message = str(parsed.get("notification_message", ""))
except (
json.JSONDecodeError,
ValueError,
TypeError,
AttributeError,
OverflowError,
) as e:
except (json.JSONDecodeError, ValueError, TypeError) as e:
logger.warning(
"VLM watch job %s: failed to parse VLM response: %s", self.job.id, e
)
@@ -413,17 +403,17 @@ def start_vlm_watch_job(
username=username,
)
cancel_ev = threading.Event()
runner = VLMWatchRunner(
job=job,
config=config,
cancel_event=cancel_ev,
frame_processor=frame_processor,
genai_manager=genai_manager,
dispatcher=dispatcher,
)
_current_job = job
_cancel_event = cancel_ev
runner = VLMWatchRunner(
job=job,
config=config,
cancel_event=cancel_ev,
frame_processor=frame_processor,
genai_manager=genai_manager,
dispatcher=dispatcher,
)
runner.start()
logger.debug(
+1 -48
View File
@@ -1,14 +1,12 @@
"""Tests for camera watch ownership in the chat tools."""
import asyncio
import threading
import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
from frigate.api.chat import _execute_start_camera_watch, _execute_stop_camera_watch
from frigate.jobs.vlm_watch import MAX_WATCH_MINUTES, VLMWatchJob, VLMWatchRunner
from frigate.types import JobStatusTypesEnum
from frigate.jobs.vlm_watch import VLMWatchJob
def _request(user: str, role: str) -> SimpleNamespace:
@@ -60,51 +58,6 @@ class TestStartCameraWatch(unittest.TestCase):
self.assertEqual(start.call_args.kwargs["username"], "alice")
@patch("frigate.api.chat.require_camera_access", new_callable=AsyncMock)
@patch("frigate.api.chat.start_vlm_watch_job", return_value="job1")
def test_rejects_non_string_labels_and_clamps_duration(self, start, _access):
request = _request("alice", "viewer")
request.app = MagicMock()
request.app.frigate_config.cameras = {"front": None}
request.app.genai_manager.chat_client.supports_vision = True
arguments = {"camera": "front", "condition": "person"}
result = asyncio.run(
_execute_start_camera_watch(request, {**arguments, "labels": [1]})
)
self.assertIn("error", result)
start.assert_not_called()
asyncio.run(
_execute_start_camera_watch(
request, {**arguments, "max_duration_minutes": 1e308}
)
)
self.assertEqual(
start.call_args.kwargs["max_duration_minutes"], MAX_WATCH_MINUTES
)
class TestWatchRunnerSetup(unittest.TestCase):
@patch("frigate.jobs.vlm_watch.DetectionSubscriber")
@patch("frigate.jobs.vlm_watch.InterProcessRequestor")
def test_setup_error_fails_job_and_closes_sockets(self, requestor, subscriber):
job = VLMWatchJob(camera="front", condition="person", labels=[1])
runner = VLMWatchRunner(
job=job,
config=MagicMock(),
cancel_event=threading.Event(),
frame_processor=MagicMock(),
genai_manager=MagicMock(),
dispatcher=MagicMock(),
)
runner.run()
self.assertEqual(job.status, JobStatusTypesEnum.failed)
requestor.return_value.stop.assert_called_once()
subscriber.return_value.stop.assert_called_once()
if __name__ == "__main__":
unittest.main()
+1 -16
View File
@@ -7,10 +7,7 @@ from unittest.mock import patch
import numpy as np
from frigate.util.classification import (
_extract_event_thumbnails,
_select_balanced_timestamps,
)
from frigate.util.classification import _extract_event_thumbnails
class TestExtractEventThumbnails(unittest.TestCase):
@@ -32,17 +29,5 @@ class TestExtractEventThumbnails(unittest.TestCase):
self.assertEqual(load.call_count, 7)
class TestSelectBalancedTimestamps(unittest.TestCase):
def test_terminates_when_items_cannot_fill_target(self):
items = [
SimpleNamespace(camera="front", start_time=1000.0, end_time=1000.0),
SimpleNamespace(camera="front", start_time=2000.0, end_time=2001.0),
]
timestamps = _select_balanced_timestamps(items, target_count=100)
self.assertEqual(len(timestamps), 1)
if __name__ == "__main__":
unittest.main()
-25
View File
@@ -19,7 +19,6 @@ import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import requests
from frigate.config import GenAIConfig, GenAIProviderEnum
@@ -822,13 +821,6 @@ class TestOllamaProvider(unittest.TestCase):
self.assertEqual(client.embed(images=[self._webp_bytes()]), [])
def test_embed_transport_error_returns_empty(self):
client = self._client()
client.provider = MagicMock()
client.provider._request_raw.side_effect = httpx.ReadError("reset")
self.assertEqual(client.embed(texts=["a person"]), [])
# ---------------------------------------------------------------------------
# llama.cpp
@@ -983,23 +975,6 @@ class TestLlamaCppProvider(unittest.TestCase):
client = self._validated_client(4096, {"context_size": 32768})
self.assertEqual(client.get_context_size(), 32768)
def test_base_url_strips_only_trailing_v1(self):
client = _make_client(
"llamacpp", model="m", base_url="http://v1-gpu.lan:8080/v1/"
)
self.assertEqual(client.provider, "http://v1-gpu.lan:8080")
def test_models_url_strips_v1_when_init_failed(self):
client = self._client()
client.provider = None
client.genai_config.base_url = "http://host:8080/v1"
with patch.object(client, "_get") as get:
get.return_value.json.return_value = {"data": []}
client._fetch_models_data()
self.assertEqual(get.call_args.args[0], "http://host:8080/v1/models")
def test_list_models_dedupes_alias_matching_id(self):
client = self._client()
models_data = [
+30
View File
@@ -122,6 +122,11 @@ class TestResolveMediaUri(unittest.TestCase):
MediaAuthResolution.CAMERA,
camera="back_door",
)
self._assert(
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4",
MediaAuthResolution.CAMERA,
camera="back_door",
)
def test_clip_flat_filename_resolves_camera(self):
self._assert(
@@ -177,6 +182,14 @@ class TestResolveMediaUri(unittest.TestCase):
camera="back_door",
)
def test_clip_triggers(self):
self._assert("/clips/triggers/", MediaAuthResolution.LISTING_MULTI_CAMERA)
self._assert(
"/clips/triggers/back_door/abc.webp",
MediaAuthResolution.CAMERA,
camera="back_door",
)
def test_clip_review_thumbs(self):
# Format: /clips/review/thumb-{camera}-{review_id}.webp (frigate/review/maintainer.py).
self._assert(
@@ -340,6 +353,14 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
self.assertIsNone(
self._deny("/clips/thumbs/front_door/abc.webp", "limited_user")
)
self.assertIsNone(
self._deny(
"/recordings/2026-05-11/14/front_door@sub/00.00.mp4", "limited_user"
)
)
self.assertIsNone(
self._deny("/clips/triggers/front_door/abc.webp", "limited_user")
)
def test_restricted_role_blocked_other_camera(self):
self.assertEqual(self._deny("/clips/back_door-1.jpg", "limited_user"), 403)
@@ -350,6 +371,15 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
self.assertEqual(
self._deny("/clips/thumbs/back_door/abc.webp", "limited_user"), 403
)
self.assertEqual(
self._deny(
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4", "limited_user"
),
403,
)
self.assertEqual(
self._deny("/clips/triggers/back_door/abc.webp", "limited_user"), 403
)
def test_restricted_role_blocked_admin_only(self):
self.assertEqual(self._deny("/clips/faces/train/foo.webp", "limited_user"), 403)
+65
View File
@@ -0,0 +1,65 @@
"""Tests for media sync orphan cleanup."""
import os
import tempfile
import unittest
from unittest.mock import patch
from peewee import SqliteDatabase
from frigate.models import Export, ExportCase
from frigate.util.media import sync_exports
class TestSyncExports(unittest.TestCase):
def setUp(self):
self.db = SqliteDatabase(":memory:")
self.enterContext(self.db.bind_ctx([Export, ExportCase]))
self.db.create_tables([Export, ExportCase])
self.tmp = tempfile.TemporaryDirectory()
self.clips_dir = os.path.join(self.tmp.name, "clips")
self.export_dir = os.path.join(self.tmp.name, "exports")
self.thumb_dir = os.path.join(self.clips_dir, "export")
os.makedirs(self.thumb_dir)
os.makedirs(self.export_dir)
patcher_clips = patch("frigate.util.media.CLIPS_DIR", self.clips_dir)
patcher_exports = patch("frigate.util.media.EXPORT_DIR", self.export_dir)
patcher_clips.start()
patcher_exports.start()
self.addCleanup(patcher_clips.stop)
self.addCleanup(patcher_exports.stop)
def tearDown(self):
self.db.close()
self.tmp.cleanup()
def _touch(self, path: str) -> str:
open(path, "wb").close()
return path
def test_orphaned_webp_and_jpg_thumbnails_are_removed(self):
for i, ext in enumerate(("webp", "jpg")):
Export.insert(
id=f"front_{i}",
camera="front",
name=f"export {i}",
date=0,
video_path=self._touch(os.path.join(self.export_dir, f"{i}.mp4")),
thumb_path=self._touch(os.path.join(self.thumb_dir, f"{i}.{ext}")),
in_progress=False,
).execute()
orphan_webp = self._touch(os.path.join(self.thumb_dir, "gone.webp"))
orphan_jpg = self._touch(os.path.join(self.thumb_dir, "gone.jpg"))
result = sync_exports()
self.assertEqual(sorted(result.orphan_paths), sorted([orphan_jpg, orphan_webp]))
self.assertEqual(result.orphans_deleted, 2)
self.assertEqual(sorted(os.listdir(self.thumb_dir)), ["0.webp", "1.jpg"])
if __name__ == "__main__":
unittest.main()
+42
View File
@@ -0,0 +1,42 @@
"""Tests for trigger push notifications."""
import unittest
from types import SimpleNamespace
from unittest.mock import MagicMock
from frigate.comms.webpush import WebPushClient
class TestTriggerNotification(unittest.TestCase):
def test_image_is_the_triggering_event_thumbnail(self):
client = WebPushClient.__new__(WebPushClient)
client.config = SimpleNamespace(
notifications=SimpleNamespace(email="admin@example.com"),
cameras={"front_door": SimpleNamespace(friendly_name=None)},
)
client.web_pushers = {"admin": []}
client.user_cameras = {"admin": {"front_door"}}
client.last_camera_notification_time = {}
client._within_cooldown = MagicMock(return_value=False)
client.check_registrations = MagicMock()
client.cleanup_registrations = MagicMock()
client.send_push_notification = MagicMock()
client.send_trigger(
{
"camera": "front_door",
"event_id": "1700000000.0-abc123",
"name": "red_car",
"type": "thumbnail",
"score": 0.9,
}
)
self.assertEqual(
client.send_push_notification.call_args.kwargs["image"],
"api/events/1700000000.0-abc123/thumbnail.webp",
)
if __name__ == "__main__":
unittest.main()
+55 -37
View File
@@ -414,6 +414,7 @@ def collect_state_classification_examples(
cameras: Dict mapping camera names to normalized crop coordinates [x1, y1, x2, y2] (0-1)
"""
model_name = model_name.strip()
dataset_dir = os.path.join(CLIPS_DIR, model_name, "dataset")
# Step 1: Get review items for the cameras
camera_names = list(cameras.keys())
@@ -428,31 +429,29 @@ def collect_state_classification_examples(
logger.warning(f"No review items found for cameras: {camera_names}")
return
# The temp directory is only created when there are review_items.
temp_dir = os.path.join(dataset_dir, "temp")
os.makedirs(temp_dir, exist_ok=True)
# Step 2: Create balanced timestamp selection (100 samples)
timestamps = _select_balanced_timestamps(review_items, target_count=100)
with tempfile.TemporaryDirectory() as temp_dir:
# Step 3: Extract keyframes from recordings with crops applied
keyframes = _extract_keyframes(
"/usr/lib/ffmpeg/8.0/bin/ffmpeg", timestamps, temp_dir, cameras
)
# Step 3: Extract keyframes from recordings with crops applied
keyframes = _extract_keyframes(
"/usr/lib/ffmpeg/8.0/bin/ffmpeg", timestamps, temp_dir, cameras
)
# Step 4: Select 24 most visually distinct images (they're already cropped)
distinct_images = _select_distinct_images(keyframes, target_count=24)
# Step 4: Select 24 most visually distinct images (they're already cropped)
distinct_images = _select_distinct_images(keyframes, target_count=24)
# Step 5: Save to train directory for later classification
_save_train_examples(model_name, distinct_images)
def _save_train_examples(model_name: str, image_paths: list[str]) -> int:
"""Replace the model's train directory with the given images."""
# Step 5: Save to train directory for later classification
train_dir = os.path.join(CLIPS_DIR, model_name, "train")
if os.path.exists(train_dir):
shutil.rmtree(train_dir)
os.makedirs(train_dir, exist_ok=True)
saved_count = 0
for idx, image_path in enumerate(image_paths):
for idx, image_path in enumerate(distinct_images):
dest_path = os.path.join(train_dir, f"example_{idx:03d}.jpg")
try:
img = cv2.imread(image_path)
@@ -463,7 +462,10 @@ def _save_train_examples(model_name: str, image_paths: list[str]) -> int:
except Exception as e:
logger.error(f"Failed to save image {image_path}: {e}")
return saved_count
try:
shutil.rmtree(temp_dir)
except Exception as e:
logger.warning(f"Failed to clean up temp directory: {e}")
def _select_balanced_timestamps(
@@ -522,20 +524,13 @@ def _select_balanced_timestamps(
}
)
# Sample more from larger groups. Zero-length items and timestamps too
# close to an existing one never add a sample, so attempts are capped.
max_attempts = target_count * 10
attempts = 0
while (
len(timestamps) < target_count
and len(timestamps) < len(review_items)
and attempts < max_attempts
):
# If we don't have enough, sample more from larger groups
while len(timestamps) < target_count and len(timestamps) < len(review_items):
for group_items in grouped.values():
if len(timestamps) >= target_count or attempts >= max_attempts:
if len(timestamps) >= target_count:
break
attempts += 1
# Pick a random item not already sampled
item = random.choice(group_items)
duration = item.end_time - item.start_time
if duration <= 0:
@@ -775,6 +770,9 @@ def collect_object_classification_examples(
label: Object label to collect (e.g., "person", "car")
"""
model_name = model_name.strip()
dataset_dir = os.path.join(CLIPS_DIR, model_name, "dataset")
temp_dir = os.path.join(dataset_dir, "temp")
os.makedirs(temp_dir, exist_ok=True)
# Step 1: Query events for the specified label and cameras
events = list(
@@ -796,21 +794,41 @@ def collect_object_classification_examples(
selected_ids = {e.id for e in selected_events}
remaining_events = [e for e in events if e.id not in selected_ids]
random.shuffle(remaining_events)
thumbnails = _extract_event_thumbnails(
selected_events + remaining_events, temp_dir, target_count=100
)
logger.debug(f"Successfully extracted {len(thumbnails)} thumbnails")
with tempfile.TemporaryDirectory() as temp_dir:
thumbnails = _extract_event_thumbnails(
selected_events + remaining_events, temp_dir, target_count=100
)
logger.debug(f"Successfully extracted {len(thumbnails)} thumbnails")
# Step 4: Select 24 most visually distinct thumbnails
distinct_images = _select_distinct_images(thumbnails, target_count=24)
logger.debug(f"Selected {len(distinct_images)} distinct images")
# Step 4: Select 24 most visually distinct thumbnails
distinct_images = _select_distinct_images(thumbnails, target_count=24)
logger.debug(f"Selected {len(distinct_images)} distinct images")
# Step 5: Save to train directory for later classification
train_dir = os.path.join(CLIPS_DIR, model_name, "train")
if os.path.exists(train_dir):
shutil.rmtree(train_dir)
os.makedirs(train_dir, exist_ok=True)
# Step 5: Save to train directory for later classification
saved_count = _save_train_examples(model_name, distinct_images)
saved_count = 0
for idx, image_path in enumerate(distinct_images):
dest_path = os.path.join(train_dir, f"example_{idx:03d}.jpg")
try:
img = cv2.imread(image_path)
logger.debug(f"Successfully collected {saved_count} classification examples")
if img is not None:
cv2.imwrite(dest_path, img)
saved_count += 1
except Exception as e:
logger.error(f"Failed to save image {image_path}: {e}")
try:
shutil.rmtree(temp_dir)
except Exception as e:
logger.warning(f"Failed to clean up temp directory: {e}")
logger.debug(
f"Successfully collected {saved_count} classification examples in {train_dir}"
)
def _select_balanced_events(
+2 -2
View File
@@ -639,7 +639,7 @@ def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:
"""Sync export files - delete files not referenced by any export record.
Export videos are stored at: EXPORT_DIR/*.mp4
Export thumbnails are stored at: CLIPS_DIR/export/*.jpg
Export thumbnails are stored at: CLIPS_DIR/export/*.webp (legacy *.jpg)
The paths are stored in Export.video_path and Export.thumb_path
"""
result = SyncResult(media_type="exports")
@@ -667,7 +667,7 @@ def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:
thumb_files: list[str] = []
if os.path.isdir(export_thumb_dir):
for file in os.listdir(export_thumb_dir):
if file.endswith(".jpg"):
if file.endswith((".webp", ".jpg")):
file_path = os.path.join(export_thumb_dir, file)
thumb_files.append(file_path)