mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 14:27:06 +03:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
297ec2ace9 | ||
|
|
550276e430 |
+2
-14
@@ -6,7 +6,6 @@ import json
|
||||
import logging
|
||||
import operator
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from functools import reduce
|
||||
from typing import Any, Literal
|
||||
@@ -1275,14 +1274,6 @@ def _pending_tool_calls_from_tail(
|
||||
return parse_tool_calls_from_message(tail)
|
||||
|
||||
|
||||
def _with_server_ids(tool_calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Give each model tool call a unique id.
|
||||
|
||||
Approvals are keyed by id, and some providers reuse ids across calls.
|
||||
"""
|
||||
return [{**tc, "id": uuid.uuid4().hex[:9]} for tc in tool_calls]
|
||||
|
||||
|
||||
def _tool_calls_awaiting_approval(
|
||||
pending_tool_calls: list[dict[str, Any]],
|
||||
body: ChatCompletionRequest,
|
||||
@@ -1608,7 +1599,6 @@ async def chat_completion(
|
||||
return
|
||||
requested = msg.get("tool_calls")
|
||||
if requested:
|
||||
requested = _with_server_ids(requested)
|
||||
stream_iterations += 1
|
||||
conversation.append(
|
||||
build_assistant_message_for_conversation(
|
||||
@@ -1694,15 +1684,13 @@ async def chat_completion(
|
||||
status_code=500,
|
||||
)
|
||||
|
||||
pending_tool_calls = response.get("tool_calls")
|
||||
if pending_tool_calls:
|
||||
pending_tool_calls = _with_server_ids(pending_tool_calls)
|
||||
conversation.append(
|
||||
build_assistant_message_for_conversation(
|
||||
response.get("content"), pending_tool_calls
|
||||
response.get("content"), response.get("tool_calls")
|
||||
)
|
||||
)
|
||||
|
||||
pending_tool_calls = response.get("tool_calls")
|
||||
if not pending_tool_calls:
|
||||
logger.debug(
|
||||
f"Chat completion finished with final answer (iterations: {tool_iterations})"
|
||||
|
||||
@@ -47,7 +47,10 @@ from frigate.const import (
|
||||
STREAM_TYPE_SUB,
|
||||
)
|
||||
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
|
||||
from frigate.output.preview import get_most_recent_preview_frame
|
||||
from frigate.output.preview import (
|
||||
get_most_recent_preview_frame,
|
||||
is_camera_preview_frame,
|
||||
)
|
||||
from frigate.track.object_processing import TrackedObjectProcessor
|
||||
from frigate.util.ffmpeg import terminate_ffmpeg_stream
|
||||
from frigate.util.file import (
|
||||
@@ -1603,7 +1606,7 @@ async def preview_gif(
|
||||
camera_files = [
|
||||
entry.name
|
||||
for entry in os.scandir(preview_dir)
|
||||
if entry.name.startswith(file_start)
|
||||
if is_camera_preview_frame(entry.name, camera_name)
|
||||
]
|
||||
camera_files.sort()
|
||||
|
||||
@@ -1794,7 +1797,7 @@ async def preview_mp4(
|
||||
camera_files = [
|
||||
entry.name
|
||||
for entry in os.scandir(preview_dir)
|
||||
if entry.name.startswith(file_start)
|
||||
if is_camera_preview_frame(entry.name, camera_name)
|
||||
]
|
||||
camera_files.sort()
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ from frigate.api.defs.response.preview_response import (
|
||||
from frigate.api.defs.tags import Tags
|
||||
from frigate.const import BASE_DIR, CACHE_DIR, PREVIEW_FRAME_TYPE
|
||||
from frigate.models import Previews
|
||||
from frigate.output.preview import is_camera_preview_frame
|
||||
from frigate.util.time import get_normalized_tz_name
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -187,7 +188,7 @@ def get_preview_frames_from_cache(camera_name: str, start_ts: float, end_ts: flo
|
||||
left = bisect.bisect_left(files, start_file)
|
||||
right = bisect.bisect_right(files, end_file)
|
||||
selected_previews = [
|
||||
file for file in files[left:right] if file.startswith(file_start)
|
||||
file for file in files[left:right] if is_camera_preview_frame(file, camera_name)
|
||||
]
|
||||
|
||||
return JSONResponse(
|
||||
|
||||
@@ -67,17 +67,6 @@ def _decode_data_uri(url: str) -> tuple[str, bytes] | None:
|
||||
return None
|
||||
|
||||
|
||||
def _tool_names_by_id(messages: list[dict[str, Any]]) -> dict[str, str]:
|
||||
"""Map each assistant tool call id to its function name."""
|
||||
return {
|
||||
tc["id"]: (tc.get("function") or {}).get("name") or ""
|
||||
for msg in messages
|
||||
if msg.get("role") == "assistant"
|
||||
for tc in msg.get("tool_calls") or []
|
||||
if tc.get("id")
|
||||
}
|
||||
|
||||
|
||||
def _parts_from_content(content: Any) -> list[types.Part]:
|
||||
"""Convert OpenAI-style message content (str or multimodal list) to Gemini parts."""
|
||||
if isinstance(content, list):
|
||||
@@ -469,7 +458,6 @@ class GeminiClient(GenAIClient):
|
||||
try:
|
||||
# Convert messages to Gemini format
|
||||
gemini_messages: list[types.Content] = []
|
||||
tool_names = _tool_names_by_id(messages)
|
||||
for msg in messages:
|
||||
role = msg.get("role", "user")
|
||||
content = msg.get("content", "")
|
||||
@@ -532,7 +520,6 @@ class GeminiClient(GenAIClient):
|
||||
parts=[
|
||||
types.Part.from_function_response(
|
||||
name=msg.get("name")
|
||||
or tool_names.get(msg.get("tool_call_id") or "")
|
||||
or msg.get("tool_call_id")
|
||||
or "",
|
||||
response=response_payload,
|
||||
@@ -727,7 +714,6 @@ class GeminiClient(GenAIClient):
|
||||
try:
|
||||
# Convert messages to Gemini format
|
||||
gemini_messages: list[types.Content] = []
|
||||
tool_names = _tool_names_by_id(messages)
|
||||
for msg in messages:
|
||||
role = msg.get("role", "user")
|
||||
content = msg.get("content", "")
|
||||
@@ -790,7 +776,6 @@ class GeminiClient(GenAIClient):
|
||||
parts=[
|
||||
types.Part.from_function_response(
|
||||
name=msg.get("name")
|
||||
or tool_names.get(msg.get("tool_call_id") or "")
|
||||
or msg.get("tool_call_id")
|
||||
or "",
|
||||
response=response_payload,
|
||||
|
||||
@@ -1333,7 +1333,7 @@ class RecordingExporter(threading.Thread):
|
||||
end_file = f"{file_start}{self.end_time}.{PREVIEW_FRAME_TYPE}"
|
||||
|
||||
for file in sorted(os.listdir(preview_dir)):
|
||||
if not file.startswith(file_start):
|
||||
if not is_camera_preview_frame(file, self.camera):
|
||||
continue
|
||||
|
||||
if file < start_file:
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Current-hour preview frame routes only return the requested camera's frames."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from frigate.const import PREVIEW_FRAME_TYPE
|
||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||
|
||||
CAMERA = "front_door"
|
||||
|
||||
# camera names that extend CAMERA with "-" share its file name prefix
|
||||
SIBLINGS = (f"{CAMERA}-2", f"{CAMERA}-door")
|
||||
|
||||
|
||||
class TestHttpPreviewFrames(BaseTestHttp):
|
||||
def setUp(self):
|
||||
super().setUp([])
|
||||
self.app = super().create_app()
|
||||
|
||||
self.cache_dir = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
|
||||
self.preview_dir = os.path.join(self.cache_dir, "preview_frames")
|
||||
os.makedirs(self.preview_dir)
|
||||
|
||||
for target, value in (
|
||||
("frigate.api.media.CACHE_DIR", self.cache_dir),
|
||||
("frigate.api.preview.CACHE_DIR", self.cache_dir),
|
||||
("frigate.api.preview._preview_listing_cache", (-1.0, [])),
|
||||
):
|
||||
patcher = patch(target, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
# ahead of now so the media routes never fall back to stored previews
|
||||
|
||||
self.start_ts = time.time() + 60
|
||||
self._write_frame(CAMERA, self.start_ts - 10)
|
||||
self.own_frames = [self._write_frame(CAMERA, self.start_ts + 1)]
|
||||
|
||||
for sibling in SIBLINGS:
|
||||
self._write_frame(sibling, self.start_ts + 1)
|
||||
|
||||
def _write_frame(self, camera: str, frame_time: float) -> str:
|
||||
name = f"preview_{camera}-{frame_time}.{PREVIEW_FRAME_TYPE}"
|
||||
with open(os.path.join(self.preview_dir, name), "wb") as f:
|
||||
f.write(b"frame")
|
||||
return name
|
||||
|
||||
def _concat_files(self, mock_run: MagicMock) -> set[str]:
|
||||
concat = mock_run.call_args.kwargs["input"].decode()
|
||||
return {
|
||||
os.path.basename(line.split("'")[1])
|
||||
for line in concat.splitlines()
|
||||
if line.startswith("file ")
|
||||
}
|
||||
|
||||
def test_frames_listing_excludes_sibling_camera(self):
|
||||
with AuthTestClient(self.app) as client:
|
||||
response = client.get(
|
||||
f"/preview/{CAMERA}/start/{self.start_ts}/end/inf/frames"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == self.own_frames
|
||||
|
||||
def test_preview_gif_excludes_sibling_camera(self):
|
||||
result = MagicMock(returncode=0, stdout=b"GIF89a")
|
||||
|
||||
with (
|
||||
patch("frigate.api.media.sp.run", return_value=result) as mock_run,
|
||||
AuthTestClient(self.app) as client,
|
||||
):
|
||||
response = client.get(
|
||||
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.gif"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert self._concat_files(mock_run) == set(self.own_frames)
|
||||
|
||||
def test_preview_mp4_excludes_sibling_camera(self):
|
||||
def fake_run(cmd, **kwargs):
|
||||
with open(cmd[-1], "wb") as f:
|
||||
f.write(b"mp4")
|
||||
return MagicMock(returncode=0)
|
||||
|
||||
with (
|
||||
patch("frigate.api.media.sp.run", side_effect=fake_run) as mock_run,
|
||||
AuthTestClient(self.app) as client,
|
||||
):
|
||||
response = client.get(
|
||||
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.mp4"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert self._concat_files(mock_run) == set(self.own_frames)
|
||||
@@ -22,7 +22,6 @@ from frigate.api.chat import (
|
||||
_execute_pending_tools,
|
||||
_pending_tool_calls_from_tail,
|
||||
_tool_calls_awaiting_approval,
|
||||
_with_server_ids,
|
||||
)
|
||||
from frigate.api.defs.request.chat_body import ChatCompletionRequest
|
||||
from frigate.genai.prompts import (
|
||||
@@ -153,22 +152,6 @@ class TestApprovalHelpers(unittest.TestCase):
|
||||
body = _body(tool_decisions={"c2": "approve", "c3": "reject"})
|
||||
self.assertEqual(_tool_calls_awaiting_approval(pending, body, WRITE_TOOLS), [])
|
||||
|
||||
def test_repeated_provider_ids_get_unique_server_ids(self):
|
||||
calls = [
|
||||
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
|
||||
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
|
||||
]
|
||||
renamed = _with_server_ids(calls)
|
||||
self.assertEqual(len({tc["id"] for tc in renamed}), 2)
|
||||
self.assertNotIn("set_camera_state", {tc["id"] for tc in renamed})
|
||||
|
||||
# A later call to the same tool is not covered by an earlier decision.
|
||||
body = _body(tool_decisions={renamed[0]["id"]: "approve"})
|
||||
later = _with_server_ids(calls[:1])
|
||||
self.assertEqual(
|
||||
len(_tool_calls_awaiting_approval(later, body, WRITE_TOOLS)), 1
|
||||
)
|
||||
|
||||
|
||||
class TestExecutePendingTools(unittest.TestCase):
|
||||
def test_rejected_call_is_not_executed(self):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Tests for export progress tracking, broadcast, and FFmpeg parsing."""
|
||||
|
||||
import datetime
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
@@ -7,11 +8,14 @@ import tempfile
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from peewee import SqliteDatabase
|
||||
|
||||
from frigate.jobs.export import (
|
||||
PROGRESS_BROADCAST_MIN_INTERVAL,
|
||||
ExportJob,
|
||||
ExportJobManager,
|
||||
)
|
||||
from frigate.models import Previews
|
||||
from frigate.record.export import (
|
||||
ExportStreamEnum,
|
||||
PlaybackSourceEnum,
|
||||
@@ -557,5 +561,38 @@ class TestChapterMetadataInProgressReview(unittest.TestCase):
|
||||
assert "title=Alert: person" in content
|
||||
|
||||
|
||||
class TestPreviewExportCommandCameraMatch(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.cache_dir = tempfile.mkdtemp(prefix="frigate_preview_export_test_")
|
||||
self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
|
||||
self.preview_dir = os.path.join(self.cache_dir, "preview_frames")
|
||||
os.makedirs(self.preview_dir)
|
||||
|
||||
def _write_frame(self, camera: str, frame_time: float) -> str:
|
||||
path = os.path.join(self.preview_dir, f"preview_{camera}-{frame_time}.webp")
|
||||
with open(path, "wb") as f:
|
||||
f.write(b"fake-webp-bytes")
|
||||
return path
|
||||
|
||||
def test_current_hour_playlist_excludes_sibling_camera(self) -> None:
|
||||
exporter = _make_exporter()
|
||||
exporter.playback_source = PlaybackSourceEnum.preview
|
||||
exporter.start_time = datetime.datetime.now(datetime.UTC).timestamp()
|
||||
exporter.end_time = 9_999_999_999
|
||||
own = self._write_frame(exporter.camera, exporter.start_time + 1)
|
||||
self._write_frame(f"{exporter.camera}-2", exporter.start_time + 1)
|
||||
|
||||
db = SqliteDatabase(":memory:")
|
||||
with (
|
||||
patch("frigate.record.export.CACHE_DIR", self.cache_dir),
|
||||
db.bind_ctx([Previews]),
|
||||
):
|
||||
Previews.create_table()
|
||||
_, playlist_lines = exporter.get_preview_export_command("out.mp4")
|
||||
|
||||
files = {line for line in playlist_lines if line.startswith("file ")}
|
||||
assert files == {f"file '{own}'"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -500,42 +500,6 @@ class TestGeminiProvider(unittest.TestCase):
|
||||
final = _final_message(_collect(client, MULTIMODAL_MESSAGES))
|
||||
self.assertEqual(final["content"], "ok")
|
||||
|
||||
def test_tool_response_name_resolves_from_call_id(self):
|
||||
from google.genai.types import FinishReason
|
||||
|
||||
client = self._client()
|
||||
self._patch_stream(
|
||||
client,
|
||||
[
|
||||
_gemini_chunk(
|
||||
parts=[_gemini_part(text="ok")], finish_reason=FinishReason.STOP
|
||||
)
|
||||
],
|
||||
)
|
||||
messages = [
|
||||
{"role": "user", "content": "turn off recordings"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "call_abc",
|
||||
"type": "function",
|
||||
"function": {"name": "set_camera_state", "arguments": "{}"},
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "call_abc", "content": "{}"},
|
||||
]
|
||||
_collect(client, messages)
|
||||
|
||||
contents = client.provider.aio.models.generate_content_stream.call_args.kwargs[
|
||||
"contents"
|
||||
]
|
||||
self.assertEqual(
|
||||
contents[-1].parts[0].function_response.name, "set_camera_state"
|
||||
)
|
||||
|
||||
|
||||
class TestGeminiImageTokens(unittest.TestCase):
|
||||
def _client(self, count_tokens):
|
||||
|
||||
Reference in New Issue
Block a user