ifseen 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ifseen/__init__.py +29 -0
- ifseen/__main__.py +5 -0
- ifseen/actions.py +348 -0
- ifseen/cli.py +612 -0
- ifseen/config.py +443 -0
- ifseen/constants.py +160 -0
- ifseen/engine.py +357 -0
- ifseen/ha.py +272 -0
- ifseen/media.py +127 -0
- ifseen/mqtt.py +399 -0
- ifseen/oneshot.py +211 -0
- ifseen/providers/__init__.py +219 -0
- ifseen/providers/base.py +176 -0
- ifseen/providers/gemini.py +73 -0
- ifseen/providers/llm.py +110 -0
- ifseen/providers/local.py +157 -0
- ifseen/providers/mock.py +48 -0
- ifseen/providers/systemone.py +80 -0
- ifseen/recipes/__init__.py +31 -0
- ifseen/recipes/appliance-done.yaml +19 -0
- ifseen/recipes/baby-monitor.yaml +37 -0
- ifseen/recipes/doorbell.yaml +27 -0
- ifseen/recipes/focus-guard.yaml +19 -0
- ifseen/recipes/kitchen.yaml +43 -0
- ifseen/recipes/legacy-screen-alarm.yaml +20 -0
- ifseen/recipes/meeting-radar.yaml +26 -0
- ifseen/recipes/pet-patrol.yaml +22 -0
- ifseen/recipes/print-failure.yaml +28 -0
- ifseen/recipes/shelf-restock.yaml +18 -0
- ifseen/recipes/warehouse-safety.yaml +26 -0
- ifseen/runtime.py +105 -0
- ifseen/server.py +661 -0
- ifseen/sources/__init__.py +47 -0
- ifseen/sources/base.py +72 -0
- ifseen/sources/camera.py +115 -0
- ifseen/sources/file.py +110 -0
- ifseen/sources/mic.py +69 -0
- ifseen/sources/screen.py +51 -0
- ifseen/sources/url.py +51 -0
- ifseen/ui.py +194 -0
- ifseen/watcher.py +780 -0
- ifseen-0.1.0.dist-info/METADATA +556 -0
- ifseen-0.1.0.dist-info/RECORD +46 -0
- ifseen-0.1.0.dist-info/WHEEL +4 -0
- ifseen-0.1.0.dist-info/entry_points.txt +2 -0
- ifseen-0.1.0.dist-info/licenses/LICENSE +21 -0
ifseen/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""ifseen - if seen (or heard), then do.
|
|
2
|
+
|
|
3
|
+
Library use::
|
|
4
|
+
|
|
5
|
+
from ifseen import Watcher, check, FireEvent
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .actions import FireEvent
|
|
9
|
+
from .config import ConfigError, WatchConfig
|
|
10
|
+
from .constants import VERSION as __version__
|
|
11
|
+
from .oneshot import CheckResult, check, check_detailed
|
|
12
|
+
from .providers import Provider, ProviderConfigError, ProviderError
|
|
13
|
+
from .sources import SourceError
|
|
14
|
+
from .watcher import Watcher
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"CheckResult",
|
|
18
|
+
"ConfigError",
|
|
19
|
+
"FireEvent",
|
|
20
|
+
"Provider",
|
|
21
|
+
"ProviderConfigError",
|
|
22
|
+
"ProviderError",
|
|
23
|
+
"SourceError",
|
|
24
|
+
"WatchConfig",
|
|
25
|
+
"Watcher",
|
|
26
|
+
"__version__",
|
|
27
|
+
"check",
|
|
28
|
+
"check_detailed",
|
|
29
|
+
]
|
ifseen/__main__.py
ADDED
ifseen/actions.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""What happens when a rule fires."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from string import Formatter
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from .config import Action, Rule
|
|
24
|
+
from .constants import HTTP_TIMEOUT_SECONDS, NTFY_DEFAULT_SERVER
|
|
25
|
+
from .media import Sample
|
|
26
|
+
|
|
27
|
+
Log = Callable[[str, str], None] # (level, message)
|
|
28
|
+
|
|
29
|
+
_SHELL_GRACE_SECONDS = 10.0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class FireEvent:
|
|
34
|
+
"""A rule firing: what actions and Python callbacks receive."""
|
|
35
|
+
|
|
36
|
+
rule: Rule
|
|
37
|
+
probability: float
|
|
38
|
+
fired_at: float
|
|
39
|
+
sample: Sample
|
|
40
|
+
source: str
|
|
41
|
+
snapshot: Path | None = None
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def name(self) -> str:
|
|
45
|
+
"""The rule's name."""
|
|
46
|
+
return self.rule.name
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def jpeg(self) -> bytes | None:
|
|
50
|
+
"""The triggering frame as JPEG bytes (None for audio-only sources)."""
|
|
51
|
+
return self.sample.jpeg
|
|
52
|
+
|
|
53
|
+
def fields(self) -> dict[str, str]:
|
|
54
|
+
return {
|
|
55
|
+
"rule": self.rule.name,
|
|
56
|
+
"when": self.rule.when,
|
|
57
|
+
"prob": f"{self.probability:.2f}",
|
|
58
|
+
"percent": f"{self.probability * 100:.0f}%",
|
|
59
|
+
"time": time.strftime("%H:%M:%S", time.localtime(self.fired_at)),
|
|
60
|
+
"source": self.source,
|
|
61
|
+
"snapshot": str(self.snapshot or ""),
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _SafeFormatter(Formatter):
|
|
66
|
+
"""str.format that leaves unknown {placeholders} untouched instead of raising."""
|
|
67
|
+
|
|
68
|
+
def get_value(self, key, args, kwargs): # type: ignore[override]
|
|
69
|
+
if isinstance(key, str) and key in kwargs:
|
|
70
|
+
return str(kwargs[key])
|
|
71
|
+
return "{" + str(key) + "}"
|
|
72
|
+
|
|
73
|
+
def format_field(self, value, format_spec): # type: ignore[override]
|
|
74
|
+
return str(value)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def render(template: str, event: FireEvent) -> str:
|
|
78
|
+
try:
|
|
79
|
+
return _SafeFormatter().format(template, **event.fields())
|
|
80
|
+
except (ValueError, IndexError):
|
|
81
|
+
return template
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ActionRunner:
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
log: Log,
|
|
88
|
+
dry_run: bool = False,
|
|
89
|
+
client: httpx.Client | None = None,
|
|
90
|
+
background: bool = True,
|
|
91
|
+
notify_by_default: bool = True,
|
|
92
|
+
):
|
|
93
|
+
self.log = log
|
|
94
|
+
self.dry_run = dry_run
|
|
95
|
+
self.notify_by_default = notify_by_default
|
|
96
|
+
self._client = client
|
|
97
|
+
self._tmpdir: Path | None = None
|
|
98
|
+
self._procs: list[subprocess.Popen] = []
|
|
99
|
+
self._procs_lock = threading.Lock()
|
|
100
|
+
self._pool = (
|
|
101
|
+
ThreadPoolExecutor(max_workers=4, thread_name_prefix="ifseen-action")
|
|
102
|
+
if background
|
|
103
|
+
else None
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def client(self) -> httpx.Client:
|
|
108
|
+
if self._client is None:
|
|
109
|
+
self._client = httpx.Client(timeout=HTTP_TIMEOUT_SECONDS)
|
|
110
|
+
return self._client
|
|
111
|
+
|
|
112
|
+
def run(self, actions: list[Action], event: FireEvent) -> bool:
|
|
113
|
+
"""Run a rule's actions. Returns True if an `exit` action asked the watcher to stop."""
|
|
114
|
+
if event.sample.jpeg is not None and event.snapshot is None:
|
|
115
|
+
event.snapshot = self._temp_snapshot(event)
|
|
116
|
+
if not actions:
|
|
117
|
+
actions = self.default_actions(event)
|
|
118
|
+
stop = False
|
|
119
|
+
for action in actions:
|
|
120
|
+
((kind, opts),) = action.items()
|
|
121
|
+
if kind == "exit":
|
|
122
|
+
stop = True
|
|
123
|
+
continue
|
|
124
|
+
if self.dry_run and kind not in ("log",):
|
|
125
|
+
self.log("dry", f"[{event.rule.name}] would run {kind}: {_describe(kind, opts)}")
|
|
126
|
+
continue
|
|
127
|
+
if self._pool is None:
|
|
128
|
+
self._safe(kind, opts, event)
|
|
129
|
+
else:
|
|
130
|
+
self._pool.submit(self._safe, kind, opts, event)
|
|
131
|
+
return stop
|
|
132
|
+
|
|
133
|
+
def default_actions(self, event: FireEvent) -> list[Action]:
|
|
134
|
+
"""What a rule with no `then:` does."""
|
|
135
|
+
return [{"notify": True}] if self.notify_by_default else []
|
|
136
|
+
|
|
137
|
+
def _temp_snapshot(self, event: FireEvent) -> Path | None:
|
|
138
|
+
try:
|
|
139
|
+
if self._tmpdir is None:
|
|
140
|
+
# private per-run dir: a shared, predictable /tmp path invites symlink attacks
|
|
141
|
+
self._tmpdir = Path(tempfile.mkdtemp(prefix="ifseen-"))
|
|
142
|
+
path = self._tmpdir / f"{event.rule.name}-latest.jpg"
|
|
143
|
+
path.write_bytes(event.sample.jpeg or b"")
|
|
144
|
+
return path
|
|
145
|
+
except OSError as e:
|
|
146
|
+
self.log("warn", f"could not write temp snapshot: {e.strerror}")
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
def close(self) -> None:
|
|
150
|
+
if self._pool is not None:
|
|
151
|
+
self._pool.shutdown(wait=True, cancel_futures=False)
|
|
152
|
+
# Shell commands may still be reading $IFSEEN_SNAPSHOT (e.g. a rule ending in
|
|
153
|
+
# `exit`), so give them a moment before deleting the frames.
|
|
154
|
+
deadline = time.monotonic() + _SHELL_GRACE_SECONDS
|
|
155
|
+
for proc in self._procs:
|
|
156
|
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
157
|
+
proc.wait(timeout=max(0.0, deadline - time.monotonic()))
|
|
158
|
+
if self._tmpdir is not None:
|
|
159
|
+
shutil.rmtree(self._tmpdir, ignore_errors=True)
|
|
160
|
+
self._tmpdir = None
|
|
161
|
+
if self._client is not None:
|
|
162
|
+
self._client.close()
|
|
163
|
+
|
|
164
|
+
# -- individual actions ----------------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
def _safe(self, kind: str, opts: Any, event: FireEvent) -> None:
|
|
167
|
+
try:
|
|
168
|
+
getattr(self, f"_do_{kind}")(opts, event)
|
|
169
|
+
except httpx.HTTPStatusError as e:
|
|
170
|
+
# never echo the URL: webhook and ntfy URLs are effectively secrets
|
|
171
|
+
self.log(
|
|
172
|
+
"error",
|
|
173
|
+
f"[{event.rule.name}] {kind} failed: HTTP {e.response.status_code} "
|
|
174
|
+
f"from {e.request.url.host}",
|
|
175
|
+
)
|
|
176
|
+
except httpx.HTTPError as e:
|
|
177
|
+
host = e.request.url.host if _has_request(e) else "?"
|
|
178
|
+
self.log("error", f"[{event.rule.name}] {kind} failed: {type(e).__name__} ({host})")
|
|
179
|
+
except Exception as e: # an action failing must never kill the watcher
|
|
180
|
+
self.log("error", f"[{event.rule.name}] {kind} failed: {type(e).__name__}: {e}")
|
|
181
|
+
|
|
182
|
+
def _do_log(self, opts: Any, event: FireEvent) -> None:
|
|
183
|
+
msg = opts if isinstance(opts, str) else "{when} ({percent})"
|
|
184
|
+
self.log("info", f"[{event.rule.name}] {render(msg, event)}")
|
|
185
|
+
|
|
186
|
+
def _do_notify(self, opts: Any, event: FireEvent) -> None:
|
|
187
|
+
title, message = "ifseen: {rule}", "{when} ({percent})"
|
|
188
|
+
if isinstance(opts, str):
|
|
189
|
+
message = opts
|
|
190
|
+
elif isinstance(opts, dict):
|
|
191
|
+
title = opts.get("title", title)
|
|
192
|
+
message = opts.get("message", message)
|
|
193
|
+
desktop_notify(render(title, event), render(message, event))
|
|
194
|
+
|
|
195
|
+
def _do_say(self, opts: Any, event: FireEvent) -> None:
|
|
196
|
+
text = render(opts if isinstance(opts, str) else "{rule}", event)
|
|
197
|
+
speak(text)
|
|
198
|
+
|
|
199
|
+
def _do_shell(self, opts: Any, event: FireEvent) -> None:
|
|
200
|
+
cmd = opts if isinstance(opts, str) else opts.get("cmd") if isinstance(opts, dict) else None
|
|
201
|
+
if not cmd:
|
|
202
|
+
raise ValueError("shell action needs a command")
|
|
203
|
+
wait = isinstance(opts, dict) and bool(opts.get("wait"))
|
|
204
|
+
env = {**os.environ, **{f"IFSEEN_{k.upper()}": v for k, v in event.fields().items()}}
|
|
205
|
+
# Values reach the command only as IFSEEN_* env vars, never spliced into the command
|
|
206
|
+
# text, so file names, URLs or rule text can't inject shell syntax.
|
|
207
|
+
proc = subprocess.Popen(cmd, shell=True, env=env)
|
|
208
|
+
with self._procs_lock:
|
|
209
|
+
self._procs = [p for p in self._procs if p.poll() is None] + [proc]
|
|
210
|
+
if wait:
|
|
211
|
+
code = proc.wait()
|
|
212
|
+
if code:
|
|
213
|
+
self.log("warn", f"[{event.rule.name}] shell exited with {code}")
|
|
214
|
+
|
|
215
|
+
def _do_webhook(self, opts: Any, event: FireEvent) -> None:
|
|
216
|
+
if isinstance(opts, str):
|
|
217
|
+
opts = {"url": opts}
|
|
218
|
+
url = render(opts["url"], event)
|
|
219
|
+
payload: dict[str, Any] = {
|
|
220
|
+
"rule": event.rule.name,
|
|
221
|
+
"when": event.rule.when,
|
|
222
|
+
"probability": round(event.probability, 4),
|
|
223
|
+
"fired_at": event.fired_at,
|
|
224
|
+
"source": event.source,
|
|
225
|
+
}
|
|
226
|
+
if opts.get("image") and event.sample.jpeg is not None:
|
|
227
|
+
import base64
|
|
228
|
+
|
|
229
|
+
payload["image_base64"] = base64.b64encode(event.sample.jpeg).decode("ascii")
|
|
230
|
+
r = self.client.request(
|
|
231
|
+
opts.get("method", "POST"), url, json=payload, headers=opts.get("headers") or {}
|
|
232
|
+
)
|
|
233
|
+
r.raise_for_status()
|
|
234
|
+
|
|
235
|
+
def _do_ntfy(self, opts: Any, event: FireEvent) -> None:
|
|
236
|
+
if isinstance(opts, str):
|
|
237
|
+
opts = {"topic": opts}
|
|
238
|
+
server = opts.get("server", NTFY_DEFAULT_SERVER).rstrip("/")
|
|
239
|
+
url = f"{server}/{render(opts['topic'], event)}"
|
|
240
|
+
params = {
|
|
241
|
+
"title": render(opts.get("title", "ifseen: {rule}"), event),
|
|
242
|
+
"message": render(opts.get("message", "{when} ({percent})"), event),
|
|
243
|
+
}
|
|
244
|
+
if opts.get("priority"):
|
|
245
|
+
params["priority"] = str(opts["priority"])
|
|
246
|
+
if opts.get("tags"):
|
|
247
|
+
params["tags"] = (
|
|
248
|
+
",".join(opts["tags"]) if isinstance(opts["tags"], list) else str(opts["tags"])
|
|
249
|
+
)
|
|
250
|
+
headers = {}
|
|
251
|
+
if opts.get("token"):
|
|
252
|
+
headers["Authorization"] = f"Bearer {opts['token']}"
|
|
253
|
+
if opts.get("image", True) and event.sample.jpeg is not None:
|
|
254
|
+
params["filename"] = f"{event.rule.name}.jpg"
|
|
255
|
+
r = self.client.put(url, params=params, content=event.sample.jpeg, headers=headers)
|
|
256
|
+
else:
|
|
257
|
+
r = self.client.post(url, params=params, content=b"", headers=headers)
|
|
258
|
+
r.raise_for_status()
|
|
259
|
+
|
|
260
|
+
def _do_snapshot(self, opts: Any, event: FireEvent) -> None:
|
|
261
|
+
if event.sample.jpeg is None:
|
|
262
|
+
self.log("warn", f"[{event.rule.name}] snapshot skipped: source has no image")
|
|
263
|
+
return
|
|
264
|
+
folder = Path(opts if isinstance(opts, str) else "ifseen-captures").expanduser()
|
|
265
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
266
|
+
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(event.fired_at))
|
|
267
|
+
path = folder / f"{event.rule.name}-{stamp}.jpg"
|
|
268
|
+
path.write_bytes(event.sample.jpeg)
|
|
269
|
+
self.log("info", f"[{event.rule.name}] saved {path}")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _describe(kind: str, opts: Any) -> str:
|
|
273
|
+
"""Dry-run description that never prints URLs, topics or tokens."""
|
|
274
|
+
if kind in ("webhook", "ntfy"):
|
|
275
|
+
return "(destination hidden)"
|
|
276
|
+
s = str(opts)
|
|
277
|
+
return s if len(s) < 60 else s[:57] + "..."
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _has_request(e: httpx.HTTPError) -> bool:
|
|
281
|
+
try:
|
|
282
|
+
e.request # noqa: B018 - raises RuntimeError when unset
|
|
283
|
+
except RuntimeError:
|
|
284
|
+
return False
|
|
285
|
+
return True
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def desktop_notify(title: str, message: str) -> None:
|
|
289
|
+
system = platform.system()
|
|
290
|
+
if system == "Darwin":
|
|
291
|
+
subprocess.run(
|
|
292
|
+
[
|
|
293
|
+
"osascript",
|
|
294
|
+
"-e",
|
|
295
|
+
"on run argv",
|
|
296
|
+
"-e",
|
|
297
|
+
"display notification (item 2 of argv) with title (item 1 of argv)",
|
|
298
|
+
"-e",
|
|
299
|
+
"end run",
|
|
300
|
+
title,
|
|
301
|
+
message,
|
|
302
|
+
],
|
|
303
|
+
check=False,
|
|
304
|
+
capture_output=True,
|
|
305
|
+
)
|
|
306
|
+
elif system == "Linux" and shutil.which("notify-send"):
|
|
307
|
+
subprocess.run(["notify-send", title, message], check=False, capture_output=True)
|
|
308
|
+
elif system == "Windows":
|
|
309
|
+
ps = (
|
|
310
|
+
"[void][Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,"
|
|
311
|
+
"ContentType=WindowsRuntime];$t=[Windows.UI.Notifications.ToastNotificationManager]::"
|
|
312
|
+
"GetTemplateContent(1);$n=$t.GetElementsByTagName('text');"
|
|
313
|
+
"$n.Item(0).AppendChild($t.CreateTextNode($args[0]))|Out-Null;"
|
|
314
|
+
"$n.Item(1).AppendChild($t.CreateTextNode($args[1]))|Out-Null;"
|
|
315
|
+
"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('ifseen')"
|
|
316
|
+
".Show([Windows.UI.Notifications.ToastNotification]::new($t))"
|
|
317
|
+
)
|
|
318
|
+
subprocess.run(
|
|
319
|
+
["powershell", "-NoProfile", "-Command", ps, title, message],
|
|
320
|
+
check=False,
|
|
321
|
+
capture_output=True,
|
|
322
|
+
)
|
|
323
|
+
else:
|
|
324
|
+
sys.stderr.write(f"\a{title}: {message}\n")
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def speak(text: str) -> None:
|
|
328
|
+
system = platform.system()
|
|
329
|
+
if system == "Darwin":
|
|
330
|
+
subprocess.run(["say", text], check=False)
|
|
331
|
+
elif shutil.which("spd-say"):
|
|
332
|
+
subprocess.run(["spd-say", text], check=False)
|
|
333
|
+
elif shutil.which("espeak"):
|
|
334
|
+
subprocess.run(["espeak", text], check=False)
|
|
335
|
+
elif system == "Windows":
|
|
336
|
+
subprocess.run(
|
|
337
|
+
[
|
|
338
|
+
"powershell",
|
|
339
|
+
"-NoProfile",
|
|
340
|
+
"-Command",
|
|
341
|
+
"Add-Type -AssemblyName System.Speech;"
|
|
342
|
+
"(New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak($args[0])",
|
|
343
|
+
text,
|
|
344
|
+
],
|
|
345
|
+
check=False,
|
|
346
|
+
)
|
|
347
|
+
else:
|
|
348
|
+
sys.stderr.write("\a")
|