plate_detection.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. """Build plate empty detection using OpenCV.
  2. Analyzes camera frames to detect if there are objects on the build plate.
  3. Uses calibration-based difference detection - compares current frame to
  4. a reference image of the empty plate.
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import os
  9. from pathlib import Path
  10. logger = logging.getLogger(__name__)
  11. # Optional OpenCV import - feature disabled if not available
  12. try:
  13. import cv2
  14. import numpy as np
  15. OPENCV_AVAILABLE = True
  16. except ImportError:
  17. OPENCV_AVAILABLE = False
  18. logger.info("OpenCV not available - plate detection feature disabled")
  19. def _get_calibration_dir() -> Path:
  20. """Get the calibration directory from settings (ensures persistence in Docker)."""
  21. from backend.app.core.config import settings
  22. return settings.plate_calibration_dir
  23. class PlateDetectionResult:
  24. """Result of plate detection analysis."""
  25. def __init__(
  26. self,
  27. is_empty: bool,
  28. confidence: float,
  29. difference_percent: float,
  30. message: str,
  31. debug_image: bytes | None = None,
  32. needs_calibration: bool = False,
  33. ):
  34. self.is_empty = is_empty
  35. self.confidence = confidence # 0.0 to 1.0
  36. self.difference_percent = difference_percent # How different from reference
  37. self.message = message
  38. self.debug_image = debug_image # Optional annotated image for debugging
  39. self.needs_calibration = needs_calibration # True if no reference image exists
  40. def to_dict(self) -> dict:
  41. return {
  42. "is_empty": bool(self.is_empty),
  43. "confidence": float(round(self.confidence, 2)),
  44. "difference_percent": float(round(self.difference_percent, 2)),
  45. "message": self.message,
  46. "has_debug_image": self.debug_image is not None,
  47. "needs_calibration": bool(self.needs_calibration),
  48. }
  49. class PlateDetector:
  50. """Detects if the build plate is empty using calibration-based difference detection."""
  51. # Default region of interest (ROI) as percentage of image dimensions
  52. # These define where the build plate typically appears in the camera view
  53. # Format: (x_start%, y_start%, width%, height%)
  54. DEFAULT_ROI = (0.15, 0.35, 0.70, 0.55) # Center-lower portion of frame
  55. # Detection thresholds for difference detection
  56. # Using mean pixel difference (0-100% scale)
  57. # Small objects may only cause 1-2% mean difference
  58. DEFAULT_DIFFERENCE_THRESHOLD = 1.0
  59. DEFAULT_BLUR_SIZE = 21 # Gaussian blur kernel size (must be odd) - unused with edge detection
  60. def __init__(
  61. self,
  62. roi: tuple[float, float, float, float] | None = None,
  63. difference_threshold: float = DEFAULT_DIFFERENCE_THRESHOLD,
  64. blur_size: int = DEFAULT_BLUR_SIZE,
  65. ):
  66. """Initialize the plate detector.
  67. Args:
  68. roi: Region of interest as (x%, y%, w%, h%) - percentages of image size
  69. difference_threshold: Percentage of pixels that must differ to trigger "not empty"
  70. blur_size: Gaussian blur kernel size for noise reduction
  71. """
  72. if not OPENCV_AVAILABLE:
  73. raise RuntimeError("OpenCV is not installed. Install with: pip install opencv-python-headless")
  74. self.roi = roi or self.DEFAULT_ROI
  75. self.difference_threshold = difference_threshold
  76. self.blur_size = blur_size if blur_size % 2 == 1 else blur_size + 1 # Must be odd
  77. # Maximum number of reference images to store per printer
  78. MAX_REFERENCES = 5
  79. def _get_metadata_path(self, printer_id: int) -> Path:
  80. """Get the path to the metadata JSON file for a printer."""
  81. _get_calibration_dir().mkdir(parents=True, exist_ok=True)
  82. return _get_calibration_dir() / f"printer_{printer_id}_metadata.json"
  83. def _load_metadata(self, printer_id: int) -> dict:
  84. """Load metadata for a printer's references."""
  85. import json
  86. meta_path = self._get_metadata_path(printer_id)
  87. if meta_path.exists():
  88. try:
  89. with open(meta_path) as f:
  90. return json.load(f)
  91. except (json.JSONDecodeError, OSError, KeyError, ValueError):
  92. pass
  93. return {"references": {}}
  94. def _save_metadata(self, printer_id: int, metadata: dict) -> None:
  95. """Save metadata for a printer's references."""
  96. import json
  97. meta_path = self._get_metadata_path(printer_id)
  98. with open(meta_path, "w") as f:
  99. json.dump(metadata, f, indent=2)
  100. def _get_reference_paths(self, printer_id: int) -> list[Path]:
  101. """Get all existing reference image paths for a printer."""
  102. _get_calibration_dir().mkdir(parents=True, exist_ok=True)
  103. paths = []
  104. for i in range(self.MAX_REFERENCES):
  105. path = _get_calibration_dir() / f"printer_{printer_id}_ref_{i}.jpg"
  106. if path.exists():
  107. paths.append(path)
  108. return paths
  109. def _rotate_references(self, printer_id: int) -> None:
  110. """Rotate references: delete oldest (0), shift others down."""
  111. # Delete slot 0
  112. slot0 = _get_calibration_dir() / f"printer_{printer_id}_ref_0.jpg"
  113. if slot0.exists():
  114. logger.info("Rotating references: removing oldest %s", slot0)
  115. slot0.unlink()
  116. # Shift others down
  117. for i in range(1, self.MAX_REFERENCES):
  118. old_path = _get_calibration_dir() / f"printer_{printer_id}_ref_{i}.jpg"
  119. new_path = _get_calibration_dir() / f"printer_{printer_id}_ref_{i - 1}.jpg"
  120. if old_path.exists():
  121. old_path.rename(new_path)
  122. # Also rotate metadata
  123. metadata = self._load_metadata(printer_id)
  124. refs = metadata.get("references", {})
  125. new_refs = {}
  126. for i in range(1, self.MAX_REFERENCES):
  127. if str(i) in refs:
  128. new_refs[str(i - 1)] = refs[str(i)]
  129. metadata["references"] = new_refs
  130. self._save_metadata(printer_id, metadata)
  131. def get_references(self, printer_id: int) -> list[dict]:
  132. """Get all references with metadata for a printer.
  133. Returns list of dicts with: index, label, timestamp, has_image
  134. """
  135. metadata = self._load_metadata(printer_id)
  136. refs = metadata.get("references", {})
  137. result = []
  138. for i in range(self.MAX_REFERENCES):
  139. path = _get_calibration_dir() / f"printer_{printer_id}_ref_{i}.jpg"
  140. if path.exists():
  141. ref_meta = refs.get(str(i), {})
  142. result.append(
  143. {
  144. "index": i,
  145. "label": ref_meta.get("label", ""),
  146. "timestamp": ref_meta.get("timestamp", ""),
  147. "has_image": True,
  148. }
  149. )
  150. return result
  151. def update_reference_label(self, printer_id: int, index: int, label: str) -> bool:
  152. """Update the label for a reference."""
  153. if index < 0 or index >= self.MAX_REFERENCES:
  154. return False
  155. path = _get_calibration_dir() / f"printer_{printer_id}_ref_{index}.jpg"
  156. if not path.exists():
  157. return False
  158. metadata = self._load_metadata(printer_id)
  159. if "references" not in metadata:
  160. metadata["references"] = {}
  161. if str(index) not in metadata["references"]:
  162. metadata["references"][str(index)] = {}
  163. metadata["references"][str(index)]["label"] = label
  164. self._save_metadata(printer_id, metadata)
  165. return True
  166. def delete_reference(self, printer_id: int, index: int) -> bool:
  167. """Delete a specific reference by index."""
  168. if index < 0 or index >= self.MAX_REFERENCES:
  169. return False
  170. path = _get_calibration_dir() / f"printer_{printer_id}_ref_{index}.jpg"
  171. if not path.exists():
  172. return False
  173. # Delete image
  174. logger.info("Deleting reference %s for printer %s: %s", index, printer_id, path)
  175. path.unlink()
  176. # Remove from metadata
  177. metadata = self._load_metadata(printer_id)
  178. refs = metadata.get("references", {})
  179. if str(index) in refs:
  180. del refs[str(index)]
  181. metadata["references"] = refs
  182. self._save_metadata(printer_id, metadata)
  183. # Shift remaining references down to fill the gap
  184. for i in range(index + 1, self.MAX_REFERENCES):
  185. old_img = _get_calibration_dir() / f"printer_{printer_id}_ref_{i}.jpg"
  186. new_img = _get_calibration_dir() / f"printer_{printer_id}_ref_{i - 1}.jpg"
  187. if old_img.exists():
  188. old_img.rename(new_img)
  189. # Also shift metadata
  190. if str(i) in refs:
  191. refs[str(i - 1)] = refs[str(i)]
  192. del refs[str(i)]
  193. metadata["references"] = refs
  194. self._save_metadata(printer_id, metadata)
  195. return True
  196. def get_reference_thumbnail(self, printer_id: int, index: int, max_size: int = 150) -> bytes | None:
  197. """Get a thumbnail of a reference image.
  198. Returns JPEG bytes or None if not found.
  199. """
  200. path = _get_calibration_dir() / f"printer_{printer_id}_ref_{index}.jpg"
  201. if not path.exists():
  202. return None
  203. try:
  204. img = cv2.imread(str(path))
  205. if img is None:
  206. return None
  207. # Calculate thumbnail size maintaining aspect ratio
  208. h, w = img.shape[:2]
  209. if w > h:
  210. new_w = max_size
  211. new_h = int(h * max_size / w)
  212. else:
  213. new_h = max_size
  214. new_w = int(w * max_size / h)
  215. thumb = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
  216. _, buffer = cv2.imencode(".jpg", thumb, [cv2.IMWRITE_JPEG_QUALITY, 80])
  217. return buffer.tobytes()
  218. except Exception as e:
  219. logger.error("Error creating thumbnail: %s", e)
  220. return None
  221. def _extract_roi(self, frame: np.ndarray) -> tuple[np.ndarray, int, int, int, int]:
  222. """Extract the region of interest from a frame.
  223. Returns:
  224. Tuple of (roi_frame, x_start, y_start, roi_width, roi_height)
  225. """
  226. height, width = frame.shape[:2]
  227. x_start = int(width * self.roi[0])
  228. y_start = int(height * self.roi[1])
  229. roi_width = int(width * self.roi[2])
  230. roi_height = int(height * self.roi[3])
  231. roi_frame = frame[y_start : y_start + roi_height, x_start : x_start + roi_width]
  232. return roi_frame, x_start, y_start, roi_width, roi_height
  233. def _preprocess_for_comparison(self, frame: np.ndarray) -> np.ndarray:
  234. """Preprocess a frame for comparison.
  235. Uses heavy blur to create "blob" representation - smooths out texture
  236. and noise while preserving large objects. Then normalizes brightness
  237. to reduce lighting sensitivity.
  238. """
  239. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  240. # Very heavy blur to smooth texture, keep only large shapes
  241. blurred = cv2.GaussianBlur(gray, (51, 51), 0)
  242. # Normalize to 0-255 range to reduce brightness sensitivity
  243. normalized = cv2.normalize(blurred, None, 0, 255, cv2.NORM_MINMAX)
  244. return normalized
  245. def calibrate(self, image_data: bytes, printer_id: int, label: str | None = None) -> tuple[bool, str, int]:
  246. """Calibrate by saving a reference image of the empty plate.
  247. Stores up to MAX_REFERENCES (5) images per printer. When all slots are full,
  248. the oldest reference is removed and others are shifted.
  249. Args:
  250. image_data: JPEG image data as bytes
  251. printer_id: Printer database ID
  252. label: Optional label for this reference (e.g., "High Temp Plate")
  253. Returns:
  254. Tuple of (success, message, index) where index is the slot used
  255. """
  256. from datetime import datetime
  257. try:
  258. # Decode image
  259. nparr = np.frombuffer(image_data, np.uint8)
  260. frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
  261. if frame is None:
  262. return False, "Failed to decode image", -1
  263. # Get existing references count
  264. existing_refs = self._get_reference_paths(printer_id)
  265. num_existing = len(existing_refs)
  266. # If all slots are full, rotate (remove oldest)
  267. if num_existing >= self.MAX_REFERENCES:
  268. self._rotate_references(printer_id)
  269. num_existing = self.MAX_REFERENCES - 1
  270. # Save to next available slot
  271. slot_index = num_existing
  272. reference_path = _get_calibration_dir() / f"printer_{printer_id}_ref_{slot_index}.jpg"
  273. write_success = cv2.imwrite(str(reference_path), frame, [cv2.IMWRITE_JPEG_QUALITY, 95])
  274. if not write_success:
  275. logger.error("cv2.imwrite failed for %s", reference_path)
  276. return False, "Failed to save reference image", -1
  277. # Verify the file actually exists and has content
  278. if not reference_path.exists():
  279. logger.error("Reference image not found after save: %s", reference_path)
  280. return False, "Reference image not found after save", -1
  281. file_size = reference_path.stat().st_size
  282. if file_size < 1000: # JPEG should be at least 1KB
  283. logger.error("Reference image too small (%s bytes): %s", file_size, reference_path)
  284. reference_path.unlink() # Clean up invalid file
  285. return False, f"Reference image corrupted (only {file_size} bytes)", -1
  286. logger.info("Saved reference image: %s (%s bytes)", reference_path, file_size)
  287. # Save metadata
  288. metadata = self._load_metadata(printer_id)
  289. if "references" not in metadata:
  290. metadata["references"] = {}
  291. metadata["references"][str(slot_index)] = {
  292. "label": label or "",
  293. "timestamp": datetime.now().isoformat(),
  294. }
  295. self._save_metadata(printer_id, metadata)
  296. logger.info(
  297. f"Saved plate calibration reference {slot_index + 1}/{self.MAX_REFERENCES} for printer {printer_id}"
  298. )
  299. return True, f"Calibration saved ({slot_index + 1}/{self.MAX_REFERENCES} references)", slot_index
  300. except Exception as e:
  301. logger.exception("Error during plate calibration")
  302. # Don't expose exception details to user - log has full info
  303. error_type = type(e).__name__
  304. return False, f"Calibration error: {error_type}", -1
  305. def get_calibration_count(self, printer_id: int) -> int:
  306. """Get the number of calibration references for a printer."""
  307. return len(self._get_reference_paths(printer_id))
  308. def has_calibration(self, printer_id: int, plate_type: str | None = None) -> bool:
  309. """Check if a printer has any calibration reference images."""
  310. return len(self._get_reference_paths(printer_id)) > 0
  311. def delete_calibration(self, printer_id: int, plate_type: str | None = None) -> bool:
  312. """Delete all calibration reference images for a printer."""
  313. paths = self._get_reference_paths(printer_id)
  314. if not paths:
  315. return False
  316. for path in paths:
  317. path.unlink()
  318. logger.info("Deleted %s plate calibration reference(s) for printer %s", len(paths), printer_id)
  319. return True
  320. def analyze_frame(
  321. self, image_data: bytes, printer_id: int, plate_type: str | None = None, include_debug_image: bool = False
  322. ) -> PlateDetectionResult:
  323. """Analyze a camera frame to detect if the plate is empty.
  324. Compares the current frame to all calibration reference images and uses
  325. the best match (lowest difference) for the final result.
  326. Args:
  327. image_data: JPEG image data as bytes
  328. printer_id: Printer database ID (for reference lookup)
  329. plate_type: Unused - kept for API compatibility
  330. include_debug_image: If True, include annotated image in result
  331. Returns:
  332. PlateDetectionResult with analysis results
  333. """
  334. try:
  335. # Check for calibration
  336. reference_paths = self._get_reference_paths(printer_id)
  337. if not reference_paths:
  338. return PlateDetectionResult(
  339. is_empty=True, # Default to empty when not calibrated
  340. confidence=0.0,
  341. difference_percent=0.0,
  342. message="No calibration - please calibrate with empty plate first",
  343. needs_calibration=True,
  344. )
  345. # Decode current image
  346. nparr = np.frombuffer(image_data, np.uint8)
  347. current_frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
  348. if current_frame is None:
  349. return PlateDetectionResult(
  350. is_empty=True,
  351. confidence=0.0,
  352. difference_percent=0.0,
  353. message="Failed to decode current image",
  354. )
  355. # Extract ROI from current frame
  356. current_roi, x_start, y_start, roi_width, roi_height = self._extract_roi(current_frame)
  357. current_processed = self._preprocess_for_comparison(current_roi)
  358. # Compare against all references, find best match (lowest difference)
  359. best_difference_percent = float("inf")
  360. best_ref_idx = -1
  361. best_diff = None
  362. for idx, ref_path in enumerate(reference_paths):
  363. # Load reference image
  364. reference_frame = cv2.imread(str(ref_path), cv2.IMREAD_COLOR)
  365. if reference_frame is None:
  366. continue
  367. # Ensure same dimensions
  368. if current_frame.shape != reference_frame.shape:
  369. reference_frame = cv2.resize(reference_frame, (current_frame.shape[1], current_frame.shape[0]))
  370. # Extract ROI and preprocess
  371. reference_roi, _, _, _, _ = self._extract_roi(reference_frame)
  372. reference_processed = self._preprocess_for_comparison(reference_roi)
  373. # Calculate absolute difference
  374. diff = cv2.absdiff(current_processed, reference_processed)
  375. # Calculate mean difference as percentage
  376. mean_diff = np.mean(diff)
  377. difference_percent = (mean_diff / 255.0) * 100
  378. if difference_percent < best_difference_percent:
  379. best_difference_percent = difference_percent
  380. best_ref_idx = idx
  381. best_diff = diff
  382. if best_ref_idx == -1:
  383. return PlateDetectionResult(
  384. is_empty=True,
  385. confidence=0.0,
  386. difference_percent=0.0,
  387. message="Failed to load any reference images - please recalibrate",
  388. needs_calibration=True,
  389. )
  390. difference_percent = best_difference_percent
  391. # Determine if plate is empty (use best match)
  392. is_empty = difference_percent < self.difference_threshold
  393. # Calculate confidence
  394. if is_empty:
  395. # Higher confidence when very little difference
  396. confidence = 1.0 - min(1.0, difference_percent / self.difference_threshold)
  397. else:
  398. # Higher confidence when clearly different
  399. confidence = min(1.0, difference_percent / (self.difference_threshold * 2))
  400. # Generate message
  401. num_refs = len(reference_paths)
  402. if is_empty:
  403. message = (
  404. f"Plate appears empty (difference: {difference_percent:.1f}%, ref {best_ref_idx + 1}/{num_refs})"
  405. )
  406. else:
  407. message = f"Objects detected on plate (difference: {difference_percent:.1f}%, best ref {best_ref_idx + 1}/{num_refs})"
  408. # Generate debug image if requested
  409. debug_image = None
  410. if include_debug_image and best_diff is not None:
  411. debug_frame = current_frame.copy()
  412. # Draw ROI rectangle
  413. cv2.rectangle(
  414. debug_frame,
  415. (x_start, y_start),
  416. (x_start + roi_width, y_start + roi_height),
  417. (0, 255, 0),
  418. 2,
  419. )
  420. # Create colored difference overlay
  421. # Red = areas that are different from reference
  422. # Amplify diff for visibility (multiply by 3, cap at 255)
  423. diff_amplified = np.minimum(best_diff * 3, 255).astype(np.uint8)
  424. diff_colored = cv2.cvtColor(diff_amplified, cv2.COLOR_GRAY2BGR)
  425. diff_colored[:, :, 0] = 0 # Remove blue
  426. diff_colored[:, :, 1] = 0 # Remove green
  427. # Red channel has the diff
  428. # Overlay difference on ROI
  429. roi_overlay = debug_frame[y_start : y_start + roi_height, x_start : x_start + roi_width]
  430. cv2.addWeighted(diff_colored, 0.5, roi_overlay, 0.5, 0, roi_overlay)
  431. # Add status text
  432. status_text = "EMPTY" if is_empty else "OBJECTS DETECTED"
  433. color = (0, 255, 0) if is_empty else (0, 0, 255)
  434. cv2.putText(debug_frame, status_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
  435. cv2.putText(
  436. debug_frame,
  437. f"Diff: {difference_percent:.1f}% (ref {best_ref_idx + 1}/{num_refs})",
  438. (10, 60),
  439. cv2.FONT_HERSHEY_SIMPLEX,
  440. 0.7,
  441. color,
  442. 2,
  443. )
  444. cv2.putText(
  445. debug_frame,
  446. f"Confidence: {confidence:.0%}",
  447. (10, 90),
  448. cv2.FONT_HERSHEY_SIMPLEX,
  449. 0.7,
  450. color,
  451. 2,
  452. )
  453. # Encode debug image as JPEG
  454. _, buffer = cv2.imencode(".jpg", debug_frame, [cv2.IMWRITE_JPEG_QUALITY, 85])
  455. debug_image = buffer.tobytes()
  456. return PlateDetectionResult(
  457. is_empty=is_empty,
  458. confidence=confidence,
  459. difference_percent=difference_percent,
  460. message=message,
  461. debug_image=debug_image,
  462. )
  463. except Exception as e:
  464. logger.exception("Error analyzing frame for plate detection")
  465. return PlateDetectionResult(
  466. is_empty=True, # Default to empty on error (don't block prints)
  467. confidence=0.0,
  468. difference_percent=0.0,
  469. message=f"Analysis error: {e!s}",
  470. )
  471. async def capture_camera_image(
  472. printer_id: int,
  473. ip_address: str,
  474. access_code: str,
  475. model: str,
  476. external_camera_url: str | None = None,
  477. external_camera_type: str | None = None,
  478. use_external: bool = False,
  479. external_camera_snapshot_url: str | None = None,
  480. ) -> tuple[bytes | None, str]:
  481. """Capture an image from the printer camera.
  482. If there's an active camera stream, uses the buffered frame instead of
  483. creating a new connection (which would fail while stream is active).
  484. Returns:
  485. Tuple of (image_data, camera_source) or (None, error_message)
  486. """
  487. image_data: bytes | None = None
  488. camera_source = "unknown"
  489. # Try external camera first if requested and available
  490. if use_external and external_camera_url and external_camera_type:
  491. try:
  492. from backend.app.api.routes.camera import live_frame_for_capture
  493. from backend.app.services.external_camera import capture_frame
  494. # What this function's docstring already promised, but only the
  495. # built-in fallback below delivered: an external camera is
  496. # single-reader too, so capturing while a viewer watches fails
  497. # (#2707).
  498. defer, buffered = live_frame_for_capture(printer_id)
  499. if defer:
  500. if buffered:
  501. image_data = buffered
  502. camera_source = "external (buffered)"
  503. logger.debug("Using buffered external frame for printer %s", printer_id)
  504. else:
  505. image_data = await capture_frame(
  506. external_camera_url,
  507. external_camera_type,
  508. snapshot_url=external_camera_snapshot_url,
  509. )
  510. if image_data:
  511. camera_source = "external"
  512. logger.debug("Captured frame from external camera for printer %s", printer_id)
  513. except Exception as e:
  514. logger.warning("Failed to capture from external camera: %s", e)
  515. # Fall back to built-in camera
  516. if image_data is None:
  517. # First, check if there's an active stream with a buffered frame
  518. # This avoids blocking when camera viewer is open
  519. try:
  520. from backend.app.api.routes.camera import get_buffered_frame
  521. buffered = get_buffered_frame(printer_id)
  522. if buffered:
  523. image_data = buffered
  524. camera_source = "built-in (buffered)"
  525. logger.debug("Using buffered frame from active stream for printer %s", printer_id)
  526. except Exception as e:
  527. logger.debug("Could not get buffered frame: %s", e)
  528. # If no buffered frame, try to capture a new one
  529. if image_data is None:
  530. import tempfile
  531. from backend.app.services.camera import capture_camera_frame
  532. fd, tmp_name = tempfile.mkstemp(suffix=".jpg")
  533. os.close(fd)
  534. tmp_path = Path(tmp_name)
  535. tmp_path.chmod(0o600)
  536. try:
  537. success = await capture_camera_frame(ip_address, access_code, model, tmp_path, timeout=10)
  538. if success:
  539. with open(tmp_path, "rb") as f:
  540. image_data = f.read()
  541. camera_source = "built-in"
  542. logger.debug("Captured frame from built-in camera for printer %s", printer_id)
  543. finally:
  544. try:
  545. tmp_path.unlink()
  546. except OSError:
  547. pass # Best-effort cleanup of temporary camera capture file
  548. return image_data, camera_source
  549. async def check_plate_empty(
  550. printer_id: int,
  551. ip_address: str,
  552. access_code: str,
  553. model: str,
  554. plate_type: str | None = None,
  555. include_debug_image: bool = False,
  556. external_camera_url: str | None = None,
  557. external_camera_type: str | None = None,
  558. use_external: bool = False,
  559. roi: tuple[float, float, float, float] | None = None,
  560. external_camera_snapshot_url: str | None = None,
  561. ) -> PlateDetectionResult:
  562. """Check if the build plate is empty for a printer.
  563. Args:
  564. printer_id: Printer database ID
  565. ip_address: Printer IP address
  566. access_code: Printer access code
  567. model: Printer model string
  568. plate_type: Type of build plate for calibration lookup
  569. include_debug_image: If True, include annotated image in result
  570. external_camera_url: URL of external camera (if configured)
  571. external_camera_type: Type of external camera (mjpeg, rtsp, snapshot)
  572. use_external: If True, prefer external camera over built-in
  573. roi: Region of interest as (x%, y%, w%, h%) - percentages of image size
  574. Returns:
  575. PlateDetectionResult with analysis results
  576. """
  577. if not OPENCV_AVAILABLE:
  578. return PlateDetectionResult(
  579. is_empty=True,
  580. confidence=0.0,
  581. difference_percent=0.0,
  582. message="OpenCV not available - plate detection disabled",
  583. )
  584. image_data, camera_source = await capture_camera_image(
  585. printer_id,
  586. ip_address,
  587. access_code,
  588. model,
  589. external_camera_url,
  590. external_camera_type,
  591. use_external,
  592. external_camera_snapshot_url=external_camera_snapshot_url,
  593. )
  594. if image_data is None:
  595. return PlateDetectionResult(
  596. is_empty=True, # Default to empty on error
  597. confidence=0.0,
  598. difference_percent=0.0,
  599. message="Failed to capture camera frame from any source",
  600. )
  601. # Analyze the captured frame
  602. detector = PlateDetector(roi=roi)
  603. result = detector.analyze_frame(image_data, printer_id, plate_type, include_debug_image)
  604. # Add camera source to message
  605. result.message = f"[{camera_source}] {result.message}"
  606. return result
  607. async def calibrate_plate(
  608. printer_id: int,
  609. ip_address: str,
  610. access_code: str,
  611. model: str,
  612. label: str | None = None,
  613. external_camera_url: str | None = None,
  614. external_camera_type: str | None = None,
  615. use_external: bool = False,
  616. external_camera_snapshot_url: str | None = None,
  617. ) -> tuple[bool, str, int]:
  618. """Calibrate plate detection by capturing a reference image of the empty plate.
  619. Args:
  620. printer_id: Printer database ID
  621. ip_address: Printer IP address
  622. access_code: Printer access code
  623. model: Printer model string
  624. label: Optional label for this reference (e.g., "High Temp Plate")
  625. external_camera_url: URL of external camera (if configured)
  626. external_camera_type: Type of external camera (mjpeg, rtsp, snapshot)
  627. use_external: If True, prefer external camera over built-in
  628. Returns:
  629. Tuple of (success, message, index)
  630. """
  631. if not OPENCV_AVAILABLE:
  632. return False, "OpenCV not available - plate detection disabled", -1
  633. image_data, camera_source = await capture_camera_image(
  634. printer_id,
  635. ip_address,
  636. access_code,
  637. model,
  638. external_camera_url,
  639. external_camera_type,
  640. use_external,
  641. external_camera_snapshot_url=external_camera_snapshot_url,
  642. )
  643. if image_data is None:
  644. return False, "Failed to capture camera frame for calibration", -1
  645. detector = PlateDetector()
  646. success, message, index = detector.calibrate(image_data, printer_id, label)
  647. if success:
  648. message = f"[{camera_source}] {message}"
  649. return success, message, index
  650. def get_calibration_status(printer_id: int, plate_type: str | None = None) -> dict:
  651. """Get calibration status for a printer.
  652. Returns:
  653. Dict with calibration info including reference count
  654. """
  655. if not OPENCV_AVAILABLE:
  656. return {
  657. "available": False,
  658. "calibrated": False,
  659. "reference_count": 0,
  660. "max_references": 5,
  661. "message": "OpenCV not available",
  662. }
  663. detector = PlateDetector()
  664. calibrated = detector.has_calibration(printer_id)
  665. ref_count = detector.get_calibration_count(printer_id)
  666. if calibrated:
  667. message = f"Calibrated with {ref_count}/{detector.MAX_REFERENCES} reference(s)"
  668. else:
  669. message = "Not calibrated - please calibrate with empty plate"
  670. return {
  671. "available": True,
  672. "calibrated": calibrated,
  673. "reference_count": ref_count,
  674. "max_references": detector.MAX_REFERENCES,
  675. "message": message,
  676. }
  677. def delete_calibration(printer_id: int, plate_type: str | None = None) -> bool:
  678. """Delete calibration for a printer and plate type."""
  679. if not OPENCV_AVAILABLE:
  680. return False
  681. detector = PlateDetector()
  682. return detector.delete_calibration(printer_id, plate_type)
  683. def is_plate_detection_available() -> bool:
  684. """Check if plate detection feature is available (OpenCV installed)."""
  685. return OPENCV_AVAILABLE