Malaji71 commited on
Commit
47fab0c
·
verified ·
1 Parent(s): be92860

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -647
app.py CHANGED
@@ -1,664 +1,49 @@
1
- import spaces
 
 
 
2
  import gradio as gr
3
  import torch
4
- from PIL import Image
5
- import numpy as np
6
- from clip_interrogator import Config, Interrogator
7
  import logging
8
- import os
9
  import warnings
10
- from datetime import datetime
11
- import gc
12
- import re
13
- import math
14
 
 
15
  warnings.filterwarnings("ignore", category=FutureWarning)
16
  warnings.filterwarnings("ignore", category=UserWarning)
17
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
18
 
 
19
  logging.basicConfig(level=logging.INFO)
20
  logger = logging.getLogger(__name__)
21
 
22
- def get_device():
23
- if torch.cuda.is_available():
24
- return "cuda"
25
- elif torch.backends.mps.is_available():
26
- return "mps"
27
- else:
28
- return "cpu"
29
-
30
- DEVICE = get_device()
31
-
32
- class UltraSupremeAnalyzer:
33
- """
34
- ULTRA SUPREME ANALYSIS ENGINE - ABSOLUTE MAXIMUM INTELLIGENCE
35
- """
36
-
37
- def __init__(self):
38
- self.forbidden_elements = ["++", "weights", "white background [en dev]"]
39
-
40
- self.micro_age_indicators = {
41
- "infant": ["baby", "infant", "newborn", "toddler"],
42
- "child": ["child", "kid", "young", "little", "small", "youth"],
43
- "teen": ["teenager", "teen", "adolescent", "young adult", "student"],
44
- "young_adult": ["young adult", "twenties", "thirty", "youthful", "fresh"],
45
- "middle_aged": ["middle-aged", "forties", "fifties", "mature", "experienced"],
46
- "senior": ["senior", "older", "elderly", "aged", "vintage", "seasoned"],
47
- "elderly": ["elderly", "old", "ancient", "weathered", "aged", "gray", "grey", "white hair", "silver", "wrinkled", "lined", "creased", "time-worn", "distinguished by age"]
48
- }
49
- self.ultra_facial_analysis = {
50
- "eye_features": {
51
- "shape": ["round eyes", "almond eyes", "narrow eyes", "wide eyes", "deep-set eyes", "prominent eyes"],
52
- "expression": ["intense gaze", "piercing stare", "gentle eyes", "wise eyes", "tired eyes", "alert eyes", "contemplative stare", "focused gaze", "distant look"],
53
- "color": ["brown eyes", "blue eyes", "green eyes", "hazel eyes", "dark eyes", "light eyes"],
54
- "condition": ["clear eyes", "bloodshot", "bright eyes", "dull eyes", "sparkling eyes"]
55
- },
56
- "eyebrow_analysis": ["thick eyebrows", "thin eyebrows", "bushy eyebrows", "arched eyebrows", "straight eyebrows", "gray eyebrows"],
57
- "nose_features": ["prominent nose", "straight nose", "aquiline nose", "small nose", "wide nose", "narrow nose"],
58
- "mouth_expression": {
59
- "shape": ["thin lips", "full lips", "small mouth", "wide mouth"],
60
- "expression": ["slight smile", "serious expression", "frown", "neutral expression", "contemplative look", "stern look", "gentle expression"]
61
- },
62
- "facial_hair_ultra": {
63
- "beard_types": ["full beard", "goatee", "mustache", "stubble", "clean-shaven", "five o'clock shadow"],
64
- "beard_texture": ["thick beard", "thin beard", "coarse beard", "fine beard", "well-groomed beard", "unkempt beard"],
65
- "beard_color": ["black beard", "brown beard", "gray beard", "grey beard", "silver beard", "white beard", "salt-and-pepper beard", "graying beard"],
66
- "beard_length": ["long beard", "short beard", "trimmed beard", "full-length beard"]
67
- },
68
- "skin_analysis": ["smooth skin", "weathered skin", "wrinkled skin", "clear skin", "rough skin", "aged skin", "youthful skin", "tanned skin", "pale skin", "olive skin"],
69
- "facial_structure": ["angular face", "round face", "oval face", "square jaw", "defined cheekbones", "high cheekbones", "strong jawline", "soft features", "sharp features"]
70
- }
71
-
72
- self.emotion_micro_expressions = {
73
- "primary_emotions": ["happy", "sad", "angry", "fearful", "surprised", "disgusted", "contemptuous"],
74
- "complex_emotions": ["contemplative", "melancholic", "serene", "intense", "peaceful", "troubled", "confident", "uncertain", "wise", "stern", "gentle", "authoritative"],
75
- "emotional_indicators": ["furrowed brow", "raised eyebrows", "squinted eyes", "pursed lips", "relaxed expression", "tense jaw", "soft eyes", "hard stare"]
76
- }
77
-
78
- self.cultural_religious_ultra = {
79
- "jewish_orthodox": ["Orthodox Jewish", "Hasidic", "Ultra-Orthodox", "religious Jewish", "traditional Jewish", "devout Jewish"],
80
- "christian": ["Christian", "Catholic", "Protestant", "Orthodox Christian", "religious Christian"],
81
- "muslim": ["Muslim", "Islamic", "religious Muslim", "devout Muslim"],
82
- "buddhist": ["Buddhist", "monk", "religious Buddhist"],
83
- "general_religious": ["religious", "devout", "pious", "spiritual", "faithful", "observant"],
84
- "traditional_clothing": {
85
- "jewish": ["yarmulke", "kippah", "tallit", "tzitzit", "black hat", "Orthodox hat", "religious hat", "traditional Jewish hat"],
86
- "general": ["religious garment", "traditional clothing", "ceremonial dress", "formal religious attire"]
87
- }
88
- }
89
- self.clothing_accessories_ultra = {
90
- "headwear": ["hat", "cap", "beret", "headband", "turban", "hood", "helmet", "crown", "headpiece"],
91
- "eyewear": ["glasses", "spectacles", "sunglasses", "reading glasses", "wire-frame glasses", "thick-rimmed glasses", "designer glasses", "vintage glasses"],
92
- "clothing_types": ["suit", "jacket", "shirt", "dress", "robe", "uniform", "casual wear", "formal wear", "business attire"],
93
- "clothing_styles": ["formal", "casual", "business", "traditional", "modern", "vintage", "classic", "contemporary"],
94
- "accessories": ["jewelry", "watch", "necklace", "ring", "bracelet", "earrings", "pin", "brooch"]
95
- }
96
-
97
- self.environmental_ultra_analysis = {
98
- "indoor_settings": {
99
- "residential": ["home", "house", "apartment", "living room", "bedroom", "kitchen", "dining room"],
100
- "office": ["office", "workplace", "conference room", "meeting room", "boardroom", "desk"],
101
- "institutional": ["school", "hospital", "government building", "court", "library"],
102
- "religious": ["church", "synagogue", "mosque", "temple", "chapel", "sanctuary"],
103
- "commercial": ["store", "restaurant", "hotel", "mall", "shop"]
104
- },
105
- "outdoor_settings": {
106
- "natural": ["park", "garden", "forest", "beach", "mountain", "countryside", "field"],
107
- "urban": ["street", "city", "downtown", "plaza", "square", "avenue"],
108
- "architectural": ["building", "monument", "bridge", "structure"]
109
- },
110
- "lighting_ultra": {
111
- "natural_light": ["sunlight", "daylight", "morning light", "afternoon light", "evening light", "golden hour", "blue hour", "overcast light", "window light"],
112
- "artificial_light": ["indoor lighting", "electric light", "lamp light", "overhead lighting", "side lighting", "fluorescent", "LED lighting"],
113
- "dramatic_lighting": ["high contrast", "low key", "high key", "chiaroscuro", "dramatic shadows", "rim lighting", "backlighting", "spotlight"],
114
- "quality": ["soft lighting", "hard lighting", "diffused light", "direct light", "ambient light", "mood lighting"]
115
- }
116
- }
117
-
118
- self.pose_body_language_ultra = {
119
- "head_position": ["head up", "head down", "head tilted", "head straight", "head turned", "profile view", "three-quarter view"],
120
- "posture": ["upright posture", "slouched", "relaxed posture", "formal posture", "casual stance", "dignified bearing"],
121
- "hand_positions": ["hands clasped", "hands folded", "hands visible", "hands hidden", "gesturing", "pointing"],
122
- "sitting_positions": ["sitting upright", "leaning forward", "leaning back", "sitting casually", "formal sitting"],
123
- "eye_contact": ["looking at camera", "looking away", "direct gaze", "averted gaze", "looking down", "looking up"],
124
- "overall_demeanor": ["confident", "reserved", "approachable", "authoritative", "gentle", "stern", "relaxed", "tense"]
125
- }
126
- self.composition_photography_ultra = {
127
- "shot_types": ["close-up", "medium shot", "wide shot", "extreme close-up", "portrait shot", "headshot", "bust shot", "full body"],
128
- "angles": ["eye level", "high angle", "low angle", "bird's eye", "worm's eye", "Dutch angle"],
129
- "framing": ["centered", "off-center", "rule of thirds", "tight framing", "loose framing"],
130
- "depth_of_field": ["shallow depth", "deep focus", "bokeh", "sharp focus", "soft focus"],
131
- "camera_movement": ["static", "handheld", "stabilized", "smooth"]
132
- }
133
-
134
- self.technical_photography_ultra = {
135
- "camera_systems": {
136
- "professional": ["Phase One XF", "Phase One XT", "Hasselblad X2D", "Fujifilm GFX", "Canon EOS R5", "Nikon Z9"],
137
- "medium_format": ["Phase One", "Hasselblad", "Fujifilm GFX", "Pentax 645"],
138
- "full_frame": ["Canon EOS R", "Nikon Z", "Sony A7", "Leica SL"]
139
- },
140
- "lenses_ultra": {
141
- "portrait": ["85mm f/1.4", "135mm f/2", "105mm f/1.4", "200mm f/2.8"],
142
- "standard": ["50mm f/1.4", "35mm f/1.4", "24-70mm f/2.8"],
143
- "wide": ["24mm f/1.4", "16-35mm f/2.8", "14mm f/2.8"]
144
- },
145
- "aperture_settings": ["f/1.4", "f/2", "f/2.8", "f/4", "f/5.6", "f/8"],
146
- "photography_styles": ["portrait photography", "documentary photography", "fine art photography", "commercial photography", "editorial photography"]
147
- }
148
-
149
- self.quality_descriptors_ultra = {
150
- "based_on_age": {
151
- "elderly": ["distinguished", "venerable", "dignified", "wise", "experienced", "seasoned", "time-honored", "revered", "weathered", "sage-like"],
152
- "middle_aged": ["professional", "accomplished", "established", "confident", "mature", "refined", "sophisticated"],
153
- "young_adult": ["vibrant", "energetic", "fresh", "youthful", "dynamic", "spirited", "lively"]
154
- },
155
- "based_on_emotion": {
156
- "contemplative": ["thoughtful", "reflective", "meditative", "introspective"],
157
- "confident": ["assured", "self-possessed", "commanding", "authoritative"],
158
- "gentle": ["kind", "warm", "compassionate", "tender"],
159
- "stern": ["serious", "grave", "solemn", "austere"]
160
- },
161
- "based_on_setting": {
162
- "formal": ["professional", "official", "ceremonial", "dignified"],
163
- "casual": ["relaxed", "informal", "comfortable", "natural"],
164
- "artistic": ["creative", "expressive", "aesthetic", "artistic"]
165
- }
166
- }
167
-
168
- def ultra_supreme_analysis(self, clip_fast, clip_classic, clip_best):
169
- """ULTRA SUPREME ANALYSIS - MAXIMUM POSSIBLE INTELLIGENCE"""
170
-
171
- combined_analysis = {
172
- "fast": clip_fast.lower(),
173
- "classic": clip_classic.lower(),
174
- "best": clip_best.lower(),
175
- "combined": f"{clip_fast} {clip_classic} {clip_best}".lower()
176
- }
177
-
178
- ultra_result = {
179
- "demographic": {"age_category": None, "age_confidence": 0, "gender": None, "cultural_religious": []},
180
- "facial_ultra": {"eyes": [], "eyebrows": [], "nose": [], "mouth": [], "facial_hair": [], "skin": [], "structure": []},
181
- "emotional_state": {"primary_emotion": None, "emotion_confidence": 0, "micro_expressions": [], "overall_demeanor": []},
182
- "clothing_accessories": {"headwear": [], "eyewear": [], "clothing": [], "accessories": []},
183
- "environmental": {"setting_type": None, "specific_location": None, "lighting_analysis": [], "atmosphere": []},
184
- "pose_composition": {"body_language": [], "head_position": [], "eye_contact": [], "posture": []},
185
- "technical_analysis": {"shot_type": None, "angle": None, "lighting_setup": None, "suggested_equipment": {}},
186
- "intelligence_metrics": {"total_features_detected": 0, "analysis_depth_score": 0, "cultural_awareness_score": 0, "technical_optimization_score": 0}
187
- }
188
- # ULTRA DEEP AGE ANALYSIS
189
- age_scores = {}
190
- for age_category, indicators in self.micro_age_indicators.items():
191
- score = sum(1 for indicator in indicators if indicator in combined_analysis["combined"])
192
- if score > 0:
193
- age_scores[age_category] = score
194
-
195
- if age_scores:
196
- ultra_result["demographic"]["age_category"] = max(age_scores, key=age_scores.get)
197
- ultra_result["demographic"]["age_confidence"] = age_scores[ultra_result["demographic"]["age_category"]]
198
-
199
- # GENDER DETECTION WITH CONFIDENCE
200
- male_indicators = ["man", "male", "gentleman", "guy", "he", "his", "masculine"]
201
- female_indicators = ["woman", "female", "lady", "she", "her", "feminine"]
202
-
203
- male_score = sum(1 for indicator in male_indicators if indicator in combined_analysis["combined"])
204
- female_score = sum(1 for indicator in female_indicators if indicator in combined_analysis["combined"])
205
-
206
- if male_score > female_score:
207
- ultra_result["demographic"]["gender"] = "man"
208
- elif female_score > male_score:
209
- ultra_result["demographic"]["gender"] = "woman"
210
-
211
- # ULTRA CULTURAL/RELIGIOUS ANALYSIS
212
- for culture_type, indicators in self.cultural_religious_ultra.items():
213
- if isinstance(indicators, list):
214
- for indicator in indicators:
215
- if indicator.lower() in combined_analysis["combined"]:
216
- ultra_result["demographic"]["cultural_religious"].append(indicator)
217
-
218
- # COMPREHENSIVE FACIAL FEATURE ANALYSIS
219
- for hair_category, features in self.ultra_facial_analysis["facial_hair_ultra"].items():
220
- for feature in features:
221
- if feature in combined_analysis["combined"]:
222
- ultra_result["facial_ultra"]["facial_hair"].append(feature)
223
-
224
- # Eyes analysis
225
- for eye_category, features in self.ultra_facial_analysis["eye_features"].items():
226
- for feature in features:
227
- if feature in combined_analysis["combined"]:
228
- ultra_result["facial_ultra"]["eyes"].append(feature)
229
-
230
- # EMOTION AND MICRO-EXPRESSION ANALYSIS
231
- emotion_scores = {}
232
- for emotion in self.emotion_micro_expressions["complex_emotions"]:
233
- if emotion in combined_analysis["combined"]:
234
- emotion_scores[emotion] = combined_analysis["combined"].count(emotion)
235
-
236
- if emotion_scores:
237
- ultra_result["emotional_state"]["primary_emotion"] = max(emotion_scores, key=emotion_scores.get)
238
- ultra_result["emotional_state"]["emotion_confidence"] = emotion_scores[ultra_result["emotional_state"]["primary_emotion"]]
239
-
240
- # CLOTHING AND ACCESSORIES ANALYSIS
241
- for category, items in self.clothing_accessories_ultra.items():
242
- if isinstance(items, list):
243
- for item in items:
244
- if item in combined_analysis["combined"]:
245
- if category == "clothing_types":
246
- ultra_result["clothing_accessories"]["clothing"].append(item)
247
- elif category == "clothing_styles":
248
- ultra_result["clothing_accessories"]["clothing"].append(item)
249
- elif category in ["headwear", "eyewear", "accessories"]:
250
- ultra_result["clothing_accessories"][category].append(item)
251
- # ENVIRONMENTAL ULTRA ANALYSIS
252
- setting_scores = {}
253
- for main_setting, sub_settings in self.environmental_ultra_analysis.items():
254
- if isinstance(sub_settings, dict):
255
- for sub_type, locations in sub_settings.items():
256
- score = sum(1 for location in locations if location in combined_analysis["combined"])
257
- if score > 0:
258
- setting_scores[sub_type] = score
259
-
260
- if setting_scores:
261
- ultra_result["environmental"]["setting_type"] = max(setting_scores, key=setting_scores.get)
262
-
263
- # LIGHTING ANALYSIS
264
- for light_category, light_types in self.environmental_ultra_analysis["lighting_ultra"].items():
265
- for light_type in light_types:
266
- if light_type in combined_analysis["combined"]:
267
- ultra_result["environmental"]["lighting_analysis"].append(light_type)
268
-
269
- # POSE AND BODY LANGUAGE ANALYSIS
270
- for pose_category, indicators in self.pose_body_language_ultra.items():
271
- for indicator in indicators:
272
- if indicator in combined_analysis["combined"]:
273
- if pose_category in ultra_result["pose_composition"]:
274
- ultra_result["pose_composition"][pose_category].append(indicator)
275
-
276
- # TECHNICAL PHOTOGRAPHY ANALYSIS
277
- for shot_type in self.composition_photography_ultra["shot_types"]:
278
- if shot_type in combined_analysis["combined"]:
279
- ultra_result["technical_analysis"]["shot_type"] = shot_type
280
- break
281
-
282
- # CALCULATE INTELLIGENCE METRICS
283
- total_features = sum(len(v) if isinstance(v, list) else (1 if v else 0) for category in ultra_result.values() if isinstance(category, dict) for v in category.values())
284
- ultra_result["intelligence_metrics"]["total_features_detected"] = total_features
285
- ultra_result["intelligence_metrics"]["analysis_depth_score"] = min(total_features * 5, 100)
286
- ultra_result["intelligence_metrics"]["cultural_awareness_score"] = len(ultra_result["demographic"]["cultural_religious"]) * 20
287
-
288
- return ultra_result
289
-
290
- def build_ultra_supreme_prompt(self, ultra_analysis, clip_results):
291
- """BUILD ULTRA SUPREME FLUX PROMPT - ABSOLUTE MAXIMUM QUALITY"""
292
-
293
- components = []
294
-
295
- # 1. ULTRA INTELLIGENT ARTICLE SELECTION
296
- subject_desc = []
297
- if ultra_analysis["demographic"]["cultural_religious"]:
298
- subject_desc.extend(ultra_analysis["demographic"]["cultural_religious"][:1])
299
- if ultra_analysis["demographic"]["age_category"] and ultra_analysis["demographic"]["age_category"] != "middle_aged":
300
- subject_desc.append(ultra_analysis["demographic"]["age_category"].replace("_", " "))
301
- if ultra_analysis["demographic"]["gender"]:
302
- subject_desc.append(ultra_analysis["demographic"]["gender"])
303
-
304
- if subject_desc:
305
- full_subject = " ".join(subject_desc)
306
- article = "An" if full_subject[0].lower() in 'aeiou' else "A"
307
- else:
308
- article = "A"
309
- components.append(article)
310
-
311
- # 2. ULTRA CONTEXTUAL ADJECTIVES (max 2-3 per Flux rules)
312
- adjectives = []
313
-
314
- # Age-based adjectives
315
- age_cat = ultra_analysis["demographic"]["age_category"]
316
- if age_cat and age_cat in self.quality_descriptors_ultra["based_on_age"]:
317
- adjectives.extend(self.quality_descriptors_ultra["based_on_age"][age_cat][:2])
318
-
319
- # Emotion-based adjectives
320
- emotion = ultra_analysis["emotional_state"]["primary_emotion"]
321
- if emotion and emotion in self.quality_descriptors_ultra["based_on_emotion"]:
322
- adjectives.extend(self.quality_descriptors_ultra["based_on_emotion"][emotion][:1])
323
-
324
- # Default if none found
325
- if not adjectives:
326
- adjectives = ["distinguished", "professional"]
327
-
328
- components.extend(adjectives[:2]) # Flux rule: max 2-3 adjectives
329
- # 3. ULTRA ENHANCED SUBJECT
330
- if subject_desc:
331
- components.append(" ".join(subject_desc))
332
- else:
333
- components.append("person")
334
-
335
- # 4. ULTRA DETAILED FACIAL FEATURES
336
- facial_details = []
337
-
338
- # Eyes
339
- if ultra_analysis["facial_ultra"]["eyes"]:
340
- eye_desc = ultra_analysis["facial_ultra"]["eyes"][0]
341
- facial_details.append(f"with {eye_desc}")
342
-
343
- # Facial hair with ultra detail
344
- if ultra_analysis["facial_ultra"]["facial_hair"]:
345
- beard_details = ultra_analysis["facial_ultra"]["facial_hair"]
346
- if any("silver" in detail or "gray" in detail or "grey" in detail for detail in beard_details):
347
- facial_details.append("with a distinguished silver beard")
348
- elif any("beard" in detail for detail in beard_details):
349
- facial_details.append("with a full well-groomed beard")
350
-
351
- if facial_details:
352
- components.extend(facial_details)
353
-
354
- # 5. CLOTHING AND ACCESSORIES ULTRA
355
- clothing_details = []
356
-
357
- # Eyewear
358
- if ultra_analysis["clothing_accessories"]["eyewear"]:
359
- eyewear = ultra_analysis["clothing_accessories"]["eyewear"][0]
360
- clothing_details.append(f"wearing {eyewear}")
361
-
362
- # Headwear
363
- if ultra_analysis["clothing_accessories"]["headwear"]:
364
- headwear = ultra_analysis["clothing_accessories"]["headwear"][0]
365
- if ultra_analysis["demographic"]["cultural_religious"]:
366
- clothing_details.append("wearing a traditional black hat")
367
- else:
368
- clothing_details.append(f"wearing a {headwear}")
369
-
370
- if clothing_details:
371
- components.extend(clothing_details)
372
-
373
- # 6. ULTRA POSE AND BODY LANGUAGE
374
- pose_description = "positioned with natural dignity"
375
-
376
- if ultra_analysis["pose_composition"]["posture"]:
377
- posture = ultra_analysis["pose_composition"]["posture"][0]
378
- pose_description = f"maintaining {posture}"
379
- elif ultra_analysis["technical_analysis"]["shot_type"] == "portrait":
380
- pose_description = "captured in contemplative portrait pose"
381
-
382
- components.append(pose_description)
383
-
384
- # 7. ULTRA ENVIRONMENTAL CONTEXT
385
- environment_desc = "in a thoughtfully composed environment"
386
-
387
- if ultra_analysis["environmental"]["setting_type"]:
388
- setting_map = {
389
- "residential": "in an intimate home setting",
390
- "office": "in a professional office environment",
391
- "religious": "in a sacred traditional space",
392
- "formal": "in a distinguished formal setting"
393
- }
394
- environment_desc = setting_map.get(ultra_analysis["environmental"]["setting_type"], "in a carefully arranged professional setting")
395
-
396
- components.append(environment_desc)
397
-
398
- # 8. ULTRA SOPHISTICATED LIGHTING
399
- lighting_desc = "illuminated by sophisticated portrait lighting that emphasizes character and facial texture"
400
-
401
- if ultra_analysis["environmental"]["lighting_analysis"]:
402
- primary_light = ultra_analysis["environmental"]["lighting_analysis"][0]
403
- if "dramatic" in primary_light:
404
- lighting_desc = "bathed in dramatic chiaroscuro lighting that creates compelling depth and shadow play"
405
- elif "natural" in primary_light or "window" in primary_light:
406
- lighting_desc = "graced by gentle natural lighting that brings out intricate facial details and warmth"
407
- elif "soft" in primary_light:
408
- lighting_desc = "softly illuminated to reveal nuanced expressions and character"
409
-
410
- components.append(lighting_desc)
411
- # 9. ULTRA TECHNICAL SPECIFICATIONS
412
- if ultra_analysis["technical_analysis"]["shot_type"] in ["portrait", "headshot", "close-up"]:
413
- camera_setup = "Shot on Phase One XF IQ4, 85mm f/1.4 lens, f/2.8 aperture"
414
- elif ultra_analysis["demographic"]["cultural_religious"]:
415
- camera_setup = "Shot on Hasselblad X2D, 90mm lens, f/2.8 aperture"
416
- else:
417
- camera_setup = "Shot on Phase One XF, 80mm lens, f/4 aperture"
418
-
419
- components.append(camera_setup)
420
-
421
- # 10. ULTRA QUALITY DESIGNATION
422
- quality_designation = "professional portrait photography"
423
-
424
- if ultra_analysis["demographic"]["cultural_religious"]:
425
- quality_designation = "fine art documentary photography"
426
- elif ultra_analysis["emotional_state"]["primary_emotion"]:
427
- quality_designation = "expressive portrait photography"
428
-
429
- components.append(quality_designation)
430
-
431
- # ULTRA FINAL ASSEMBLY
432
- prompt = ", ".join(components)
433
-
434
- # Ultra cleaning and optimization
435
- prompt = re.sub(r'\s+', ' ', prompt)
436
- prompt = re.sub(r',\s*,+', ',', prompt)
437
- prompt = re.sub(r'\s*,\s*', ', ', prompt)
438
- prompt = prompt.replace(" ,", ",")
439
-
440
- if prompt:
441
- prompt = prompt[0].upper() + prompt[1:]
442
-
443
- return prompt
444
-
445
- def calculate_ultra_supreme_score(self, prompt, ultra_analysis):
446
- """ULTRA SUPREME INTELLIGENCE SCORING"""
447
-
448
- score = 0
449
- breakdown = {}
450
-
451
- # Structure Excellence (15 points)
452
- structure_score = 0
453
- if prompt.startswith(("A", "An")):
454
- structure_score += 5
455
- if prompt.count(",") >= 8:
456
- structure_score += 10
457
- score += structure_score
458
- breakdown["structure"] = structure_score
459
-
460
- # Feature Detection Depth (25 points)
461
- features_score = min(ultra_analysis["intelligence_metrics"]["total_features_detected"] * 2, 25)
462
- score += features_score
463
- breakdown["features"] = features_score
464
-
465
- # Cultural/Religious Awareness (20 points)
466
- cultural_score = min(len(ultra_analysis["demographic"]["cultural_religious"]) * 10, 20)
467
- score += cultural_score
468
- breakdown["cultural"] = cultural_score
469
-
470
- # Emotional Intelligence (15 points)
471
- emotion_score = 0
472
- if ultra_analysis["emotional_state"]["primary_emotion"]:
473
- emotion_score += 10
474
- if ultra_analysis["emotional_state"]["emotion_confidence"] > 1:
475
- emotion_score += 5
476
- score += emotion_score
477
- breakdown["emotional"] = emotion_score
478
-
479
- # Technical Sophistication (15 points)
480
- tech_score = 0
481
- if "Phase One" in prompt or "Hasselblad" in prompt:
482
- tech_score += 5
483
- if any(aperture in prompt for aperture in ["f/1.4", "f/2.8", "f/4"]):
484
- tech_score += 5
485
- if any(lens in prompt for lens in ["85mm", "90mm", "80mm"]):
486
- tech_score += 5
487
- score += tech_score
488
- breakdown["technical"] = tech_score
489
-
490
- # Environmental Context (10 points)
491
- env_score = 0
492
- if ultra_analysis["environmental"]["setting_type"]:
493
- env_score += 5
494
- if ultra_analysis["environmental"]["lighting_analysis"]:
495
- env_score += 5
496
- score += env_score
497
- breakdown["environmental"] = env_score
498
-
499
- return min(score, 100), breakdown
500
-
501
- class UltraSupremeOptimizer:
502
- def __init__(self):
503
- self.interrogator = None
504
- self.analyzer = UltraSupremeAnalyzer()
505
- self.usage_count = 0
506
- self.device = DEVICE
507
- self.is_initialized = False
508
-
509
- def initialize_model(self):
510
- if self.is_initialized:
511
- return True
512
-
513
- try:
514
- config = Config(
515
- clip_model_name="ViT-L-14/openai",
516
- download_cache=True,
517
- chunk_size=2048,
518
- quiet=True,
519
- device=self.device
520
- )
521
-
522
- self.interrogator = Interrogator(config)
523
- self.is_initialized = True
524
-
525
- if self.device == "cpu":
526
- gc.collect()
527
- else:
528
- torch.cuda.empty_cache()
529
-
530
- return True
531
-
532
- except Exception as e:
533
- logger.error(f"Initialization error: {e}")
534
- return False
535
-
536
- def optimize_image(self, image):
537
- if image is None:
538
- return None
539
-
540
- if isinstance(image, np.ndarray):
541
- image = Image.fromarray(image)
542
- elif not isinstance(image, Image.Image):
543
- image = Image.open(image)
544
-
545
- if image.mode != 'RGB':
546
- image = image.convert('RGB')
547
-
548
- max_size = 768 if self.device != "cpu" else 512
549
- if image.size[0] > max_size or image.size[1] > max_size:
550
- image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
551
-
552
- return image
553
-
554
- @spaces.GPU
555
- def generate_ultra_supreme_prompt(self, image):
556
- try:
557
- if not self.is_initialized:
558
- if not self.initialize_model():
559
- return "❌ Model initialization failed.", "Please refresh and try again.", 0, {}
560
-
561
- if image is None:
562
- return "❌ Please upload an image.", "No image provided.", 0, {}
563
-
564
- self.usage_count += 1
565
-
566
- image = self.optimize_image(image)
567
- if image is None:
568
- return "❌ Image processing failed.", "Invalid image format.", 0, {}
569
-
570
- start_time = datetime.now()
571
-
572
- # ULTRA SUPREME TRIPLE CLIP ANALYSIS
573
- logger.info("ULTRA SUPREME ANALYSIS - Maximum intelligence deployment")
574
-
575
- clip_fast = self.interrogator.interrogate_fast(image)
576
- clip_classic = self.interrogator.interrogate_classic(image)
577
- clip_best = self.interrogator.interrogate(image)
578
-
579
- logger.info(f"ULTRA CLIP Results:\nFast: {clip_fast}\nClassic: {clip_classic}\nBest: {clip_best}")
580
-
581
- # ULTRA SUPREME ANALYSIS
582
- ultra_analysis = self.analyzer.ultra_supreme_analysis(clip_fast, clip_classic, clip_best)
583
-
584
- # BUILD ULTRA SUPREME FLUX PROMPT
585
- optimized_prompt = self.analyzer.build_ultra_supreme_prompt(ultra_analysis, [clip_fast, clip_classic, clip_best])
586
-
587
- # CALCULATE ULTRA SUPREME SCORE
588
- score, breakdown = self.analyzer.calculate_ultra_supreme_score(optimized_prompt, ultra_analysis)
589
-
590
- end_time = datetime.now()
591
- duration = (end_time - start_time).total_seconds()
592
-
593
- # Memory cleanup
594
- if self.device == "cpu":
595
- gc.collect()
596
- else:
597
- torch.cuda.empty_cache()
598
- # ULTRA COMPREHENSIVE ANALYSIS REPORT
599
- gpu_status = "⚡ ZeroGPU" if torch.cuda.is_available() else "💻 CPU"
600
-
601
- # Format detected elements
602
- features = ", ".join(ultra_analysis["facial_ultra"]["facial_hair"]) if ultra_analysis["facial_ultra"]["facial_hair"] else "None detected"
603
- cultural = ", ".join(ultra_analysis["demographic"]["cultural_religious"]) if ultra_analysis["demographic"]["cultural_religious"] else "None detected"
604
- clothing = ", ".join(ultra_analysis["clothing_accessories"]["eyewear"] + ultra_analysis["clothing_accessories"]["headwear"]) if ultra_analysis["clothing_accessories"]["eyewear"] or ultra_analysis["clothing_accessories"]["headwear"] else "None detected"
605
-
606
- analysis_info = f"""**🚀 ULTRA SUPREME ANALYSIS COMPLETE**
607
- **Processing:** {gpu_status} • {duration:.1f}s • Triple CLIP Ultra Intelligence
608
- **Ultra Score:** {score}/100 • Breakdown: Structure({breakdown.get('structure',0)}) Features({breakdown.get('features',0)}) Cultural({breakdown.get('cultural',0)}) Emotional({breakdown.get('emotional',0)}) Technical({breakdown.get('technical',0)})
609
- **Generation:** #{self.usage_count}
610
- **🧠 ULTRA DEEP DETECTION:**
611
- - **Age Category:** {ultra_analysis["demographic"].get("age_category", "Unspecified").replace("_", " ").title()} (Confidence: {ultra_analysis["demographic"].get("age_confidence", 0)})
612
- - **Cultural Context:** {cultural}
613
- - **Facial Features:** {features}
614
- - **Accessories:** {clothing}
615
- - **Setting:** {ultra_analysis["environmental"].get("setting_type", "Standard").title()}
616
- - **Emotion:** {ultra_analysis["emotional_state"].get("primary_emotion", "Neutral").title()}
617
- - **Total Features:** {ultra_analysis["intelligence_metrics"]["total_features_detected"]}
618
- **📊 CLIP ANALYSIS SOURCES:**
619
- - **Fast:** {clip_fast[:50]}...
620
- - **Classic:** {clip_classic[:50]}...
621
- - **Best:** {clip_best[:50]}...
622
- **⚡ ULTRA OPTIMIZATION:** Applied absolute maximum depth analysis with Pariente AI research rules"""
623
-
624
- return optimized_prompt, analysis_info, score, breakdown
625
-
626
- except Exception as e:
627
- logger.error(f"Ultra supreme generation error: {e}")
628
- return f"❌ Error: {str(e)}", "Please try with a different image.", 0, {}
629
-
630
- # Initialize the optimizer
631
  optimizer = UltraSupremeOptimizer()
632
 
 
633
  def process_ultra_supreme_analysis(image):
634
- """Ultra supreme analysis wrapper"""
635
  try:
636
  prompt, info, score, breakdown = optimizer.generate_ultra_supreme_prompt(image)
637
 
638
- # Ultra enhanced score display
639
- if score >= 95:
640
- color = "#059669"
641
- grade = "LEGENDARY"
642
- elif score >= 90:
643
- color = "#10b981"
644
- grade = "EXCELLENT"
645
- elif score >= 80:
646
- color = "#22c55e"
647
- grade = "VERY GOOD"
648
- elif score >= 70:
649
- color = "#f59e0b"
650
- grade = "GOOD"
651
- elif score >= 60:
652
- color = "#f97316"
653
- grade = "FAIR"
654
- else:
655
- color = "#ef4444"
656
- grade = "NEEDS WORK"
657
 
658
  score_html = f'''
659
- <div style="text-align: center; padding: 2rem; background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%); border: 3px solid {color}; border-radius: 16px; margin: 1rem 0; box-shadow: 0 8px 25px -5px rgba(0, 0, 0, 0.1);">
660
- <div style="font-size: 3rem; font-weight: 800; color: {color}; margin: 0; text-shadow: 0 2px 4px rgba(0,0,0,0.1);">{score}</div>
661
- <div style="font-size: 1.25rem; color: #15803d; margin: 0.5rem 0; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700;">{grade}</div>
662
  <div style="font-size: 1rem; color: #15803d; margin: 0; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 500;">Ultra Supreme Intelligence Score</div>
663
  </div>
664
  '''
@@ -669,13 +54,18 @@ def process_ultra_supreme_analysis(image):
669
  logger.error(f"Ultra supreme wrapper error: {e}")
670
  return "❌ Processing failed", f"Error: {str(e)}", '<div style="text-align: center; color: red;">Error</div>'
671
 
 
672
  def clear_outputs():
 
673
  gc.collect()
674
  if torch.cuda.is_available():
675
  torch.cuda.empty_cache()
676
  return "", "", '<div style="text-align: center; padding: 1rem;"><div style="font-size: 2rem; color: #ccc;">--</div><div style="font-size: 0.875rem; color: #999;">Ultra Supreme Score</div></div>'
677
 
678
- def create_interface(): # <-- Esta línea debe empezar en la columna 0, sin espacios al inicio
 
 
 
679
  css = """
680
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
681
 
@@ -749,19 +139,34 @@ def create_interface(): # <-- Esta línea debe empezar en la columna 0, sin esp
749
  transform: translateY(-2px) !important;
750
  }
751
 
752
- /* Fix para texto en el footer que aparece blanco sobre blanco */
753
  footer, .footer, [class*="footer"] {
754
  color: #374151 !important;
755
  }
756
 
757
- /* Asegurar que todo el texto del footer sea visible */
758
  footer *, .footer *, [class*="footer"] * {
759
  color: #374151 !important;
760
  }
761
 
762
- /* Fix específico para links en el footer */
763
  footer a, .footer a, [class*="footer"] a {
764
  color: #3b82f6 !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
765
  }
766
  """
767
 
@@ -855,11 +260,12 @@ def create_interface(): # <-- Esta línea debe empezar en la columna 0, sin esp
855
  understanding and applies research-validated Flux rules with supreme intelligence.
856
 
857
  **🔬 Pariente AI Research Laboratory** • **🚀 Ultra Supreme Intelligence Engine**
858
- """, elem_classes=["footer-content"])
859
 
860
  return interface
861
 
862
- # Launch the application
 
863
  if __name__ == "__main__":
864
  demo = create_interface()
865
  demo.launch(
 
1
+ """
2
+ Ultra Supreme Flux Optimizer - Main Gradio Interface
3
+ """
4
+
5
  import gradio as gr
6
  import torch
7
+ import gc
 
 
8
  import logging
 
9
  import warnings
10
+ import os
11
+
12
+ from optimizer import UltraSupremeOptimizer
13
+ from constants import SCORE_GRADES
14
 
15
+ # Configure warnings and environment
16
  warnings.filterwarnings("ignore", category=FutureWarning)
17
  warnings.filterwarnings("ignore", category=UserWarning)
18
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
19
 
20
+ # Configure logging
21
  logging.basicConfig(level=logging.INFO)
22
  logger = logging.getLogger(__name__)
23
 
24
+ # Initialize the optimizer globally
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  optimizer = UltraSupremeOptimizer()
26
 
27
+
28
  def process_ultra_supreme_analysis(image):
29
+ """Process image and generate ultra supreme analysis"""
30
  try:
31
  prompt, info, score, breakdown = optimizer.generate_ultra_supreme_prompt(image)
32
 
33
+ # Find appropriate grade based on score
34
+ grade_info = None
35
+ for threshold, grade_data in sorted(SCORE_GRADES.items(), reverse=True):
36
+ if score >= threshold:
37
+ grade_info = grade_data
38
+ break
39
+
40
+ if not grade_info:
41
+ grade_info = SCORE_GRADES[0] # Default to lowest grade
 
 
 
 
 
 
 
 
 
 
42
 
43
  score_html = f'''
44
+ <div style="text-align: center; padding: 2rem; background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%); border: 3px solid {grade_info["color"]}; border-radius: 16px; margin: 1rem 0; box-shadow: 0 8px 25px -5px rgba(0, 0, 0, 0.1);">
45
+ <div style="font-size: 3rem; font-weight: 800; color: {grade_info["color"]}; margin: 0; text-shadow: 0 2px 4px rgba(0,0,0,0.1);">{score}</div>
46
+ <div style="font-size: 1.25rem; color: #15803d; margin: 0.5rem 0; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700;">{grade_info["grade"]}</div>
47
  <div style="font-size: 1rem; color: #15803d; margin: 0; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 500;">Ultra Supreme Intelligence Score</div>
48
  </div>
49
  '''
 
54
  logger.error(f"Ultra supreme wrapper error: {e}")
55
  return "❌ Processing failed", f"Error: {str(e)}", '<div style="text-align: center; color: red;">Error</div>'
56
 
57
+
58
  def clear_outputs():
59
+ """Clear all outputs and free memory"""
60
  gc.collect()
61
  if torch.cuda.is_available():
62
  torch.cuda.empty_cache()
63
  return "", "", '<div style="text-align: center; padding: 1rem;"><div style="font-size: 2rem; color: #ccc;">--</div><div style="font-size: 0.875rem; color: #999;">Ultra Supreme Score</div></div>'
64
 
65
+
66
+ def create_interface():
67
+ """Create the Gradio interface"""
68
+
69
  css = """
70
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
71
 
 
139
  transform: translateY(-2px) !important;
140
  }
141
 
142
+ /* Fix for footer text visibility */
143
  footer, .footer, [class*="footer"] {
144
  color: #374151 !important;
145
  }
146
 
 
147
  footer *, .footer *, [class*="footer"] * {
148
  color: #374151 !important;
149
  }
150
 
 
151
  footer a, .footer a, [class*="footer"] a {
152
  color: #3b82f6 !important;
153
+ text-decoration: underline;
154
+ }
155
+
156
+ footer a:hover, .footer a:hover, [class*="footer"] a:hover {
157
+ color: #2563eb !important;
158
+ }
159
+
160
+ /* Additional style fixes for Gradio components */
161
+ .gr-button-primary {
162
+ background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important;
163
+ border: none !important;
164
+ }
165
+
166
+ .gr-button-primary:hover {
167
+ background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%) !important;
168
+ transform: translateY(-1px);
169
+ box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
170
  }
171
  """
172
 
 
260
  understanding and applies research-validated Flux rules with supreme intelligence.
261
 
262
  **🔬 Pariente AI Research Laboratory** • **🚀 Ultra Supreme Intelligence Engine**
263
+ """)
264
 
265
  return interface
266
 
267
+
268
+ # Main execution
269
  if __name__ == "__main__":
270
  demo = create_interface()
271
  demo.launch(