Spaces:
Runtime error
Runtime error
File size: 10,050 Bytes
2747d77 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | """
Shared multi-layer validation flow for API and Gradio paths.
This module centralizes pre-DL checks so both entry points make identical
validation decisions and emit consistent diagnostics.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
import cv2
import numpy as np
from src.preprocessing.card_detector import (
POKEMON_CARD_DETECTION_CONFIG,
detect_card_boundary_with_hand,
)
from src.preprocessing.image_utils import check_image_quality
FRONT_SATURATION_THRESHOLD = 35.0
BACK_SATURATION_THRESHOLD = 15.0
FRONT_BACK_BLUE_THRESHOLD = 0.25
@dataclass
class ColorValidation:
"""Color/pattern validation result."""
passed: bool
confidence: float
reason: str
@dataclass
class SideValidation:
"""Layered validation state for one image side."""
side: str
provided: bool
quality: Dict[str, Any]
corners_detected: bool
saturation: float
saturation_threshold: float
layer1_passed: bool
layer1_failure: str = ""
failure: str = ""
@dataclass
class MultiLayerValidationResult:
"""Unified validation output consumed by API and Gradio."""
front: SideValidation
back: SideValidation
processed_sides: List[str]
pokemon_back_validation: Optional[ColorValidation] = None
front_not_back_validation: Optional[ColorValidation] = None
rejection_category: Optional[str] = None
rejection_message: Optional[str] = None
rejection_details: Dict[str, Any] = field(default_factory=dict)
@property
def rejected(self) -> bool:
return self.rejection_category is not None
def _default_quality() -> Dict[str, Any]:
return {
"blur_score": 0.0,
"brightness": 0.0,
"contrast": 0.0,
"is_acceptable": False,
}
def _extract_quality_info(image: Optional[np.ndarray]) -> Dict[str, Any]:
if image is None:
return _default_quality()
try:
quality = check_image_quality(image)
return {
"blur_score": float(quality["blur_score"]),
"brightness": float(quality["brightness"]),
"contrast": float(quality["contrast"]),
"is_acceptable": bool(quality["is_acceptable"]),
}
except Exception:
return _default_quality()
def _mean_saturation_in_region(image: np.ndarray, corners: np.ndarray, max_dim: int = 512) -> float:
"""
Estimate mean HSV saturation inside the detected card polygon.
"""
try:
height, width = image.shape[:2]
if height <= 0 or width <= 0:
return 0.0
scale = 1.0
work_image = image
if max(height, width) > max_dim:
scale = max_dim / float(max(height, width))
new_w = max(1, int(width * scale))
new_h = max(1, int(height * scale))
work_image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
scaled_corners = (corners * scale).astype(np.int32)
hsv = cv2.cvtColor(work_image, cv2.COLOR_BGR2HSV)
mask = np.zeros(work_image.shape[:2], dtype=np.uint8)
cv2.fillPoly(mask, [scaled_corners], 255)
if cv2.countNonZero(mask) == 0:
return 0.0
saturation = hsv[:, :, 1]
return float(saturation[mask == 255].mean())
except Exception:
return 0.0
def _validate_layer1(side: str, image: Optional[np.ndarray], sat_threshold: float) -> SideValidation:
quality = _extract_quality_info(image)
if image is None:
return SideValidation(
side=side,
provided=False,
quality=quality,
corners_detected=False,
saturation=0.0,
saturation_threshold=sat_threshold,
layer1_passed=False,
layer1_failure="not provided",
failure="not provided",
)
corners = detect_card_boundary_with_hand(image, **POKEMON_CARD_DETECTION_CONFIG)
corners_detected = corners is not None
saturation = _mean_saturation_in_region(image, corners) if corners_detected else 0.0
layer1_passed = corners_detected and saturation >= sat_threshold
if layer1_passed:
failure = ""
layer1_failure = ""
elif not corners_detected:
failure = "aspect ratio"
layer1_failure = "aspect ratio"
else:
failure = "low saturation"
layer1_failure = "low saturation"
return SideValidation(
side=side,
provided=True,
quality=quality,
corners_detected=corners_detected,
saturation=saturation,
saturation_threshold=sat_threshold,
layer1_passed=layer1_passed,
layer1_failure=layer1_failure,
failure=failure,
)
def _build_no_side_rejection(
front: SideValidation,
back: SideValidation,
back_validation: Optional[ColorValidation],
front_not_back_validation: Optional[ColorValidation],
) -> tuple[str, str, Dict[str, Any]]:
if front.failure == "front_is_back" and front_not_back_validation is not None:
return (
"front_is_back",
"Both images appear to be card backs",
{
"front_confidence": front_not_back_validation.confidence,
"reason": front_not_back_validation.reason,
},
)
if back.failure == "back_pattern" and back_validation is not None:
return (
"back_pattern",
"Back image does not show a Pokemon card",
{
"validation_confidence": back_validation.confidence,
"reason": back_validation.reason,
},
)
if front.provided and back.provided:
return (
"geometry",
"No Pokemon card detected in either image",
{
"front_failure": front.layer1_failure or front.failure,
"back_failure": back.layer1_failure or back.failure,
"front_saturation": front.saturation,
"back_saturation": back.saturation,
},
)
if front.provided:
return (
"geometry",
"No Pokemon card detected in front image",
{
"front_failure": front.layer1_failure or front.failure,
"front_saturation": front.saturation,
},
)
if back.provided:
return (
"geometry",
"No Pokemon card detected in back image",
{
"back_failure": back.layer1_failure or back.failure,
"back_saturation": back.saturation,
},
)
return (
"geometry",
"No input images provided",
{},
)
def run_multilayer_validation(
front_image: Optional[np.ndarray],
back_image: Optional[np.ndarray],
feature_validator: Optional[Any] = None,
require_both_sides: bool = False,
) -> MultiLayerValidationResult:
"""
Run shared pre-DL validation and return side-level decisions.
Args:
front_image: Front image in BGR format.
back_image: Back image in BGR format.
feature_validator: Optional FeatureBasedValidator instance.
require_both_sides: If True, reject when only one side is valid.
"""
front = _validate_layer1("front", front_image, FRONT_SATURATION_THRESHOLD)
back = _validate_layer1("back", back_image, BACK_SATURATION_THRESHOLD)
processed_sides: List[str] = []
if front.layer1_passed:
processed_sides.append("front")
if back.layer1_passed:
processed_sides.append("back")
back_validation: Optional[ColorValidation] = None
if "back" in processed_sides and feature_validator is not None and back_image is not None:
is_pokemon_back, confidence, reason = feature_validator.validate_pokemon_back_colors(back_image)
back_validation = ColorValidation(
passed=bool(is_pokemon_back),
confidence=float(confidence),
reason=reason,
)
if not is_pokemon_back:
processed_sides.remove("back")
back.failure = "back_pattern"
front_not_back_validation: Optional[ColorValidation] = None
if "front" in processed_sides and feature_validator is not None and front_image is not None:
is_front_also_back, confidence, reason = feature_validator.validate_pokemon_back_colors(
front_image,
blue_threshold=FRONT_BACK_BLUE_THRESHOLD,
)
front_not_back_validation = ColorValidation(
passed=not bool(is_front_also_back),
confidence=float(confidence),
reason=reason,
)
if is_front_also_back:
processed_sides.remove("front")
front.failure = "front_is_back"
result = MultiLayerValidationResult(
front=front,
back=back,
processed_sides=processed_sides,
pokemon_back_validation=back_validation,
front_not_back_validation=front_not_back_validation,
)
if (
require_both_sides
and front.provided
and back.provided
and len(processed_sides) == 1
):
passing_side = processed_sides[0]
failing_side = "back" if passing_side == "front" else "front"
result.rejection_category = "mismatch"
result.rejection_message = f"Only {passing_side} image shows a valid card"
result.rejection_details = {
"front_passed": passing_side == "front",
"back_passed": passing_side == "back",
"failing_side": failing_side,
}
return result
if not processed_sides:
category, message, details = _build_no_side_rejection(
front=front,
back=back,
back_validation=back_validation,
front_not_back_validation=front_not_back_validation,
)
result.rejection_category = category
result.rejection_message = message
result.rejection_details = details
return result
|