Malaji71 commited on
Commit
85f2f4b
·
verified ·
1 Parent(s): 690bd1f

Create analyzer.py

Browse files
Files changed (1) hide show
  1. analyzer.py +378 -0
analyzer.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ultra Supreme Analyzer for image analysis and prompt building
3
+ """
4
+
5
+ import re
6
+ from typing import Dict, List, Any, Tuple
7
+
8
+ from constants import (
9
+ FORBIDDEN_ELEMENTS,
10
+ MICRO_AGE_INDICATORS,
11
+ ULTRA_FACIAL_ANALYSIS,
12
+ EMOTION_MICRO_EXPRESSIONS,
13
+ CULTURAL_RELIGIOUS_ULTRA,
14
+ CLOTHING_ACCESSORIES_ULTRA,
15
+ ENVIRONMENTAL_ULTRA_ANALYSIS,
16
+ POSE_BODY_LANGUAGE_ULTRA,
17
+ COMPOSITION_PHOTOGRAPHY_ULTRA,
18
+ TECHNICAL_PHOTOGRAPHY_ULTRA,
19
+ QUALITY_DESCRIPTORS_ULTRA,
20
+ GENDER_INDICATORS
21
+ )
22
+
23
+
24
+ class UltraSupremeAnalyzer:
25
+ """
26
+ ULTRA SUPREME ANALYSIS ENGINE - ABSOLUTE MAXIMUM INTELLIGENCE
27
+ """
28
+
29
+ def __init__(self):
30
+ self.forbidden_elements = FORBIDDEN_ELEMENTS
31
+ self.micro_age_indicators = MICRO_AGE_INDICATORS
32
+ self.ultra_facial_analysis = ULTRA_FACIAL_ANALYSIS
33
+ self.emotion_micro_expressions = EMOTION_MICRO_EXPRESSIONS
34
+ self.cultural_religious_ultra = CULTURAL_RELIGIOUS_ULTRA
35
+ self.clothing_accessories_ultra = CLOTHING_ACCESSORIES_ULTRA
36
+ self.environmental_ultra_analysis = ENVIRONMENTAL_ULTRA_ANALYSIS
37
+ self.pose_body_language_ultra = POSE_BODY_LANGUAGE_ULTRA
38
+ self.composition_photography_ultra = COMPOSITION_PHOTOGRAPHY_ULTRA
39
+ self.technical_photography_ultra = TECHNICAL_PHOTOGRAPHY_ULTRA
40
+ self.quality_descriptors_ultra = QUALITY_DESCRIPTORS_ULTRA
41
+
42
+ def ultra_supreme_analysis(self, clip_fast: str, clip_classic: str, clip_best: str) -> Dict[str, Any]:
43
+ """ULTRA SUPREME ANALYSIS - MAXIMUM POSSIBLE INTELLIGENCE"""
44
+
45
+ combined_analysis = {
46
+ "fast": clip_fast.lower(),
47
+ "classic": clip_classic.lower(),
48
+ "best": clip_best.lower(),
49
+ "combined": f"{clip_fast} {clip_classic} {clip_best}".lower()
50
+ }
51
+
52
+ ultra_result = {
53
+ "demographic": {"age_category": None, "age_confidence": 0, "gender": None, "cultural_religious": []},
54
+ "facial_ultra": {"eyes": [], "eyebrows": [], "nose": [], "mouth": [], "facial_hair": [], "skin": [], "structure": []},
55
+ "emotional_state": {"primary_emotion": None, "emotion_confidence": 0, "micro_expressions": [], "overall_demeanor": []},
56
+ "clothing_accessories": {"headwear": [], "eyewear": [], "clothing": [], "accessories": []},
57
+ "environmental": {"setting_type": None, "specific_location": None, "lighting_analysis": [], "atmosphere": []},
58
+ "pose_composition": {"body_language": [], "head_position": [], "eye_contact": [], "posture": []},
59
+ "technical_analysis": {"shot_type": None, "angle": None, "lighting_setup": None, "suggested_equipment": {}},
60
+ "intelligence_metrics": {"total_features_detected": 0, "analysis_depth_score": 0, "cultural_awareness_score": 0, "technical_optimization_score": 0}
61
+ }
62
+
63
+ # ULTRA DEEP AGE ANALYSIS
64
+ age_scores = {}
65
+ for age_category, indicators in self.micro_age_indicators.items():
66
+ score = sum(1 for indicator in indicators if indicator in combined_analysis["combined"])
67
+ if score > 0:
68
+ age_scores[age_category] = score
69
+
70
+ if age_scores:
71
+ ultra_result["demographic"]["age_category"] = max(age_scores, key=age_scores.get)
72
+ ultra_result["demographic"]["age_confidence"] = age_scores[ultra_result["demographic"]["age_category"]]
73
+
74
+ # GENDER DETECTION WITH CONFIDENCE
75
+ male_score = sum(1 for indicator in GENDER_INDICATORS["male"] if indicator in combined_analysis["combined"])
76
+ female_score = sum(1 for indicator in GENDER_INDICATORS["female"] if indicator in combined_analysis["combined"])
77
+
78
+ if male_score > female_score:
79
+ ultra_result["demographic"]["gender"] = "man"
80
+ elif female_score > male_score:
81
+ ultra_result["demographic"]["gender"] = "woman"
82
+
83
+ # ULTRA CULTURAL/RELIGIOUS ANALYSIS
84
+ for culture_type, indicators in self.cultural_religious_ultra.items():
85
+ if isinstance(indicators, list):
86
+ for indicator in indicators:
87
+ if indicator.lower() in combined_analysis["combined"]:
88
+ ultra_result["demographic"]["cultural_religious"].append(indicator)
89
+
90
+ # COMPREHENSIVE FACIAL FEATURE ANALYSIS
91
+ for hair_category, features in self.ultra_facial_analysis["facial_hair_ultra"].items():
92
+ for feature in features:
93
+ if feature in combined_analysis["combined"]:
94
+ ultra_result["facial_ultra"]["facial_hair"].append(feature)
95
+
96
+ # Eyes analysis
97
+ for eye_category, features in self.ultra_facial_analysis["eye_features"].items():
98
+ for feature in features:
99
+ if feature in combined_analysis["combined"]:
100
+ ultra_result["facial_ultra"]["eyes"].append(feature)
101
+
102
+ # EMOTION AND MICRO-EXPRESSION ANALYSIS
103
+ emotion_scores = {}
104
+ for emotion in self.emotion_micro_expressions["complex_emotions"]:
105
+ if emotion in combined_analysis["combined"]:
106
+ emotion_scores[emotion] = combined_analysis["combined"].count(emotion)
107
+
108
+ if emotion_scores:
109
+ ultra_result["emotional_state"]["primary_emotion"] = max(emotion_scores, key=emotion_scores.get)
110
+ ultra_result["emotional_state"]["emotion_confidence"] = emotion_scores[ultra_result["emotional_state"]["primary_emotion"]]
111
+
112
+ # CLOTHING AND ACCESSORIES ANALYSIS
113
+ for category, items in self.clothing_accessories_ultra.items():
114
+ if isinstance(items, list):
115
+ for item in items:
116
+ if item in combined_analysis["combined"]:
117
+ if category == "clothing_types":
118
+ ultra_result["clothing_accessories"]["clothing"].append(item)
119
+ elif category == "clothing_styles":
120
+ ultra_result["clothing_accessories"]["clothing"].append(item)
121
+ elif category in ["headwear", "eyewear", "accessories"]:
122
+ ultra_result["clothing_accessories"][category].append(item)
123
+
124
+ # ENVIRONMENTAL ULTRA ANALYSIS
125
+ setting_scores = {}
126
+ for main_setting, sub_settings in self.environmental_ultra_analysis.items():
127
+ if isinstance(sub_settings, dict):
128
+ for sub_type, locations in sub_settings.items():
129
+ score = sum(1 for location in locations if location in combined_analysis["combined"])
130
+ if score > 0:
131
+ setting_scores[sub_type] = score
132
+
133
+ if setting_scores:
134
+ ultra_result["environmental"]["setting_type"] = max(setting_scores, key=setting_scores.get)
135
+
136
+ # LIGHTING ANALYSIS
137
+ for light_category, light_types in self.environmental_ultra_analysis["lighting_ultra"].items():
138
+ for light_type in light_types:
139
+ if light_type in combined_analysis["combined"]:
140
+ ultra_result["environmental"]["lighting_analysis"].append(light_type)
141
+
142
+ # POSE AND BODY LANGUAGE ANALYSIS
143
+ for pose_category, indicators in self.pose_body_language_ultra.items():
144
+ for indicator in indicators:
145
+ if indicator in combined_analysis["combined"]:
146
+ if pose_category in ultra_result["pose_composition"]:
147
+ ultra_result["pose_composition"][pose_category].append(indicator)
148
+
149
+ # TECHNICAL PHOTOGRAPHY ANALYSIS
150
+ for shot_type in self.composition_photography_ultra["shot_types"]:
151
+ if shot_type in combined_analysis["combined"]:
152
+ ultra_result["technical_analysis"]["shot_type"] = shot_type
153
+ break
154
+
155
+ # CALCULATE INTELLIGENCE METRICS
156
+ total_features = sum(len(v) if isinstance(v, list) else (1 if v else 0)
157
+ for category in ultra_result.values()
158
+ if isinstance(category, dict)
159
+ for v in category.values())
160
+ ultra_result["intelligence_metrics"]["total_features_detected"] = total_features
161
+ ultra_result["intelligence_metrics"]["analysis_depth_score"] = min(total_features * 5, 100)
162
+ ultra_result["intelligence_metrics"]["cultural_awareness_score"] = len(ultra_result["demographic"]["cultural_religious"]) * 20
163
+
164
+ return ultra_result
165
+
166
+ def build_ultra_supreme_prompt(self, ultra_analysis: Dict[str, Any], clip_results: List[str]) -> str:
167
+ """BUILD ULTRA SUPREME FLUX PROMPT - ABSOLUTE MAXIMUM QUALITY"""
168
+
169
+ components = []
170
+
171
+ # 1. ULTRA INTELLIGENT ARTICLE SELECTION
172
+ subject_desc = []
173
+ if ultra_analysis["demographic"]["cultural_religious"]:
174
+ subject_desc.extend(ultra_analysis["demographic"]["cultural_religious"][:1])
175
+ if ultra_analysis["demographic"]["age_category"] and ultra_analysis["demographic"]["age_category"] != "middle_aged":
176
+ subject_desc.append(ultra_analysis["demographic"]["age_category"].replace("_", " "))
177
+ if ultra_analysis["demographic"]["gender"]:
178
+ subject_desc.append(ultra_analysis["demographic"]["gender"])
179
+
180
+ if subject_desc:
181
+ full_subject = " ".join(subject_desc)
182
+ article = "An" if full_subject[0].lower() in 'aeiou' else "A"
183
+ else:
184
+ article = "A"
185
+ components.append(article)
186
+
187
+ # 2. ULTRA CONTEXTUAL ADJECTIVES (max 2-3 per Flux rules)
188
+ adjectives = []
189
+
190
+ # Age-based adjectives
191
+ age_cat = ultra_analysis["demographic"]["age_category"]
192
+ if age_cat and age_cat in self.quality_descriptors_ultra["based_on_age"]:
193
+ adjectives.extend(self.quality_descriptors_ultra["based_on_age"][age_cat][:2])
194
+
195
+ # Emotion-based adjectives
196
+ emotion = ultra_analysis["emotional_state"]["primary_emotion"]
197
+ if emotion and emotion in self.quality_descriptors_ultra["based_on_emotion"]:
198
+ adjectives.extend(self.quality_descriptors_ultra["based_on_emotion"][emotion][:1])
199
+
200
+ # Default if none found
201
+ if not adjectives:
202
+ adjectives = ["distinguished", "professional"]
203
+
204
+ components.extend(adjectives[:2]) # Flux rule: max 2-3 adjectives
205
+
206
+ # 3. ULTRA ENHANCED SUBJECT
207
+ if subject_desc:
208
+ components.append(" ".join(subject_desc))
209
+ else:
210
+ components.append("person")
211
+
212
+ # 4. ULTRA DETAILED FACIAL FEATURES
213
+ facial_details = []
214
+
215
+ # Eyes
216
+ if ultra_analysis["facial_ultra"]["eyes"]:
217
+ eye_desc = ultra_analysis["facial_ultra"]["eyes"][0]
218
+ facial_details.append(f"with {eye_desc}")
219
+
220
+ # Facial hair with ultra detail
221
+ if ultra_analysis["facial_ultra"]["facial_hair"]:
222
+ beard_details = ultra_analysis["facial_ultra"]["facial_hair"]
223
+ if any("silver" in detail or "gray" in detail or "grey" in detail for detail in beard_details):
224
+ facial_details.append("with a distinguished silver beard")
225
+ elif any("beard" in detail for detail in beard_details):
226
+ facial_details.append("with a full well-groomed beard")
227
+
228
+ if facial_details:
229
+ components.extend(facial_details)
230
+
231
+ # 5. CLOTHING AND ACCESSORIES ULTRA
232
+ clothing_details = []
233
+
234
+ # Eyewear
235
+ if ultra_analysis["clothing_accessories"]["eyewear"]:
236
+ eyewear = ultra_analysis["clothing_accessories"]["eyewear"][0]
237
+ clothing_details.append(f"wearing {eyewear}")
238
+
239
+ # Headwear
240
+ if ultra_analysis["clothing_accessories"]["headwear"]:
241
+ headwear = ultra_analysis["clothing_accessories"]["headwear"][0]
242
+ if ultra_analysis["demographic"]["cultural_religious"]:
243
+ clothing_details.append("wearing a traditional black hat")
244
+ else:
245
+ clothing_details.append(f"wearing a {headwear}")
246
+
247
+ if clothing_details:
248
+ components.extend(clothing_details)
249
+
250
+ # 6. ULTRA POSE AND BODY LANGUAGE
251
+ pose_description = "positioned with natural dignity"
252
+
253
+ if ultra_analysis["pose_composition"]["posture"]:
254
+ posture = ultra_analysis["pose_composition"]["posture"][0]
255
+ pose_description = f"maintaining {posture}"
256
+ elif ultra_analysis["technical_analysis"]["shot_type"] == "portrait":
257
+ pose_description = "captured in contemplative portrait pose"
258
+
259
+ components.append(pose_description)
260
+
261
+ # 7. ULTRA ENVIRONMENTAL CONTEXT
262
+ environment_desc = "in a thoughtfully composed environment"
263
+
264
+ if ultra_analysis["environmental"]["setting_type"]:
265
+ setting_map = {
266
+ "residential": "in an intimate home setting",
267
+ "office": "in a professional office environment",
268
+ "religious": "in a sacred traditional space",
269
+ "formal": "in a distinguished formal setting"
270
+ }
271
+ environment_desc = setting_map.get(ultra_analysis["environmental"]["setting_type"],
272
+ "in a carefully arranged professional setting")
273
+
274
+ components.append(environment_desc)
275
+
276
+ # 8. ULTRA SOPHISTICATED LIGHTING
277
+ lighting_desc = "illuminated by sophisticated portrait lighting that emphasizes character and facial texture"
278
+
279
+ if ultra_analysis["environmental"]["lighting_analysis"]:
280
+ primary_light = ultra_analysis["environmental"]["lighting_analysis"][0]
281
+ if "dramatic" in primary_light:
282
+ lighting_desc = "bathed in dramatic chiaroscuro lighting that creates compelling depth and shadow play"
283
+ elif "natural" in primary_light or "window" in primary_light:
284
+ lighting_desc = "graced by gentle natural lighting that brings out intricate facial details and warmth"
285
+ elif "soft" in primary_light:
286
+ lighting_desc = "softly illuminated to reveal nuanced expressions and character"
287
+
288
+ components.append(lighting_desc)
289
+
290
+ # 9. ULTRA TECHNICAL SPECIFICATIONS
291
+ if ultra_analysis["technical_analysis"]["shot_type"] in ["portrait", "headshot", "close-up"]:
292
+ camera_setup = "Shot on Phase One XF IQ4, 85mm f/1.4 lens, f/2.8 aperture"
293
+ elif ultra_analysis["demographic"]["cultural_religious"]:
294
+ camera_setup = "Shot on Hasselblad X2D, 90mm lens, f/2.8 aperture"
295
+ else:
296
+ camera_setup = "Shot on Phase One XF, 80mm lens, f/4 aperture"
297
+
298
+ components.append(camera_setup)
299
+
300
+ # 10. ULTRA QUALITY DESIGNATION
301
+ quality_designation = "professional portrait photography"
302
+
303
+ if ultra_analysis["demographic"]["cultural_religious"]:
304
+ quality_designation = "fine art documentary photography"
305
+ elif ultra_analysis["emotional_state"]["primary_emotion"]:
306
+ quality_designation = "expressive portrait photography"
307
+
308
+ components.append(quality_designation)
309
+
310
+ # ULTRA FINAL ASSEMBLY
311
+ prompt = ", ".join(components)
312
+
313
+ # Ultra cleaning and optimization
314
+ prompt = re.sub(r'\s+', ' ', prompt)
315
+ prompt = re.sub(r',\s*,+', ',', prompt)
316
+ prompt = re.sub(r'\s*,\s*', ', ', prompt)
317
+ prompt = prompt.replace(" ,", ",")
318
+
319
+ if prompt:
320
+ prompt = prompt[0].upper() + prompt[1:]
321
+
322
+ return prompt
323
+
324
+ def calculate_ultra_supreme_score(self, prompt: str, ultra_analysis: Dict[str, Any]) -> Tuple[int, Dict[str, int]]:
325
+ """ULTRA SUPREME INTELLIGENCE SCORING"""
326
+
327
+ score = 0
328
+ breakdown = {}
329
+
330
+ # Structure Excellence (15 points)
331
+ structure_score = 0
332
+ if prompt.startswith(("A", "An")):
333
+ structure_score += 5
334
+ if prompt.count(",") >= 8:
335
+ structure_score += 10
336
+ score += structure_score
337
+ breakdown["structure"] = structure_score
338
+
339
+ # Feature Detection Depth (25 points)
340
+ features_score = min(ultra_analysis["intelligence_metrics"]["total_features_detected"] * 2, 25)
341
+ score += features_score
342
+ breakdown["features"] = features_score
343
+
344
+ # Cultural/Religious Awareness (20 points)
345
+ cultural_score = min(len(ultra_analysis["demographic"]["cultural_religious"]) * 10, 20)
346
+ score += cultural_score
347
+ breakdown["cultural"] = cultural_score
348
+
349
+ # Emotional Intelligence (15 points)
350
+ emotion_score = 0
351
+ if ultra_analysis["emotional_state"]["primary_emotion"]:
352
+ emotion_score += 10
353
+ if ultra_analysis["emotional_state"]["emotion_confidence"] > 1:
354
+ emotion_score += 5
355
+ score += emotion_score
356
+ breakdown["emotional"] = emotion_score
357
+
358
+ # Technical Sophistication (15 points)
359
+ tech_score = 0
360
+ if "Phase One" in prompt or "Hasselblad" in prompt:
361
+ tech_score += 5
362
+ if any(aperture in prompt for aperture in ["f/1.4", "f/2.8", "f/4"]):
363
+ tech_score += 5
364
+ if any(lens in prompt for lens in ["85mm", "90mm", "80mm"]):
365
+ tech_score += 5
366
+ score += tech_score
367
+ breakdown["technical"] = tech_score
368
+
369
+ # Environmental Context (10 points)
370
+ env_score = 0
371
+ if ultra_analysis["environmental"]["setting_type"]:
372
+ env_score += 5
373
+ if ultra_analysis["environmental"]["lighting_analysis"]:
374
+ env_score += 5
375
+ score += env_score
376
+ breakdown["environmental"] = env_score
377
+
378
+ return min(score, 100), breakdown