plate_detection.py 32 KB

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