fix genai and classification error paths

- Catch all httpx errors in the Ollama plugin so a dropped connection no longer ends the embeddings thread
- Strip only a trailing /v1 from the llama.cpp base_url
- Cap the timestamp top-up loop in state example generation, which looped forever on zero-length review items
- Run state example generation in a thread under the example collection lock
- Stage example frames in a system temp dir so a leftover dataset/temp folder can't become a training class
- Report face training success only after the image is written, and return 404 when the event has no face attributes or snapshot
- Move VLM watch setup inside the runner's try block, build the runner before claiming the watch slot, bound max_duration_minutes, and reject non-string labels and zones from the chat tool
This commit is contained in:
Josh Hawkins
2026-11-23 18:26:48 -06:00
parent d20d6dcf72
commit 06feb4b591
10 changed files with 201 additions and 123 deletions
+2
View File
@@ -9630,6 +9630,8 @@ components:
title: Condition title: Condition
max_duration_minutes: max_duration_minutes:
type: integer type: integer
maximum: 1440.0
minimum: 1.0
title: Max Duration Minutes title: Max Duration Minutes
default: 60 default: 60
labels: labels:
+8 -2
View File
@@ -14,7 +14,7 @@ import cv2
import numpy as np import numpy as np
from fastapi import APIRouter, Body, Depends, HTTPException, Request from fastapi import APIRouter, Body, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, StreamingResponse from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel from pydantic import BaseModel, Field
from frigate.api.auth import ( from frigate.api.auth import (
allow_any_authenticated, allow_any_authenticated,
@@ -56,6 +56,7 @@ from frigate.genai.utils import (
) )
from frigate.jobs.export import ExportQueueFullError, start_export_job from frigate.jobs.export import ExportQueueFullError, start_export_job
from frigate.jobs.vlm_watch import ( from frigate.jobs.vlm_watch import (
MAX_WATCH_MINUTES,
VLMWatchJob, VLMWatchJob,
get_vlm_watch_job, get_vlm_watch_job,
start_vlm_watch_job, start_vlm_watch_job,
@@ -88,7 +89,7 @@ class VLMMonitorRequest(BaseModel):
camera: str camera: str
condition: str condition: str
max_duration_minutes: int = 60 max_duration_minutes: int = Field(default=60, ge=1, le=MAX_WATCH_MINUTES)
labels: list[str] = [] labels: list[str] = []
zones: list[str] = [] zones: list[str] = []
@@ -1030,12 +1031,17 @@ async def _execute_start_camera_watch(
camera = arguments.get("camera", "").strip() camera = arguments.get("camera", "").strip()
condition = arguments.get("condition", "").strip() condition = arguments.get("condition", "").strip()
max_duration_minutes = int(arguments.get("max_duration_minutes", 60)) 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 [] labels = arguments.get("labels") or []
zones = arguments.get("zones") or [] zones = arguments.get("zones") or []
if not camera or not condition: if not camera or not condition:
return {"error": "camera and condition are required."} 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 config = request.app.frigate_config
if camera not in config.cameras: if camera not in config.cameras:
return {"error": f"Camera '{camera}' not found."} return {"error": f"Camera '{camera}' not found."}
+24 -19
View File
@@ -216,26 +216,28 @@ def train_face(request: Request, name: str, body: dict = None):
status_code=404, status_code=404,
) )
snapshot = get_event_snapshot(event) attributes = (event.data or {}).get("attributes") or []
face_box = event.data["attributes"][0]["box"] snapshot = get_event_snapshot(event) if attributes else None
detect_config: DetectConfig = request.app.frigate_config.cameras[ success = False
event.camera
].detect
# crop onto the face box minus the bounding box itself if snapshot is not None:
x1 = int(face_box[0] * detect_config.width) + 2 face_box = attributes[0]["box"]
y1 = int(face_box[1] * detect_config.height) + 2 detect_config: DetectConfig = request.app.frigate_config.cameras[
x2 = x1 + int(face_box[2] * detect_config.width) - 4 event.camera
y2 = y1 + int(face_box[3] * detect_config.height) - 4 ].detect
face = snapshot[y1:y2, x1:x2]
success = True
if face.size > 0: # crop onto the face box minus the bounding box itself
try: x1 = int(face_box[0] * detect_config.width) + 2
cv2.imwrite(os.path.join(new_file_folder, new_name), face) y1 = int(face_box[1] * detect_config.height) + 2
success = True x2 = x1 + int(face_box[2] * detect_config.width) - 4
except Exception: y2 = y1 + int(face_box[3] * detect_config.height) - 4
pass 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 not success: if not success:
return JSONResponse( return JSONResponse(
@@ -1273,7 +1275,10 @@ async def generate_state_examples(request: Request, body: GenerateStateExamplesB
if camera_name in request.app.frigate_config.cameras if camera_name in request.app.frigate_config.cameras
} }
collect_state_classification_examples(model_name, cameras_normalized) async with example_collection_lock:
await asyncio.to_thread(
collect_state_classification_examples, model_name, cameras_normalized
)
return JSONResponse( return JSONResponse(
content={"success": True, "message": "Example generation completed"}, content={"success": True, "message": "Example generation completed"},
+9 -12
View File
@@ -110,6 +110,13 @@ class LlamaCppClient(GenAIClient):
"""POST with the configured auth headers injected.""" """POST with the configured auth headers injected."""
return requests.post(url, headers=self._auth_headers(), **kwargs) 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]: def _fetch_llama_props(self, base_url: str, model: str) -> dict[str, Any]:
"""Fetch /props from a llama.cpp server, with llama-swap fallback. """Fetch /props from a llama.cpp server, with llama-swap fallback.
@@ -143,16 +150,10 @@ class LlamaCppClient(GenAIClient):
self._supports_tools = False self._supports_tools = False
self._supports_reasoning = False self._supports_reasoning = False
base_url = ( base_url = self._server_url()
self.genai_config.base_url.rstrip("/")
if self.genai_config.base_url
else None
)
if base_url is None: if base_url is None:
return None return None
else:
base_url = base_url.replace("/v1", "") # Strip /v1 if included in base_url
if not self.validate_model: if not self.validate_model:
# Probe path # Probe path
@@ -506,11 +507,7 @@ class LlamaCppClient(GenAIClient):
def _fetch_models_data(self) -> list[dict[str, Any]]: def _fetch_models_data(self) -> list[dict[str, Any]]:
"""Return the raw /v1/models entries, or an empty list if unreachable.""" """Return the raw /v1/models entries, or an empty list if unreachable."""
base_url = self.provider or ( base_url = self.provider or self._server_url()
self.genai_config.base_url.rstrip("/")
if self.genai_config.base_url
else None
)
if base_url is None: if base_url is None:
return [] return []
+5 -16
View File
@@ -8,7 +8,7 @@ from collections.abc import AsyncGenerator
from typing import Any from typing import Any
import numpy as np import numpy as np
from httpx import RemoteProtocolError, TimeoutException from httpx import HTTPError
from ollama import AsyncClient as OllamaAsyncClient from ollama import AsyncClient as OllamaAsyncClient
from ollama import Client as ApiClient from ollama import Client as ApiClient
from ollama import ResponseError from ollama import ResponseError
@@ -282,12 +282,7 @@ class OllamaClient(GenAIClient):
try: try:
response = self.provider.chat(**request_params) response = self.provider.chat(**request_params)
except ( except (HTTPError, ResponseError, ConnectionError) as e:
TimeoutException,
ResponseError,
RemoteProtocolError,
ConnectionError,
) as e:
logger.warning("Ollama returned an error: %s", str(e)) logger.warning("Ollama returned an error: %s", str(e))
return None return None
@@ -406,13 +401,7 @@ class OllamaClient(GenAIClient):
# image items have to bypass it and post the JSON directly. # image items have to bypass it and post the JSON directly.
response = self.provider._request_raw("POST", "/api/embed", json=payload) response = self.provider._request_raw("POST", "/api/embed", json=payload)
body = response.json() body = response.json()
except ( except (HTTPError, ResponseError, ConnectionError, ValueError) as e:
TimeoutException,
ResponseError,
RemoteProtocolError,
ConnectionError,
ValueError,
) as e:
logger.warning("Ollama embeddings error: %s", str(e)) logger.warning("Ollama embeddings error: %s", str(e))
return [] return []
@@ -553,7 +542,7 @@ class OllamaClient(GenAIClient):
) )
response = self.provider.chat(**request_params) response = self.provider.chat(**request_params)
return self._message_from_response(response) return self._message_from_response(response)
except (TimeoutException, ResponseError, ConnectionError) as e: except (HTTPError, ResponseError, ConnectionError) as e:
logger.warning("Ollama returned an error: %s", str(e)) logger.warning("Ollama returned an error: %s", str(e))
return { return {
"content": None, "content": None,
@@ -685,7 +674,7 @@ class OllamaClient(GenAIClient):
"finish_reason": "stop", "finish_reason": "stop",
}, },
) )
except (TimeoutException, ResponseError, ConnectionError) as e: except (HTTPError, ResponseError, ConnectionError) as e:
logger.warning("Ollama streaming error: %s", str(e)) logger.warning("Ollama streaming error: %s", str(e))
yield ( yield (
"message", "message",
+27 -17
View File
@@ -28,6 +28,8 @@ _MAX_INTERVAL = 300
# Minimum seconds between VLM iterations when woken by detections (no zone filter) # Minimum seconds between VLM iterations when woken by detections (no zone filter)
_DETECTION_COOLDOWN_WITHOUT_ZONE = 10 _DETECTION_COOLDOWN_WITHOUT_ZONE = 10
MAX_WATCH_MINUTES = 1440
# Max user/assistant turn pairs to keep in conversation history # Max user/assistant turn pairs to keep in conversation history
_MAX_HISTORY = 10 _MAX_HISTORY = 10
@@ -75,15 +77,17 @@ class VLMWatchRunner(threading.Thread):
self.conversation: list[dict[str, Any]] = [] self.conversation: list[dict[str, Any]] = []
def run(self) -> None: 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: 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(): while not self.cancel_event.is_set():
if time.monotonic() > max_end_time: if time.monotonic() > max_end_time:
logger.debug( logger.debug(
@@ -204,7 +208,13 @@ class VLMWatchRunner(threading.Thread):
) )
reasoning = str(parsed.get("reasoning", "")) reasoning = str(parsed.get("reasoning", ""))
notification_message = str(parsed.get("notification_message", "")) notification_message = str(parsed.get("notification_message", ""))
except (json.JSONDecodeError, ValueError, TypeError) as e: except (
json.JSONDecodeError,
ValueError,
TypeError,
AttributeError,
OverflowError,
) as e:
logger.warning( logger.warning(
"VLM watch job %s: failed to parse VLM response: %s", self.job.id, e "VLM watch job %s: failed to parse VLM response: %s", self.job.id, e
) )
@@ -403,17 +413,17 @@ def start_vlm_watch_job(
username=username, username=username,
) )
cancel_ev = threading.Event() 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 _current_job = job
_cancel_event = cancel_ev _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() runner.start()
logger.debug( logger.debug(
+48 -1
View File
@@ -1,12 +1,14 @@
"""Tests for camera watch ownership in the chat tools.""" """Tests for camera watch ownership in the chat tools."""
import asyncio import asyncio
import threading
import unittest import unittest
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch from unittest.mock import AsyncMock, MagicMock, patch
from frigate.api.chat import _execute_start_camera_watch, _execute_stop_camera_watch from frigate.api.chat import _execute_start_camera_watch, _execute_stop_camera_watch
from frigate.jobs.vlm_watch import VLMWatchJob from frigate.jobs.vlm_watch import MAX_WATCH_MINUTES, VLMWatchJob, VLMWatchRunner
from frigate.types import JobStatusTypesEnum
def _request(user: str, role: str) -> SimpleNamespace: def _request(user: str, role: str) -> SimpleNamespace:
@@ -58,6 +60,51 @@ class TestStartCameraWatch(unittest.TestCase):
self.assertEqual(start.call_args.kwargs["username"], "alice") 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__": if __name__ == "__main__":
unittest.main() unittest.main()
+16 -1
View File
@@ -7,7 +7,10 @@ from unittest.mock import patch
import numpy as np import numpy as np
from frigate.util.classification import _extract_event_thumbnails from frigate.util.classification import (
_extract_event_thumbnails,
_select_balanced_timestamps,
)
class TestExtractEventThumbnails(unittest.TestCase): class TestExtractEventThumbnails(unittest.TestCase):
@@ -29,5 +32,17 @@ class TestExtractEventThumbnails(unittest.TestCase):
self.assertEqual(load.call_count, 7) 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__": if __name__ == "__main__":
unittest.main() unittest.main()
+25
View File
@@ -19,6 +19,7 @@ import unittest
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import requests import requests
from frigate.config import GenAIConfig, GenAIProviderEnum from frigate.config import GenAIConfig, GenAIProviderEnum
@@ -821,6 +822,13 @@ class TestOllamaProvider(unittest.TestCase):
self.assertEqual(client.embed(images=[self._webp_bytes()]), []) 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 # llama.cpp
@@ -975,6 +983,23 @@ class TestLlamaCppProvider(unittest.TestCase):
client = self._validated_client(4096, {"context_size": 32768}) client = self._validated_client(4096, {"context_size": 32768})
self.assertEqual(client.get_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): def test_list_models_dedupes_alias_matching_id(self):
client = self._client() client = self._client()
models_data = [ models_data = [
+37 -55
View File
@@ -414,7 +414,6 @@ def collect_state_classification_examples(
cameras: Dict mapping camera names to normalized crop coordinates [x1, y1, x2, y2] (0-1) cameras: Dict mapping camera names to normalized crop coordinates [x1, y1, x2, y2] (0-1)
""" """
model_name = model_name.strip() model_name = model_name.strip()
dataset_dir = os.path.join(CLIPS_DIR, model_name, "dataset")
# Step 1: Get review items for the cameras # Step 1: Get review items for the cameras
camera_names = list(cameras.keys()) camera_names = list(cameras.keys())
@@ -429,29 +428,31 @@ def collect_state_classification_examples(
logger.warning(f"No review items found for cameras: {camera_names}") logger.warning(f"No review items found for cameras: {camera_names}")
return 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) # Step 2: Create balanced timestamp selection (100 samples)
timestamps = _select_balanced_timestamps(review_items, target_count=100) timestamps = _select_balanced_timestamps(review_items, target_count=100)
# Step 3: Extract keyframes from recordings with crops applied with tempfile.TemporaryDirectory() as temp_dir:
keyframes = _extract_keyframes( # Step 3: Extract keyframes from recordings with crops applied
"/usr/lib/ffmpeg/8.0/bin/ffmpeg", timestamps, temp_dir, cameras 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) # Step 4: Select 24 most visually distinct images (they're already cropped)
distinct_images = _select_distinct_images(keyframes, target_count=24) distinct_images = _select_distinct_images(keyframes, target_count=24)
# Step 5: Save to train directory for later classification # 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."""
train_dir = os.path.join(CLIPS_DIR, model_name, "train") train_dir = os.path.join(CLIPS_DIR, model_name, "train")
if os.path.exists(train_dir): if os.path.exists(train_dir):
shutil.rmtree(train_dir) shutil.rmtree(train_dir)
os.makedirs(train_dir, exist_ok=True) os.makedirs(train_dir, exist_ok=True)
saved_count = 0 saved_count = 0
for idx, image_path in enumerate(distinct_images): for idx, image_path in enumerate(image_paths):
dest_path = os.path.join(train_dir, f"example_{idx:03d}.jpg") dest_path = os.path.join(train_dir, f"example_{idx:03d}.jpg")
try: try:
img = cv2.imread(image_path) img = cv2.imread(image_path)
@@ -462,10 +463,7 @@ def collect_state_classification_examples(
except Exception as e: except Exception as e:
logger.error(f"Failed to save image {image_path}: {e}") logger.error(f"Failed to save image {image_path}: {e}")
try: return saved_count
shutil.rmtree(temp_dir)
except Exception as e:
logger.warning(f"Failed to clean up temp directory: {e}")
def _select_balanced_timestamps( def _select_balanced_timestamps(
@@ -524,13 +522,20 @@ def _select_balanced_timestamps(
} }
) )
# If we don't have enough, sample more from larger groups # Sample more from larger groups. Zero-length items and timestamps too
while len(timestamps) < target_count and len(timestamps) < len(review_items): # 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
):
for group_items in grouped.values(): for group_items in grouped.values():
if len(timestamps) >= target_count: if len(timestamps) >= target_count or attempts >= max_attempts:
break break
# Pick a random item not already sampled attempts += 1
item = random.choice(group_items) item = random.choice(group_items)
duration = item.end_time - item.start_time duration = item.end_time - item.start_time
if duration <= 0: if duration <= 0:
@@ -770,9 +775,6 @@ def collect_object_classification_examples(
label: Object label to collect (e.g., "person", "car") label: Object label to collect (e.g., "person", "car")
""" """
model_name = model_name.strip() 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 # Step 1: Query events for the specified label and cameras
events = list( events = list(
@@ -794,41 +796,21 @@ def collect_object_classification_examples(
selected_ids = {e.id for e in selected_events} selected_ids = {e.id for e in selected_events}
remaining_events = [e for e in events if e.id not in selected_ids] remaining_events = [e for e in events if e.id not in selected_ids]
random.shuffle(remaining_events) 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")
# Step 4: Select 24 most visually distinct thumbnails with tempfile.TemporaryDirectory() as temp_dir:
distinct_images = _select_distinct_images(thumbnails, target_count=24) thumbnails = _extract_event_thumbnails(
logger.debug(f"Selected {len(distinct_images)} distinct images") selected_events + remaining_events, temp_dir, target_count=100
)
logger.debug(f"Successfully extracted {len(thumbnails)} thumbnails")
# Step 5: Save to train directory for later classification # Step 4: Select 24 most visually distinct thumbnails
train_dir = os.path.join(CLIPS_DIR, model_name, "train") distinct_images = _select_distinct_images(thumbnails, target_count=24)
if os.path.exists(train_dir): logger.debug(f"Selected {len(distinct_images)} distinct images")
shutil.rmtree(train_dir)
os.makedirs(train_dir, exist_ok=True)
saved_count = 0 # Step 5: Save to train directory for later classification
for idx, image_path in enumerate(distinct_images): saved_count = _save_train_examples(model_name, distinct_images)
dest_path = os.path.join(train_dir, f"example_{idx:03d}.jpg")
try:
img = cv2.imread(image_path)
if img is not None: logger.debug(f"Successfully collected {saved_count} classification examples")
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( def _select_balanced_events(