File size: 9,279 Bytes
1227ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Utility functions for FLUX Prompt Optimizer
Clean, focused, and reusable utilities
"""

import re
import logging
import gc
from typing import Optional, Tuple, Dict, Any, List
from PIL import Image
import torch
import numpy as np

from config import PROCESSING_CONFIG, FLUX_RULES

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


def setup_logging(level: str = "INFO") -> None:
    """Setup logging configuration"""
    logging.basicConfig(
        level=getattr(logging, level.upper()),
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )


def optimize_image(image: Any) -> Optional[Image.Image]:
    """
    Optimize image for processing
    
    Args:
        image: Input image (PIL, numpy array, or file path)
        
    Returns:
        Optimized PIL Image or None if failed
    """
    if image is None:
        return None
        
    try:
        # Convert to PIL Image if necessary
        if isinstance(image, np.ndarray):
            image = Image.fromarray(image)
        elif isinstance(image, str):
            image = Image.open(image)
        elif not isinstance(image, Image.Image):
            logger.error(f"Unsupported image type: {type(image)}")
            return None
        
        # Convert to RGB if necessary
        if image.mode != 'RGB':
            image = image.convert('RGB')
        
        # Resize if too large
        max_size = PROCESSING_CONFIG["max_image_size"]
        if image.size[0] > max_size or image.size[1] > max_size:
            image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
            logger.info(f"Image resized to {image.size}")
        
        return image
        
    except Exception as e:
        logger.error(f"Image optimization failed: {e}")
        return None


def validate_image(image: Any) -> bool:
    """
    Validate if image is processable
    
    Args:
        image: Input image to validate
        
    Returns:
        True if valid, False otherwise
    """
    if image is None:
        return False
        
    try:
        optimized = optimize_image(image)
        return optimized is not None
    except Exception:
        return False


def clean_memory() -> None:
    """Clean up memory and GPU cache"""
    try:
        gc.collect()
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
            torch.cuda.synchronize()
        logger.debug("Memory cleaned")
    except Exception as e:
        logger.warning(f"Memory cleanup failed: {e}")


def apply_flux_rules(prompt: str) -> str:
    """
    Apply Flux optimization rules to a prompt
    
    Args:
        prompt: Raw prompt text
        
    Returns:
        Optimized prompt following Flux rules
    """
    if not prompt or not isinstance(prompt, str):
        return ""
    
    # Clean the prompt from unwanted elements
    cleaned_prompt = prompt
    for pattern in FLUX_RULES["remove_patterns"]:
        cleaned_prompt = re.sub(pattern, '', cleaned_prompt, flags=re.IGNORECASE)
    
    # Detect image type and add appropriate camera configuration
    prompt_lower = cleaned_prompt.lower()
    camera_config = ""
    
    if any(word in prompt_lower for word in ['portrait', 'person', 'man', 'woman', 'face']):
        camera_config = FLUX_RULES["camera_configs"]["portrait"]
    elif any(word in prompt_lower for word in ['landscape', 'mountain', 'nature', 'outdoor']):
        camera_config = FLUX_RULES["camera_configs"]["landscape"]
    elif any(word in prompt_lower for word in ['street', 'urban', 'city']):
        camera_config = FLUX_RULES["camera_configs"]["street"]
    else:
        camera_config = FLUX_RULES["camera_configs"]["default"]
    
    # Add lighting enhancements if not present
    if 'lighting' not in prompt_lower:
        if 'dramatic' in prompt_lower:
            cleaned_prompt += FLUX_RULES["lighting_enhancements"]["dramatic"]
        elif 'portrait' in prompt_lower:
            cleaned_prompt += FLUX_RULES["lighting_enhancements"]["portrait"]
        else:
            cleaned_prompt += FLUX_RULES["lighting_enhancements"]["default"]
    
    # Build final prompt
    final_prompt = cleaned_prompt + camera_config
    
    # Clean up formatting
    final_prompt = _clean_prompt_formatting(final_prompt)
    
    return final_prompt


def _clean_prompt_formatting(prompt: str) -> str:
    """Clean up prompt formatting"""
    if not prompt:
        return ""
    
    # Ensure it starts with capital letter
    prompt = prompt.strip()
    if prompt:
        prompt = prompt[0].upper() + prompt[1:] if len(prompt) > 1 else prompt.upper()
    
    # Clean up spaces and commas
    prompt = re.sub(r'\s+', ' ', prompt)
    prompt = re.sub(r',\s*,+', ',', prompt)
    prompt = re.sub(r'^\s*,\s*', '', prompt)  # Remove leading commas
    prompt = re.sub(r'\s*,\s*$', '', prompt)  # Remove trailing commas
    
    return prompt.strip()


def calculate_prompt_score(prompt: str, analysis_data: Optional[Dict[str, Any]] = None) -> Tuple[int, Dict[str, int]]:
    """
    Calculate quality score for a prompt
    
    Args:
        prompt: The prompt to score
        analysis_data: Optional analysis data to enhance scoring
        
    Returns:
        Tuple of (total_score, breakdown_dict)
    """
    if not prompt:
        return 0, {"prompt_quality": 0, "technical_details": 0, "artistic_value": 0, "flux_optimization": 0}
    
    breakdown = {}
    
    # Prompt quality score (0-30 points)
    length_score = min(20, len(prompt) // 8)  # Reward decent length
    detail_score = min(10, len(prompt.split(',')) * 2)  # Reward detail
    breakdown["prompt_quality"] = length_score + detail_score
    
    # Technical details score (0-25 points)
    tech_keywords = ['shot on', 'lens', 'photography', 'lighting', 'camera']
    tech_score = sum(5 for keyword in tech_keywords if keyword in prompt.lower())
    breakdown["technical_details"] = min(25, tech_score)
    
    # Artistic value score (0-25 points)
    art_keywords = ['masterful', 'professional', 'cinematic', 'dramatic', 'beautiful']
    art_score = sum(5 for keyword in art_keywords if keyword in prompt.lower())
    breakdown["artistic_value"] = min(25, art_score)
    
    # Flux optimization score (0-20 points)
    flux_score = 0
    if any(camera in prompt for camera in FLUX_RULES["camera_configs"].values()):
        flux_score += 10
    if any(lighting in prompt for lighting in FLUX_RULES["lighting_enhancements"].values()):
        flux_score += 10
    breakdown["flux_optimization"] = flux_score
    
    # Calculate total
    total_score = sum(breakdown.values())
    
    return total_score, breakdown


def get_score_grade(score: int) -> Dict[str, str]:
    """
    Get grade information for a score
    
    Args:
        score: Numeric score
        
    Returns:
        Dictionary with grade and color information
    """
    from config import SCORING_CONFIG
    
    for threshold, grade_info in sorted(SCORING_CONFIG["grade_thresholds"].items(), reverse=True):
        if score >= threshold:
            return grade_info
    
    # Default to lowest grade
    return SCORING_CONFIG["grade_thresholds"][0]


def format_analysis_report(analysis_data: Dict[str, Any], processing_time: float) -> str:
    """
    Format analysis data into a readable report
    
    Args:
        analysis_data: Analysis results
        processing_time: Time taken for processing
        
    Returns:
        Formatted markdown report
    """
    model_used = analysis_data.get("model_used", "Unknown")
    prompt_length = len(analysis_data.get("prompt", ""))
    
    report = f"""**πŸš€ FLUX OPTIMIZATION COMPLETE**
**Model:** {model_used} β€’ **Time:** {processing_time:.1f}s β€’ **Length:** {prompt_length} chars

**πŸ“Š ANALYSIS SUMMARY:**
{analysis_data.get("summary", "Analysis completed successfully")}

**🎯 OPTIMIZATIONS APPLIED:**
βœ… Flux camera configuration
βœ… Professional lighting setup  
βœ… Technical photography details
βœ… Artistic enhancement keywords

**⚑ Powered by Pariente AI Research**"""
    
    return report


def safe_execute(func, *args, **kwargs) -> Tuple[bool, Any]:
    """
    Safely execute a function with error handling
    
    Args:
        func: Function to execute
        *args: Function arguments
        **kwargs: Function keyword arguments
        
    Returns:
        Tuple of (success: bool, result: Any)
    """
    try:
        result = func(*args, **kwargs)
        return True, result
    except Exception as e:
        logger.error(f"Safe execution failed for {func.__name__}: {e}")
        return False, str(e)


def truncate_text(text: str, max_length: int = 100) -> str:
    """
    Truncate text to specified length with ellipsis
    
    Args:
        text: Text to truncate
        max_length: Maximum length
        
    Returns:
        Truncated text
    """
    if not text or len(text) <= max_length:
        return text
    
    return text[:max_length-3] + "..."


# Export main functions
__all__ = [
    "setup_logging",
    "optimize_image", 
    "validate_image",
    "clean_memory",
    "apply_flux_rules",
    "calculate_prompt_score",
    "get_score_grade",
    "format_analysis_report",
    "safe_execute",
    "truncate_text"
]