Add steel surface gate before defect segmentation
Browse filesFiles changed (9)
8 unmodified lines910118 unmodified linesHF_CHAT_MODEL=meta-llama/Llama-3.1-8B-Instruct:cerebrasHF_ROUTER_BASE_URL=https://router.huggingface.co/v1MAX_UPLOAD_SIZE_MB=88 unmodified lines910111213141516171819202122238 unmodified linesHF_CHAT_MODEL=meta-llama/Llama-3.1-8B-Instruct:cerebrasHF_ROUTER_BASE_URL=https://router.huggingface.co/v1MAX_UPLOAD_SIZE_MB=8SURFACE_GATE_ENABLED=trueSURFACE_CLASSIFIER_PATH=SURFACE_CLASSIFIER_STEEL_LABEL=steelSURFACE_MIN_STEEL_CONFIDENCE=0.55SURFACE_GRAY_DELTA=16SURFACE_MIN_GRAY_RATIO=0.72SURFACE_LOW_SAT_PIXEL_THRESHOLD=45SURFACE_MIN_LOW_SAT_RATIO=0.78SURFACE_MAX_MEAN_SATURATION=40SURFACE_MAX_COLORFULNESS=24SURFACE_MAX_SKIN_RATIO=0.16SURFACE_MIN_TEXTURE_VARIANCE=80
14 unmodified lines15161718192059 unmodified lines80818283848514 unmodified linesreturn str(path if path.is_absolute() else (BASE_DIR / path).resolve())def _parse_origins() -> tuple[str, ...]:raw_origins = os.getenv("CORS_ORIGINS",59 unmodified linesIMAGE_SIZE: int = field(default_factory=lambda: int(os.getenv("IMAGE_SIZE", "896")))MIN_DEFECT_AREA: int = field(default_factory=lambda: int(os.getenv("MIN_DEFECT_AREA", "120")))MAX_AREA_RATIO: float = field(default_factory=lambda: float(os.getenv("MAX_AREA_RATIO", "0.12")))# -----------------------------# API / UI14 unmodified lines151617181920212223242526272829303132333435363738394059 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414 unmodified linesreturn str(path if path.is_absolute() else (BASE_DIR / path).resolve())def _resolve_optional_path(env_name: str,default_relative_path: str | None = None,) -> str | None:raw_value = os.getenv(env_name)if raw_value:path = Path(raw_value)return str(path if path.is_absolute() else (BASE_DIR / path).resolve())if not default_relative_path:return Nonedefault_path = (BASE_DIR / default_relative_path).resolve()if default_path.exists():return str(default_path)return Nonedef _parse_origins() -> tuple[str, ...]:raw_origins = os.getenv("CORS_ORIGINS",59 unmodified linesIMAGE_SIZE: int = field(default_factory=lambda: int(os.getenv("IMAGE_SIZE", "896")))MIN_DEFECT_AREA: int = field(default_factory=lambda: int(os.getenv("MIN_DEFECT_AREA", "120")))MAX_AREA_RATIO: float = field(default_factory=lambda: float(os.getenv("MAX_AREA_RATIO", "0.12")))SURFACE_GATE_ENABLED: bool = field(default_factory=lambda: _parse_bool("SURFACE_GATE_ENABLED", True))SURFACE_CLASSIFIER_PATH: str | None = field(default_factory=lambda: _resolve_optional_path("SURFACE_CLASSIFIER_PATH","models/steel_surface_classifier.pt",))SURFACE_CLASSIFIER_STEEL_LABEL: str = field(default_factory=lambda: os.getenv("SURFACE_CLASSIFIER_STEEL_LABEL", "steel"))SURFACE_MIN_STEEL_CONFIDENCE: float = field(default_factory=lambda: float(os.getenv("SURFACE_MIN_STEEL_CONFIDENCE", "0.55")))SURFACE_GRAY_DELTA: int = field(default_factory=lambda: int(os.getenv("SURFACE_GRAY_DELTA", "16")))SURFACE_MIN_GRAY_RATIO: float = field(default_factory=lambda: float(os.getenv("SURFACE_MIN_GRAY_RATIO", "0.72")))SURFACE_LOW_SAT_PIXEL_THRESHOLD: int = field(default_factory=lambda: int(os.getenv("SURFACE_LOW_SAT_PIXEL_THRESHOLD", "45")))SURFACE_MIN_LOW_SAT_RATIO: float = field(default_factory=lambda: float(os.getenv("SURFACE_MIN_LOW_SAT_RATIO", "0.78")))SURFACE_MAX_MEAN_SATURATION: float = field(default_factory=lambda: float(os.getenv("SURFACE_MAX_MEAN_SATURATION", "40")))SURFACE_MAX_COLORFULNESS: float = field(default_factory=lambda: float(os.getenv("SURFACE_MAX_COLORFULNESS", "24")))SURFACE_MAX_SKIN_RATIO: float = field(default_factory=lambda: float(os.getenv("SURFACE_MAX_SKIN_RATIO", "0.16")))SURFACE_MIN_TEXTURE_VARIANCE: float = field(default_factory=lambda: float(os.getenv("SURFACE_MIN_TEXTURE_VARIANCE", "80")))# -----------------------------# API / UI
11 unmodified lines121314151611 unmodified linesDECISION_COLOR = {"PASS": (0, 255, 0),"REVIEW": (0, 165, 255),"FAIL": (0, 0, 255)}11 unmodified lines12131415161711 unmodified linesDECISION_COLOR = {"PASS": (0, 255, 0),"REVIEW": (0, 165, 255),"FAIL": (0, 0, 255),"SKIPPED": (255, 191, 0),}
8 unmodified lines910111213141561 unmodified lines7778798081828384858 unmodified lines},{title: "AI Detection Engine",detail: "Run the steel defect model to identify surface anomalies, geometry, and severity.",},{title: "Inspection Formatter",61 unmodified linestitle: "Capture",detail: "Acquire a shop-floor image from upload, live camera, or the simulation loop.",},{title: "Infer",detail: "Run segmentation and extract contours, bounding boxes, severity, and geometry.",},{title: "Decide",8 unmodified lines910111213141561 unmodified lines777879808182838485868788898 unmodified lines},{title: "AI Detection Engine",detail: "Validate that the frame is really a steel surface, then run the defect model to identify anomalies, geometry, and severity.",},{title: "Inspection Formatter",61 unmodified linestitle: "Capture",detail: "Acquire a shop-floor image from upload, live camera, or the simulation loop.",},{title: "Validate Surface",detail: "Reject non-steel frames before segmentation so faces, tools, and background objects do not enter the defect pipeline.",},{title: "Infer",detail: "Run segmentation only on steel frames and extract contours, bounding boxes, severity, and geometry.",},{title: "Decide",
1 unmodified line2345671 unmodified lineif (decision === "FAIL") return "danger"if (decision === "REVIEW") return "warning"if (decision === "PASS") return "success"return "neutral"}1 unmodified line23456781 unmodified lineif (decision === "FAIL") return "danger"if (decision === "REVIEW") return "warning"if (decision === "PASS") return "success"if (decision === "SKIPPED") return "info"return "neutral"}
184 unmodified lines185186187188189190191192193194195108 unmodified lines304305306307308309310109 unmodified lines42042142242342442544 unmodified lines47047147247347447547647711 unmodified lines489490491492493494495184 unmodified linessetInspectionResult(result)setLastInspectedAt(result.timestamp)setCameraStatus(result.total_defects > 0? `Detected ${result.total_defects} defect${result.total_defects > 1 ? "s" : ""} in the latest frame`: "No actionable defects detected in the latest frame")if (alertsEnabled && result.decision === "FAIL" && lastAlertDecision.current !== "FAIL") {playAlertTone()108 unmodified lines<input type="file" accept="image/*" className="hidden" onChange={handleImageSelection} /><p className="text-lg font-medium text-slate-100">Drop or choose a steel surface image</p><p className="mt-3 max-w-xl text-sm leading-7 text-slate-400">Use this mode to inspect saved surface samples, log a full report, and broadcast the result to the dashboard and history views.</p></label>109 unmodified lines{lastInspectedAt ? `Last inspection: ${formatDateTime(lastInspectedAt)}` : "Waiting for the first live inspection result."}</p></div><div className="rounded-3xl border border-amber-300/20 bg-amber-400/10 px-4 py-4 text-sm leading-7 text-amber-50">Keep deep analysis off during continuous monitoring for the fastest real-time response. Turn it on only when you want a slower GenAI explanation for a specific frame.</div>44 unmodified lines<div className="rounded-[28px] border border-cyan-300/20 bg-cyan-400/10 p-5"><div className="flex flex-wrap items-center gap-3"><StatusBadgelabel={inspectionResult.agent_mode === "llm" ? "Ollama AI" : "Fallback AI"}tone={inspectionResult.agent_mode === "llm" ? "info" : "warning"}/><div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200">{inspectionResult.agent_provider} {inspectionResult.agent_model && inspectionResult.agent_model !== "fallback" ? `· ${inspectionResult.agent_model}` : ""}11 unmodified lines</div><div className="space-y-3">{(inspectionResult.defects || []).length ? ((inspectionResult.defects || []).map((defect, index) => (<div key={`${defect.type}-${index}`} className="rounded-3xl border border-white/10 bg-white/5 px-4 py-4"><div className="flex flex-wrap items-center justify-between gap-3">184 unmodified lines185186187188189190191192193194195196197198199108 unmodified lines308309310311312313314109 unmodified lines42442542642742842943043143244 unmodified lines47747847948048148248348448548648748848949049149249349449549611 unmodified lines508509510511512513514515516517518184 unmodified linessetInspectionResult(result)setLastInspectedAt(result.timestamp)if (result.inspection_state === "non_steel_surface") {setCameraStatus("Non-steel frame skipped. Point the camera directly at the steel surface to continue.")} else {setCameraStatus(result.total_defects > 0? `Detected ${result.total_defects} defect${result.total_defects > 1 ? "s" : ""} in the latest frame`: "No actionable defects detected in the latest frame")}if (alertsEnabled && result.decision === "FAIL" && lastAlertDecision.current !== "FAIL") {playAlertTone()108 unmodified lines<input type="file" accept="image/*" className="hidden" onChange={handleImageSelection} /><p className="text-lg font-medium text-slate-100">Drop or choose a steel surface image</p><p className="mt-3 max-w-xl text-sm leading-7 text-slate-400">Use this mode to inspect saved surface samples, log a full report, and broadcast the result to the dashboard and history views. Non-steel uploads are now filtered before defect segmentation starts.</p></label>109 unmodified lines{lastInspectedAt ? `Last inspection: ${formatDateTime(lastInspectedAt)}` : "Waiting for the first live inspection result."}</p></div><div className="rounded-3xl border border-white/10 bg-white/5 px-4 py-4 text-sm leading-7 text-slate-300">Every live frame first passes through a steel-surface gate. If the scene contains faces, hands, machinery, or general background objects, the frame is skipped before YOLO defect segmentation runs.</div><div className="rounded-3xl border border-amber-300/20 bg-amber-400/10 px-4 py-4 text-sm leading-7 text-amber-50">Keep deep analysis off during continuous monitoring for the fastest real-time response. Turn it on only when you want a slower GenAI explanation for a specific frame.</div>44 unmodified lines<div className="rounded-[28px] border border-cyan-300/20 bg-cyan-400/10 p-5"><div className="flex flex-wrap items-center gap-3"><StatusBadgelabel={inspectionResult.agent_mode === "llm"? "GenAI Analysis": inspectionResult.agent_mode === "surface_gate"? "Surface Gate": "Fallback AI"}tone={inspectionResult.agent_mode === "llm"? "info": inspectionResult.agent_mode === "surface_gate"? "info": "warning"}/><div className="rounded-full border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200">{inspectionResult.agent_provider} {inspectionResult.agent_model && inspectionResult.agent_model !== "fallback" ? `· ${inspectionResult.agent_model}` : ""}11 unmodified lines</div><div className="space-y-3">{inspectionResult.inspection_state === "non_steel_surface" ? (<div className="rounded-3xl border border-cyan-300/20 bg-cyan-400/10 px-4 py-4 text-sm leading-7 text-cyan-50">The latest image was skipped before defect detection because the system could not confidently confirm a steel inspection surface. Reframe the camera closer to the metal and remove background objects from view.</div>) : (inspectionResult.defects || []).length ? ((inspectionResult.defects || []).map((defect, index) => (<div key={`${defect.type}-${index}`} className="rounded-3xl border border-white/10 bg-white/5 px-4 py-4"><div className="flex flex-wrap items-center justify-between gap-3">
1234511 unmodified lines1718192021223 unmodified lines2627282930315 unmodified lines37383940414263 unmodified lines10610710810911011130 unmodified lines1421431441451461471487 unmodified lines1561571581591601612 unmodified lines16416516616716816917017117217317417517617721 unmodified lines199200201202203204import base64import binasciifrom typing import Anyimport cv211 unmodified linespersist_inspection,)from inspection.severity import classify_defectSEVERITY_COLOR = {3 unmodified lines}_INSPECTOR: DefectInspector | None = Nonedef get_inspector() -> DefectInspector:5 unmodified linesreturn _INSPECTORdef decode_base64_image(data_url: str) -> np.ndarray:encoded = data_url.split(",", 1)[1] if "," in data_url else data_url63 unmodified linesimage: np.ndarray,defects: list[dict[str, Any]],decision: str,) -> np.ndarray:annotated = image.copy()30 unmodified lines2,)if not defects:cv2.putText(annotated,"No actionable defects detected in current frame",7 unmodified linesreturn annotateddef inspect_image_array(image: np.ndarray,*,2 unmodified linespersist: bool = True,llm_mode: str = "auto",) -> dict[str, Any]:inspector = get_inspector()detections = inspector.inspect_image(image)public_defects, drawable_defects = _build_serializable_defects(detections, image.shape)resolved_metadata = {**(metadata or {}),"persist": persist,"llm_mode": llm_mode,}output = format_inspection_output(public_defects,21 unmodified lines"minor": output["summary"]["Minor"],"moderate": output["summary"]["Moderate"],"critical": output["summary"]["Critical"],"inspection_state": ("defects_detected" if output["total_defects"] > 0 else "clear_frame"),12345611 unmodified lines181920212223243 unmodified lines282930313233345 unmodified lines40414243444546474849505152535455565763 unmodified lines12112212312412512612730 unmodified lines1581591601611621631641651661671681691701711721731741757 unmodified lines1831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322 unmodified lines23523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426521 unmodified lines287288289290291292293import base64import binasciiimport textwrapfrom typing import Anyimport cv211 unmodified linespersist_inspection,)from inspection.severity import classify_defectfrom inspection.surface_gate import SteelSurfaceGate, SurfaceGateResultSEVERITY_COLOR = {3 unmodified lines}_INSPECTOR: DefectInspector | None = None_SURFACE_GATE: SteelSurfaceGate | None = Nonedef get_inspector() -> DefectInspector:5 unmodified linesreturn _INSPECTORdef get_surface_gate() -> SteelSurfaceGate | None:global _SURFACE_GATEif not settings.SURFACE_GATE_ENABLED:return Noneif _SURFACE_GATE is None:_SURFACE_GATE = SteelSurfaceGate()return _SURFACE_GATEdef decode_base64_image(data_url: str) -> np.ndarray:encoded = data_url.split(",", 1)[1] if "," in data_url else data_url63 unmodified linesimage: np.ndarray,defects: list[dict[str, Any]],decision: str,note: str | None = None,) -> np.ndarray:annotated = image.copy()30 unmodified lines2,)if note:for index, line in enumerate(textwrap.wrap(note, width=48)[:3]):cv2.putText(annotated,line,(34, 132 + (index * 28)),cv2.FONT_HERSHEY_SIMPLEX,0.56,(225, 232, 240),2,)elif not defects:cv2.putText(annotated,"No actionable defects detected in current frame",7 unmodified linesreturn annotateddef build_surface_gate_result(image: np.ndarray,*,source: str,metadata: dict[str, Any],surface_result: SurfaceGateResult,) -> dict[str, Any]:output = format_inspection_output([],source=source,metadata={**metadata,"surface_gate": surface_result.to_metadata(),},decision="SKIPPED",recommendation=("Frame skipped because the system could not confirm a steel inspection surface. ""Point the camera only at the sheet, coil, or sample before retrying."),)output["summary_text"] = surface_result.reasonoutput["agent_mode"] = "surface_gate"output["agent_provider"] = "Steel Surface Gate"output["agent_model"] = surface_result.modeannotated_image = annotate_image(image,[],output["decision"],note=surface_result.reason,)return {**output,"minor": 0,"moderate": 0,"critical": 0,"inspection_state": "non_steel_surface","surface_gate": surface_result.to_metadata(),"annotated_image": encode_image_to_data_url(annotated_image),}def inspect_image_array(image: np.ndarray,*,2 unmodified linespersist: bool = True,llm_mode: str = "auto",) -> dict[str, Any]:resolved_metadata = {**(metadata or {}),"persist": persist,"persist_requested": persist,"persist_applied": persist,"llm_mode": llm_mode,}surface_gate = get_surface_gate()if surface_gate is not None:surface_result = surface_gate.evaluate(image)resolved_metadata["surface_gate"] = surface_result.to_metadata()if not surface_result.is_steel:resolved_metadata["persist_applied"] = Falsereturn build_surface_gate_result(image,source=source,metadata=resolved_metadata,surface_result=surface_result,)inspector = get_inspector()detections = inspector.inspect_image(image)public_defects, drawable_defects = _build_serializable_defects(detections, image.shape)output = format_inspection_output(public_defects,21 unmodified lines"minor": output["summary"]["Minor"],"moderate": output["summary"]["Moderate"],"critical": output["summary"]["Critical"],"surface_gate": resolved_metadata.get("surface_gate"),"inspection_state": ("defects_detected" if output["total_defects"] > 0 else "clear_frame"),
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243from __future__ import annotations
from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any
import cv2import numpy as np
from core.config import settingsfrom core.logger import logger
try: from ultralytics import YOLOexcept Exception: # pragma: no cover - optional import guard YOLO = None
@dataclass(frozen=True)class SurfaceGateResult: is_steel: bool confidence: float mode: str label: str reason: str metrics: dict[str, float]
def to_metadata(self) -> dict[str, Any]: return { "passed": self.is_steel, "confidence": round(self.confidence, 3), "mode": self.mode, "label": self.label, "reason": self.reason, "metrics": self.metrics, }
class SteelSurfaceGate: def __init__(self, model_path: str | None = None): self.model_path = model_path or settings.SURFACE_CLASSIFIER_PATH self.model = None self.mode = "heuristic"
if not self.model_path: return
resolved_path = Path(self.model_path) if not resolved_path.exists(): logger.warning( "Surface classifier path does not exist, using heuristic gate: %s", resolved_path, ) return
if YOLO is None: logger.warning("Ultralytics is unavailable for the surface classifier, using heuristic gate") return
try: self.model = YOLO(str(resolved_path)) self.mode = "classifier" logger.info("Surface gate classifier loaded from: %s", resolved_path) except Exception as exc: # pragma: no cover - defensive runtime fallback logger.warning("Surface classifier failed to load, using heuristic gate: %s", exc)
def evaluate(self, image: np.ndarray) -> SurfaceGateResult: if self.model is not None: try: return self._evaluate_with_classifier(image) except Exception as exc: # pragma: no cover - runtime safeguard logger.warning("Surface classifier inference failed, using heuristic gate: %s", exc)
return self._evaluate_with_heuristic(image)
def _evaluate_with_classifier(self, image: np.ndarray) -> SurfaceGateResult: results = self.model(image, verbose=False) result = results[0] probs = getattr(result, "probs", None) names = getattr(result, "names", None) or getattr(self.model, "names", {})
if probs is None: raise RuntimeError("Classification model returned no probabilities")
top_index = int(getattr(probs, "top1", 0)) top_confidence_raw = getattr(probs, "top1conf") top_confidence = float( top_confidence_raw.item() if hasattr(top_confidence_raw, "item") else top_confidence_raw )
if isinstance(names, dict): label = str(names.get(top_index, top_index)) else: label = str(names[top_index])
steel_label = settings.SURFACE_CLASSIFIER_STEEL_LABEL.strip().lower() normalized_label = label.strip().lower() is_steel = ( normalized_label == steel_label or steel_label in normalized_label or normalized_label in steel_label ) meets_threshold = top_confidence >= settings.SURFACE_MIN_STEEL_CONFIDENCE
if is_steel and meets_threshold: reason = ( f"Steel surface classifier accepted the frame with {top_confidence:.0%} confidence." ) elif is_steel: reason = ( "Frame resembles steel, but the classifier confidence is too low for reliable defect analysis." ) else: reason = ( f'Classifier labeled the frame as "{label}" instead of steel, so the defect model was skipped.' )
return SurfaceGateResult( is_steel=bool(is_steel and meets_threshold), confidence=top_confidence, mode="classifier", label=label, reason=reason, metrics={}, )
def _evaluate_with_heuristic(self, image: np.ndarray) -> SurfaceGateResult: features = self._extract_features(image)
checks = { "gray_ratio": features["gray_ratio"] >= settings.SURFACE_MIN_GRAY_RATIO, "low_sat_ratio": features["low_saturation_ratio"] >= settings.SURFACE_MIN_LOW_SAT_RATIO, "mean_saturation": features["mean_saturation"] <= settings.SURFACE_MAX_MEAN_SATURATION, "colorfulness": features["colorfulness"] <= settings.SURFACE_MAX_COLORFULNESS, "skin_ratio": features["skin_ratio"] <= settings.SURFACE_MAX_SKIN_RATIO, "texture_variance": features["texture_variance"] >= settings.SURFACE_MIN_TEXTURE_VARIANCE, }
weights = { "gray_ratio": 0.24, "low_sat_ratio": 0.22, "mean_saturation": 0.16, "colorfulness": 0.16, "skin_ratio": 0.12, "texture_variance": 0.10, }
score = sum(weights[name] for name, passed in checks.items() if passed) chroma_gate = checks["gray_ratio"] and checks["low_sat_ratio"] is_steel = score >= 0.72 and chroma_gate and checks["skin_ratio"]
failed_checks = [name for name, passed in checks.items() if not passed] confidence = score if is_steel else min(0.99, max(0.55, 1.0 - score + 0.08 * len(failed_checks)))
if is_steel: reason = ( f"Frame passed the steel-surface gate with {confidence:.0%} confidence and proceeded to defect segmentation." ) else: reason = self._build_failure_reason(features, failed_checks)
return SurfaceGateResult( is_steel=is_steel, confidence=confidence, mode="heuristic", label="steel" if is_steel else "non_steel", reason=reason, metrics={key: round(value, 4) for key, value in features.items()}, )
def _extract_features(self, image: np.ndarray) -> dict[str, float]: height, width = image.shape[:2] target_width = min(320, max(96, width)) target_height = max(96, int(height * target_width / max(width, 1))) resized = cv2.resize(image, (target_width, target_height))
hsv = cv2.cvtColor(resized, cv2.COLOR_BGR2HSV) gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) ycrcb = cv2.cvtColor(resized, cv2.COLOR_BGR2YCrCb)
b_channel, g_channel, r_channel = [channel.astype(np.float32) for channel in cv2.split(resized)] saturation = hsv[:, :, 1].astype(np.float32)
gray_delta = settings.SURFACE_GRAY_DELTA gray_mask = ( (np.abs(r_channel - g_channel) <= gray_delta) & (np.abs(r_channel - b_channel) <= gray_delta) & (np.abs(g_channel - b_channel) <= gray_delta) )
rg = np.abs(r_channel - g_channel) yb = np.abs(0.5 * (r_channel + g_channel) - b_channel) colorfulness = ( np.sqrt(float(rg.std()) ** 2 + float(yb.std()) ** 2) + 0.3 * np.sqrt(float(rg.mean()) ** 2 + float(yb.mean()) ** 2) )
luminance, cr_channel, cb_channel = cv2.split(ycrcb) skin_mask = ( (cr_channel > 135) & (cr_channel < 180) & (cb_channel > 85) & (cb_channel < 135) & (luminance > 60) )
return { "gray_ratio": float(gray_mask.mean()), "low_saturation_ratio": float( (saturation <= settings.SURFACE_LOW_SAT_PIXEL_THRESHOLD).mean() ), "mean_saturation": float(saturation.mean()), "colorfulness": float(colorfulness), "skin_ratio": float(skin_mask.mean()), "texture_variance": float(cv2.Laplacian(gray, cv2.CV_32F).var()), }
def _build_failure_reason(self, features: dict[str, float], failed_checks: list[str]) -> str: if features["skin_ratio"] > settings.SURFACE_MAX_SKIN_RATIO: return ( "Frame skipped because prominent skin-tone regions were detected. Aim the camera only at the steel surface." ) if features["gray_ratio"] < settings.SURFACE_MIN_GRAY_RATIO: return ( "Frame skipped because it contains too much color variation to match the expected steel surface appearance." ) if features["low_saturation_ratio"] < settings.SURFACE_MIN_LOW_SAT_RATIO: return ( "Frame skipped because the image is too saturated. Move closer to the metal surface and reduce background content." ) if features["texture_variance"] < settings.SURFACE_MIN_TEXTURE_VARIANCE: return ( "Frame skipped because the visible area is too flat or out of focus for reliable steel-surface validation." ) if features["colorfulness"] > settings.SURFACE_MAX_COLORFULNESS: return ( "Frame skipped because the scene looks like a general object view instead of a steel inspection close-up." )
failed_text = ", ".join(failed_checks) if failed_checks else "multiple surface validation checks" return ( f"Frame skipped because it did not pass the steel-surface gate ({failed_text}). Reposition the camera toward the material and retry." )15 unmodified lines1617181920214 unmodified lines26272829303133 unmodified lines65666768697015 unmodified linespersist_inspection,)from inspection.class_map import CLASS_MAPfrom agent.langgraph_agent import run_agent4 unmodified linesdef main():inspector = DefectInspector(settings.MODEL_PATH)tracker = DefectTracker()lifecycle = DefectLifecycleManager(settings.MAX_MISSING_FRAMES)33 unmodified linesframe_count += 1# ---------------- DETECTION ----------------detections = inspector.inspect_image(frame)defects = tracker.update(detections)15 unmodified lines16171819202122234 unmodified lines2829303132333433 unmodified lines686970717273747576777879808182838485868788899015 unmodified linespersist_inspection,)from inspection.class_map import CLASS_MAPfrom inspection.service import annotate_imagefrom inspection.surface_gate import SteelSurfaceGatefrom agent.langgraph_agent import run_agent4 unmodified linesdef main():inspector = DefectInspector(settings.MODEL_PATH)surface_gate = SteelSurfaceGate() if settings.SURFACE_GATE_ENABLED else Nonetracker = DefectTracker()lifecycle = DefectLifecycleManager(settings.MAX_MISSING_FRAMES)33 unmodified linesframe_count += 1if surface_gate is not None:surface_result = surface_gate.evaluate(frame)if not surface_result.is_steel:annotated = annotate_image(display_frame,[],"SKIPPED",note=surface_result.reason,)cv2.imshow("Inspection System", annotated)key = cv2.waitKey(500) & 0xFFif key == 27 or key == ord('q'):logger.info("Exit signal received")breakcontinue# ---------------- DETECTION ----------------detections = inspector.inspect_image(frame)defects = tracker.update(detections)
.env.example+12
core/config.py+59
core/constants.py+3-2
dashboard/src/content/systemBrief.js+6-2
dashboard/src/lib/status.js+1
dashboard/src/pages/Live.jsx+32-9
inspection/service.py+93-4
inspection/surface_gate.pyAdded+243
live_camera.py+20