File size: 13,374 Bytes
270799c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
πŸ–ΌοΈ EKALAVYA Vision AI - Image Generation & Analysis
🎨 Generate Images β€’ πŸ‘οΈ Understand Images β€’ πŸ“Š Analyze Visual Data
"""

import numpy as np
from typing import Dict, List, Optional, Tuple
from PIL import Image, ImageDraw, ImageFilter
import io
import base64

class VisionAI:
    """πŸ–ΌοΈ Advanced image generation and analysis"""
    
    def __init__(self):
        self.generation_history = []
        self.analysis_cache = {}
    
    # 🎨 IMAGE GENERATION
    
    def generate_image(self, prompt: str, style: str = "realistic", size: Tuple[int, int] = (512, 512)) -> Dict:
        """🎨 Generate image from text prompt"""
        print(f"🎨 Generating image: {prompt}")
        
        # Create image based on prompt keywords
        img = Image.new('RGB', size, color='white')
        draw = ImageDraw.Draw(img)
        
        # Parse prompt for visual elements
        elements = self._parse_prompt(prompt)
        
        # Generate visual elements
        if 'landscape' in elements or 'nature' in elements:
            self._draw_landscape(draw, size)
        elif 'portrait' in elements or 'person' in elements:
            self._draw_portrait(draw, size)
        elif 'abstract' in elements or 'art' in elements:
            self._draw_abstract(draw, size)
        elif 'geometric' in elements or 'shape' in elements:
            self._draw_geometric(draw, size)
        else:
            self._draw_generic(draw, size, prompt)
        
        # Convert to base64
        buffer = io.BytesIO()
        img.save(buffer, format='PNG')
        img_base64 = base64.b64encode(buffer.getvalue()).decode()
        
        return {
            "status": "βœ… success",
            "prompt": prompt,
            "style": style,
            "size": size,
            "image_base64": img_base64,
            "emoji": "🎨",
            "message": "🎨 Image generated successfully!"
        }
    
    def _parse_prompt(self, prompt: str) -> List[str]:
        """πŸ” Parse prompt for visual elements"""
        elements = []
        prompt_lower = prompt.lower()
        
        keywords = {
            'landscape': ['mountain', 'forest', 'ocean', 'sky', 'sunset', 'sunrise'],
            'portrait': ['person', 'face', 'portrait', 'human', 'people'],
            'abstract': ['abstract', 'art', 'creative', 'creative', 'artistic'],
            'geometric': ['geometric', 'shape', 'circle', 'square', 'triangle', 'pattern']
        }
        
        for category, words in keywords.items():
            if any(word in prompt_lower for word in words):
                elements.append(category)
        
        return elements if elements else ['generic']
    
    def _draw_landscape(self, draw: ImageDraw.Draw, size: Tuple[int, int]):
        """πŸ”οΈ Draw landscape"""
        width, height = size
        
        # Sky gradient
        for y in range(height // 2):
            color = (135, 206, 235, int(255 * (1 - y / (height // 2))))
            draw.line([(0, y), (width, y)], fill=(135, 206, 235))
        
        # Mountains
        points = [(0, height // 2)]
        for x in range(0, width, 50):
            y = height // 2 + np.random.randint(-50, 50)
            points.append((x, y))
        points.append((width, height // 2))
        points.append((width, height))
        points.append((0, height))
        draw.polygon(points, fill=(34, 139, 34))
        
        # Sun
        draw.ellipse([width - 100, 50, width - 50, 100], fill=(255, 215, 0))
    
    def _draw_portrait(self, draw: ImageDraw.Draw, size: Tuple[int, int]):
        """πŸ‘€ Draw portrait"""
        width, height = size
        center_x, center_y = width // 2, height // 2
        
        # Head
        draw.ellipse([center_x - 80, center_y - 100, center_x + 80, center_y + 100], 
                    fill=(255, 218, 185))
        
        # Eyes
        draw.ellipse([center_x - 40, center_y - 20, center_x - 20, center_y], fill=(0, 0, 0))
        draw.ellipse([center_x + 20, center_y - 20, center_x + 40, center_y], fill=(0, 0, 0))
        
        # Mouth
        draw.arc([center_x - 30, center_y + 30, center_x + 30, center_y + 60], 
                0, 180, fill=(0, 0, 0), width=2)
    
    def _draw_abstract(self, draw: ImageDraw.Draw, size: Tuple[int, int]):
        """🎨 Draw abstract art"""
        width, height = size
        
        # Random colorful shapes
        for _ in range(20):
            x1 = np.random.randint(0, width)
            y1 = np.random.randint(0, height)
            x2 = x1 + np.random.randint(50, 150)
            y2 = y1 + np.random.randint(50, 150)
            color = tuple(np.random.randint(0, 255, 3))
            
            if np.random.rand() > 0.5:
                draw.ellipse([x1, y1, x2, y2], fill=color)
            else:
                draw.rectangle([x1, y1, x2, y2], fill=color)
    
    def _draw_geometric(self, draw: ImageDraw.Draw, size: Tuple[int, int]):
        """πŸ”· Draw geometric patterns"""
        width, height = size
        
        # Grid pattern
        for x in range(0, width, 50):
            draw.line([(x, 0), (x, height)], fill=(100, 100, 100), width=2)
        for y in range(0, height, 50):
            draw.line([(0, y), (width, y)], fill=(100, 100, 100), width=2)
        
        # Shapes
        for i in range(5):
            x = (i + 1) * 100
            y = (i + 1) * 80
            draw.polygon([(x, y), (x + 50, y + 50), (x, y + 50)], fill=(255, 0, 0))
    
    def _draw_generic(self, draw: ImageDraw.Draw, size: Tuple[int, int], prompt: str):
        """πŸ–ΌοΈ Draw generic image"""
        width, height = size
        
        # Background
        draw.rectangle([0, 0, width, height], fill=(240, 240, 240))
        
        # Text
        draw.text((50, height // 2), prompt[:50], fill=(0, 0, 0))
    
    # πŸ‘οΈ IMAGE ANALYSIS
    
    def analyze_image(self, image_data: str) -> Dict:
        """πŸ‘οΈ Analyze image content"""
        print("πŸ‘οΈ Analyzing image...")
        
        # Decode base64 image
        try:
            if image_data.startswith('data:image'):
                image_data = image_data.split(',')[1]
            image_bytes = base64.b64decode(image_data)
            img = Image.open(io.BytesIO(image_bytes))
        except Exception as e:
            return {"error": f"❌ Cannot decode image: {e}"}
        
        # Analyze image properties
        width, height = img.size
        mode = img.mode
        
        # Convert to RGB if needed
        if mode != 'RGB':
            img = img.convert('RGB')
        
        # Convert to numpy array for analysis
        img_array = np.array(img)
        
        # Calculate image statistics
        analysis = {
            "dimensions": {"width": width, "height": height},
            "mode": mode,
            "statistics": {
                "mean_brightness": float(np.mean(img_array)),
                "std_brightness": float(np.std(img_array)),
                "min_brightness": float(np.min(img_array)),
                "max_brightness": float(np.max(img_array))
            },
            "color_analysis": self._analyze_colors(img_array),
            "detected_objects": self._detect_objects(img_array),
            "scene_type": self._classify_scene(img_array),
            "quality_metrics": self._assess_quality(img_array)
        }
        
        return {
            "status": "βœ… success",
            "analysis": analysis,
            "emoji": "πŸ‘οΈ",
            "message": "πŸ‘οΈ Image analysis complete!"
        }
    
    def _analyze_colors(self, img_array: np.ndarray) -> Dict:
        """🎨 Analyze color distribution"""
        # Flatten image to 2D array (pixels x channels)
        pixels = img_array.reshape(-1, 3)
        
        # Calculate dominant colors
        # Simple color quantization
        r_mean, g_mean, b_mean = np.mean(pixels, axis=0)
        
        # Determine dominant color family
        if r_mean > g_mean and r_mean > b_mean:
            dominant = "πŸ”΄ Red/Warm"
        elif g_mean > r_mean and g_mean > b_mean:
            dominant = "🟒 Green/Nature"
        elif b_mean > r_mean and b_mean > g_mean:
            dominant = "πŸ”΅ Blue/Cool"
        else:
            dominant = "βšͺ Neutral"
        
        return {
            "dominant_color": dominant,
            "rgb_mean": [float(r_mean), float(g_mean), float(b_mean)],
            "color_variance": float(np.std(pixels))
        }
    
    def _detect_objects(self, img_array: np.ndarray) -> List[str]:
        """πŸ” Detect objects in image (simplified)"""
        objects = []
        
        # Simple heuristic-based detection
        # In production, use actual object detection model
        
        # Check for faces (skin color detection)
        skin_mask = (img_array[:,:,0] > 95) & (img_array[:,:,1] > 40) & (img_array[:,:,2] > 20)
        if np.sum(skin_mask) > 1000:
            objects.append("πŸ‘€ Person/Face")
        
        # Check for text (high contrast regions)
        gray = np.mean(img_array, axis=2)
        if np.std(gray) > 50:
            objects.append("πŸ“ Text/Documents")
        
        # Check for nature (green regions)
        green_mask = (img_array[:,:,1] > img_array[:,:,0]) & (img_array[:,:,1] > img_array[:,:,2])
        if np.sum(green_mask) > 10000:
            objects.append("🌿 Nature/Plants")
        
        # Check for sky (blue regions)
        blue_mask = (img_array[:,:,2] > img_array[:,:,0]) & (img_array[:,:,2] > img_array[:,:,1])
        if np.sum(blue_mask) > 20000:
            objects.append("☁️ Sky")
        
        return objects if objects else ["πŸ–ΌοΈ General Image"]
    
    def _classify_scene(self, img_array: np.ndarray) -> str:
        """🏞️ Classify scene type"""
        # Calculate brightness and color statistics
        brightness = np.mean(img_array)
        color_variance = np.std(img_array)
        
        if brightness > 200:
            return "β˜€οΈ Bright/Daylight"
        elif brightness < 50:
            return "πŸŒ™ Dark/Night"
        elif color_variance > 80:
            return "🎨 Colorful/Vibrant"
        elif color_variance < 30:
            return "βšͺ Monotone/Minimal"
        else:
            return "πŸ“Έ Standard Photo"
    
    def _assess_quality(self, img_array: np.ndarray) -> Dict:
        """πŸ“Š Assess image quality"""
        # Calculate sharpness (edge detection)
        from PIL import ImageFilter
        img = Image.fromarray(img_array)
        edges = img.filter(ImageFilter.FIND_EDGES)
        edge_array = np.array(edges)
        sharpness = np.mean(edge_array)
        
        # Calculate noise (variance in uniform regions)
        noise = np.std(img_array)
        
        # Overall quality score
        quality_score = min(100, sharpness * 2 + (100 - noise * 0.5))
        
        return {
            "sharpness": float(sharpness),
            "noise_level": float(noise),
            "quality_score": float(quality_score),
            "rating": "🌟 Excellent" if quality_score > 80 else "βœ… Good" if quality_score > 60 else "⚠️ Fair"
        }
    
    # πŸ”„ IMAGE PROCESSING
    
    def process_image(self, image_data: str, operation: str = "enhance") -> Dict:
        """πŸ”§ Process image with various operations"""
        print(f"πŸ”§ Processing image: {operation}")
        
        # Decode image
        try:
            if image_data.startswith('data:image'):
                image_data = image_data.split(',')[1]
            image_bytes = base64.b64decode(image_data)
            img = Image.open(io.BytesIO(image_bytes))
        except Exception as e:
            return {"error": f"❌ Cannot decode image: {e}"}
        
        # Apply operation
        if operation == "enhance":
            processed = self._enhance_image(img)
        elif operation == "resize":
            processed = img.resize((256, 256))
        elif operation == "grayscale":
            processed = img.convert('L').convert('RGB')
        elif operation == "blur":
            processed = img.filter(ImageFilter.BLUR)
        elif operation == "sharpen":
            processed = img.filter(ImageFilter.SHARPEN)
        elif operation == "edge_detect":
            processed = img.filter(ImageFilter.FIND_EDGES).convert('RGB')
        else:
            processed = img
        
        # Convert to base64
        buffer = io.BytesIO()
        processed.save(buffer, format='PNG')
        processed_base64 = base64.b64encode(buffer.getvalue()).decode()
        
        return {
            "status": "βœ… success",
            "operation": operation,
            "processed_image_base64": processed_base64,
            "emoji": "πŸ”§",
            "message": f"πŸ”§ Image {operation} complete!"
        }
    
    def _enhance_image(self, img: Image.Image) -> Image.Image:
        """✨ Enhance image quality"""
        # Enhance contrast
        from PIL import ImageEnhance
        enhancer = ImageEnhance.Contrast(img)
        img = enhancer.enhance(1.5)
        
        # Enhance sharpness
        enhancer = ImageEnhance.Sharpness(img)
        img = enhancer.enhance(1.3)
        
        # Enhance color
        enhancer = ImageEnhance.Color(img)
        img = enhancer.enhance(1.2)
        
        return img

# Export class
__all__ = ['VisionAI']