obico_detection.py 21 KB

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