Spaces:
Running
on
Zero
Running
on
Zero
| """ | |
| Ultra Supreme Analyzer for image analysis and prompt building | |
| """ | |
| import re | |
| from typing import Dict, List, Any, Tuple | |
| from constants import ( | |
| FORBIDDEN_ELEMENTS, | |
| MICRO_AGE_INDICATORS, | |
| ULTRA_FACIAL_ANALYSIS, | |
| EMOTION_MICRO_EXPRESSIONS, | |
| CULTURAL_RELIGIOUS_ULTRA, | |
| CLOTHING_ACCESSORIES_ULTRA, | |
| ENVIRONMENTAL_ULTRA_ANALYSIS, | |
| POSE_BODY_LANGUAGE_ULTRA, | |
| COMPOSITION_PHOTOGRAPHY_ULTRA, | |
| TECHNICAL_PHOTOGRAPHY_ULTRA, | |
| QUALITY_DESCRIPTORS_ULTRA, | |
| GENDER_INDICATORS | |
| ) | |
| class UltraSupremeAnalyzer: | |
| """ | |
| ULTRA SUPREME ANALYSIS ENGINE - ABSOLUTE MAXIMUM INTELLIGENCE | |
| """ | |
| def __init__(self): | |
| self.forbidden_elements = FORBIDDEN_ELEMENTS | |
| self.micro_age_indicators = MICRO_AGE_INDICATORS | |
| self.ultra_facial_analysis = ULTRA_FACIAL_ANALYSIS | |
| self.emotion_micro_expressions = EMOTION_MICRO_EXPRESSIONS | |
| self.cultural_religious_ultra = CULTURAL_RELIGIOUS_ULTRA | |
| self.clothing_accessories_ultra = CLOTHING_ACCESSORIES_ULTRA | |
| self.environmental_ultra_analysis = ENVIRONMENTAL_ULTRA_ANALYSIS | |
| self.pose_body_language_ultra = POSE_BODY_LANGUAGE_ULTRA | |
| self.composition_photography_ultra = COMPOSITION_PHOTOGRAPHY_ULTRA | |
| self.technical_photography_ultra = TECHNICAL_PHOTOGRAPHY_ULTRA | |
| self.quality_descriptors_ultra = QUALITY_DESCRIPTORS_ULTRA | |
| def ultra_supreme_analysis(self, clip_fast: str, clip_classic: str, clip_best: str) -> Dict[str, Any]: | |
| """ULTRA SUPREME ANALYSIS - MAXIMUM POSSIBLE INTELLIGENCE""" | |
| combined_analysis = { | |
| "fast": clip_fast.lower(), | |
| "classic": clip_classic.lower(), | |
| "best": clip_best.lower(), | |
| "combined": f"{clip_fast} {clip_classic} {clip_best}".lower() | |
| } | |
| ultra_result = { | |
| "demographic": {"age_category": None, "age_confidence": 0, "gender": None, "cultural_religious": []}, | |
| "facial_ultra": {"eyes": [], "eyebrows": [], "nose": [], "mouth": [], "facial_hair": [], "skin": [], "structure": []}, | |
| "emotional_state": {"primary_emotion": None, "emotion_confidence": 0, "micro_expressions": [], "overall_demeanor": []}, | |
| "clothing_accessories": {"headwear": [], "eyewear": [], "clothing": [], "accessories": []}, | |
| "environmental": {"setting_type": None, "specific_location": None, "lighting_analysis": [], "atmosphere": []}, | |
| "pose_composition": {"body_language": [], "head_position": [], "eye_contact": [], "posture": []}, | |
| "technical_analysis": {"shot_type": None, "angle": None, "lighting_setup": None, "suggested_equipment": {}}, | |
| "intelligence_metrics": {"total_features_detected": 0, "analysis_depth_score": 0, "cultural_awareness_score": 0, "technical_optimization_score": 0} | |
| } | |
| # ULTRA DEEP AGE ANALYSIS | |
| age_scores = {} | |
| for age_category, indicators in self.micro_age_indicators.items(): | |
| score = sum(1 for indicator in indicators if indicator in combined_analysis["combined"]) | |
| if score > 0: | |
| age_scores[age_category] = score | |
| if age_scores: | |
| ultra_result["demographic"]["age_category"] = max(age_scores, key=age_scores.get) | |
| ultra_result["demographic"]["age_confidence"] = age_scores[ultra_result["demographic"]["age_category"]] | |
| # GENDER DETECTION WITH CONFIDENCE | |
| male_score = sum(1 for indicator in GENDER_INDICATORS["male"] if indicator in combined_analysis["combined"]) | |
| female_score = sum(1 for indicator in GENDER_INDICATORS["female"] if indicator in combined_analysis["combined"]) | |
| if male_score > female_score: | |
| ultra_result["demographic"]["gender"] = "man" | |
| elif female_score > male_score: | |
| ultra_result["demographic"]["gender"] = "woman" | |
| # ULTRA CULTURAL/RELIGIOUS ANALYSIS | |
| for culture_type, indicators in self.cultural_religious_ultra.items(): | |
| if isinstance(indicators, list): | |
| for indicator in indicators: | |
| if indicator.lower() in combined_analysis["combined"]: | |
| ultra_result["demographic"]["cultural_religious"].append(indicator) | |
| # COMPREHENSIVE FACIAL FEATURE ANALYSIS | |
| for hair_category, features in self.ultra_facial_analysis["facial_hair_ultra"].items(): | |
| for feature in features: | |
| if feature in combined_analysis["combined"]: | |
| ultra_result["facial_ultra"]["facial_hair"].append(feature) | |
| # Eyes analysis | |
| for eye_category, features in self.ultra_facial_analysis["eye_features"].items(): | |
| for feature in features: | |
| if feature in combined_analysis["combined"]: | |
| ultra_result["facial_ultra"]["eyes"].append(feature) | |
| # EMOTION AND MICRO-EXPRESSION ANALYSIS | |
| emotion_scores = {} | |
| for emotion in self.emotion_micro_expressions["complex_emotions"]: | |
| if emotion in combined_analysis["combined"]: | |
| emotion_scores[emotion] = combined_analysis["combined"].count(emotion) | |
| if emotion_scores: | |
| ultra_result["emotional_state"]["primary_emotion"] = max(emotion_scores, key=emotion_scores.get) | |
| ultra_result["emotional_state"]["emotion_confidence"] = emotion_scores[ultra_result["emotional_state"]["primary_emotion"]] | |
| # CLOTHING AND ACCESSORIES ANALYSIS | |
| for category, items in self.clothing_accessories_ultra.items(): | |
| if isinstance(items, list): | |
| for item in items: | |
| if item in combined_analysis["combined"]: | |
| if category == "clothing_types": | |
| ultra_result["clothing_accessories"]["clothing"].append(item) | |
| elif category == "clothing_styles": | |
| ultra_result["clothing_accessories"]["clothing"].append(item) | |
| elif category in ["headwear", "eyewear", "accessories"]: | |
| ultra_result["clothing_accessories"][category].append(item) | |
| # ENVIRONMENTAL ULTRA ANALYSIS | |
| setting_scores = {} | |
| for main_setting, sub_settings in self.environmental_ultra_analysis.items(): | |
| if isinstance(sub_settings, dict): | |
| for sub_type, locations in sub_settings.items(): | |
| score = sum(1 for location in locations if location in combined_analysis["combined"]) | |
| if score > 0: | |
| setting_scores[sub_type] = score | |
| if setting_scores: | |
| ultra_result["environmental"]["setting_type"] = max(setting_scores, key=setting_scores.get) | |
| # LIGHTING ANALYSIS | |
| for light_category, light_types in self.environmental_ultra_analysis["lighting_ultra"].items(): | |
| for light_type in light_types: | |
| if light_type in combined_analysis["combined"]: | |
| ultra_result["environmental"]["lighting_analysis"].append(light_type) | |
| # POSE AND BODY LANGUAGE ANALYSIS | |
| for pose_category, indicators in self.pose_body_language_ultra.items(): | |
| for indicator in indicators: | |
| if indicator in combined_analysis["combined"]: | |
| if pose_category in ultra_result["pose_composition"]: | |
| ultra_result["pose_composition"][pose_category].append(indicator) | |
| # TECHNICAL PHOTOGRAPHY ANALYSIS | |
| for shot_type in self.composition_photography_ultra["shot_types"]: | |
| if shot_type in combined_analysis["combined"]: | |
| ultra_result["technical_analysis"]["shot_type"] = shot_type | |
| break | |
| # CALCULATE INTELLIGENCE METRICS | |
| 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()) | |
| ultra_result["intelligence_metrics"]["total_features_detected"] = total_features | |
| ultra_result["intelligence_metrics"]["analysis_depth_score"] = min(total_features * 5, 100) | |
| ultra_result["intelligence_metrics"]["cultural_awareness_score"] = len(ultra_result["demographic"]["cultural_religious"]) * 20 | |
| return ultra_result | |
| def build_ultra_supreme_prompt(self, ultra_analysis: Dict[str, Any], clip_results: List[str]) -> str: | |
| """BUILD ULTRA SUPREME FLUX PROMPT - ABSOLUTE MAXIMUM QUALITY""" | |
| components = [] | |
| # 1. ULTRA INTELLIGENT ARTICLE SELECTION | |
| subject_desc = [] | |
| if ultra_analysis["demographic"]["cultural_religious"]: | |
| subject_desc.extend(ultra_analysis["demographic"]["cultural_religious"][:1]) | |
| if ultra_analysis["demographic"]["age_category"] and ultra_analysis["demographic"]["age_category"] != "middle_aged": | |
| subject_desc.append(ultra_analysis["demographic"]["age_category"].replace("_", " ")) | |
| if ultra_analysis["demographic"]["gender"]: | |
| subject_desc.append(ultra_analysis["demographic"]["gender"]) | |
| if subject_desc: | |
| full_subject = " ".join(subject_desc) | |
| article = "An" if full_subject[0].lower() in 'aeiou' else "A" | |
| else: | |
| article = "A" | |
| components.append(article) | |
| # 2. ULTRA CONTEXTUAL ADJECTIVES (max 2-3 per Flux rules) | |
| adjectives = [] | |
| # Age-based adjectives | |
| age_cat = ultra_analysis["demographic"]["age_category"] | |
| if age_cat and age_cat in self.quality_descriptors_ultra["based_on_age"]: | |
| adjectives.extend(self.quality_descriptors_ultra["based_on_age"][age_cat][:2]) | |
| # Emotion-based adjectives | |
| emotion = ultra_analysis["emotional_state"]["primary_emotion"] | |
| if emotion and emotion in self.quality_descriptors_ultra["based_on_emotion"]: | |
| adjectives.extend(self.quality_descriptors_ultra["based_on_emotion"][emotion][:1]) | |
| # Default if none found | |
| if not adjectives: | |
| adjectives = ["distinguished", "professional"] | |
| components.extend(adjectives[:2]) # Flux rule: max 2-3 adjectives | |
| # 3. ULTRA ENHANCED SUBJECT | |
| if subject_desc: | |
| components.append(" ".join(subject_desc)) | |
| else: | |
| components.append("person") | |
| # 4. ULTRA DETAILED FACIAL FEATURES | |
| facial_details = [] | |
| # Eyes | |
| if ultra_analysis["facial_ultra"]["eyes"]: | |
| eye_desc = ultra_analysis["facial_ultra"]["eyes"][0] | |
| facial_details.append(f"with {eye_desc}") | |
| # Facial hair with ultra detail | |
| if ultra_analysis["facial_ultra"]["facial_hair"]: | |
| beard_details = ultra_analysis["facial_ultra"]["facial_hair"] | |
| if any("silver" in detail or "gray" in detail or "grey" in detail for detail in beard_details): | |
| facial_details.append("with a distinguished silver beard") | |
| elif any("beard" in detail for detail in beard_details): | |
| facial_details.append("with a full well-groomed beard") | |
| if facial_details: | |
| components.extend(facial_details) | |
| # 5. CLOTHING AND ACCESSORIES ULTRA | |
| clothing_details = [] | |
| # Eyewear | |
| if ultra_analysis["clothing_accessories"]["eyewear"]: | |
| eyewear = ultra_analysis["clothing_accessories"]["eyewear"][0] | |
| clothing_details.append(f"wearing {eyewear}") | |
| # Headwear | |
| if ultra_analysis["clothing_accessories"]["headwear"]: | |
| headwear = ultra_analysis["clothing_accessories"]["headwear"][0] | |
| if ultra_analysis["demographic"]["cultural_religious"]: | |
| clothing_details.append("wearing a traditional black hat") | |
| else: | |
| clothing_details.append(f"wearing a {headwear}") | |
| if clothing_details: | |
| components.extend(clothing_details) | |
| # 6. ULTRA POSE AND BODY LANGUAGE | |
| pose_description = "positioned with natural dignity" | |
| if ultra_analysis["pose_composition"]["posture"]: | |
| posture = ultra_analysis["pose_composition"]["posture"][0] | |
| pose_description = f"maintaining {posture}" | |
| elif ultra_analysis["technical_analysis"]["shot_type"] == "portrait": | |
| pose_description = "captured in contemplative portrait pose" | |
| components.append(pose_description) | |
| # 7. ULTRA ENVIRONMENTAL CONTEXT | |
| environment_desc = "in a thoughtfully composed environment" | |
| if ultra_analysis["environmental"]["setting_type"]: | |
| setting_map = { | |
| "residential": "in an intimate home setting", | |
| "office": "in a professional office environment", | |
| "religious": "in a sacred traditional space", | |
| "formal": "in a distinguished formal setting" | |
| } | |
| environment_desc = setting_map.get(ultra_analysis["environmental"]["setting_type"], | |
| "in a carefully arranged professional setting") | |
| components.append(environment_desc) | |
| # 8. ULTRA SOPHISTICATED LIGHTING | |
| lighting_desc = "illuminated by sophisticated portrait lighting that emphasizes character and facial texture" | |
| if ultra_analysis["environmental"]["lighting_analysis"]: | |
| primary_light = ultra_analysis["environmental"]["lighting_analysis"][0] | |
| if "dramatic" in primary_light: | |
| lighting_desc = "bathed in dramatic chiaroscuro lighting that creates compelling depth and shadow play" | |
| elif "natural" in primary_light or "window" in primary_light: | |
| lighting_desc = "graced by gentle natural lighting that brings out intricate facial details and warmth" | |
| elif "soft" in primary_light: | |
| lighting_desc = "softly illuminated to reveal nuanced expressions and character" | |
| components.append(lighting_desc) | |
| # 9. ULTRA TECHNICAL SPECIFICATIONS | |
| if ultra_analysis["technical_analysis"]["shot_type"] in ["portrait", "headshot", "close-up"]: | |
| camera_setup = "Shot on Phase One XF IQ4, 85mm f/1.4 lens, f/2.8 aperture" | |
| elif ultra_analysis["demographic"]["cultural_religious"]: | |
| camera_setup = "Shot on Hasselblad X2D, 90mm lens, f/2.8 aperture" | |
| else: | |
| camera_setup = "Shot on Phase One XF, 80mm lens, f/4 aperture" | |
| components.append(camera_setup) | |
| # 10. ULTRA QUALITY DESIGNATION | |
| quality_designation = "professional portrait photography" | |
| if ultra_analysis["demographic"]["cultural_religious"]: | |
| quality_designation = "fine art documentary photography" | |
| elif ultra_analysis["emotional_state"]["primary_emotion"]: | |
| quality_designation = "expressive portrait photography" | |
| components.append(quality_designation) | |
| # ULTRA FINAL ASSEMBLY | |
| prompt = ", ".join(components) | |
| # Ultra cleaning and optimization | |
| prompt = re.sub(r'\s+', ' ', prompt) | |
| prompt = re.sub(r',\s*,+', ',', prompt) | |
| prompt = re.sub(r'\s*,\s*', ', ', prompt) | |
| prompt = prompt.replace(" ,", ",") | |
| if prompt: | |
| prompt = prompt[0].upper() + prompt[1:] | |
| return prompt | |
| def calculate_ultra_supreme_score(self, prompt: str, ultra_analysis: Dict[str, Any]) -> Tuple[int, Dict[str, int]]: | |
| """ULTRA SUPREME INTELLIGENCE SCORING""" | |
| score = 0 | |
| breakdown = {} | |
| # Structure Excellence (15 points) | |
| structure_score = 0 | |
| if prompt.startswith(("A", "An")): | |
| structure_score += 5 | |
| if prompt.count(",") >= 8: | |
| structure_score += 10 | |
| score += structure_score | |
| breakdown["structure"] = structure_score | |
| # Feature Detection Depth (25 points) | |
| features_score = min(ultra_analysis["intelligence_metrics"]["total_features_detected"] * 2, 25) | |
| score += features_score | |
| breakdown["features"] = features_score | |
| # Cultural/Religious Awareness (20 points) | |
| cultural_score = min(len(ultra_analysis["demographic"]["cultural_religious"]) * 10, 20) | |
| score += cultural_score | |
| breakdown["cultural"] = cultural_score | |
| # Emotional Intelligence (15 points) | |
| emotion_score = 0 | |
| if ultra_analysis["emotional_state"]["primary_emotion"]: | |
| emotion_score += 10 | |
| if ultra_analysis["emotional_state"]["emotion_confidence"] > 1: | |
| emotion_score += 5 | |
| score += emotion_score | |
| breakdown["emotional"] = emotion_score | |
| # Technical Sophistication (15 points) | |
| tech_score = 0 | |
| if "Phase One" in prompt or "Hasselblad" in prompt: | |
| tech_score += 5 | |
| if any(aperture in prompt for aperture in ["f/1.4", "f/2.8", "f/4"]): | |
| tech_score += 5 | |
| if any(lens in prompt for lens in ["85mm", "90mm", "80mm"]): | |
| tech_score += 5 | |
| score += tech_score | |
| breakdown["technical"] = tech_score | |
| # Environmental Context (10 points) | |
| env_score = 0 | |
| if ultra_analysis["environmental"]["setting_type"]: | |
| env_score += 5 | |
| if ultra_analysis["environmental"]["lighting_analysis"]: | |
| env_score += 5 | |
| score += env_score | |
| breakdown["environmental"] = env_score | |
| return min(score, 100), breakdown |