File size: 28,794 Bytes
ce98582
30c8cdc
 
 
 
cf7819d
30c8cdc
 
3f0776a
30c8cdc
3f0776a
ce98582
3f0776a
 
 
 
30c8cdc
cf7819d
30c8cdc
 
3f0776a
 
 
 
ce98582
3f0776a
 
 
 
 
6a59263
ce98582
6a59263
ce98582
 
 
 
 
6a59263
 
 
 
 
 
ce98582
 
d8ac97c
6a59263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ac97c
 
6a59263
 
 
 
 
 
d8ac97c
 
6a59263
 
 
 
 
 
d8ac97c
 
6a59263
 
 
 
 
d8ac97c
 
6a59263
 
 
 
 
 
 
 
d8ac97c
ce98582
6a59263
 
 
 
 
 
d8ac97c
 
6a59263
 
 
 
 
 
d8ac97c
6a59263
 
d8ac97c
6a59263
d8ac97c
ce98582
6a59263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ac97c
6a59263
ce98582
6a59263
 
ce98582
6a59263
 
d8ac97c
6a59263
 
 
 
d8ac97c
6a59263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ac97c
 
 
6a59263
 
ce98582
 
6a59263
 
 
 
 
 
d8ac97c
 
ce98582
 
6a59263
d8ac97c
ce98582
6a59263
 
 
 
 
 
 
 
 
 
d8ac97c
ce98582
6a59263
 
 
 
 
 
 
 
 
 
 
ce98582
6a59263
d8ac97c
6a59263
 
ce98582
6a59263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce98582
6a59263
 
d8ac97c
6a59263
d8ac97c
ce98582
6a59263
 
 
 
 
 
 
d8ac97c
ce98582
d8ac97c
6a59263
d8ac97c
6a59263
d8ac97c
ce98582
6a59263
 
 
 
 
 
 
 
 
 
d8ac97c
6a59263
ce98582
6a59263
 
 
 
 
 
 
 
ce98582
6a59263
ce98582
6a59263
d8ac97c
6a59263
 
 
 
ce98582
 
6a59263
d8ac97c
6a59263
 
 
 
 
ce98582
 
 
6a59263
 
ce98582
6a59263
ce98582
6a59263
d8ac97c
 
6a59263
 
 
 
 
 
 
ce98582
6a59263
 
 
 
 
ce98582
6a59263
ce98582
6a59263
 
 
 
 
 
 
d8ac97c
6a59263
 
d8ac97c
 
6a59263
 
30c8cdc
6a59263
30c8cdc
3f0776a
6a59263
30c8cdc
3f0776a
 
30c8cdc
b3f99d4
3f0776a
 
 
30c8cdc
 
 
 
cf7819d
3f0776a
 
30c8cdc
3f0776a
 
 
 
 
 
 
 
30c8cdc
3f0776a
 
30c8cdc
ce98582
3f0776a
30c8cdc
3f0776a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf7819d
6a59263
30c8cdc
3f0776a
b3f99d4
 
3f0776a
30c8cdc
b3f99d4
30c8cdc
 
 
3f0776a
 
b3f99d4
30c8cdc
3f0776a
30c8cdc
6a59263
 
 
 
 
 
 
 
d8ac97c
6a59263
 
ce98582
6a59263
 
ce98582
6a59263
 
30c8cdc
3f0776a
 
 
ce98582
3f0776a
 
 
 
 
6a59263
ce98582
cf7819d
6a59263
 
 
 
d8ac97c
6a59263
3f0776a
6a59263
d8ac97c
6a59263
ce98582
30c8cdc
6a59263
 
 
 
 
 
 
 
d8ac97c
6a59263
 
 
 
 
 
30c8cdc
ce98582
30c8cdc
 
6a59263
b3f99d4
3f0776a
6a59263
3f0776a
6a59263
 
b3f99d4
6a59263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3f99d4
6a59263
 
 
 
b3f99d4
 
 
 
 
 
6a59263
b3f99d4
30c8cdc
3f0776a
 
 
 
6a59263
30c8cdc
 
cf7819d
6a59263
ce98582
30c8cdc
6a59263
ce98582
 
 
30c8cdc
ce98582
 
 
 
6a59263
ce98582
 
 
6a59263
30c8cdc
ce98582
30c8cdc
6a59263
 
ce98582
 
6a59263
30c8cdc
 
ce98582
30c8cdc
ce98582
30c8cdc
6a59263
ce98582
6a59263
ce98582
 
 
 
 
 
6a59263
ce98582
 
6a59263
 
 
ce98582
30c8cdc
 
ce98582
 
6a59263
ce98582
 
30c8cdc
cf7819d
ce98582
6a59263
 
ce98582
30c8cdc
 
 
 
6a59263
ce98582
30c8cdc
6a59263
30c8cdc
6a59263
30c8cdc
 
6a59263
 
ce98582
 
 
d8ac97c
 
6a59263
d8ac97c
6a59263
 
 
 
d8ac97c
6a59263
 
 
 
 
 
d8ac97c
6a59263
d8ac97c
30c8cdc
 
6a59263
ce98582
30c8cdc
6a59263
 
 
 
30c8cdc
b3f99d4
30c8cdc
 
ce98582
6a59263
ce98582
 
b3f99d4
30c8cdc
6a59263
30c8cdc
cf7819d
ce98582
6a59263
ce98582
6a59263
 
ce98582
6a59263
30c8cdc
 
6a59263
 
 
d8ac97c
ce98582
30c8cdc
 
 
3f0776a
ce98582
 
30c8cdc
 
 
 
6a59263
30c8cdc
 
 
 
cf7819d
30c8cdc
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
import spaces
import gradio as gr
import torch
from PIL import Image
import numpy as np
from clip_interrogator import Config, Interrogator
import logging
import os
import warnings
from datetime import datetime
import gc
import re

warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
os.environ["TOKENIZERS_PARALLELISM"] = "false"

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def get_device():
    if torch.cuda.is_available():
        return "cuda"
    elif torch.backends.mps.is_available():
        return "mps"
    else:
        return "cpu"

DEVICE = get_device()

class MaximumFluxAnalyzer:
    """
    Maximum depth analysis engine - extracts EVERYTHING possible from images
    """
    
    def __init__(self):
        self.forbidden_elements = ["++", "weights", "white background [en dev]"]
        
        # EXPANDED VOCABULARIES FOR MAXIMUM DETECTION
        
        self.age_keywords = {
            "elderly": ["old", "elderly", "aged", "senior", "mature", "weathered", "wrinkled", "gray", "grey", "white hair", "silver", "graying", "ancient", "vintage"],
            "middle": ["middle-aged", "adult", "grown", "middle", "forties", "fifties"],
            "young": ["young", "youth", "teenage", "boy", "girl", "child", "kid", "adolescent"]
        }
        
        self.facial_features = {
            "beard_full": ["beard", "bearded", "facial hair", "full beard", "thick beard", "heavy beard"],
            "beard_color": ["gray beard", "grey beard", "silver beard", "white beard", "salt pepper", "graying beard"],
            "mustache": ["mustache", "moustache", "facial hair"],
            "glasses": ["glasses", "spectacles", "eyeglasses", "wire-frame", "rimmed glasses", "reading glasses"],
            "eyes": ["eyes", "gaze", "stare", "looking", "piercing", "intense", "deep eyes"],
            "wrinkles": ["wrinkled", "lines", "aged", "weathered", "creased"],
            "expression": ["serious", "contemplative", "thoughtful", "stern", "wise", "solemn"]
        }
        
        self.religious_cultural = {
            "jewish": ["jewish", "orthodox", "hasidic", "rabbi", "religious", "traditional", "ceremonial"],
            "hat_types": ["hat", "cap", "yarmulke", "kippah", "black hat", "traditional hat", "religious headwear"],
            "clothing": ["suit", "jacket", "formal", "black clothing", "traditional dress", "religious attire"]
        }
        
        self.hair_descriptors = {
            "color": ["gray", "grey", "silver", "white", "black", "brown", "blonde", "salt and pepper"],
            "texture": ["curly", "wavy", "straight", "thick", "thin", "coarse", "fine"],
            "style": ["long", "short", "receding", "balding", "full head"]
        }
        
        self.setting_environments = {
            "indoor": ["indoor", "inside", "interior", "room", "office", "home", "building"],
            "formal": ["formal setting", "office", "meeting room", "conference", "official"],
            "religious": ["synagogue", "temple", "religious", "ceremonial", "sacred"],
            "studio": ["studio", "backdrop", "professional", "photography studio"],
            "casual": ["casual", "relaxed", "informal", "comfortable"]
        }
        
        self.lighting_types = {
            "natural": ["natural light", "window light", "daylight", "sunlight"],
            "artificial": ["artificial light", "lamp", "electric", "indoor lighting"],
            "dramatic": ["dramatic", "contrast", "shadow", "chiaroscuro", "moody"],
            "soft": ["soft", "gentle", "diffused", "even", "flattering"],
            "harsh": ["harsh", "direct", "strong", "bright", "intense"]
        }
        
        self.composition_styles = {
            "portrait": ["portrait", "headshot", "face", "facial", "close-up", "bust"],
            "seated": ["sitting", "seated", "chair", "sitting down"],
            "standing": ["standing", "upright", "vertical"],
            "three_quarter": ["three quarter", "three-quarter", "angled", "turned"]
        }
        
        self.quality_adjectives = {
            "age_based": {
                "elderly": ["distinguished", "dignified", "venerable", "wise", "weathered", "experienced"],
                "middle": ["professional", "mature", "confident", "established"],
                "young": ["youthful", "fresh", "vibrant", "energetic"]
            },
            "cultural": ["traditional", "Orthodox", "religious", "ceremonial", "devout"],
            "general": ["elegant", "refined", "sophisticated", "classic", "timeless"]
        }
    
    def extract_maximum_info(self, clip_fast, clip_classic, clip_best):
        """Combine all three CLIP analyses for maximum information extraction"""
        
        # Combine all analyses
        combined_text = f"{clip_fast} {clip_classic} {clip_best}".lower()
        
        analysis = {
            "age": None,
            "age_confidence": 0,
            "gender": None,
            "facial_features": [],
            "hair_description": [],
            "clothing_items": [],
            "cultural_religious": [],
            "setting": None,
            "lighting": None,
            "composition": None,
            "mood": None,
            "technical_suggestions": {}
        }
        
        # DEEP AGE DETECTION
        age_scores = {"elderly": 0, "middle": 0, "young": 0}
        for age_type, keywords in self.age_keywords.items():
            for keyword in keywords:
                if keyword in combined_text:
                    age_scores[age_type] += 1
        
        if max(age_scores.values()) > 0:
            analysis["age"] = max(age_scores, key=age_scores.get)
            analysis["age_confidence"] = age_scores[analysis["age"]]
        
        # GENDER DETECTION
        if any(word in combined_text for word in ["man", "male", "gentleman", "guy", "he", "his"]):
            analysis["gender"] = "man"
        elif any(word in combined_text for word in ["woman", "female", "lady", "she", "her"]):
            analysis["gender"] = "woman"
        
        # COMPREHENSIVE FACIAL FEATURES
        if any(word in combined_text for word in self.facial_features["beard_full"]):
            if any(word in combined_text for word in self.facial_features["beard_color"]):
                analysis["facial_features"].append("silver beard")
            else:
                analysis["facial_features"].append("full beard")
        
        if any(word in combined_text for word in self.facial_features["glasses"]):
            analysis["facial_features"].append("wire-frame glasses")
        
        if any(word in combined_text for word in self.facial_features["wrinkles"]):
            analysis["facial_features"].append("weathered features")
        
        # HAIR ANALYSIS
        hair_colors = [color for color in self.hair_descriptors["color"] if color in combined_text]
        if hair_colors:
            analysis["hair_description"].extend(hair_colors)
        
        # CULTURAL/RELIGIOUS DETECTION
        if any(word in combined_text for word in self.religious_cultural["jewish"]):
            analysis["cultural_religious"].append("Orthodox Jewish")
        
        if any(word in combined_text for word in self.religious_cultural["hat_types"]):
            analysis["clothing_items"].append("traditional black hat")
        
        if any(word in combined_text for word in self.religious_cultural["clothing"]):
            analysis["clothing_items"].append("formal religious attire")
        
        # ENHANCED SETTING DETECTION
        setting_scores = {}
        for setting_type, keywords in self.setting_environments.items():
            score = sum(1 for keyword in keywords if keyword in combined_text)
            if score > 0:
                setting_scores[setting_type] = score
        
        if setting_scores:
            analysis["setting"] = max(setting_scores, key=setting_scores.get)
        
        # LIGHTING ANALYSIS
        lighting_detected = []
        for light_type, keywords in self.lighting_types.items():
            if any(keyword in combined_text for keyword in keywords):
                lighting_detected.append(light_type)
        
        if lighting_detected:
            analysis["lighting"] = lighting_detected[0]  # Take first/strongest match
        
        # COMPOSITION DETECTION
        for comp_type, keywords in self.composition_styles.items():
            if any(keyword in combined_text for keyword in keywords):
                analysis["composition"] = comp_type
                break
        
        # TECHNICAL SUGGESTIONS BASED ON ANALYSIS
        if analysis["composition"] == "portrait":
            analysis["technical_suggestions"] = {
                "lens": "85mm lens",
                "aperture": "f/2.8 aperture",
                "camera": "Shot on Phase One XF"
            }
        elif analysis["composition"] == "seated":
            analysis["technical_suggestions"] = {
                "lens": "85mm lens", 
                "aperture": "f/4 aperture",
                "camera": "Shot on Phase One"
            }
        else:
            analysis["technical_suggestions"] = {
                "lens": "50mm lens",
                "aperture": "f/2.8 aperture", 
                "camera": "Shot on Phase One"
            }
        
        return analysis
    
    def build_maximum_flux_prompt(self, analysis, original_clips):
        """Build the most detailed Flux prompt possible"""
        components = []
        
        # 1. INTELLIGENT ARTICLE SELECTION
        if analysis["cultural_religious"] and analysis["age"]:
            # "An elderly Orthodox Jewish man"
            article = "An" if analysis["age"] == "elderly" else "A"
        elif analysis["gender"]:
            article = "A"
        else:
            article = "A"
        components.append(article)
        
        # 2. CONTEXT-AWARE ADJECTIVES (max 2-3 per Flux rules)
        adjectives = []
        
        if analysis["age"] and analysis["age"] in self.quality_adjectives["age_based"]:
            adjectives.extend(self.quality_adjectives["age_based"][analysis["age"]][:2])
        
        if analysis["cultural_religious"]:
            adjectives.extend(self.quality_adjectives["cultural"][:1])
        
        if not adjectives:
            adjectives = self.quality_adjectives["general"][:2]
        
        # Limit to 2-3 adjectives as per Flux rules
        components.extend(adjectives[:2])
        
        # 3. ENHANCED SUBJECT DESCRIPTION
        subject_parts = []
        
        if analysis["cultural_religious"]:
            subject_parts.extend(analysis["cultural_religious"])
        
        if analysis["age"] and analysis["age"] != "middle":
            subject_parts.append(analysis["age"])
        
        if analysis["gender"]:
            subject_parts.append(analysis["gender"])
        else:
            subject_parts.append("person")
        
        main_subject = " ".join(subject_parts)
        components.append(main_subject)
        
        # 4. DETAILED FACIAL FEATURES
        if analysis["facial_features"]:
            feature_desc = "with " + " and ".join(analysis["facial_features"])
            components.append(feature_desc)
        
        # 5. CLOTHING AND ACCESSORIES
        if analysis["clothing_items"]:
            clothing_desc = "wearing " + " and ".join(analysis["clothing_items"])
            components.append(clothing_desc)
        
        # 6. ACTION/POSE (based on composition)
        action_map = {
            "seated": "seated in contemplative pose",
            "standing": "standing with dignified presence", 
            "portrait": "captured in intimate portrait style",
            "three_quarter": "positioned in three-quarter view"
        }
        
        if analysis["composition"]:
            action = action_map.get(analysis["composition"], "positioned thoughtfully")
        else:
            action = "positioned with natural composure"
        components.append(action)
        
        # 7. ENHANCED ENVIRONMENTAL CONTEXT
        setting_descriptions = {
            "indoor": "in a warmly lit indoor environment",
            "formal": "in a professional formal setting",
            "religious": "in a traditional religious space",
            "studio": "in a controlled studio environment",
            "casual": "in a comfortable informal setting"
        }
        
        if analysis["setting"]:
            context = setting_descriptions.get(analysis["setting"], "in a thoughtfully composed environment")
        else:
            context = "within a carefully arranged scene"
        components.append(context)
        
        # 8. SOPHISTICATED LIGHTING DESCRIPTION
        lighting_descriptions = {
            "natural": "bathed in gentle natural lighting that enhances facial texture and depth",
            "dramatic": "illuminated by dramatic lighting that creates compelling shadows and highlights",
            "soft": "softly lit to emphasize character and warmth",
            "artificial": "under controlled artificial lighting for optimal detail capture"
        }
        
        if analysis["lighting"]:
            lighting_desc = lighting_descriptions.get(analysis["lighting"], "with professional lighting that emphasizes facial features and texture")
        else:
            lighting_desc = "captured with sophisticated portrait lighting that brings out intricate facial details"
        
        components.append(lighting_desc)
        
        # 9. TECHNICAL SPECIFICATIONS
        tech_parts = []
        if analysis["technical_suggestions"]:
            tech_parts.append(analysis["technical_suggestions"]["camera"])
            tech_parts.append(analysis["technical_suggestions"]["lens"])
            tech_parts.append(analysis["technical_suggestions"]["aperture"])
        else:
            tech_parts = ["Shot on Phase One", "85mm lens", "f/2.8 aperture"]
        
        components.append(", ".join(tech_parts))
        
        # 10. QUALITY MARKER
        components.append("professional portrait photography")
        
        # FINAL ASSEMBLY AND OPTIMIZATION
        prompt = ", ".join(components)
        
        # Clean up the prompt
        prompt = re.sub(r'\s+', ' ', prompt)  # Remove extra spaces
        prompt = re.sub(r',\s*,', ',', prompt)  # Remove double commas
        prompt = prompt.replace(" ,", ",")  # Fix spacing around commas
        
        # Ensure proper capitalization
        prompt = prompt[0].upper() + prompt[1:] if prompt else ""
        
        return prompt
    
    def calculate_maximum_score(self, prompt, analysis):
        """Calculate intelligence score based on depth of analysis"""
        score = 0
        max_possible = 100
        
        # Structure compliance (10 points)
        if prompt.startswith(("A", "An")):
            score += 10
        
        # Feature detection depth (20 points)
        feature_score = len(analysis["facial_features"]) * 5
        score += min(feature_score, 20)
        
        # Cultural/contextual awareness (20 points)
        if analysis["cultural_religious"]:
            score += 15
        if analysis["age"]:
            score += 5
        
        # Technical appropriateness (15 points)
        if "85mm" in prompt and analysis["composition"] in ["portrait", "seated"]:
            score += 15
        elif "50mm" in prompt:
            score += 10
        
        # Lighting sophistication (15 points)
        if "lighting" in prompt and len(prompt.split("lighting")[1].split(",")[0]) > 10:
            score += 15
        
        # Setting context (10 points)
        if analysis["setting"]:
            score += 10
        
        # Forbidden elements check (10 points)
        if not any(forbidden in prompt for forbidden in self.forbidden_elements):
            score += 10
        
        return min(score, max_possible)

class MaximumFluxOptimizer:
    def __init__(self):
        self.interrogator = None
        self.analyzer = MaximumFluxAnalyzer()
        self.usage_count = 0
        self.device = DEVICE
        self.is_initialized = False
    
    def initialize_model(self):
        if self.is_initialized:
            return True
            
        try:
            config = Config(
                clip_model_name="ViT-L-14/openai",
                download_cache=True,
                chunk_size=2048,
                quiet=True,
                device=self.device
            )
            
            self.interrogator = Interrogator(config)
            self.is_initialized = True
            
            if self.device == "cpu":
                gc.collect()
            else:
                torch.cuda.empty_cache()
                
            return True
            
        except Exception as e:
            logger.error(f"Initialization error: {e}")
            return False
    
    def optimize_image(self, image):
        if image is None:
            return None
            
        if isinstance(image, np.ndarray):
            image = Image.fromarray(image)
        elif not isinstance(image, Image.Image):
            image = Image.open(image)
        
        if image.mode != 'RGB':
            image = image.convert('RGB')
        
        max_size = 768 if self.device != "cpu" else 512
        if image.size[0] > max_size or image.size[1] > max_size:
            image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
        
        return image
    
    @spaces.GPU
    def generate_maximum_prompt(self, image):
        try:
            if not self.is_initialized:
                if not self.initialize_model():
                    return "❌ Model initialization failed.", "Please refresh and try again.", 0
            
            if image is None:
                return "❌ Please upload an image.", "No image provided.", 0
            
            self.usage_count += 1
            
            image = self.optimize_image(image)
            if image is None:
                return "❌ Image processing failed.", "Invalid image format.", 0
            
            start_time = datetime.now()
            
            # TRIPLE CLIP ANALYSIS FOR MAXIMUM INFORMATION
            logger.info("Starting MAXIMUM analysis - Triple CLIP interrogation")
            
            clip_fast = self.interrogator.interrogate_fast(image)
            clip_classic = self.interrogator.interrogate_classic(image) 
            clip_best = self.interrogator.interrogate(image)
            
            logger.info(f"CLIP Results:\nFast: {clip_fast}\nClassic: {clip_classic}\nBest: {clip_best}")
            
            # MAXIMUM DEPTH ANALYSIS
            deep_analysis = self.analyzer.extract_maximum_info(clip_fast, clip_classic, clip_best)
            
            # BUILD MAXIMUM QUALITY FLUX PROMPT
            optimized_prompt = self.analyzer.build_maximum_flux_prompt(deep_analysis, [clip_fast, clip_classic, clip_best])
            
            # CALCULATE INTELLIGENCE SCORE
            score = self.analyzer.calculate_maximum_score(optimized_prompt, deep_analysis)
            
            end_time = datetime.now()
            duration = (end_time - start_time).total_seconds()
            
            # Memory cleanup
            if self.device == "cpu":
                gc.collect()
            else:
                torch.cuda.empty_cache()
            
            # COMPREHENSIVE ANALYSIS REPORT
            gpu_status = "⚑ ZeroGPU" if torch.cuda.is_available() else "πŸ’» CPU"
            
            # Format detected elements
            features = ", ".join(deep_analysis["facial_features"]) if deep_analysis["facial_features"] else "None detected"
            cultural = ", ".join(deep_analysis["cultural_religious"]) if deep_analysis["cultural_religious"] else "None detected"
            clothing = ", ".join(deep_analysis["clothing_items"]) if deep_analysis["clothing_items"] else "None detected"
            
            analysis_info = f"""**MAXIMUM ANALYSIS COMPLETE**

**Processing:** {gpu_status} β€’ {duration:.1f}s β€’ Triple CLIP interrogation  
**Intelligence Score:** {score}/100  
**Analysis Confidence:** {deep_analysis.get("age_confidence", 0)} age indicators detected  
**Generation:** #{self.usage_count}  

**DEEP DETECTION RESULTS:**
β€’ **Age Category:** {deep_analysis.get("age", "Unspecified").title()}
β€’ **Cultural Context:** {cultural}  
β€’ **Facial Features:** {features}
β€’ **Clothing/Accessories:** {clothing}
β€’ **Setting:** {deep_analysis.get("setting", "Standard").title()}
β€’ **Composition:** {deep_analysis.get("composition", "Standard").title()}
β€’ **Lighting:** {deep_analysis.get("lighting", "Standard").title()}

**CLIP ANALYSIS SOURCES:**
β€’ **Fast:** {clip_fast[:60]}...
β€’ **Classic:** {clip_classic[:60]}...  
β€’ **Best:** {clip_best[:60]}...

**FLUX OPTIMIZATION:** Applied maximum depth analysis with Pariente AI research rules"""
            
            return optimized_prompt, analysis_info, score
            
        except Exception as e:
            logger.error(f"Maximum generation error: {e}")
            return f"❌ Error: {str(e)}", "Please try with a different image.", 0

optimizer = MaximumFluxOptimizer()

def process_maximum_analysis(image):
    """Maximum analysis wrapper"""
    try:
        prompt, info, score = optimizer.generate_maximum_prompt(image)
        
        # Enhanced score display
        if score >= 90:
            color = "#10b981"
            grade = "EXCELLENT"
        elif score >= 80:
            color = "#22c55e" 
            grade = "VERY GOOD"
        elif score >= 70:
            color = "#f59e0b"
            grade = "GOOD"
        elif score >= 60:
            color = "#f97316"
            grade = "FAIR"
        else:
            color = "#ef4444"
            grade = "NEEDS WORK"
            
        score_html = f'''
        <div style="text-align: center; padding: 1.5rem; background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%); border: 2px solid {color}; border-radius: 12px; margin: 1rem 0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
            <div style="font-size: 2.5rem; font-weight: 700; color: {color}; margin: 0;">{score}</div>
            <div style="font-size: 1rem; color: #15803d; margin: 0; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 600;">{grade}</div>
            <div style="font-size: 0.875rem; color: #15803d; margin: 0; text-transform: uppercase; letter-spacing: 0.05em;">Maximum Intelligence Score</div>
        </div>
        '''
        
        return prompt, info, score_html
        
    except Exception as e:
        logger.error(f"Maximum wrapper error: {e}")
        return "❌ Processing failed", f"Error: {str(e)}", '<div style="text-align: center; color: red;">Error</div>'

def clear_outputs():
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    return "", "", '<div style="text-align: center; padding: 1rem;"><div style="font-size: 2rem; color: #ccc;">--</div><div style="font-size: 0.875rem; color: #999;">Maximum Intelligence Score</div></div>'

def create_interface():
    css = """
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
    
    .gradio-container {
        max-width: 1400px !important;
        margin: 0 auto !important;
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%) !important;
    }
    
    .main-header {
        text-align: center;
        padding: 2rem 0 3rem 0;
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #334155 100%);
        color: white;
        margin: -2rem -2rem 2rem -2rem;
        border-radius: 0 0 24px 24px;
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
    }
    
    .main-title {
        font-size: 3rem !important;
        font-weight: 800 !important;
        margin: 0 0 0.5rem 0 !important;
        letter-spacing: -0.025em !important;
        background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 50%, #2563eb 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .subtitle {
        font-size: 1.25rem !important;
        font-weight: 400 !important;
        opacity: 0.9 !important;
        margin: 0 !important;
    }
    
    .prompt-output {
        font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace !important;
        font-size: 14px !important;
        line-height: 1.7 !important;
        background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%) !important;
        border: 1px solid #e2e8f0 !important;
        border-radius: 16px !important;
        padding: 2rem !important;
        box-shadow: 0 8px 25px -5px rgba(0, 0, 0, 0.1) !important;
    }
    """
    
    with gr.Blocks(
        theme=gr.themes.Soft(),
        title="Maximum Flux Prompt Optimizer",
        css=css
    ) as interface:
        
        gr.HTML("""
        <div class="main-header">
            <div class="main-title">🧠 Maximum Flux Optimizer</div>
            <div class="subtitle">Triple CLIP Analysis β€’ Maximum Intelligence β€’ Zero Configuration</div>
        </div>
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("## πŸ”¬ Maximum Analysis")
                
                image_input = gr.Image(
                    label="Upload your image for maximum analysis",
                    type="pil",
                    height=450
                )
                
                analyze_btn = gr.Button(
                    "πŸš€ MAXIMUM ANALYSIS",
                    variant="primary",
                    size="lg"
                )
                
                gr.Markdown("""
                ### Maximum Intelligence Engine
                
                **Triple CLIP Interrogation:**
                β€’ Fast analysis for broad context
                β€’ Classic analysis for detailed features  
                β€’ Best analysis for maximum depth
                
                **Deep Feature Extraction:**
                β€’ Age, gender, cultural context
                β€’ Facial features, expressions, accessories
                β€’ Clothing, religious/cultural indicators
                β€’ Environmental setting and lighting
                β€’ Composition and technical optimization
                
                **No configuration needed** - Maximum intelligence applied automatically.
                """)
            
            with gr.Column(scale=1):
                gr.Markdown("## ⚑ Maximum Result")
                
                prompt_output = gr.Textbox(
                    label="Maximum Optimized Flux Prompt",
                    placeholder="Upload an image to see the maximum intelligence analysis...",
                    lines=10,
                    max_lines=15,
                    elem_classes=["prompt-output"],
                    show_copy_button=True
                )
                
                score_output = gr.HTML(
                    value='<div style="text-align: center; padding: 1rem;"><div style="font-size: 2rem; color: #ccc;">--</div><div style="font-size: 0.875rem; color: #999;">Maximum Intelligence Score</div></div>'
                )
                
                info_output = gr.Markdown(value="")
                
                clear_btn = gr.Button("πŸ—‘οΈ Clear Analysis", size="sm")
        
        gr.Markdown("""
        ---
        ### πŸ”¬ Maximum Research Foundation
        
        This system represents the absolute maximum in image analysis and Flux prompt optimization. Using triple CLIP interrogation 
        and deep feature extraction, it identifies every possible detail and applies research-validated Flux rules with maximum intelligence.
        
        **Pariente AI Research Laboratory** β€’ Maximum Intelligence β€’ Research-Driven β€’ Zero Compromise
        """)
        
        # Maximum event handlers
        analyze_btn.click(
            fn=process_maximum_analysis,
            inputs=[image_input],
            outputs=[prompt_output, info_output, score_output]
        )
        
        clear_btn.click(
            fn=clear_outputs,
            outputs=[prompt_output, info_output, score_output]
        )
    
    return interface

if __name__ == "__main__":
    logger.info("πŸš€ Starting MAXIMUM Flux Prompt Optimizer")
    interface = create_interface()
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True
    )