obico_detection.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. """Obico AI print-failure detection service.
  2. Polls a self-hosted Obico ML API with snapshots from each monitored printer
  3. while a print is running, smooths scores over time, and dispatches a configured
  4. action (notify / pause / pause_and_off) when a sustained failure is detected.
  5. See `obico_smoothing.py` for the per-print EWM + rolling-mean math.
  6. """
  7. import asyncio
  8. import json
  9. import logging
  10. import secrets
  11. import time
  12. from collections import deque
  13. from datetime import datetime, timezone
  14. import httpx
  15. from sqlalchemy import select
  16. from backend.app.core.database import async_session
  17. from backend.app.models.printer import Printer
  18. from backend.app.models.settings import Settings
  19. from backend.app.services.obico_smoothing import (
  20. PrintState,
  21. classify,
  22. score_from_detections,
  23. thresholds,
  24. )
  25. logger = logging.getLogger(__name__)
  26. HISTORY_MAX = 50
  27. HEALTH_TIMEOUT = 5.0
  28. DETECTION_TIMEOUT = 30.0
  29. SNAPSHOT_CAPTURE_TIMEOUT = 20 # seconds — we control this, not Obico
  30. FRAME_CACHE_TTL = 30.0 # seconds — Obico usually fetches within 1s of receiving the URL
  31. # Module-level one-shot frame cache. Obico's ML API is GET-only (/p/?img=URL) and
  32. # fetches the URL itself with a hardcoded 5s read timeout. We capture locally first,
  33. # stash the JPEG under a random nonce, and hand Obico a URL that serves the cached
  34. # bytes instantly — so the 5s ceiling never races RTSP keyframe wait.
  35. _frame_cache: dict[str, tuple[bytes, float]] = {}
  36. _frame_cache_lock = asyncio.Lock()
  37. def auth_headers(token: str | None) -> dict[str, str]:
  38. """Bearer header for the ML API, or nothing when no token is configured.
  39. Obico's ML API gates ``/p/`` behind ``ML_API_TOKEN`` (``ml_api/auth.py``):
  40. with the variable set it answers a bare 401 to any request whose
  41. ``Authorization`` header isn't ``Bearer <token>``, and with it unset it
  42. ignores the header entirely. Sending nothing when unconfigured keeps the
  43. request byte-identical to what shipped before the setting existed.
  44. """
  45. token = (token or "").strip()
  46. return {"Authorization": f"Bearer {token}"} if token else {}
  47. def _prune_frame_cache() -> None:
  48. """Drop entries older than FRAME_CACHE_TTL. Called under the cache lock."""
  49. now = time.monotonic()
  50. expired = [k for k, (_b, ts) in _frame_cache.items() if now - ts > FRAME_CACHE_TTL]
  51. for k in expired:
  52. _frame_cache.pop(k, None)
  53. async def stash_frame(data: bytes) -> str:
  54. """Store JPEG bytes and return a URL-safe nonce that serves them once."""
  55. nonce = secrets.token_urlsafe(32)
  56. async with _frame_cache_lock:
  57. _prune_frame_cache()
  58. _frame_cache[nonce] = (data, time.monotonic())
  59. return nonce
  60. async def pop_frame(nonce: str) -> bytes | None:
  61. """Return and remove a cached frame by nonce; None if missing or expired."""
  62. async with _frame_cache_lock:
  63. _prune_frame_cache()
  64. entry = _frame_cache.pop(nonce, None)
  65. if entry is None:
  66. return None
  67. data, ts = entry
  68. if time.monotonic() - ts > FRAME_CACHE_TTL:
  69. return None
  70. return data
  71. class ObicoDetectionService:
  72. """Singleton service that polls the ML API and acts on sustained failures."""
  73. def __init__(self):
  74. self._task: asyncio.Task | None = None
  75. # printer_id -> PrintState (reset when a new print starts)
  76. self._states: dict[int, PrintState] = {}
  77. # printer_id -> task_name active when state was created (used to detect new prints)
  78. self._state_keys: dict[int, str] = {}
  79. # printer_id -> last classification ("safe"/"warning"/"failure").
  80. # Only written after an inference actually came back, so a missing entry
  81. # means "we have no verdict", which is not the same as "safe" (#2952).
  82. self._last_class: dict[int, str] = {}
  83. # printer_id -> why the most recent poll produced no verdict, or absent
  84. # when the last poll succeeded. Per-printer rather than global so a card
  85. # can say what went wrong for *that* printer.
  86. self._errors: dict[int, str] = {}
  87. # printer_id -> whether an action has already been fired for the current print
  88. self._action_fired: dict[int, bool] = {}
  89. # Global detection event log (most-recent-first)
  90. self._history: deque = deque(maxlen=HISTORY_MAX)
  91. self._last_error: str | None = None
  92. def forget_printer(self, printer_id: int) -> None:
  93. """A deleted printer's verdict and score, not the next printer's given its id."""
  94. for state in (self._states, self._state_keys, self._last_class, self._errors, self._action_fired):
  95. state.pop(printer_id, None)
  96. # ---- lifecycle ----
  97. async def start(self):
  98. if self._task is not None:
  99. return
  100. logger.info("Starting Obico detection service")
  101. self._task = asyncio.create_task(self._loop())
  102. def stop(self):
  103. if self._task:
  104. self._task.cancel()
  105. self._task = None
  106. logger.info("Stopped Obico detection service")
  107. # ---- settings ----
  108. async def _load_settings(self) -> dict:
  109. keys = [
  110. "obico_enabled",
  111. "obico_ml_url",
  112. "bambuddy_internal_url",
  113. "obico_ml_token",
  114. "obico_sensitivity",
  115. "obico_action",
  116. "obico_poll_interval",
  117. "obico_enabled_printers",
  118. "external_url",
  119. ]
  120. async with async_session() as db:
  121. result = await db.execute(select(Settings).where(Settings.key.in_(keys)))
  122. rows = {r.key: r.value for r in result.scalars().all()}
  123. enabled_printers_raw = rows.get("obico_enabled_printers", "")
  124. if enabled_printers_raw:
  125. try:
  126. enabled_printers = set(json.loads(enabled_printers_raw))
  127. except json.JSONDecodeError:
  128. enabled_printers = set()
  129. else:
  130. enabled_printers = None # None = all printers
  131. return {
  132. "enabled": rows.get("obico_enabled", "false").lower() == "true",
  133. "ml_url": (rows.get("obico_ml_url") or "").rstrip("/"),
  134. "ml_token": (rows.get("obico_ml_token") or "").strip(),
  135. "sensitivity": rows.get("obico_sensitivity", "medium"),
  136. "action": rows.get("obico_action", "notify"),
  137. "poll_interval": int(rows.get("obico_poll_interval", "10")),
  138. "enabled_printers": enabled_printers,
  139. # Where Obico's ML server fetches snapshots: the Internal URL when
  140. # set, otherwise the public External URL.
  141. "snapshot_base_url": (
  142. (rows.get("bambuddy_internal_url") or "").strip() or (rows.get("external_url") or "").strip()
  143. ).rstrip("/"),
  144. }
  145. # ---- main loop ----
  146. async def _loop(self):
  147. """Poll active printers while enabled. Adjusts interval from settings each cycle."""
  148. while True:
  149. try:
  150. settings = await self._load_settings()
  151. interval = max(5, settings.get("poll_interval", 10))
  152. if not settings["enabled"] or not settings["ml_url"]:
  153. await asyncio.sleep(interval)
  154. continue
  155. await self._poll_once(settings)
  156. await asyncio.sleep(interval)
  157. except asyncio.CancelledError:
  158. break
  159. except Exception as e:
  160. logger.error("Obico detection loop error: %s", e)
  161. self._last_error = str(e) or type(e).__name__
  162. await asyncio.sleep(30)
  163. async def _poll_once(self, settings: dict):
  164. # Late import to avoid cycles at module load time
  165. from backend.app.services.printer_manager import printer_manager
  166. statuses = printer_manager.get_all_statuses()
  167. for printer_id, status in list(statuses.items()):
  168. if settings["enabled_printers"] is not None and printer_id not in settings["enabled_printers"]:
  169. continue
  170. if not printer_manager.is_connected(printer_id):
  171. continue
  172. if not status or getattr(status, "state", None) != "RUNNING":
  173. # Reset state when not printing so the next print starts fresh
  174. self._states.pop(printer_id, None)
  175. self._state_keys.pop(printer_id, None)
  176. self._action_fired.pop(printer_id, None)
  177. self._last_class.pop(printer_id, None)
  178. self._errors.pop(printer_id, None)
  179. continue
  180. await self._check_printer(printer_id, status, settings)
  181. async def _capture_frame(self, printer_id: int) -> bytes | None:
  182. """Capture one JPEG frame from the printer camera. Returns None on failure."""
  183. # Late import to avoid cycles at module load time
  184. from backend.app.services.camera import capture_camera_frame_bytes
  185. from backend.app.services.external_camera import capture_frame as capture_external_frame
  186. async with async_session() as db:
  187. printer = await db.get(Printer, printer_id)
  188. if printer is None:
  189. self._last_error = f"Printer {printer_id} not found"
  190. return None
  191. if printer.external_camera_enabled and printer.external_camera_url:
  192. # Same rule as the built-in branch below, which this used to skip:
  193. # an external camera is single-reader too, so polling while a viewer
  194. # is attached just fails (#2707).
  195. from backend.app.api.routes.camera import live_frame_for_capture
  196. defer, buffered = live_frame_for_capture(printer_id)
  197. if defer:
  198. if buffered:
  199. return buffered
  200. logger.info(
  201. "Obico: viewer attached for printer %s but buffer empty; "
  202. "skipping this poll to avoid competing camera handle (#2707)",
  203. printer_id,
  204. )
  205. return None
  206. return await capture_external_frame(
  207. printer.external_camera_url,
  208. printer.external_camera_type,
  209. timeout=SNAPSHOT_CAPTURE_TIMEOUT,
  210. snapshot_url=printer.external_camera_snapshot_url,
  211. )
  212. # Reuse the fan-out broadcaster's buffered frame when a viewer is
  213. # already watching — avoids opening a second concurrent RTSP socket
  214. # on printers that allow only one camera connection (e.g. X2D
  215. # firmware 01.01.00.00; see #1271). Buffered frame is <1s old while
  216. # a viewer is connected.
  217. #
  218. # When a viewer is attached but no frame is buffered yet (startup
  219. # race, mid-reconnect), we DELIBERATELY skip this poll cycle instead
  220. # of falling through to capture_camera_frame_bytes. Opening a fresh
  221. # RTSP/chamber socket would compete with the live viewer and kick
  222. # the fan-out connection on most firmwares — exactly the freeze
  223. # reported in #1348. The poll loop retries in ~10s.
  224. from backend.app.api.routes.camera import is_stream_active, try_get_active_buffered_frame
  225. if is_stream_active(printer_id):
  226. buffered = try_get_active_buffered_frame(printer_id)
  227. if buffered:
  228. return buffered
  229. logger.info(
  230. "Obico: viewer attached for printer %s but buffer empty; skipping this poll to avoid competing camera socket (#1348)",
  231. printer_id,
  232. )
  233. return None
  234. return await capture_camera_frame_bytes(
  235. ip_address=printer.ip_address,
  236. access_code=printer.access_code,
  237. model=printer.model,
  238. timeout=SNAPSHOT_CAPTURE_TIMEOUT,
  239. )
  240. def _no_verdict(self, printer_id: int, reason: str) -> None:
  241. """Record that this poll produced no verdict for ``printer_id``.
  242. Kept separate from the classification so the status surface can say
  243. "not checking" instead of inheriting the previous verdict — or, worse,
  244. the default "safe" a printer used to get before its first inference.
  245. """
  246. if printer_id not in self._states:
  247. return # deleted while the check waited (forget_printer)
  248. self._errors[printer_id] = reason
  249. self._last_error = reason
  250. logger.warning(reason)
  251. async def _check_printer(self, printer_id: int, status, settings: dict):
  252. task_name = getattr(status, "task_name", None) or getattr(status, "subtask_name", "") or ""
  253. key = f"{task_name}"
  254. if self._state_keys.get(printer_id) != key:
  255. self._states[printer_id] = PrintState()
  256. self._state_keys[printer_id] = key
  257. self._action_fired[printer_id] = False
  258. # Capture locally first, then hand Obico a nonce URL that returns the
  259. # cached bytes instantly. Obico's ML API is GET-only (/p/?img=URL) with a
  260. # hardcoded 5s read timeout which would otherwise race our /camera/snapshot
  261. # keyframe wait.
  262. frame = await self._capture_frame(printer_id)
  263. if not frame:
  264. self._no_verdict(printer_id, f"Failed to capture snapshot for printer {printer_id}")
  265. return
  266. snapshot_base_url = settings.get("snapshot_base_url") or ""
  267. if not snapshot_base_url:
  268. self._no_verdict(
  269. printer_id,
  270. "bambuddy_internal_url and external_url settings are empty — Obico's ML API needs a reachable URL to fetch the snapshot from. "
  271. "Set Settings → Failure Detection → Bambuddy Internal URL or Settings → Network → External URL.",
  272. )
  273. return
  274. nonce = await stash_frame(frame)
  275. snapshot_url = f"{snapshot_base_url}/api/v1/obico/cached-frame/{nonce}"
  276. ml_url = f"{settings['ml_url']}/p/"
  277. try:
  278. async with httpx.AsyncClient(timeout=DETECTION_TIMEOUT) as client:
  279. resp = await client.get(
  280. ml_url,
  281. params={"img": snapshot_url},
  282. headers=auth_headers(settings.get("ml_token")),
  283. )
  284. if resp.status_code == 401:
  285. # The server runs with ML_API_TOKEN set and rejected ours.
  286. # Say so plainly: the health endpoint is ungated, so "Test
  287. # Connection" passes against exactly this configuration and
  288. # a raw 401 gives the user nothing to act on (#2733).
  289. #
  290. # Obico's auth decorator runs before the handler, so a call
  291. # rejected here leaves no trace in the ML API's own log —
  292. # which is how #2952 came to be reported as "the loop never
  293. # calls the ML API" while it was calling it every 10s.
  294. self._no_verdict(
  295. printer_id,
  296. "Obico ML API rejected the token (401). Set Settings → Failure Detection → "
  297. "ML API Token to the ML_API_TOKEN the server runs with, or clear ML_API_TOKEN "
  298. "on the server.",
  299. )
  300. return
  301. resp.raise_for_status()
  302. payload = resp.json()
  303. except Exception as e:
  304. detail = str(e) or type(e).__name__
  305. self._no_verdict(printer_id, f"ML API call failed for printer {printer_id}: {detail}")
  306. return
  307. detections = payload.get("detections", []) if isinstance(payload, dict) else []
  308. current_p = score_from_detections(detections)
  309. state = self._states.get(printer_id)
  310. if state is None:
  311. return # deleted while the check waited (forget_printer)
  312. score = state.update(current_p)
  313. verdict = classify(score, settings["sensitivity"])
  314. self._last_class[printer_id] = verdict
  315. # A successful capture + ML call clears any transient error from previous
  316. # polls (typical case: cold-start RTSP timeout on first frame after startup,
  317. # followed by healthy polls that otherwise leave the banner stuck in the UI).
  318. self._errors.pop(printer_id, None)
  319. self._last_error = None
  320. # Log every non-safe sample — safe samples would flood history
  321. if verdict != "safe" or detections:
  322. self._history.appendleft(
  323. {
  324. "printer_id": printer_id,
  325. "task_name": task_name,
  326. "timestamp": datetime.now(timezone.utc).isoformat(),
  327. "current_p": round(current_p, 4),
  328. "score": round(score, 4),
  329. "class": verdict,
  330. "detections": len(detections),
  331. }
  332. )
  333. if verdict == "failure" and not self._action_fired.get(printer_id):
  334. self._action_fired[printer_id] = True
  335. await self._dispatch_action(printer_id, settings["action"], task_name, score, frame)
  336. async def _dispatch_action(
  337. self, printer_id: int, action: str, task_name: str, score: float, frame: bytes | None = None
  338. ):
  339. from backend.app.services.obico_actions import execute_action
  340. logger.warning(
  341. "Obico: failure detected on printer %s (task=%r score=%.3f) — action=%s",
  342. printer_id,
  343. task_name,
  344. score,
  345. action,
  346. )
  347. try:
  348. # Same frame the ML model flagged, not a fresh capture — the
  349. # printer's moved on by the time this fires.
  350. await execute_action(printer_id, action, task_name, score, frame)
  351. except Exception as e:
  352. self._last_error = f"Action dispatch failed: {e or type(e).__name__}"
  353. logger.error(self._last_error)
  354. # ---- queries ----
  355. def get_per_printer(self) -> dict:
  356. """Live classification per actively monitored printer.
  357. Only printers with a running, monitored print have a state entry, so
  358. consumers get "show nothing" for idle printers for free.
  359. Four classes, and the two non-verdict ones matter as much as the rest:
  360. ``error`` the most recent poll produced no verdict. ``error`` carries
  361. the reason — a rejected token, an unreachable ML API, a
  362. camera that would not yield a frame, a missing Bambuddy address.
  363. ``unknown`` monitored, but no inference has come back yet. The state
  364. entry is created when the print is first seen, which is
  365. before the first capture, so this is the honest answer for
  366. that window.
  367. ``safe`` / ``warning`` / ``failure``
  368. an actual verdict from an actual inference.
  369. This used to default to ``safe`` whenever no verdict had been recorded,
  370. so a printer whose detection had never once succeeded rendered exactly
  371. like a healthy one: a green badge reading "Safe" at score 0.000. That is
  372. the worst possible failure mode for a safety feature — it asserts the
  373. print is being watched precisely when it is not (#2952).
  374. """
  375. result = {}
  376. for pid, state in self._states.items():
  377. error = self._errors.get(pid)
  378. if error:
  379. verdict = "error"
  380. else:
  381. verdict = self._last_class.get(pid) or "unknown"
  382. result[pid] = {
  383. "class": verdict,
  384. "frame_count": state.frame_count,
  385. "score": round(state.ewm_mean, 4),
  386. "error": error,
  387. }
  388. return result
  389. def get_status(self, sensitivity: str = "medium") -> dict:
  390. # Report the thresholds for the configured sensitivity, not a hardcoded
  391. # "medium" — otherwise the Status panel always shows the medium row
  392. # regardless of the user's selection (#1469). thresholds() falls back
  393. # to the medium multiplier for any unrecognized value.
  394. low, high = thresholds(sensitivity)
  395. return {
  396. "is_running": self._task is not None and not self._task.done(),
  397. "last_error": self._last_error,
  398. "per_printer": self.get_per_printer(),
  399. "thresholds": {"low": low, "high": high},
  400. "history": list(self._history),
  401. }
  402. async def test_connection(self, url: str, token: str = "") -> dict:
  403. """Ping the ML API and check the token. Returns {ok, status_code, body, error, auth_ok}.
  404. The stored ``obico_ml_url`` setting is validated at the schema layer,
  405. but this route takes its URL from the request body, so the same
  406. LAN-service policy has to be applied here or the guard is trivially
  407. sidestepped by testing a URL instead of saving it. The response body
  408. is returned to the caller (it is the health signal — the endpoint
  409. answers "ok"), which is exactly why the destination must be inside
  410. policy before the request is made.
  411. ``token`` is used verbatim — resolving "not supplied" to the saved
  412. setting is the route's job, so this stays a pure outbound call.
  413. Health alone cannot answer whether the token works, because Obico
  414. gates ``/p/`` but leaves ``/hc/`` open — which is how a token-protected
  415. server passed this test while every detection call came back 401
  416. (#2733). So a second, side-effect-free probe follows: ``/p/`` with no
  417. ``img`` parameter. The auth decorator runs before the handler, so 401
  418. means the token was rejected and 422 ("Invalid request params") means
  419. it was accepted. No inference work is done either way.
  420. """
  421. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  422. try:
  423. assert_safe_lan_service_url(url, label="Obico ML URL")
  424. except ValueError as exc:
  425. return {"ok": False, "status_code": None, "body": None, "error": str(exc), "auth_ok": None}
  426. headers = auth_headers(token)
  427. base = url.rstrip("/")
  428. try:
  429. async with httpx.AsyncClient(timeout=HEALTH_TIMEOUT) as client:
  430. resp = await client.get(f"{base}/hc/", headers=headers)
  431. body = resp.text.strip()
  432. healthy = resp.status_code == 200 and body.lower() == "ok"
  433. if not healthy:
  434. return {
  435. "ok": False,
  436. "status_code": resp.status_code,
  437. "body": body,
  438. "error": None,
  439. "auth_ok": None,
  440. }
  441. auth_ok: bool | None
  442. try:
  443. probe = await client.get(f"{base}/p/", headers=headers)
  444. auth_ok = probe.status_code != 401
  445. except Exception:
  446. # The health check already succeeded, so don't fail the
  447. # whole test on the probe — report the token as unknown.
  448. auth_ok = None
  449. except Exception as e:
  450. return {
  451. "ok": False,
  452. "status_code": None,
  453. "body": None,
  454. "error": str(e) or type(e).__name__,
  455. "auth_ok": None,
  456. }
  457. if auth_ok is False:
  458. return {
  459. "ok": False,
  460. "status_code": 401,
  461. "body": body,
  462. "error": (
  463. "The ML API is reachable but rejected the token. It runs with ML_API_TOKEN set — "
  464. "enter that value as the ML API Token, or clear ML_API_TOKEN on the server."
  465. ),
  466. "auth_ok": False,
  467. }
  468. return {"ok": True, "status_code": resp.status_code, "body": body, "error": None, "auth_ok": auth_ok}
  469. obico_detection_service = ObicoDetectionService()