File size: 45,789 Bytes
7d583e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
import gc
import logging
import time
import traceback
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple, Union

import cv2
import numpy as np
import torch
from PIL import Image, ImageFilter

from diffusers import ControlNetModel, DPMSolverMultistepScheduler
from diffusers import StableDiffusionXLControlNetInpaintPipeline
from diffusers import StableDiffusionXLInpaintPipeline
from transformers import AutoImageProcessor, AutoModelForDepthEstimation
from transformers import DPTImageProcessor, DPTForDepthEstimation

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


@dataclass
class InpaintingConfig:
    """Configuration for inpainting operations."""

    # ControlNet settings
    controlnet_conditioning_scale: float = 0.7
    conditioning_type: str = "canny"  # "canny" or "depth"

    # Canny edge detection parameters
    canny_low_threshold: int = 100
    canny_high_threshold: int = 200

    # Mask settings
    feather_radius: int = 8
    min_mask_coverage: float = 0.01
    max_mask_coverage: float = 0.95

    # Generation settings
    num_inference_steps: int = 25
    guidance_scale: float = 7.5
    preview_steps: int = 15
    preview_guidance_scale: float = 8.0

    # Quality settings
    enable_auto_optimization: bool = True
    max_optimization_retries: int = 3
    min_quality_score: float = 70.0

    # Memory settings
    enable_vae_tiling: bool = True
    enable_attention_slicing: bool = True
    max_resolution: int = 1024


@dataclass
class InpaintingResult:
    """Result container for inpainting operations."""

    success: bool
    result_image: Optional[Image.Image] = None
    preview_image: Optional[Image.Image] = None
    control_image: Optional[Image.Image] = None
    blended_image: Optional[Image.Image] = None
    quality_score: float = 0.0
    quality_details: Dict[str, Any] = field(default_factory=dict)
    generation_time: float = 0.0
    retries: int = 0
    error_message: str = ""
    metadata: Dict[str, Any] = field(default_factory=dict)


class InpaintingModule:
    """
    ControlNet-based Inpainting Module for SceneWeaver.

    Implements StableDiffusionXLControlNetInpaintPipeline with support for
    Canny edge and depth map conditioning. Features two-stage generation
    (preview + full quality) and automatic quality optimization.

    Attributes:
        device: Computation device (cuda/mps/cpu)
        config: InpaintingConfig instance
        is_initialized: Whether pipeline is loaded

    Example:
        >>> module = InpaintingModule(device="cuda")
        >>> module.load_inpainting_pipeline(progress_callback=my_callback)
        >>> result = module.execute_inpainting(
        ...     image=my_image,
        ...     mask=my_mask,
        ...     prompt="a beautiful garden"
        ... )
    """

    # Model identifiers
    CONTROLNET_CANNY_MODEL = "diffusers/controlnet-canny-sdxl-1.0"
    CONTROLNET_DEPTH_MODEL = "diffusers/controlnet-depth-sdxl-1.0"
    DEPTH_MODEL_PRIMARY = "LiheYoung/depth-anything-small-hf"
    DEPTH_MODEL_FALLBACK = "Intel/dpt-hybrid-midas"
    BASE_MODEL = "stabilityai/stable-diffusion-xl-base-1.0"

    def __init__(
        self,
        device: str = "auto",
        config: Optional[InpaintingConfig] = None
    ):
        """
        Initialize the InpaintingModule.

        Parameters
        ----------
        device : str, optional
            Computation device. "auto" for automatic detection.
        config : InpaintingConfig, optional
            Configuration object. Uses defaults if not provided.
        """
        self.device = self._setup_device(device)
        self.config = config or InpaintingConfig()

        # Pipeline instances (lazy loaded)
        self._inpaint_pipeline = None
        self._controlnet_canny = None
        self._controlnet_depth = None
        self._depth_estimator = None
        self._depth_processor = None

        # State tracking
        self.is_initialized = False
        self._current_conditioning_type = None
        self._last_seed = None
        self._cached_latents = None
        self._use_controlnet = True  # Track if ControlNet is available

        # Reference to model manager (set by SceneWeaverCore)
        self._model_manager = None

        logger.info(f"InpaintingModule initialized on {self.device}")

    def _setup_device(self, device: str) -> str:
        """
        Setup computation device.

        Parameters
        ----------
        device : str
            Device specification or "auto"

        Returns
        -------
        str
            Resolved device name
        """
        if device == "auto":
            if torch.cuda.is_available():
                return "cuda"
            elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
                return "mps"
            return "cpu"
        return device

    def set_model_manager(self, manager: Any) -> None:
        """
        Set reference to ModelManager for coordinated model lifecycle.

        Parameters
        ----------
        manager : ModelManager
            The global model manager instance
        """
        self._model_manager = manager
        logger.info("ModelManager reference set for InpaintingModule")

    def _memory_cleanup(self, aggressive: bool = False) -> None:
        """
        Perform memory cleanup.

        Parameters
        ----------
        aggressive : bool
            If True, perform multiple GC rounds and sync CUDA
        """
        rounds = 5 if aggressive else 2
        for _ in range(rounds):
            gc.collect()

        if torch.cuda.is_available():
            torch.cuda.empty_cache()
            if aggressive:
                torch.cuda.ipc_collect()
                torch.cuda.synchronize()

        logger.debug(f"Memory cleanup completed (aggressive={aggressive})")

    def _check_memory_status(self) -> Dict[str, float]:
        """
        Check current GPU memory status.

        Returns
        -------
        dict
            Memory statistics including allocated, total, and usage ratio
        """
        if not torch.cuda.is_available():
            return {"available": True, "usage_ratio": 0.0}

        allocated = torch.cuda.memory_allocated() / 1024**3
        total = torch.cuda.get_device_properties(0).total_memory / 1024**3
        usage_ratio = allocated / total

        return {
            "allocated_gb": round(allocated, 2),
            "total_gb": round(total, 2),
            "free_gb": round(total - allocated, 2),
            "usage_ratio": round(usage_ratio, 3),
            "available": usage_ratio < 0.9
        }

    def load_inpainting_pipeline(
        self,
        conditioning_type: str = "canny",
        progress_callback: Optional[Callable[[str, int], None]] = None
    ) -> Tuple[bool, str]:
        """
        Load the ControlNet inpainting pipeline.

        Implements mutual exclusion with background generation pipeline.
        Only one pipeline can be loaded at a time.

        Parameters
        ----------
        conditioning_type : str
            Type of ControlNet conditioning: "canny" or "depth"
        progress_callback : callable, optional
            Function(message, percentage) for progress updates

        Returns
        -------
        tuple
            (success: bool, error_message: str)
        """
        if self.is_initialized and self._current_conditioning_type == conditioning_type:
            logger.info(f"Inpainting pipeline already loaded with {conditioning_type}")
            return True, ""

        logger.info(f"Loading inpainting pipeline with {conditioning_type} conditioning...")

        try:
            self._memory_cleanup(aggressive=True)

            if progress_callback:
                progress_callback("Preparing to load inpainting models...", 5)

            # Unload existing pipeline if different conditioning type
            if self._inpaint_pipeline is not None:
                self._unload_pipeline()

            # Use ControlNet inpainting by default
            use_controlnet_inpaint = True
            logger.info("Using StableDiffusionXLControlNetInpaintPipeline")

            if progress_callback:
                progress_callback("Loading ControlNet model...", 20)

            # Load appropriate ControlNet
            dtype = torch.float16 if self.device == "cuda" else torch.float32
            controlnet = None

            if use_controlnet_inpaint:
                if conditioning_type == "canny":
                    controlnet = ControlNetModel.from_pretrained(
                        self.CONTROLNET_CANNY_MODEL,
                        torch_dtype=dtype,
                        use_safetensors=True
                    )
                    self._controlnet_canny = controlnet
                    logger.info("Loaded ControlNet Canny model")

                elif conditioning_type == "depth":
                    controlnet = ControlNetModel.from_pretrained(
                        self.CONTROLNET_DEPTH_MODEL,
                        torch_dtype=dtype,
                        use_safetensors=True
                    )
                    self._controlnet_depth = controlnet

                    # Load depth estimator
                    if progress_callback:
                        progress_callback("Loading depth estimation model...", 35)
                    self._load_depth_estimator()
                    logger.info("Loaded ControlNet Depth model")
                else:
                    raise ValueError(f"Unknown conditioning type: {conditioning_type}")
            else:
                # Skip ControlNet loading for fallback mode
                logger.info(f"Skipping ControlNet loading (fallback mode)")

            if progress_callback:
                progress_callback("Loading SDXL Inpainting pipeline...", 50)

            # Load the inpainting pipeline
            if use_controlnet_inpaint and controlnet is not None:
                self._inpaint_pipeline = StableDiffusionXLControlNetInpaintPipeline.from_pretrained(
                    self.BASE_MODEL,
                    controlnet=controlnet,
                    torch_dtype=dtype,
                    use_safetensors=True,
                    variant="fp16" if dtype == torch.float16 else None
                )
            else:
                # Fallback: Use dedicated inpainting model without ControlNet
                self._inpaint_pipeline = StableDiffusionXLInpaintPipeline.from_pretrained(
                    "diffusers/stable-diffusion-xl-1.0-inpainting-0.1",
                    torch_dtype=dtype,
                    use_safetensors=True,
                    variant="fp16" if dtype == torch.float16 else None
                )
                self._use_controlnet = False

            # Track ControlNet usage
            self._use_controlnet = use_controlnet_inpaint and controlnet is not None

            if progress_callback:
                progress_callback("Configuring scheduler...", 70)

            # Configure scheduler for faster generation
            self._inpaint_pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
                self._inpaint_pipeline.scheduler.config
            )

            # Move to device
            self._inpaint_pipeline = self._inpaint_pipeline.to(self.device)

            if progress_callback:
                progress_callback("Applying optimizations...", 85)

            # Apply memory optimizations
            self._apply_pipeline_optimizations()

            # Set eval mode
            self._inpaint_pipeline.unet.eval()
            if hasattr(self._inpaint_pipeline, 'vae'):
                self._inpaint_pipeline.vae.eval()

            self.is_initialized = True
            self._current_conditioning_type = conditioning_type if self._use_controlnet else "none"

            if progress_callback:
                progress_callback("Inpainting pipeline ready!", 100)

            # Log memory status
            mem_status = self._check_memory_status()
            logger.info(f"Pipeline loaded. GPU memory: {mem_status.get('allocated_gb', 0):.1f}GB used")

            return True, ""

        except Exception as e:
            error_msg = str(e)
            logger.error(f"Failed to load inpainting pipeline: {error_msg}")
            traceback.print_exc()
            self._unload_pipeline()
            return False, error_msg

    def _load_depth_estimator(self) -> None:
        """
        Load depth estimation model with fallback strategy.

        Tries Depth-Anything first, falls back to MiDaS if unavailable.
        """
        try:
            logger.info(f"Attempting to load depth model: {self.DEPTH_MODEL_PRIMARY}")

            self._depth_processor = AutoImageProcessor.from_pretrained(
                self.DEPTH_MODEL_PRIMARY
            )
            self._depth_estimator = AutoModelForDepthEstimation.from_pretrained(
                self.DEPTH_MODEL_PRIMARY,
                torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
            )
            self._depth_estimator.to(self.device)
            self._depth_estimator.eval()

            logger.info("Successfully loaded Depth-Anything model")

        except Exception as e:
            logger.warning(f"Primary depth model failed: {e}, trying fallback...")

            try:
                self._depth_processor = DPTImageProcessor.from_pretrained(
                    self.DEPTH_MODEL_FALLBACK
                )
                self._depth_estimator = DPTForDepthEstimation.from_pretrained(
                    self.DEPTH_MODEL_FALLBACK,
                    torch_dtype=torch.float16 if self.device == "cuda" else torch.float32
                )
                self._depth_estimator.to(self.device)
                self._depth_estimator.eval()

                logger.info("Successfully loaded MiDaS fallback model")

            except Exception as fallback_e:
                logger.error(f"Fallback depth model also failed: {fallback_e}")
                raise RuntimeError("Unable to load any depth estimation model")

    def _apply_pipeline_optimizations(self) -> None:
        """Apply memory and performance optimizations to the pipeline."""
        if self._inpaint_pipeline is None:
            return

        # Try xformers first
        try:
            self._inpaint_pipeline.enable_xformers_memory_efficient_attention()
            logger.info("Enabled xformers memory efficient attention")
        except Exception:
            try:
                self._inpaint_pipeline.enable_attention_slicing()
                logger.info("Enabled attention slicing")
            except Exception:
                logger.warning("No attention optimization available")

        # VAE optimizations
        if self.config.enable_vae_tiling:
            if hasattr(self._inpaint_pipeline, 'enable_vae_tiling'):
                self._inpaint_pipeline.enable_vae_tiling()
                logger.debug("Enabled VAE tiling")

        if hasattr(self._inpaint_pipeline, 'enable_vae_slicing'):
            self._inpaint_pipeline.enable_vae_slicing()
            logger.debug("Enabled VAE slicing")

    def _unload_pipeline(self) -> None:
        """Unload the inpainting pipeline and free memory."""
        logger.info("Unloading inpainting pipeline...")

        if self._inpaint_pipeline is not None:
            del self._inpaint_pipeline
            self._inpaint_pipeline = None

        if self._controlnet_canny is not None:
            del self._controlnet_canny
            self._controlnet_canny = None

        if self._controlnet_depth is not None:
            del self._controlnet_depth
            self._controlnet_depth = None

        if self._depth_estimator is not None:
            del self._depth_estimator
            self._depth_estimator = None

        if self._depth_processor is not None:
            del self._depth_processor
            self._depth_processor = None

        self.is_initialized = False
        self._current_conditioning_type = None
        self._cached_latents = None

        self._memory_cleanup(aggressive=True)
        logger.info("Inpainting pipeline unloaded")

    def prepare_control_image(
        self,
        image: Image.Image,
        mode: str = "canny"
    ) -> Image.Image:
        """
        Generate ControlNet conditioning image.

        Parameters
        ----------
        image : PIL.Image
            Input image
        mode : str
            Conditioning mode: "canny" or "depth"

        Returns
        -------
        PIL.Image
            Generated control image (edges or depth map)
        """
        logger.info(f"Preparing control image with mode: {mode}")

        # Convert to RGB if needed
        if image.mode != 'RGB':
            image = image.convert('RGB')

        img_array = np.array(image)

        if mode == "canny":
            return self._generate_canny_edges(img_array)
        elif mode == "depth":
            return self._generate_depth_map(image)
        else:
            raise ValueError(f"Unknown control mode: {mode}")

    def _generate_canny_edges(self, img_array: np.ndarray) -> Image.Image:
        """
        Generate Canny edge detection image.

        Parameters
        ----------
        img_array : np.ndarray
            Input image as RGB numpy array

        Returns
        -------
        PIL.Image
            Edge detection result as grayscale image
        """
        # Convert to grayscale
        gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)

        # Apply Gaussian blur to reduce noise
        blurred = cv2.GaussianBlur(gray, (5, 5), 1.4)

        # Canny edge detection
        edges = cv2.Canny(
            blurred,
            self.config.canny_low_threshold,
            self.config.canny_high_threshold
        )

        # Convert to 3-channel for ControlNet
        edges_3ch = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)

        logger.debug(f"Generated Canny edges with thresholds "
                    f"{self.config.canny_low_threshold}/{self.config.canny_high_threshold}")

        return Image.fromarray(edges_3ch)

    def _generate_depth_map(self, image: Image.Image) -> Image.Image:
        """
        Generate depth map using depth estimation model.

        Parameters
        ----------
        image : PIL.Image
            Input RGB image

        Returns
        -------
        PIL.Image
            Depth map as grayscale image
        """
        if self._depth_estimator is None or self._depth_processor is None:
            raise RuntimeError("Depth estimator not loaded")

        # Preprocess
        inputs = self._depth_processor(images=image, return_tensors="pt")
        inputs = {k: v.to(self.device) for k, v in inputs.items()}

        # Inference
        with torch.no_grad():
            outputs = self._depth_estimator(**inputs)
            predicted_depth = outputs.predicted_depth

        # Interpolate to original size
        prediction = torch.nn.functional.interpolate(
            predicted_depth.unsqueeze(1),
            size=image.size[::-1],  # (H, W)
            mode="bicubic",
            align_corners=False
        )

        # Normalize to 0-255
        depth_array = prediction.squeeze().cpu().numpy()
        depth_min = depth_array.min()
        depth_max = depth_array.max()

        if depth_max - depth_min > 0:
            depth_normalized = ((depth_array - depth_min) / (depth_max - depth_min) * 255)
        else:
            depth_normalized = np.zeros_like(depth_array)

        depth_normalized = depth_normalized.astype(np.uint8)

        # Convert to 3-channel for ControlNet
        depth_3ch = cv2.cvtColor(depth_normalized, cv2.COLOR_GRAY2RGB)

        logger.debug(f"Generated depth map, range: {depth_min:.2f} - {depth_max:.2f}")

        return Image.fromarray(depth_3ch)

    def prepare_mask(
        self,
        mask: Image.Image,
        target_size: Tuple[int, int],
        feather_radius: Optional[int] = None
    ) -> Tuple[Image.Image, Dict[str, Any]]:
        """
        Prepare and validate mask for inpainting.

        Parameters
        ----------
        mask : PIL.Image
            Input mask (white = inpaint area)
        target_size : tuple
            Target (width, height) to match input image
        feather_radius : int, optional
            Feathering radius in pixels. Uses config default if None.

        Returns
        -------
        tuple
            (processed_mask, validation_info)

        Raises
        ------
        ValueError
            If mask coverage is outside acceptable range
        """
        feather = feather_radius if feather_radius is not None else self.config.feather_radius

        # Convert to grayscale
        if mask.mode != 'L':
            mask = mask.convert('L')

        # Resize to match target
        if mask.size != target_size:
            mask = mask.resize(target_size, Image.LANCZOS)

        # Convert to array for processing
        mask_array = np.array(mask)

        # Calculate coverage
        total_pixels = mask_array.size
        white_pixels = np.count_nonzero(mask_array > 127)
        coverage = white_pixels / total_pixels

        validation_info = {
            "coverage": coverage,
            "white_pixels": white_pixels,
            "total_pixels": total_pixels,
            "feather_radius": feather,
            "valid": True,
            "warning": ""
        }

        # Validate coverage
        if coverage < self.config.min_mask_coverage:
            validation_info["valid"] = False
            validation_info["warning"] = (
                f"Mask coverage too low ({coverage:.1%}). "
                f"Please select a larger area to inpaint."
            )
            logger.warning(f"Mask coverage {coverage:.1%} below minimum {self.config.min_mask_coverage:.1%}")

        elif coverage > self.config.max_mask_coverage:
            validation_info["valid"] = False
            validation_info["warning"] = (
                f"Mask coverage too high ({coverage:.1%}). "
                f"Consider using background generation instead."
            )
            logger.warning(f"Mask coverage {coverage:.1%} above maximum {self.config.max_mask_coverage:.1%}")

        # Apply feathering
        if feather > 0:
            mask_array = cv2.GaussianBlur(
                mask_array,
                (feather * 2 + 1, feather * 2 + 1),
                feather / 2
            )
            logger.debug(f"Applied {feather}px feathering to mask")

        processed_mask = Image.fromarray(mask_array, mode='L')

        return processed_mask, validation_info

    def enhance_prompt_for_inpainting(
        self,
        prompt: str,
        image: Image.Image,
        mask: Image.Image
    ) -> Tuple[str, str]:
        """
        Enhance prompt based on non-masked region analysis.

        Analyzes the surrounding context to generate appropriate
        lighting and color descriptors.

        Parameters
        ----------
        prompt : str
            User-provided prompt
        image : PIL.Image
            Original image
        mask : PIL.Image
            Inpainting mask

        Returns
        -------
        tuple
            (enhanced_prompt, negative_prompt)
        """
        logger.info("Enhancing prompt for inpainting context...")

        # Convert to arrays
        img_array = np.array(image.convert('RGB'))
        mask_array = np.array(mask.convert('L'))

        # Analyze non-masked regions
        non_masked = mask_array < 127

        if not np.any(non_masked):
            # No context available
            enhanced_prompt = f"{prompt}, high quality, detailed, photorealistic"
            negative_prompt = self._get_inpainting_negative_prompt()
            return enhanced_prompt, negative_prompt

        # Extract context pixels
        context_pixels = img_array[non_masked]

        # Convert to Lab for analysis
        context_lab = cv2.cvtColor(
            context_pixels.reshape(-1, 1, 3),
            cv2.COLOR_RGB2LAB
        ).reshape(-1, 3)

        # Use robust statistics (median) to avoid outlier influence
        median_l = np.median(context_lab[:, 0])
        median_a = np.median(context_lab[:, 1])
        median_b = np.median(context_lab[:, 2])

        # Analyze lighting conditions
        lighting_descriptors = []

        if median_l > 170:
            lighting_descriptors.append("bright")
        elif median_l > 130:
            lighting_descriptors.append("well-lit")
        elif median_l > 80:
            lighting_descriptors.append("moderate lighting")
        else:
            lighting_descriptors.append("dim lighting")

        # Analyze color temperature (b channel: blue(-) to yellow(+))
        if median_b > 140:
            lighting_descriptors.append("warm golden tones")
        elif median_b > 120:
            lighting_descriptors.append("warm afternoon light")
        elif median_b < 110:
            lighting_descriptors.append("cool neutral tones")

        # Calculate saturation from context
        hsv = cv2.cvtColor(context_pixels.reshape(-1, 1, 3), cv2.COLOR_RGB2HSV)
        median_saturation = np.median(hsv[:, :, 1])

        if median_saturation > 150:
            lighting_descriptors.append("vibrant colors")
        elif median_saturation < 80:
            lighting_descriptors.append("subtle muted colors")

        # Build enhanced prompt
        lighting_desc = ", ".join(lighting_descriptors) if lighting_descriptors else ""
        quality_suffix = "high quality, detailed, photorealistic, seamless integration"

        if lighting_desc:
            enhanced_prompt = f"{prompt}, {lighting_desc}, {quality_suffix}"
        else:
            enhanced_prompt = f"{prompt}, {quality_suffix}"

        negative_prompt = self._get_inpainting_negative_prompt()

        logger.info(f"Enhanced prompt with context: {lighting_desc}")

        return enhanced_prompt, negative_prompt

    def _get_inpainting_negative_prompt(self) -> str:
        """Get standard negative prompt for inpainting."""
        return (
            "inconsistent lighting, wrong perspective, mismatched colors, "
            "visible seams, blending artifacts, color bleeding, "
            "blurry, low quality, distorted, deformed, "
            "harsh edges, unnatural transition"
        )

    def execute_inpainting(
        self,
        image: Image.Image,
        mask: Image.Image,
        prompt: str,
        preview_only: bool = False,
        seed: Optional[int] = None,
        progress_callback: Optional[Callable[[str, int], None]] = None,
        **kwargs
    ) -> InpaintingResult:
        """
        Execute the inpainting operation.

        Implements two-stage generation: fast preview followed by
        full quality generation if requested.

        Parameters
        ----------
        image : PIL.Image
            Original image to inpaint
        mask : PIL.Image
            Inpainting mask (white = area to regenerate)
        prompt : str
            Text description of desired content
        preview_only : bool
            If True, only generate preview (faster)
        seed : int, optional
            Random seed for reproducibility
        progress_callback : callable, optional
            Progress update function(message, percentage)
        **kwargs
            Additional parameters:
            - controlnet_conditioning_scale: float
            - feather_radius: int
            - num_inference_steps: int
            - guidance_scale: float

        Returns
        -------
        InpaintingResult
            Result container with generated images and metadata
        """
        start_time = time.time()

        if not self.is_initialized:
            return InpaintingResult(
                success=False,
                error_message="Inpainting pipeline not initialized. Call load_inpainting_pipeline() first."
            )

        logger.info(f"Starting inpainting: prompt='{prompt[:50]}...', preview_only={preview_only}")

        try:
            # Update config with kwargs
            conditioning_scale = kwargs.get(
                'controlnet_conditioning_scale',
                self.config.controlnet_conditioning_scale
            )
            feather_radius = kwargs.get('feather_radius', self.config.feather_radius)

            if progress_callback:
                progress_callback("Preparing images...", 5)

            # Prepare image
            if image.mode != 'RGB':
                image = image.convert('RGB')

            # Ensure dimensions are multiple of 8
            width, height = image.size
            new_width = (width // 8) * 8
            new_height = (height // 8) * 8

            if new_width != width or new_height != height:
                image = image.resize((new_width, new_height), Image.LANCZOS)

            # Check and potentially reduce resolution for memory
            max_res = self.config.max_resolution
            if max(new_width, new_height) > max_res:
                scale = max_res / max(new_width, new_height)
                new_width = int(new_width * scale) // 8 * 8
                new_height = int(new_height * scale) // 8 * 8
                image = image.resize((new_width, new_height), Image.LANCZOS)
                logger.info(f"Reduced resolution to {new_width}x{new_height} for memory")

            # Prepare mask
            if progress_callback:
                progress_callback("Processing mask...", 10)

            processed_mask, mask_info = self.prepare_mask(
                mask,
                (new_width, new_height),
                feather_radius
            )

            if not mask_info["valid"]:
                return InpaintingResult(
                    success=False,
                    error_message=mask_info["warning"]
                )

            # Generate control image
            if progress_callback:
                progress_callback("Generating control image...", 20)

            control_image = self.prepare_control_image(
                image,
                self._current_conditioning_type
            )

            # Enhance prompt
            if progress_callback:
                progress_callback("Enhancing prompt...", 25)

            enhanced_prompt, negative_prompt = self.enhance_prompt_for_inpainting(
                prompt, image, processed_mask
            )

            # Setup generator for reproducibility
            if seed is None:
                seed = int(time.time() * 1000) % (2**32)
            self._last_seed = seed
            generator = torch.Generator(device=self.device).manual_seed(seed)

            # Stage 1: Preview generation
            if progress_callback:
                progress_callback("Generating preview...", 30)

            preview_result = self._generate_inpaint(
                image=image,
                mask=processed_mask,
                control_image=control_image,
                prompt=enhanced_prompt,
                negative_prompt=negative_prompt,
                num_inference_steps=self.config.preview_steps,
                guidance_scale=self.config.preview_guidance_scale,
                controlnet_conditioning_scale=conditioning_scale,
                generator=generator
            )

            if preview_only:
                generation_time = time.time() - start_time

                return InpaintingResult(
                    success=True,
                    preview_image=preview_result,
                    control_image=control_image,
                    generation_time=generation_time,
                    metadata={
                        "seed": seed,
                        "prompt": enhanced_prompt,
                        "conditioning_type": self._current_conditioning_type,
                        "conditioning_scale": conditioning_scale,
                        "preview_only": True
                    }
                )

            # Stage 2: Full quality generation
            if progress_callback:
                progress_callback("Generating full quality...", 60)

            # Use same seed for reproducibility
            generator = torch.Generator(device=self.device).manual_seed(seed)

            num_steps = kwargs.get('num_inference_steps', self.config.num_inference_steps)
            guidance = kwargs.get('guidance_scale', self.config.guidance_scale)

            full_result = self._generate_inpaint(
                image=image,
                mask=processed_mask,
                control_image=control_image,
                prompt=enhanced_prompt,
                negative_prompt=negative_prompt,
                num_inference_steps=num_steps,
                guidance_scale=guidance,
                controlnet_conditioning_scale=conditioning_scale,
                generator=generator
            )

            if progress_callback:
                progress_callback("Blending result...", 90)

            # Blend result
            blended = self.blend_result(image, full_result, processed_mask)

            generation_time = time.time() - start_time

            if progress_callback:
                progress_callback("Complete!", 100)

            return InpaintingResult(
                success=True,
                result_image=full_result,
                preview_image=preview_result,
                control_image=control_image,
                blended_image=blended,
                generation_time=generation_time,
                metadata={
                    "seed": seed,
                    "prompt": enhanced_prompt,
                    "negative_prompt": negative_prompt,
                    "conditioning_type": self._current_conditioning_type,
                    "conditioning_scale": conditioning_scale,
                    "num_inference_steps": num_steps,
                    "guidance_scale": guidance,
                    "feather_radius": feather_radius,
                    "mask_coverage": mask_info["coverage"],
                    "preview_only": False
                }
            )

        except torch.cuda.OutOfMemoryError:
            logger.error("CUDA out of memory during inpainting")
            self._memory_cleanup(aggressive=True)
            return InpaintingResult(
                success=False,
                error_message="GPU memory exhausted. Try reducing image size or closing other applications."
            )

        except Exception as e:
            logger.error(f"Inpainting failed: {e}")
            logger.error(traceback.format_exc())
            return InpaintingResult(
                success=False,
                error_message=f"Inpainting failed: {str(e)}"
            )

    def _generate_inpaint(
        self,
        image: Image.Image,
        mask: Image.Image,
        control_image: Image.Image,
        prompt: str,
        negative_prompt: str,
        num_inference_steps: int,
        guidance_scale: float,
        controlnet_conditioning_scale: float,
        generator: torch.Generator
    ) -> Image.Image:
        """
        Internal method to run the inpainting pipeline.

        Supports both ControlNet and non-ControlNet pipelines.

        Parameters
        ----------
        image : PIL.Image
            Original image
        mask : PIL.Image
            Processed mask
        control_image : PIL.Image
            ControlNet conditioning image (ignored if ControlNet not available)
        prompt : str
            Enhanced prompt
        negative_prompt : str
            Negative prompt
        num_inference_steps : int
            Number of denoising steps
        guidance_scale : float
            Classifier-free guidance scale
        controlnet_conditioning_scale : float
            ControlNet influence strength (ignored if ControlNet not available)
        generator : torch.Generator
            Random generator for reproducibility

        Returns
        -------
        PIL.Image
            Generated image
        """
        with torch.inference_mode():
            if self._use_controlnet:
                # Full ControlNet inpainting pipeline
                result = self._inpaint_pipeline(
                    prompt=prompt,
                    negative_prompt=negative_prompt,
                    image=image,
                    mask_image=mask,
                    control_image=control_image,
                    num_inference_steps=num_inference_steps,
                    guidance_scale=guidance_scale,
                    controlnet_conditioning_scale=controlnet_conditioning_scale,
                    generator=generator
                )
            else:
                # Fallback: Standard SDXL inpainting without ControlNet
                result = self._inpaint_pipeline(
                    prompt=prompt,
                    negative_prompt=negative_prompt,
                    image=image,
                    mask_image=mask,
                    num_inference_steps=num_inference_steps,
                    guidance_scale=guidance_scale,
                    generator=generator
                )

        return result.images[0]

    def blend_result(
        self,
        original: Image.Image,
        generated: Image.Image,
        mask: Image.Image
    ) -> Image.Image:
        """
        Blend generated content with original image.

        Uses linear color space blending for accurate results.

        Parameters
        ----------
        original : PIL.Image
            Original image
        generated : PIL.Image
            Generated inpainted image
        mask : PIL.Image
            Blending mask (white = use generated)

        Returns
        -------
        PIL.Image
            Blended result
        """
        logger.info("Blending inpainting result...")

        # Ensure same size
        if generated.size != original.size:
            generated = generated.resize(original.size, Image.LANCZOS)
        if mask.size != original.size:
            mask = mask.resize(original.size, Image.LANCZOS)

        # Convert to arrays
        orig_array = np.array(original.convert('RGB')).astype(np.float32)
        gen_array = np.array(generated.convert('RGB')).astype(np.float32)
        mask_array = np.array(mask.convert('L')).astype(np.float32) / 255.0

        # sRGB to linear conversion
        def srgb_to_linear(img):
            img_norm = img / 255.0
            return np.where(
                img_norm <= 0.04045,
                img_norm / 12.92,
                np.power((img_norm + 0.055) / 1.055, 2.4)
            )

        def linear_to_srgb(img):
            img_clipped = np.clip(img, 0, 1)
            return np.where(
                img_clipped <= 0.0031308,
                12.92 * img_clipped,
                1.055 * np.power(img_clipped, 1/2.4) - 0.055
            )

        # Convert to linear space
        orig_linear = srgb_to_linear(orig_array)
        gen_linear = srgb_to_linear(gen_array)

        # Alpha blending in linear space
        alpha = mask_array[:, :, np.newaxis]
        result_linear = gen_linear * alpha + orig_linear * (1 - alpha)

        # Convert back to sRGB
        result_srgb = linear_to_srgb(result_linear)
        result_array = (result_srgb * 255).astype(np.uint8)

        logger.debug("Blending completed in linear color space")

        return Image.fromarray(result_array)

    def execute_with_auto_optimization(
        self,
        image: Image.Image,
        mask: Image.Image,
        prompt: str,
        quality_checker: Any,
        progress_callback: Optional[Callable[[str, int], None]] = None,
        **kwargs
    ) -> InpaintingResult:
        """
        Execute inpainting with automatic quality-based optimization.

        Retries with adjusted parameters if quality score is below threshold.

        Parameters
        ----------
        image : PIL.Image
            Original image
        mask : PIL.Image
            Inpainting mask
        prompt : str
            Text prompt
        quality_checker : QualityChecker
            Quality assessment instance
        progress_callback : callable, optional
            Progress update function
        **kwargs
            Additional inpainting parameters

        Returns
        -------
        InpaintingResult
            Best result achieved (may include retry information)
        """
        if not self.config.enable_auto_optimization:
            return self.execute_inpainting(
                image, mask, prompt,
                progress_callback=progress_callback,
                **kwargs
            )

        best_result = None
        best_score = 0.0
        retry_count = 0
        prev_score = 0.0

        # Mutable parameters for optimization
        current_feather = kwargs.get('feather_radius', self.config.feather_radius)
        current_scale = kwargs.get(
            'controlnet_conditioning_scale',
            self.config.controlnet_conditioning_scale
        )
        current_guidance = kwargs.get('guidance_scale', self.config.guidance_scale)
        current_prompt = prompt

        while retry_count <= self.config.max_optimization_retries:
            if progress_callback and retry_count > 0:
                progress_callback(f"Optimizing (attempt {retry_count + 1})...", 5)

            # Execute inpainting
            result = self.execute_inpainting(
                image, mask, current_prompt,
                preview_only=False,
                feather_radius=current_feather,
                controlnet_conditioning_scale=current_scale,
                guidance_scale=current_guidance,
                progress_callback=progress_callback if retry_count == 0 else None,
                **{k: v for k, v in kwargs.items()
                   if k not in ['feather_radius', 'controlnet_conditioning_scale',
                               'guidance_scale']}
            )

            if not result.success:
                return result

            # Evaluate quality
            if result.blended_image is not None:
                quality_results = quality_checker.run_all_checks(
                    foreground=image,
                    background=result.result_image,
                    mask=mask,
                    combined=result.blended_image
                )
                quality_score = quality_results.get("overall_score", 0)
            else:
                quality_score = 50.0  # Default if no blended image

            result.quality_score = quality_score
            result.quality_details = quality_results if result.blended_image else {}
            result.retries = retry_count

            logger.info(f"Quality score: {quality_score:.1f} (attempt {retry_count + 1})")

            # Track best result
            if quality_score > best_score:
                best_score = quality_score
                best_result = result

            # Check if quality is acceptable
            if quality_score >= self.config.min_quality_score:
                logger.info(f"Quality threshold met: {quality_score:.1f}")
                return best_result

            # Check for minimal improvement (early termination)
            if retry_count > 0 and abs(quality_score - prev_score) < 5.0:
                logger.info("Minimal improvement, stopping optimization")
                return best_result

            prev_score = quality_score
            retry_count += 1

            if retry_count > self.config.max_optimization_retries:
                break

            # Adjust parameters based on quality issues
            checks = quality_results.get("checks", {})

            edge_score = checks.get("edge_continuity", {}).get("score", 100)
            harmony_score = checks.get("color_harmony", {}).get("score", 100)

            if edge_score < 60:
                # Edge issues: increase feathering, decrease control strength
                current_feather = min(20, current_feather + 3)
                current_scale = max(0.5, current_scale - 0.1)
                logger.debug(f"Adjusting for edges: feather={current_feather}, scale={current_scale}")

            if harmony_score < 60:
                # Color harmony issues: emphasize consistency in prompt
                if "color consistent" not in current_prompt.lower():
                    current_prompt = f"{current_prompt}, color consistent with surroundings, matching lighting"
                current_guidance = min(12.0, current_guidance + 1.0)
                logger.debug(f"Adjusting for harmony: guidance={current_guidance}")

            if edge_score < 60 and harmony_score < 60:
                # Both issues: stronger guidance
                current_guidance = min(12.0, current_guidance + 1.5)

        logger.info(f"Optimization complete. Best score: {best_score:.1f}")
        return best_result

    def get_status(self) -> Dict[str, Any]:
        """
        Get current module status.

        Returns
        -------
        dict
            Status information including initialization state and memory usage
        """
        status = {
            "initialized": self.is_initialized,
            "device": self.device,
            "conditioning_type": self._current_conditioning_type,
            "last_seed": self._last_seed,
            "config": {
                "controlnet_conditioning_scale": self.config.controlnet_conditioning_scale,
                "feather_radius": self.config.feather_radius,
                "num_inference_steps": self.config.num_inference_steps,
                "guidance_scale": self.config.guidance_scale
            }
        }

        status["memory"] = self._check_memory_status()

        return status