MogensR commited on
Commit
9bd9bcd
·
1 Parent(s): 3c8897a

Update utils/utils.py

Browse files
Files changed (1) hide show
  1. utils/utils.py +3 -1094
utils/utils.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
- Unified Utilities Module for BackgroundFX Pro
3
- Combines FileManager, VideoUtils, ImageUtils, ValidationUtils, and CV utilities
4
  """
5
 
6
  # Set OMP_NUM_THREADS at the very beginning to prevent libgomp errors
@@ -16,7 +16,6 @@
16
  from typing import Optional, List, Union, Tuple, Dict, Any
17
  from datetime import datetime
18
  import subprocess
19
- import time
20
  import re
21
 
22
  import cv2
@@ -26,90 +25,6 @@
26
 
27
  logger = logging.getLogger(__name__)
28
 
29
- # ============================================================================
30
- # CONFIGURATION AND CONSTANTS
31
- # ============================================================================
32
-
33
- # Version control flags for CV functions
34
- USE_ENHANCED_SEGMENTATION = True
35
- USE_AUTO_TEMPORAL_CONSISTENCY = True
36
- USE_INTELLIGENT_PROMPTING = True
37
- USE_ITERATIVE_REFINEMENT = True
38
-
39
- # Professional background templates
40
- PROFESSIONAL_BACKGROUNDS = {
41
- "office_modern": {
42
- "name": "Modern Office",
43
- "type": "gradient",
44
- "colors": ["#f8f9fa", "#e9ecef", "#dee2e6"],
45
- "direction": "diagonal",
46
- "description": "Clean, contemporary office environment",
47
- "brightness": 0.95,
48
- "contrast": 1.1
49
- },
50
- "studio_blue": {
51
- "name": "Professional Blue",
52
- "type": "gradient",
53
- "colors": ["#1e3c72", "#2a5298", "#3498db"],
54
- "direction": "radial",
55
- "description": "Broadcast-quality blue studio",
56
- "brightness": 0.9,
57
- "contrast": 1.2
58
- },
59
- "studio_green": {
60
- "name": "Broadcast Green",
61
- "type": "color",
62
- "colors": ["#00b894"],
63
- "chroma_key": True,
64
- "description": "Professional green screen replacement",
65
- "brightness": 1.0,
66
- "contrast": 1.0
67
- },
68
- "minimalist": {
69
- "name": "Minimalist White",
70
- "type": "gradient",
71
- "colors": ["#ffffff", "#f1f2f6", "#ddd"],
72
- "direction": "soft_radial",
73
- "description": "Clean, minimal background",
74
- "brightness": 0.98,
75
- "contrast": 0.9
76
- },
77
- "warm_gradient": {
78
- "name": "Warm Sunset",
79
- "type": "gradient",
80
- "colors": ["#ff7675", "#fd79a8", "#fdcb6e"],
81
- "direction": "diagonal",
82
- "description": "Warm, inviting atmosphere",
83
- "brightness": 0.85,
84
- "contrast": 1.15
85
- },
86
- "tech_dark": {
87
- "name": "Tech Dark",
88
- "type": "gradient",
89
- "colors": ["#0c0c0c", "#2d3748", "#4a5568"],
90
- "direction": "vertical",
91
- "description": "Modern tech/gaming setup",
92
- "brightness": 0.7,
93
- "contrast": 1.3
94
- }
95
- }
96
-
97
- # ============================================================================
98
- # CUSTOM EXCEPTIONS
99
- # ============================================================================
100
-
101
- class SegmentationError(Exception):
102
- """Custom exception for segmentation failures"""
103
- pass
104
-
105
- class MaskRefinementError(Exception):
106
- """Custom exception for mask refinement failures"""
107
- pass
108
-
109
- class BackgroundReplacementError(Exception):
110
- """Custom exception for background replacement failures"""
111
- pass
112
-
113
  # ============================================================================
114
  # VALIDATION UTILS CLASS
115
  # ============================================================================
@@ -1023,7 +938,7 @@ def get_image_info(image_path: Union[str, Path]) -> Dict[str, Any]:
1023
 
1024
  except Exception as e:
1025
  logger.error(f"Error getting image info for {image_path}: {e}")
1026
- return {"exists": False, "error": str(e)}
1027
 
1028
  @staticmethod
1029
  def save_image(image: Image.Image,
@@ -1052,1012 +967,6 @@ def save_image(image: Image.Image,
1052
  logger.error(f"Failed to save image to {output_path}: {e}")
1053
  return False
1054
 
1055
- # ============================================================================
1056
- # COMPUTER VISION FUNCTIONS (from utilities.py)
1057
- # ============================================================================
1058
-
1059
- def segment_person_hq(image: np.ndarray, predictor: Any, fallback_enabled: bool = True) -> np.ndarray:
1060
- """High-quality person segmentation with intelligent automation"""
1061
- if not USE_ENHANCED_SEGMENTATION:
1062
- return segment_person_hq_original(image, predictor, fallback_enabled)
1063
-
1064
- logger.debug("Using ENHANCED segmentation with intelligent automation")
1065
-
1066
- if image is None or image.size == 0:
1067
- raise SegmentationError("Invalid input image")
1068
-
1069
- try:
1070
- if predictor is None:
1071
- if fallback_enabled:
1072
- logger.warning("SAM2 predictor not available, using fallback")
1073
- return _fallback_segmentation(image)
1074
- else:
1075
- raise SegmentationError("SAM2 predictor not available")
1076
-
1077
- try:
1078
- predictor.set_image(image)
1079
- except Exception as e:
1080
- logger.error(f"Failed to set image in predictor: {e}")
1081
- if fallback_enabled:
1082
- return _fallback_segmentation(image)
1083
- else:
1084
- raise SegmentationError(f"Predictor setup failed: {e}")
1085
-
1086
- if USE_INTELLIGENT_PROMPTING:
1087
- mask = _segment_with_intelligent_prompts(image, predictor)
1088
- else:
1089
- mask = _segment_with_basic_prompts(image, predictor)
1090
-
1091
- if USE_ITERATIVE_REFINEMENT and mask is not None:
1092
- mask = _auto_refine_mask_iteratively(image, mask, predictor)
1093
-
1094
- if not _validate_mask_quality(mask, image.shape[:2]):
1095
- logger.warning("Mask quality validation failed")
1096
- if fallback_enabled:
1097
- return _fallback_segmentation(image)
1098
- else:
1099
- raise SegmentationError("Poor mask quality")
1100
-
1101
- logger.debug(f"Enhanced segmentation successful - mask range: {mask.min()}-{mask.max()}")
1102
- return mask
1103
-
1104
- except SegmentationError:
1105
- raise
1106
- except Exception as e:
1107
- logger.error(f"Unexpected segmentation error: {e}")
1108
- if fallback_enabled:
1109
- return _fallback_segmentation(image)
1110
- else:
1111
- raise SegmentationError(f"Unexpected error: {e}")
1112
-
1113
- def segment_person_hq_original(image: np.ndarray, predictor: Any, fallback_enabled: bool = True) -> np.ndarray:
1114
- """Original version of person segmentation for rollback"""
1115
- if image is None or image.size == 0:
1116
- raise SegmentationError("Invalid input image")
1117
-
1118
- try:
1119
- if predictor is None:
1120
- if fallback_enabled:
1121
- logger.warning("SAM2 predictor not available, using fallback")
1122
- return _fallback_segmentation(image)
1123
- else:
1124
- raise SegmentationError("SAM2 predictor not available")
1125
-
1126
- try:
1127
- predictor.set_image(image)
1128
- except Exception as e:
1129
- logger.error(f"Failed to set image in predictor: {e}")
1130
- if fallback_enabled:
1131
- return _fallback_segmentation(image)
1132
- else:
1133
- raise SegmentationError(f"Predictor setup failed: {e}")
1134
-
1135
- h, w = image.shape[:2]
1136
-
1137
- points = np.array([
1138
- [w//2, h//4],
1139
- [w//2, h//2],
1140
- [w//2, 3*h//4],
1141
- [w//3, h//2],
1142
- [2*w//3, h//2],
1143
- [w//2, h//6],
1144
- [w//4, 2*h//3],
1145
- [3*w//4, 2*h//3],
1146
- ], dtype=np.float32)
1147
-
1148
- labels = np.ones(len(points), dtype=np.int32)
1149
-
1150
- try:
1151
- with torch.no_grad():
1152
- masks, scores, _ = predictor.predict(
1153
- point_coords=points,
1154
- point_labels=labels,
1155
- multimask_output=True
1156
- )
1157
- except Exception as e:
1158
- logger.error(f"SAM2 prediction failed: {e}")
1159
- if fallback_enabled:
1160
- return _fallback_segmentation(image)
1161
- else:
1162
- raise SegmentationError(f"Prediction failed: {e}")
1163
-
1164
- if masks is None or len(masks) == 0:
1165
- logger.warning("SAM2 returned no masks")
1166
- if fallback_enabled:
1167
- return _fallback_segmentation(image)
1168
- else:
1169
- raise SegmentationError("No masks generated")
1170
-
1171
- if scores is None or len(scores) == 0:
1172
- logger.warning("SAM2 returned no scores")
1173
- best_mask = masks[0]
1174
- else:
1175
- best_idx = np.argmax(scores)
1176
- best_mask = masks[best_idx]
1177
- logger.debug(f"Selected mask {best_idx} with score {scores[best_idx]:.3f}")
1178
-
1179
- mask = _process_mask(best_mask)
1180
-
1181
- if not _validate_mask_quality(mask, image.shape[:2]):
1182
- logger.warning("Mask quality validation failed")
1183
- if fallback_enabled:
1184
- return _fallback_segmentation(image)
1185
- else:
1186
- raise SegmentationError("Poor mask quality")
1187
-
1188
- logger.debug(f"Segmentation successful - mask range: {mask.min()}-{mask.max()}")
1189
- return mask
1190
-
1191
- except SegmentationError:
1192
- raise
1193
- except Exception as e:
1194
- logger.error(f"Unexpected segmentation error: {e}")
1195
- if fallback_enabled:
1196
- return _fallback_segmentation(image)
1197
- else:
1198
- raise SegmentationError(f"Unexpected error: {e}")
1199
-
1200
- def refine_mask_hq(image: np.ndarray, mask: np.ndarray, matanyone_processor: Any,
1201
- fallback_enabled: bool = True) -> np.ndarray:
1202
- """Enhanced mask refinement with MatAnyone and robust fallbacks"""
1203
- if image is None or mask is None:
1204
- raise MaskRefinementError("Invalid input image or mask")
1205
-
1206
- try:
1207
- mask = _process_mask(mask)
1208
-
1209
- if matanyone_processor is not None:
1210
- try:
1211
- logger.debug("Attempting MatAnyone refinement")
1212
- refined_mask = _matanyone_refine(image, mask, matanyone_processor)
1213
-
1214
- if refined_mask is not None and _validate_mask_quality(refined_mask, image.shape[:2]):
1215
- logger.debug("MatAnyone refinement successful")
1216
- return refined_mask
1217
- else:
1218
- logger.warning("MatAnyone produced poor quality mask")
1219
-
1220
- except Exception as e:
1221
- logger.warning(f"MatAnyone refinement failed: {e}")
1222
-
1223
- if fallback_enabled:
1224
- logger.debug("Using enhanced OpenCV refinement")
1225
- return enhance_mask_opencv_advanced(image, mask)
1226
- else:
1227
- raise MaskRefinementError("MatAnyone failed and fallback disabled")
1228
-
1229
- except MaskRefinementError:
1230
- raise
1231
- except Exception as e:
1232
- logger.error(f"Unexpected mask refinement error: {e}")
1233
- if fallback_enabled:
1234
- return enhance_mask_opencv_advanced(image, mask)
1235
- else:
1236
- raise MaskRefinementError(f"Unexpected error: {e}")
1237
-
1238
- def enhance_mask_opencv_advanced(image: np.ndarray, mask: np.ndarray) -> np.ndarray:
1239
- """Advanced OpenCV-based mask enhancement with multiple techniques"""
1240
- try:
1241
- if len(mask.shape) == 3:
1242
- mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
1243
-
1244
- if mask.max() <= 1.0:
1245
- mask = (mask * 255).astype(np.uint8)
1246
-
1247
- refined_mask = cv2.bilateralFilter(mask, 9, 75, 75)
1248
- refined_mask = _guided_filter_approx(image, refined_mask, radius=8, eps=0.2)
1249
-
1250
- kernel_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
1251
- refined_mask = cv2.morphologyEx(refined_mask, cv2.MORPH_CLOSE, kernel_close)
1252
-
1253
- kernel_open = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
1254
- refined_mask = cv2.morphologyEx(refined_mask, cv2.MORPH_OPEN, kernel_open)
1255
-
1256
- refined_mask = cv2.GaussianBlur(refined_mask, (3, 3), 0.8)
1257
-
1258
- _, refined_mask = cv2.threshold(refined_mask, 127, 255, cv2.THRESH_BINARY)
1259
-
1260
- return refined_mask
1261
-
1262
- except Exception as e:
1263
- logger.warning(f"Enhanced OpenCV refinement failed: {e}")
1264
- return cv2.GaussianBlur(mask, (5, 5), 1.0)
1265
-
1266
- def replace_background_hq(frame: np.ndarray, mask: np.ndarray, background: np.ndarray,
1267
- fallback_enabled: bool = True) -> np.ndarray:
1268
- """Enhanced background replacement with comprehensive error handling"""
1269
- if frame is None or mask is None or background is None:
1270
- raise BackgroundReplacementError("Invalid input frame, mask, or background")
1271
-
1272
- try:
1273
- background = cv2.resize(background, (frame.shape[1], frame.shape[0]),
1274
- interpolation=cv2.INTER_LANCZOS4)
1275
-
1276
- if len(mask.shape) == 3:
1277
- mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
1278
-
1279
- if mask.dtype != np.uint8:
1280
- mask = mask.astype(np.uint8)
1281
-
1282
- if mask.max() <= 1.0:
1283
- logger.debug("Converting normalized mask to 0-255 range")
1284
- mask = (mask * 255).astype(np.uint8)
1285
-
1286
- try:
1287
- result = _advanced_compositing(frame, mask, background)
1288
- logger.debug("Advanced compositing successful")
1289
- return result
1290
-
1291
- except Exception as e:
1292
- logger.warning(f"Advanced compositing failed: {e}")
1293
- if fallback_enabled:
1294
- return _simple_compositing(frame, mask, background)
1295
- else:
1296
- raise BackgroundReplacementError(f"Advanced compositing failed: {e}")
1297
-
1298
- except BackgroundReplacementError:
1299
- raise
1300
- except Exception as e:
1301
- logger.error(f"Unexpected background replacement error: {e}")
1302
- if fallback_enabled:
1303
- return _simple_compositing(frame, mask, background)
1304
- else:
1305
- raise BackgroundReplacementError(f"Unexpected error: {e}")
1306
-
1307
- def create_professional_background(bg_config: Dict[str, Any], width: int, height: int) -> np.ndarray:
1308
- """Enhanced professional background creation with quality improvements"""
1309
- try:
1310
- if bg_config["type"] == "color":
1311
- background = _create_solid_background(bg_config, width, height)
1312
- elif bg_config["type"] == "gradient":
1313
- background = _create_gradient_background_enhanced(bg_config, width, height)
1314
- else:
1315
- background = np.full((height, width, 3), (128, 128, 128), dtype=np.uint8)
1316
-
1317
- background = _apply_background_adjustments(background, bg_config)
1318
-
1319
- return background
1320
-
1321
- except Exception as e:
1322
- logger.error(f"Background creation error: {e}")
1323
- return np.full((height, width, 3), (128, 128, 128), dtype=np.uint8)
1324
-
1325
- def validate_video_file(video_path: str) -> Tuple[bool, str]:
1326
- """Enhanced video file validation with detailed checks"""
1327
- if not video_path or not os.path.exists(video_path):
1328
- return False, "Video file not found"
1329
-
1330
- try:
1331
- file_size = os.path.getsize(video_path)
1332
- if file_size == 0:
1333
- return False, "Video file is empty"
1334
-
1335
- if file_size > 2 * 1024 * 1024 * 1024:
1336
- return False, "Video file too large (>2GB)"
1337
-
1338
- cap = cv2.VideoCapture(video_path)
1339
- if not cap.isOpened():
1340
- return False, "Cannot open video file"
1341
-
1342
- frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
1343
- fps = cap.get(cv2.CAP_PROP_FPS)
1344
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
1345
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
1346
-
1347
- cap.release()
1348
-
1349
- if frame_count == 0:
1350
- return False, "Video appears to be empty (0 frames)"
1351
-
1352
- if fps <= 0 or fps > 120:
1353
- return False, f"Invalid frame rate: {fps}"
1354
-
1355
- if width <= 0 or height <= 0:
1356
- return False, f"Invalid resolution: {width}x{height}"
1357
-
1358
- if width > 4096 or height > 4096:
1359
- return False, f"Resolution too high: {width}x{height} (max 4096x4096)"
1360
-
1361
- duration = frame_count / fps
1362
- if duration > 300:
1363
- return False, f"Video too long: {duration:.1f}s (max 300s)"
1364
-
1365
- return True, f"Valid video: {width}x{height}, {fps:.1f}fps, {duration:.1f}s"
1366
-
1367
- except Exception as e:
1368
- return False, f"Error validating video: {str(e)}"
1369
-
1370
- # ============================================================================
1371
- # HELPER FUNCTIONS (from utilities.py)
1372
- # ============================================================================
1373
-
1374
- def _segment_with_intelligent_prompts(image: np.ndarray, predictor: Any) -> np.ndarray:
1375
- """Intelligent automatic prompt generation for segmentation"""
1376
- try:
1377
- h, w = image.shape[:2]
1378
- pos_points, neg_points = _generate_smart_prompts(image)
1379
-
1380
- if len(pos_points) == 0:
1381
- pos_points = np.array([[w//2, h//2]], dtype=np.float32)
1382
-
1383
- points = np.vstack([pos_points, neg_points])
1384
- labels = np.hstack([
1385
- np.ones(len(pos_points), dtype=np.int32),
1386
- np.zeros(len(neg_points), dtype=np.int32)
1387
- ])
1388
-
1389
- logger.debug(f"Using {len(pos_points)} positive, {len(neg_points)} negative points")
1390
-
1391
- with torch.no_grad():
1392
- masks, scores, _ = predictor.predict(
1393
- point_coords=points,
1394
- point_labels=labels,
1395
- multimask_output=True
1396
- )
1397
-
1398
- if masks is None or len(masks) == 0:
1399
- raise SegmentationError("No masks generated")
1400
-
1401
- if scores is not None and len(scores) > 0:
1402
- best_idx = np.argmax(scores)
1403
- best_mask = masks[best_idx]
1404
- logger.debug(f"Selected mask {best_idx} with score {scores[best_idx]:.3f}")
1405
- else:
1406
- best_mask = masks[0]
1407
-
1408
- return _process_mask(best_mask)
1409
-
1410
- except Exception as e:
1411
- logger.error(f"Intelligent prompting failed: {e}")
1412
- raise
1413
-
1414
- def _segment_with_basic_prompts(image: np.ndarray, predictor: Any) -> np.ndarray:
1415
- """Basic prompting method for segmentation"""
1416
- h, w = image.shape[:2]
1417
-
1418
- positive_points = np.array([
1419
- [w//2, h//3],
1420
- [w//2, h//2],
1421
- [w//2, 2*h//3],
1422
- ], dtype=np.float32)
1423
-
1424
- negative_points = np.array([
1425
- [w//10, h//10],
1426
- [9*w//10, h//10],
1427
- [w//10, 9*h//10],
1428
- [9*w//10, 9*h//10],
1429
- ], dtype=np.float32)
1430
-
1431
- points = np.vstack([positive_points, negative_points])
1432
- labels = np.array([1, 1, 1, 0, 0, 0, 0], dtype=np.int32)
1433
-
1434
- with torch.no_grad():
1435
- masks, scores, _ = predictor.predict(
1436
- point_coords=points,
1437
- point_labels=labels,
1438
- multimask_output=True
1439
- )
1440
-
1441
- if masks is None or len(masks) == 0:
1442
- raise SegmentationError("No masks generated")
1443
-
1444
- best_idx = np.argmax(scores) if scores is not None and len(scores) > 0 else 0
1445
- best_mask = masks[best_idx]
1446
-
1447
- return _process_mask(best_mask)
1448
-
1449
- def _generate_smart_prompts(image: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
1450
- """Generate optimal positive/negative points automatically"""
1451
- try:
1452
- h, w = image.shape[:2]
1453
-
1454
- try:
1455
- saliency = cv2.saliency.StaticSaliencySpectralResidual_create()
1456
- success, saliency_map = saliency.computeSaliency(image)
1457
-
1458
- if success:
1459
- saliency_thresh = cv2.threshold(saliency_map, 0.7, 1, cv2.THRESH_BINARY)[1]
1460
- contours, _ = cv2.findContours((saliency_thresh * 255).astype(np.uint8),
1461
- cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1462
-
1463
- positive_points = []
1464
- if contours:
1465
- for contour in sorted(contours, key=cv2.contourArea, reverse=True)[:3]:
1466
- M = cv2.moments(contour)
1467
- if M["m00"] != 0:
1468
- cx = int(M["m10"] / M["m00"])
1469
- cy = int(M["m01"] / M["m00"])
1470
- if 0 < cx < w and 0 < cy < h:
1471
- positive_points.append([cx, cy])
1472
-
1473
- if positive_points:
1474
- logger.debug(f"Generated {len(positive_points)} saliency-based points")
1475
- positive_points = np.array(positive_points, dtype=np.float32)
1476
- else:
1477
- raise Exception("No valid saliency points found")
1478
-
1479
- except Exception as e:
1480
- logger.debug(f"Saliency method failed: {e}, using fallback")
1481
- positive_points = np.array([
1482
- [w//2, h//3],
1483
- [w//2, h//2],
1484
- [w//2, 2*h//3],
1485
- ], dtype=np.float32)
1486
-
1487
- negative_points = np.array([
1488
- [10, 10],
1489
- [w-10, 10],
1490
- [10, h-10],
1491
- [w-10, h-10],
1492
- [w//2, 5],
1493
- [w//2, h-5],
1494
- ], dtype=np.float32)
1495
-
1496
- return positive_points, negative_points
1497
-
1498
- except Exception as e:
1499
- logger.warning(f"Smart prompt generation failed: {e}")
1500
- h, w = image.shape[:2]
1501
- positive_points = np.array([[w//2, h//2]], dtype=np.float32)
1502
- negative_points = np.array([[10, 10], [w-10, 10]], dtype=np.float32)
1503
- return positive_points, negative_points
1504
-
1505
- def _auto_refine_mask_iteratively(image: np.ndarray, initial_mask: np.ndarray,
1506
- predictor: Any, max_iterations: int = 2) -> np.ndarray:
1507
- """Automatically refine mask based on quality assessment"""
1508
- try:
1509
- current_mask = initial_mask.copy()
1510
-
1511
- for iteration in range(max_iterations):
1512
- quality_score = _assess_mask_quality(current_mask, image)
1513
- logger.debug(f"Iteration {iteration}: quality score = {quality_score:.3f}")
1514
-
1515
- if quality_score > 0.85:
1516
- logger.debug(f"Quality sufficient after {iteration} iterations")
1517
- break
1518
-
1519
- problem_areas = _find_mask_errors(current_mask, image)
1520
-
1521
- if np.any(problem_areas):
1522
- corrective_points, corrective_labels = _generate_corrective_prompts(
1523
- image, current_mask, problem_areas
1524
- )
1525
-
1526
- if len(corrective_points) > 0:
1527
- try:
1528
- with torch.no_grad():
1529
- masks, scores, _ = predictor.predict(
1530
- point_coords=corrective_points,
1531
- point_labels=corrective_labels,
1532
- mask_input=current_mask[None, :, :],
1533
- multimask_output=False
1534
- )
1535
-
1536
- if masks is not None and len(masks) > 0:
1537
- refined_mask = _process_mask(masks[0])
1538
-
1539
- if _assess_mask_quality(refined_mask, image) > quality_score:
1540
- current_mask = refined_mask
1541
- logger.debug(f"Improved mask in iteration {iteration}")
1542
- else:
1543
- logger.debug(f"Refinement didn't improve quality in iteration {iteration}")
1544
- break
1545
-
1546
- except Exception as e:
1547
- logger.debug(f"Refinement iteration {iteration} failed: {e}")
1548
- break
1549
- else:
1550
- logger.debug("No problem areas detected")
1551
- break
1552
-
1553
- return current_mask
1554
-
1555
- except Exception as e:
1556
- logger.warning(f"Iterative refinement failed: {e}")
1557
- return initial_mask
1558
-
1559
- def _assess_mask_quality(mask: np.ndarray, image: np.ndarray) -> float:
1560
- """Assess mask quality automatically"""
1561
- try:
1562
- h, w = image.shape[:2]
1563
- scores = []
1564
-
1565
- mask_area = np.sum(mask > 127)
1566
- total_area = h * w
1567
- area_ratio = mask_area / total_area
1568
-
1569
- if 0.05 <= area_ratio <= 0.8:
1570
- area_score = 1.0
1571
- elif area_ratio < 0.05:
1572
- area_score = area_ratio / 0.05
1573
- else:
1574
- area_score = max(0, 1.0 - (area_ratio - 0.8) / 0.2)
1575
- scores.append(area_score)
1576
-
1577
- mask_binary = mask > 127
1578
- if np.any(mask_binary):
1579
- mask_center_y, mask_center_x = np.where(mask_binary)
1580
- center_y = np.mean(mask_center_y) / h
1581
- center_x = np.mean(mask_center_x) / w
1582
-
1583
- center_score = 1.0 - min(abs(center_x - 0.5), abs(center_y - 0.5))
1584
- scores.append(center_score)
1585
- else:
1586
- scores.append(0.0)
1587
-
1588
- edges = cv2.Canny(mask, 50, 150)
1589
- edge_density = np.sum(edges > 0) / total_area
1590
- smoothness_score = max(0, 1.0 - edge_density * 10)
1591
- scores.append(smoothness_score)
1592
-
1593
- num_labels, _ = cv2.connectedComponents(mask)
1594
- connectivity_score = max(0, 1.0 - (num_labels - 2) * 0.2)
1595
- scores.append(connectivity_score)
1596
-
1597
- weights = [0.3, 0.2, 0.3, 0.2]
1598
- overall_score = np.average(scores, weights=weights)
1599
-
1600
- return overall_score
1601
-
1602
- except Exception as e:
1603
- logger.warning(f"Quality assessment failed: {e}")
1604
- return 0.5
1605
-
1606
- def _find_mask_errors(mask: np.ndarray, image: np.ndarray) -> np.ndarray:
1607
- """Identify problematic areas in mask"""
1608
- try:
1609
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
1610
- edges = cv2.Canny(gray, 50, 150)
1611
- mask_edges = cv2.Canny(mask, 50, 150)
1612
- edge_discrepancy = cv2.bitwise_xor(edges, mask_edges)
1613
- kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
1614
- error_regions = cv2.dilate(edge_discrepancy, kernel, iterations=1)
1615
- return error_regions > 0
1616
- except Exception as e:
1617
- logger.warning(f"Error detection failed: {e}")
1618
- return np.zeros_like(mask, dtype=bool)
1619
-
1620
- def _generate_corrective_prompts(image: np.ndarray, mask: np.ndarray,
1621
- problem_areas: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
1622
- """Generate corrective prompts based on problem areas"""
1623
- try:
1624
- contours, _ = cv2.findContours(problem_areas.astype(np.uint8),
1625
- cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1626
-
1627
- corrective_points = []
1628
- corrective_labels = []
1629
-
1630
- for contour in contours:
1631
- if cv2.contourArea(contour) > 100:
1632
- M = cv2.moments(contour)
1633
- if M["m00"] != 0:
1634
- cx = int(M["m10"] / M["m00"])
1635
- cy = int(M["m01"] / M["m00"])
1636
-
1637
- current_mask_value = mask[cy, cx]
1638
-
1639
- if current_mask_value < 127:
1640
- corrective_points.append([cx, cy])
1641
- corrective_labels.append(1)
1642
- else:
1643
- corrective_points.append([cx, cy])
1644
- corrective_labels.append(0)
1645
-
1646
- return (np.array(corrective_points, dtype=np.float32) if corrective_points else np.array([]).reshape(0, 2),
1647
- np.array(corrective_labels, dtype=np.int32) if corrective_labels else np.array([], dtype=np.int32))
1648
-
1649
- except Exception as e:
1650
- logger.warning(f"Corrective prompt generation failed: {e}")
1651
- return np.array([]).reshape(0, 2), np.array([], dtype=np.int32)
1652
-
1653
- def _process_mask(mask: np.ndarray) -> np.ndarray:
1654
- """Process raw mask to ensure correct format and range"""
1655
- try:
1656
- if len(mask.shape) > 2:
1657
- mask = mask.squeeze()
1658
-
1659
- if len(mask.shape) > 2:
1660
- mask = mask[:, :, 0] if mask.shape[2] > 0 else mask.sum(axis=2)
1661
-
1662
- if mask.dtype == bool:
1663
- mask = mask.astype(np.uint8) * 255
1664
- elif mask.dtype == np.float32 or mask.dtype == np.float64:
1665
- if mask.max() <= 1.0:
1666
- mask = (mask * 255).astype(np.uint8)
1667
- else:
1668
- mask = np.clip(mask, 0, 255).astype(np.uint8)
1669
- else:
1670
- mask = mask.astype(np.uint8)
1671
-
1672
- kernel = np.ones((3, 3), np.uint8)
1673
- mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
1674
- mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
1675
-
1676
- _, mask = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)
1677
-
1678
- return mask
1679
-
1680
- except Exception as e:
1681
- logger.error(f"Mask processing failed: {e}")
1682
- h, w = mask.shape[:2] if len(mask.shape) >= 2 else (256, 256)
1683
- fallback = np.zeros((h, w), dtype=np.uint8)
1684
- fallback[h//4:3*h//4, w//4:3*w//4] = 255
1685
- return fallback
1686
-
1687
- def _validate_mask_quality(mask: np.ndarray, image_shape: Tuple[int, int]) -> bool:
1688
- """Validate that the mask meets quality criteria"""
1689
- try:
1690
- h, w = image_shape
1691
- mask_area = np.sum(mask > 127)
1692
- total_area = h * w
1693
-
1694
- area_ratio = mask_area / total_area
1695
- if area_ratio < 0.05 or area_ratio > 0.8:
1696
- logger.warning(f"Suspicious mask area ratio: {area_ratio:.3f}")
1697
- return False
1698
-
1699
- mask_binary = mask > 127
1700
- mask_center_y, mask_center_x = np.where(mask_binary)
1701
-
1702
- if len(mask_center_y) == 0:
1703
- logger.warning("Empty mask")
1704
- return False
1705
-
1706
- center_y = np.mean(mask_center_y)
1707
- center_x = np.mean(mask_center_x)
1708
-
1709
- if center_y < h * 0.2 or center_y > h * 0.9:
1710
- logger.warning(f"Mask center too far from expected person location: y={center_y/h:.2f}")
1711
- return False
1712
-
1713
- return True
1714
-
1715
- except Exception as e:
1716
- logger.warning(f"Mask validation error: {e}")
1717
- return True
1718
-
1719
- def _fallback_segmentation(image: np.ndarray) -> np.ndarray:
1720
- """Fallback segmentation when AI models fail"""
1721
- try:
1722
- logger.info("Using fallback segmentation strategy")
1723
- h, w = image.shape[:2]
1724
-
1725
- try:
1726
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
1727
-
1728
- edge_pixels = np.concatenate([
1729
- gray[0, :], gray[-1, :], gray[:, 0], gray[:, -1]
1730
- ])
1731
- bg_color = np.median(edge_pixels)
1732
-
1733
- diff = np.abs(gray.astype(float) - bg_color)
1734
- mask = (diff > 30).astype(np.uint8) * 255
1735
-
1736
- kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
1737
- mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
1738
- mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
1739
-
1740
- if _validate_mask_quality(mask, image.shape[:2]):
1741
- logger.info("Background subtraction fallback successful")
1742
- return mask
1743
-
1744
- except Exception as e:
1745
- logger.warning(f"Background subtraction fallback failed: {e}")
1746
-
1747
- mask = np.zeros((h, w), dtype=np.uint8)
1748
-
1749
- center_x, center_y = w // 2, h // 2
1750
- radius_x, radius_y = w // 3, h // 2.5
1751
-
1752
- y, x = np.ogrid[:h, :w]
1753
- mask_ellipse = ((x - center_x) / radius_x) ** 2 + ((y - center_y) / radius_y) ** 2 <= 1
1754
- mask[mask_ellipse] = 255
1755
-
1756
- logger.info("Using geometric fallback mask")
1757
- return mask
1758
-
1759
- except Exception as e:
1760
- logger.error(f"All fallback strategies failed: {e}")
1761
- h, w = image.shape[:2]
1762
- mask = np.zeros((h, w), dtype=np.uint8)
1763
- mask[h//6:5*h//6, w//4:3*w//4] = 255
1764
- return mask
1765
-
1766
- def _matanyone_refine(image: np.ndarray, mask: np.ndarray, processor: Any) -> Optional[np.ndarray]:
1767
- """Attempt MatAnyone mask refinement"""
1768
- try:
1769
- if hasattr(processor, 'infer'):
1770
- refined_mask = processor.infer(image, mask)
1771
- elif hasattr(processor, 'process'):
1772
- refined_mask = processor.process(image, mask)
1773
- elif callable(processor):
1774
- refined_mask = processor(image, mask)
1775
- else:
1776
- logger.warning("Unknown MatAnyone interface")
1777
- return None
1778
-
1779
- if refined_mask is None:
1780
- return None
1781
-
1782
- refined_mask = _process_mask(refined_mask)
1783
- logger.debug("MatAnyone refinement successful")
1784
- return refined_mask
1785
-
1786
- except Exception as e:
1787
- logger.warning(f"MatAnyone processing error: {e}")
1788
- return None
1789
-
1790
- def _guided_filter_approx(guide: np.ndarray, mask: np.ndarray, radius: int = 8, eps: float = 0.2) -> np.ndarray:
1791
- """Approximation of guided filter for edge-aware smoothing"""
1792
- try:
1793
- guide_gray = cv2.cvtColor(guide, cv2.COLOR_BGR2GRAY) if len(guide.shape) == 3 else guide
1794
- guide_gray = guide_gray.astype(np.float32) / 255.0
1795
- mask_float = mask.astype(np.float32) / 255.0
1796
-
1797
- kernel_size = 2 * radius + 1
1798
-
1799
- mean_guide = cv2.boxFilter(guide_gray, -1, (kernel_size, kernel_size))
1800
- mean_mask = cv2.boxFilter(mask_float, -1, (kernel_size, kernel_size))
1801
- corr_guide_mask = cv2.boxFilter(guide_gray * mask_float, -1, (kernel_size, kernel_size))
1802
-
1803
- cov_guide_mask = corr_guide_mask - mean_guide * mean_mask
1804
- mean_guide_sq = cv2.boxFilter(guide_gray * guide_gray, -1, (kernel_size, kernel_size))
1805
- var_guide = mean_guide_sq - mean_guide * mean_guide
1806
-
1807
- a = cov_guide_mask / (var_guide + eps)
1808
- b = mean_mask - a * mean_guide
1809
-
1810
- mean_a = cv2.boxFilter(a, -1, (kernel_size, kernel_size))
1811
- mean_b = cv2.boxFilter(b, -1, (kernel_size, kernel_size))
1812
-
1813
- output = mean_a * guide_gray + mean_b
1814
- output = np.clip(output * 255, 0, 255).astype(np.uint8)
1815
-
1816
- return output
1817
-
1818
- except Exception as e:
1819
- logger.warning(f"Guided filter approximation failed: {e}")
1820
- return mask
1821
-
1822
- def _advanced_compositing(frame: np.ndarray, mask: np.ndarray, background: np.ndarray) -> np.ndarray:
1823
- """Advanced compositing with edge feathering and color correction"""
1824
- try:
1825
- threshold = 100
1826
- _, mask_binary = cv2.threshold(mask, threshold, 255, cv2.THRESH_BINARY)
1827
-
1828
- kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
1829
- mask_binary = cv2.morphologyEx(mask_binary, cv2.MORPH_CLOSE, kernel)
1830
- mask_binary = cv2.morphologyEx(mask_binary, cv2.MORPH_OPEN, kernel)
1831
-
1832
- mask_smooth = cv2.GaussianBlur(mask_binary.astype(np.float32), (5, 5), 1.0)
1833
- mask_smooth = mask_smooth / 255.0
1834
-
1835
- mask_smooth = np.power(mask_smooth, 0.8)
1836
-
1837
- mask_smooth = np.where(mask_smooth > 0.5,
1838
- np.minimum(mask_smooth * 1.1, 1.0),
1839
- mask_smooth * 0.9)
1840
-
1841
- frame_adjusted = _color_match_edges(frame, background, mask_smooth)
1842
-
1843
- alpha_3ch = np.stack([mask_smooth] * 3, axis=2)
1844
-
1845
- frame_float = frame_adjusted.astype(np.float32)
1846
- background_float = background.astype(np.float32)
1847
-
1848
- result = frame_float * alpha_3ch + background_float * (1 - alpha_3ch)
1849
- result = np.clip(result, 0, 255).astype(np.uint8)
1850
-
1851
- return result
1852
-
1853
- except Exception as e:
1854
- logger.error(f"Advanced compositing error: {e}")
1855
- raise
1856
-
1857
- def _color_match_edges(frame: np.ndarray, background: np.ndarray, alpha: np.ndarray) -> np.ndarray:
1858
- """Subtle color matching at edges to reduce halos"""
1859
- try:
1860
- edge_mask = cv2.Sobel(alpha, cv2.CV_64F, 1, 1, ksize=3)
1861
- edge_mask = np.abs(edge_mask)
1862
- edge_mask = (edge_mask > 0.1).astype(np.float32)
1863
-
1864
- edge_areas = edge_mask > 0
1865
- if not np.any(edge_areas):
1866
- return frame
1867
-
1868
- frame_adjusted = frame.copy().astype(np.float32)
1869
- background_float = background.astype(np.float32)
1870
-
1871
- adjustment_strength = 0.1
1872
- for c in range(3):
1873
- frame_adjusted[:, :, c] = np.where(
1874
- edge_areas,
1875
- frame_adjusted[:, :, c] * (1 - adjustment_strength) +
1876
- background_float[:, :, c] * adjustment_strength,
1877
- frame_adjusted[:, :, c]
1878
- )
1879
-
1880
- return np.clip(frame_adjusted, 0, 255).astype(np.uint8)
1881
-
1882
- except Exception as e:
1883
- logger.warning(f"Color matching failed: {e}")
1884
- return frame
1885
-
1886
- def _simple_compositing(frame: np.ndarray, mask: np.ndarray, background: np.ndarray) -> np.ndarray:
1887
- """Simple fallback compositing method"""
1888
- try:
1889
- logger.info("Using simple compositing fallback")
1890
-
1891
- background = cv2.resize(background, (frame.shape[1], frame.shape[0]))
1892
-
1893
- if len(mask.shape) == 3:
1894
- mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
1895
- if mask.max() <= 1.0:
1896
- mask = (mask * 255).astype(np.uint8)
1897
-
1898
- _, mask_binary = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)
1899
-
1900
- mask_norm = mask_binary.astype(np.float32) / 255.0
1901
- mask_3ch = np.stack([mask_norm] * 3, axis=2)
1902
-
1903
- result = frame * mask_3ch + background * (1 - mask_3ch)
1904
- return result.astype(np.uint8)
1905
-
1906
- except Exception as e:
1907
- logger.error(f"Simple compositing failed: {e}")
1908
- return frame
1909
-
1910
- def _create_solid_background(bg_config: Dict[str, Any], width: int, height: int) -> np.ndarray:
1911
- """Create solid color background"""
1912
- color_hex = bg_config["colors"][0].lstrip('#')
1913
- color_rgb = tuple(int(color_hex[i:i+2], 16) for i in (0, 2, 4))
1914
- color_bgr = color_rgb[::-1]
1915
- return np.full((height, width, 3), color_bgr, dtype=np.uint8)
1916
-
1917
- def _create_gradient_background_enhanced(bg_config: Dict[str, Any], width: int, height: int) -> np.ndarray:
1918
- """Create enhanced gradient background with better quality"""
1919
- try:
1920
- colors = bg_config["colors"]
1921
- direction = bg_config.get("direction", "vertical")
1922
-
1923
- rgb_colors = []
1924
- for color_hex in colors:
1925
- color_hex = color_hex.lstrip('#')
1926
- rgb = tuple(int(color_hex[i:i+2], 16) for i in (0, 2, 4))
1927
- rgb_colors.append(rgb)
1928
-
1929
- if not rgb_colors:
1930
- rgb_colors = [(128, 128, 128)]
1931
-
1932
- if direction == "vertical":
1933
- background = _create_vertical_gradient(rgb_colors, width, height)
1934
- elif direction == "horizontal":
1935
- background = _create_horizontal_gradient(rgb_colors, width, height)
1936
- elif direction == "diagonal":
1937
- background = _create_diagonal_gradient(rgb_colors, width, height)
1938
- elif direction in ["radial", "soft_radial"]:
1939
- background = _create_radial_gradient(rgb_colors, width, height, direction == "soft_radial")
1940
- else:
1941
- background = _create_vertical_gradient(rgb_colors, width, height)
1942
-
1943
- return cv2.cvtColor(background, cv2.COLOR_RGB2BGR)
1944
-
1945
- except Exception as e:
1946
- logger.error(f"Gradient creation error: {e}")
1947
- return np.full((height, width, 3), (128, 128, 128), dtype=np.uint8)
1948
-
1949
- def _create_vertical_gradient(colors: list, width: int, height: int) -> np.ndarray:
1950
- """Create vertical gradient using NumPy for performance"""
1951
- gradient = np.zeros((height, width, 3), dtype=np.uint8)
1952
-
1953
- for y in range(height):
1954
- progress = y / height if height > 0 else 0
1955
- color = _interpolate_color(colors, progress)
1956
- gradient[y, :] = color
1957
-
1958
- return gradient
1959
-
1960
- def _create_horizontal_gradient(colors: list, width: int, height: int) -> np.ndarray:
1961
- """Create horizontal gradient using NumPy for performance"""
1962
- gradient = np.zeros((height, width, 3), dtype=np.uint8)
1963
-
1964
- for x in range(width):
1965
- progress = x / width if width > 0 else 0
1966
- color = _interpolate_color(colors, progress)
1967
- gradient[:, x] = color
1968
-
1969
- return gradient
1970
-
1971
- def _create_diagonal_gradient(colors: list, width: int, height: int) -> np.ndarray:
1972
- """Create diagonal gradient using vectorized operations"""
1973
- y_coords, x_coords = np.mgrid[0:height, 0:width]
1974
- max_distance = width + height
1975
- progress = (x_coords + y_coords) / max_distance
1976
- progress = np.clip(progress, 0, 1)
1977
-
1978
- gradient = np.zeros((height, width, 3), dtype=np.uint8)
1979
- for c in range(3):
1980
- gradient[:, :, c] = _vectorized_color_interpolation(colors, progress, c)
1981
-
1982
- return gradient
1983
-
1984
- def _create_radial_gradient(colors: list, width: int, height: int, soft: bool = False) -> np.ndarray:
1985
- """Create radial gradient using vectorized operations"""
1986
- center_x, center_y = width // 2, height // 2
1987
- max_distance = np.sqrt(center_x**2 + center_y**2)
1988
-
1989
- y_coords, x_coords = np.mgrid[0:height, 0:width]
1990
- distances = np.sqrt((x_coords - center_x)**2 + (y_coords - center_y)**2)
1991
- progress = distances / max_distance
1992
- progress = np.clip(progress, 0, 1)
1993
-
1994
- if soft:
1995
- progress = np.power(progress, 0.7)
1996
-
1997
- gradient = np.zeros((height, width, 3), dtype=np.uint8)
1998
- for c in range(3):
1999
- gradient[:, :, c] = _vectorized_color_interpolation(colors, progress, c)
2000
-
2001
- return gradient
2002
-
2003
- def _vectorized_color_interpolation(colors: list, progress: np.ndarray, channel: int) -> np.ndarray:
2004
- """Vectorized color interpolation for performance"""
2005
- if len(colors) == 1:
2006
- return np.full_like(progress, colors[0][channel], dtype=np.uint8)
2007
-
2008
- num_segments = len(colors) - 1
2009
- segment_progress = progress * num_segments
2010
- segment_indices = np.floor(segment_progress).astype(int)
2011
- segment_indices = np.clip(segment_indices, 0, num_segments - 1)
2012
- local_progress = segment_progress - segment_indices
2013
-
2014
- start_colors = np.array([colors[i][channel] for i in range(len(colors))])
2015
- end_colors = np.array([colors[min(i + 1, len(colors) - 1)][channel] for i in range(len(colors))])
2016
-
2017
- start_vals = start_colors[segment_indices]
2018
- end_vals = end_colors[segment_indices]
2019
-
2020
- result = start_vals + (end_vals - start_vals) * local_progress
2021
- return np.clip(result, 0, 255).astype(np.uint8)
2022
-
2023
- def _interpolate_color(colors: list, progress: float) -> tuple:
2024
- """Interpolate between multiple colors"""
2025
- if len(colors) == 1:
2026
- return colors[0]
2027
- elif len(colors) == 2:
2028
- r = int(colors[0][0] + (colors[1][0] - colors[0][0]) * progress)
2029
- g = int(colors[0][1] + (colors[1][1] - colors[0][1]) * progress)
2030
- b = int(colors[0][2] + (colors[1][2] - colors[0][2]) * progress)
2031
- return (r, g, b)
2032
- else:
2033
- segment = progress * (len(colors) - 1)
2034
- idx = int(segment)
2035
- local_progress = segment - idx
2036
- if idx >= len(colors) - 1:
2037
- return colors[-1]
2038
- c1, c2 = colors[idx], colors[idx + 1]
2039
- r = int(c1[0] + (c2[0] - c1[0]) * local_progress)
2040
- g = int(c1[1] + (c2[1] - c1[1]) * local_progress)
2041
- b = int(c1[2] + (c2[2] - c1[2]) * local_progress)
2042
- return (r, g, b)
2043
-
2044
- def _apply_background_adjustments(background: np.ndarray, bg_config: Dict[str, Any]) -> np.ndarray:
2045
- """Apply brightness and contrast adjustments to background"""
2046
- try:
2047
- brightness = bg_config.get("brightness", 1.0)
2048
- contrast = bg_config.get("contrast", 1.0)
2049
-
2050
- if brightness != 1.0 or contrast != 1.0:
2051
- background = background.astype(np.float32)
2052
- background = background * contrast * brightness
2053
- background = np.clip(background, 0, 255).astype(np.uint8)
2054
-
2055
- return background
2056
-
2057
- except Exception as e:
2058
- logger.warning(f"Background adjustment failed: {e}")
2059
- return background
2060
-
2061
  # ============================================================================
2062
  # DEFAULT INSTANCES
2063
  # ============================================================================
 
1
  """
2
+ Core Utilities Module for BackgroundFX Pro
3
+ Contains FileManager, VideoUtils, ImageUtils, and ValidationUtils
4
  """
5
 
6
  # Set OMP_NUM_THREADS at the very beginning to prevent libgomp errors
 
16
  from typing import Optional, List, Union, Tuple, Dict, Any
17
  from datetime import datetime
18
  import subprocess
 
19
  import re
20
 
21
  import cv2
 
25
 
26
  logger = logging.getLogger(__name__)
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  # ============================================================================
29
  # VALIDATION UTILS CLASS
30
  # ============================================================================
 
938
 
939
  except Exception as e:
940
  logger.error(f"Error getting image info for {image_path}: {e}")
941
+ return {"exists": False, "error": str(e)}"
942
 
943
  @staticmethod
944
  def save_image(image: Image.Image,
 
967
  logger.error(f"Failed to save image to {output_path}: {e}")
968
  return False
969
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970
  # ============================================================================
971
  # DEFAULT INSTANCES
972
  # ============================================================================