File size: 31,218 Bytes
a146cd6
ddd5292
 
 
 
 
 
 
 
 
 
a146cd6
ddd5292
a146cd6
ddd5292
1245652
ddd5292
1245652
 
 
 
ddd5292
1245652
 
 
 
 
ddd5292
 
 
 
 
 
 
1245652
 
 
 
ddd5292
 
1245652
 
ddd5292
1245652
 
ddd5292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
import os
import torch
import open_clip
from PIL import Image, ImageEnhance, ImageFilter
import numpy as np
import cv2
from typing import Dict, List, Tuple, Optional
import json
import colorsys
from sklearn.cluster import KMeans
import openai
from pathlib import Path
import base64

# ===== CONFIGURAÇÃO PARA HUGGING FACE SPACES =====
def setup_directories():
    """Configura diretórios com permissão de escrita para Hugging Face Spaces"""
    # Diretórios permitidos no Hugging Face Spaces
    temp_dir = Path(os.getenv('TEMP_PATH', '/tmp/temp'))
    thumbnails_dir = Path(os.getenv('THUMBNAILS_PATH', '/tmp/thumbnails'))
    data_dir = Path(os.getenv('DATA_PATH', '/tmp/data'))
    models_dir = Path(os.getenv('MODELS_PATH', '/tmp/models'))
    
    # Cria os diretórios se não existirem
    temp_dir.mkdir(parents=True, exist_ok=True)
    thumbnails_dir.mkdir(parents=True, exist_ok=True)
    data_dir.mkdir(parents=True, exist_ok=True)
    models_dir.mkdir(parents=True, exist_ok=True)
    
    print(f"✅ Diretórios configurados:")
    print(f"   📁 Temp: {temp_dir}")
    print(f"   📁 Thumbnails: {thumbnails_dir}")
    print(f"   📁 Data: {data_dir}")
    print(f"   📁 Models: {models_dir}")
    
    return {
        'temp': temp_dir,
        'thumbnails': thumbnails_dir,
        'data': data_dir,
        'models': models_dir
    }

# Configura diretórios globalmente
DIRS = setup_directories()

class JewelryImageProcessor:
    def __init__(self):
        """Inicializa o processador especializado em joias"""
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        
        # Carrega modelo OpenCLIP (melhor que CLIP padrão)
        model_name = os.getenv('EMBEDDING_MODEL', 'ViT-L-14')
        pretrained = os.getenv('EMBEDDING_PRETRAINED', 'laion2b_s32b_b82k')
        
        try:
            self.model, _, self.preprocess = open_clip.create_model_and_transforms(
                model_name, pretrained=pretrained, device=self.device
            )
            self.tokenizer = open_clip.get_tokenizer(model_name)
            print(f"🤖 Modelo {model_name} carregado no dispositivo: {self.device}")
        except Exception as e:
            print(f"❌ Erro ao carregar modelo OpenCLIP: {e}")
            # Fallback para modelo básico
            model_name = 'ViT-B-32'
            pretrained = 'openai'
            self.model, _, self.preprocess = open_clip.create_model_and_transforms(
                model_name, pretrained=pretrained, device=self.device
            )
            self.tokenizer = open_clip.get_tokenizer(model_name)
            print(f"🔄 Usando modelo fallback: {model_name}")
        
        # Configuração OpenAI para descrições
        openai.api_key = os.getenv('OPENAI_API_KEY')
        
        # Configuração de caminhos usando diretórios seguros
        self.temp_dir = DIRS['temp']
        self.thumbnails_dir = DIRS['thumbnails']
        self.data_dir = DIRS['data']
        
    def generate_embedding(self, image_path: str) -> Optional[np.ndarray]:
        """Gera embedding da imagem usando OpenCLIP"""
        try:
            image = Image.open(image_path).convert('RGB')
            image_input = self.preprocess(image).unsqueeze(0).to(self.device)
            
            with torch.no_grad():
                image_features = self.model.encode_image(image_input)
                # Normaliza o vetor
                image_features = image_features / image_features.norm(dim=-1, keepdim=True)
                
            return image_features.cpu().numpy().flatten()
        except Exception as e:
            print(f"❌ Erro ao gerar embedding para {image_path}: {e}")
            return None
    
    def generate_text_embedding(self, text: str) -> Optional[np.ndarray]:
        """Gera embedding de texto usando OpenCLIP"""
        try:
            text_tokens = self.tokenizer([text]).to(self.device)
            
            with torch.no_grad():
                text_features = self.model.encode_text(text_tokens)
                # Normaliza o vetor
                text_features = text_features / text_features.norm(dim=-1, keepdim=True)
                
            return text_features.cpu().numpy().flatten()
        except Exception as e:
            print(f"❌ Erro ao gerar embedding de texto para '{text}': {e}")
            return None
    
    def analyze_jewelry_technical(self, image_path: str) -> Dict:
        """Análise técnica especializada para joias"""
        try:
            # Carrega imagem
            image = cv2.imread(image_path)
            if image is None:
                print(f"❌ Não foi possível carregar a imagem: {image_path}")
                return {}
                
            image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            
            analysis = {
                "basic_metrics": self._analyze_basic_metrics(image_rgb),
                "color_analysis": self._analyze_jewelry_colors(image_rgb),
                "metal_analysis": self._analyze_metal_properties(image_rgb),
                "stone_analysis": self._analyze_stones(image_rgb),
                "shape_analysis": self._analyze_jewelry_shapes(image_rgb),
                "texture_analysis": self._analyze_textures(image_rgb),
                "reflection_analysis": self._analyze_reflections(image_rgb),
                "quality_assessment": self._assess_image_quality(image_rgb)
            }
            
            return analysis
        except Exception as e:
            print(f"❌ Erro na análise técnica de {image_path}: {e}")
            return {}
    
    def _analyze_basic_metrics(self, image: np.ndarray) -> Dict:
        """Métricas básicas da imagem"""
        try:
            height, width = image.shape[:2]
            
            # Brilho médio
            brightness = np.mean(image)
            
            # Contraste
            gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
            contrast = np.std(gray)
            
            # Saturação
            hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
            saturation = np.mean(hsv[:, :, 1])
            
            return {
                "dimensions": {"width": int(width), "height": int(height)},
                "brightness": float(brightness),
                "contrast": float(contrast),
                "saturation": float(saturation),
                "aspect_ratio": float(width / height)
            }
        except Exception as e:
            print(f"❌ Erro na análise básica: {e}")
            return {}
    
    def _analyze_jewelry_colors(self, image: np.ndarray) -> Dict:
        """Análise de cores específica para joias"""
        try:
            # Extrai cores dominantes
            dominant_colors = self._extract_dominant_colors(image, k=8)
            
            # Classifica cores por categoria de joia
            color_categories = self._classify_jewelry_colors(dominant_colors)
            
            # Analisa temperatura de cor
            color_temperature = self._analyze_color_temperature(image)
            
            return {
                "dominant_colors": dominant_colors,
                "color_categories": color_categories,
                "color_temperature": color_temperature,
                "color_harmony": self._analyze_color_harmony(dominant_colors)
            }
        except Exception as e:
            print(f"❌ Erro na análise de cores: {e}")
            return {}
    
    def _analyze_metal_properties(self, image: np.ndarray) -> Dict:
        """Análise específica para propriedades metálicas"""
        try:
            # Converte para HSV para melhor análise de metais
            hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
            
            # Detecta áreas metálicas por brilho e saturação
            brightness_mask = hsv[:, :, 2] > 150  # Áreas brilhantes
            low_saturation_mask = hsv[:, :, 1] < 100  # Baixa saturação (típico de metais)
            metal_mask = brightness_mask & low_saturation_mask
            
            metal_percentage = np.sum(metal_mask) / (image.shape[0] * image.shape[1])
            
            # Analisa tons metálicos
            metal_regions = image[metal_mask]
            if len(metal_regions) > 0:
                avg_metal_color = np.mean(metal_regions, axis=0)
                metal_type = self._classify_metal_type(avg_metal_color)
            else:
                metal_type = "unknown"
                avg_metal_color = [0, 0, 0]
            
            return {
                "metal_percentage": float(metal_percentage),
                "metal_type": metal_type,
                "average_metal_color": avg_metal_color.tolist(),
                "metallic_shine_intensity": self._calculate_shine_intensity(image, metal_mask)
            }
        except Exception as e:
            print(f"❌ Erro na análise de metais: {e}")
            return {}
    
    def _analyze_stones(self, image: np.ndarray) -> Dict:
        """Análise específica para pedras preciosas"""
        try:
            # Detecta áreas com alta saturação (típico de pedras coloridas)
            hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
            high_saturation_mask = hsv[:, :, 1] > 100
            
            stone_percentage = np.sum(high_saturation_mask) / (image.shape[0] * image.shape[1])
            
            # Analisa cores das pedras
            stone_regions = image[high_saturation_mask]
            stone_colors = []
            
            if len(stone_regions) > 0:
                # Agrupa cores das pedras
                try:
                    kmeans = KMeans(n_clusters=min(5, max(1, len(stone_regions)//100)), random_state=42, n_init=10)
                    if len(stone_regions) > 100:
                        kmeans.fit(stone_regions)
                        stone_colors = [color.tolist() for color in kmeans.cluster_centers_]
                except Exception as kmeans_error:
                    print(f"❌ Erro no K-means para pedras: {kmeans_error}")
                    stone_colors = []
            
            return {
                "stone_percentage": float(stone_percentage),
                "stone_colors": stone_colors,
                "stone_types": [self._classify_stone_type(color) for color in stone_colors],
                "transparency_level": self._analyze_transparency(image, high_saturation_mask)
            }
        except Exception as e:
            print(f"❌ Erro na análise de pedras: {e}")
            return {}
    
    def _analyze_jewelry_shapes(self, image: np.ndarray) -> Dict:
        """Análise de formas geométricas típicas de joias"""
        try:
            gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
            
            # Detecta bordas
            edges = cv2.Canny(gray, 50, 150)
            
            # Encontra contornos
            contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            
            shapes = []
            for contour in contours:
                area = cv2.contourArea(contour)
                if area > 100:  # Filtra contornos muito pequenos
                    shape_type = self._classify_jewelry_shape(contour)
                    shapes.append({
                        "type": shape_type,
                        "area": float(area),
                        "perimeter": float(cv2.arcLength(contour, True))
                    })
            
            return {
                "detected_shapes": shapes,
                "primary_shape": shapes[0]["type"] if shapes else "irregular",
                "shape_complexity": len(shapes),
                "edge_density": float(np.sum(edges > 0) / (edges.shape[0] * edges.shape[1]))
            }
        except Exception as e:
            print(f"❌ Erro na análise de formas: {e}")
            return {}
    
    def _analyze_textures(self, image: np.ndarray) -> Dict:
        """Análise de texturas (polido, fosco, texturizado)"""
        try:
            gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
            
            # Calcula variância local (indica textura)
            kernel = np.ones((9, 9), np.float32) / 81
            mean = cv2.filter2D(gray.astype(np.float32), -1, kernel)
            sqr_mean = cv2.filter2D((gray.astype(np.float32))**2, -1, kernel)
            variance = sqr_mean - mean**2
            
            texture_intensity = np.mean(variance)
            
            # Detecta padrões repetitivos
            pattern_score = self._detect_patterns(gray)
            
            return {
                "texture_intensity": float(texture_intensity),
                "texture_type": self._classify_texture_type(texture_intensity),
                "pattern_score": float(pattern_score),
                "surface_finish": self._classify_surface_finish(texture_intensity, np.std(gray))
            }
        except Exception as e:
            print(f"❌ Erro na análise de texturas: {e}")
            return {}
    
    def _analyze_reflections(self, image: np.ndarray) -> Dict:
        """Análise de reflexos e brilho (importante para joias)"""
        try:
            gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
            
            # Detecta áreas muito brilhantes (reflexos)
            bright_threshold = np.percentile(gray, 95)
            reflection_mask = gray > bright_threshold
            
            reflection_percentage = np.sum(reflection_mask) / (gray.shape[0] * gray.shape[1])
            
            # Analisa distribuição dos reflexos
            reflection_distribution = self._analyze_reflection_distribution(reflection_mask)
            
            return {
                "reflection_percentage": float(reflection_percentage),
                "reflection_intensity": float(np.mean(gray[reflection_mask]) if np.any(reflection_mask) else 0),
                "reflection_distribution": reflection_distribution,
                "shine_quality": self._assess_shine_quality(reflection_percentage, reflection_distribution)
            }
        except Exception as e:
            print(f"❌ Erro na análise de reflexos: {e}")
            return {}
    
    def _assess_image_quality(self, image: np.ndarray) -> Dict:
        """Avalia qualidade geral da imagem para joias"""
        try:
            gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
            
            # Nitidez (usando variância do Laplaciano)
            sharpness = cv2.Laplacian(gray, cv2.CV_64F).var()
            
            # Exposição (distribuição de histograma)
            hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
            exposure_score = self._calculate_exposure_score(hist)
            
            # Score geral de qualidade
            quality_score = min(1.0, (sharpness / 1000 + exposure_score) / 2)
            
            return {
                "sharpness": float(sharpness),
                "exposure_score": float(exposure_score),
                "overall_quality": float(quality_score),
                "quality_grade": self._grade_quality(quality_score)
            }
        except Exception as e:
            print(f"❌ Erro na avaliação de qualidade: {e}")
            return {}
    
    def generate_ai_description(self, image_path: str, piece_metadata: Dict) -> str:
        """Gera descrição detalhada usando GPT-4 Vision"""
        try:
            # Verifica se a chave da OpenAI está disponível
            if not openai.api_key:
                return f"Joia {piece_metadata.get('name', 'sem nome')} da coleção {piece_metadata.get('collection', 'N/A')} - Descrição IA não disponível"
            
            # Converte imagem para base64
            with open(image_path, "rb") as image_file:
                base64_image = base64.b64encode(image_file.read()).decode('utf-8')
            
            prompt = f"""
            Analise esta imagem de joia e forneça uma descrição detalhada e técnica em português.
            
            Metadados da peça:
            - SKU: {piece_metadata.get('sku', 'N/A')}
            - Nome: {piece_metadata.get('name', 'N/A')}
            - Material: {piece_metadata.get('material', 'N/A')}
            - Pedra: {piece_metadata.get('stone', 'N/A')}
            - Coleção: {piece_metadata.get('collection', 'N/A')}
            
            Descreva:
            1. Tipo de joia e formato geral
            2. Materiais visíveis (metais, pedras, acabamentos)
            3. Cores predominantes e secundárias
            4. Estilo e design (moderno, clássico, vintage, etc.)
            5. Detalhes técnicos visíveis (lapidação, engastes, texturas)
            6. Qualidade aparente e acabamento
            7. Características que facilitariam a busca por similaridade
            
            Seja específico e use termos técnicos de joalheria quando apropriado.
            """
            
            response = openai.ChatCompletion.create(
                model="gpt-4-vision-preview",
                messages=[
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt},
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": f"data:image/png;base64,{base64_image}"
                                }
                            }
                        ]
                    }
                ],
                max_tokens=500
            )
            
            return response.choices[0].message.content
            
        except Exception as e:
            print(f"❌ Erro ao gerar descrição IA: {e}")
            return f"Joia {piece_metadata.get('name', 'sem nome')} da coleção {piece_metadata.get('collection', 'N/A')}"
    
    def create_thumbnail(self, image_path: str, output_path: str, size: Tuple[int, int] = (200, 200)) -> bool:
        """Cria thumbnail da imagem usando o diretório seguro"""
        try:
            # Garante que o diretório de output está no local correto
            output_path = str(self.thumbnails_dir / Path(output_path).name)
            
            with Image.open(image_path) as img:
                # Mantém proporção
                img.thumbnail(size, Image.Resampling.LANCZOS)
                
                # Cria imagem quadrada com fundo branco
                thumbnail = Image.new('RGB', size, (255, 255, 255))
                
                # Centraliza a imagem
                x = (size[0] - img.width) // 2
                y = (size[1] - img.height) // 2
                thumbnail.paste(img, (x, y))
                
                # Salva thumbnail
                thumbnail.save(output_path, 'PNG', quality=95)
                return True
        except Exception as e:
            print(f"❌ Erro ao criar thumbnail de {image_path}: {e}")
            return False
    
    # ===== MÉTODOS AUXILIARES DE CLASSIFICAÇÃO =====
    
    def _extract_dominant_colors(self, image: np.ndarray, k: int = 8) -> List[Dict]:
        """Extrai cores dominantes com informações detalhadas"""
        try:
            pixels = image.reshape(-1, 3)
            kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
            kmeans.fit(pixels)
            
            colors = []
            labels = kmeans.labels_
            unique, counts = np.unique(labels, return_counts=True)
            
            for i, color in enumerate(kmeans.cluster_centers_):
                percentage = counts[i] / len(labels) * 100
                rgb = [int(c) for c in color]
                
                colors.append({
                    "rgb": rgb,
                    "hex": "#{:02x}{:02x}{:02x}".format(*rgb),
                    "percentage": float(percentage),
                    "hsl": self._rgb_to_hsl(rgb),
                    "color_name": self._get_color_name(rgb)
                })
            
            return sorted(colors, key=lambda x: x['percentage'], reverse=True)
        except Exception as e:
            print(f"❌ Erro ao extrair cores dominantes: {e}")
            return []
    
    def _classify_metal_type(self, color: np.ndarray) -> str:
        """Classifica tipo de metal baseado na cor"""
        try:
            r, g, b = color
            
            # Ouro amarelo
            if r > 200 and g > 180 and b < 150:
                return "gold_yellow"
            # Ouro branco/prata
            elif abs(r - g) < 20 and abs(g - b) < 20 and r > 180:
                return "silver_white_gold"
            # Ouro rosé
            elif r > 200 and g > 150 and g < 180 and b < 150:
                return "rose_gold"
            # Cobre
            elif r > 180 and g > 100 and g < 150 and b < 100:
                return "copper"
            else:
                return "unknown_metal"
        except:
            return "unknown_metal"
    
    def _classify_stone_type(self, color: List[float]) -> str:
        """Classifica tipo de pedra baseado na cor"""
        try:
            r, g, b = color
            
            if r < 100 and g < 100 and b > 150:
                return "blue_stone"  # Safira, topázio azul
            elif r > 150 and g < 100 and b < 100:
                return "red_stone"   # Rubi, granada
            elif r < 100 and g > 150 and b < 100:
                return "green_stone" # Esmeralda, jade
            elif r > 200 and g > 200 and b > 200:
                return "clear_stone" # Diamante, cristal
            elif r > 150 and g > 100 and b > 150:
                return "purple_stone" # Ametista
            else:
                return "colored_stone"
        except:
            return "unknown_stone"
    
    def _rgb_to_hsl(self, rgb: List[int]) -> List[float]:
        """Converte RGB para HSL"""
        try:
            r, g, b = [x/255.0 for x in rgb]
            h, l, s = colorsys.rgb_to_hls(r, g, b)
            return [h*360, s*100, l*100]
        except:
            return [0, 0, 0]
    
    def _get_color_name(self, rgb: List[int]) -> str:
        """Retorna nome aproximado da cor"""
        try:
            r, g, b = rgb
            
            # Cores básicas para joias
            if r > 200 and g > 200 and b > 200:
                return "branco"
            elif r < 50 and g < 50 and b < 50:
                return "preto"
            elif r > 200 and g > 180 and b < 100:
                return "dourado"
            elif r > 180 and g > 180 and b > 180:
                return "prateado"
            elif r > 150 and g < 100 and b < 100:
                return "vermelho"
            elif r < 100 and g < 100 and b > 150:
                return "azul"
            elif r < 100 and g > 150 and b < 100:
                return "verde"
            elif r > 150 and g > 100 and b > 150:
                return "roxo"
            elif r > 200 and g > 150 and b < 100:
                return "laranja"
            else:
                return "multicolorido"
        except:
            return "indefinido"
    
    def _classify_jewelry_colors(self, colors: List[Dict]) -> Dict:
        """Classifica cores por categorias de joias"""
        try:
            categories = {
                "metal_tones": [],
                "stone_colors": [],
                "accent_colors": []
            }
            
            for color in colors:
                color_name = color.get("color_name", "")
                if color_name in ["dourado", "prateado", "branco"]:
                    categories["metal_tones"].append(color)
                elif color.get("percentage", 0) > 5:  # Cores significativas
                    categories["stone_colors"].append(color)
                else:
                    categories["accent_colors"].append(color)
            
            return categories
        except:
            return {"metal_tones": [], "stone_colors": [], "accent_colors": []}
    
    def _analyze_color_temperature(self, image: np.ndarray) -> str:
        """Analisa temperatura de cor da imagem"""
        try:
            avg_color = np.mean(image, axis=(0, 1))
            r, g, b = avg_color
            
            if r > g and r > b:
                return "warm"  # Tons quentes
            elif b > r and b > g:
                return "cool"  # Tons frios
            else:
                return "neutral"
        except:
            return "neutral"
    
    def _analyze_color_harmony(self, colors: List[Dict]) -> str:
        """Analisa harmonia das cores"""
        try:
            if len(colors) < 2:
                return "monochromatic"
            
            # Analisa diferenças de matiz
            hues = [color.get("hsl", [0, 0, 0])[0] for color in colors[:3]]  # Top 3 cores
            hue_differences = [abs(hues[i] - hues[i+1]) for i in range(len(hues)-1)]
            
            if not hue_differences:
                return "monochromatic"
                
            avg_diff = np.mean(hue_differences)
            
            if avg_diff < 30:
                return "analogous"
            elif avg_diff > 150:
                return "complementary"
            else:
                return "triadic"
        except:
            return "neutral"
    
    # ===== MÉTODOS AUXILIARES ESPECÍFICOS =====
    
    def _calculate_shine_intensity(self, image: np.ndarray, metal_mask: np.ndarray) -> float:
        """Calcula intensidade do brilho metálico"""
        try:
            if not np.any(metal_mask):
                return 0.0
            gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
            metal_brightness = np.mean(gray[metal_mask])
            return float(metal_brightness / 255.0)
        except:
            return 0.0
    
    def _analyze_transparency(self, image: np.ndarray, stone_mask: np.ndarray) -> str:
        """Analisa nível de transparência das pedras"""
        try:
            if not np.any(stone_mask):
                return "opaque"
            
            # Calcula variância de brilho nas áreas das pedras
            gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
            stone_variance = np.var(gray[stone_mask])
            
            if stone_variance > 1000:
                return "transparent"
            elif stone_variance > 500:
                return "translucent"
            else:
                return "opaque"
        except:
            return "opaque"
    
    def _classify_jewelry_shape(self, contour: np.ndarray) -> str:
        """Classifica forma geométrica de joias"""
        try:
            # Aproxima contorno
            epsilon = 0.02 * cv2.arcLength(contour, True)
            approx = cv2.approxPolyDP(contour, epsilon, True)
            
            # Classifica baseado no número de vértices
            vertices = len(approx)
            
            if vertices == 3:
                return "triangular"
            elif vertices == 4:
                return "quadrilateral"
            elif vertices > 8:
                return "circular"
            else:
                return "polygonal"
        except:
            return "irregular"
    
    def _detect_patterns(self, gray: np.ndarray) -> float:
        """Detecta padrões repetitivos na textura"""
        try:
            # Usa transformada de Fourier para detectar padrões
            f_transform = np.fft.fft2(gray)
            f_shift = np.fft.fftshift(f_transform)
            magnitude_spectrum = 20 * np.log(np.abs(f_shift) + 1)
            
            # Calcula energia dos picos (indica padrões)
            threshold = np.percentile(magnitude_spectrum, 95)
            pattern_energy = np.sum(magnitude_spectrum > threshold)
            
            return float(pattern_energy / (gray.shape[0] * gray.shape[1]))
        except:
            return 0.0
    
    def _classify_texture_type(self, texture_intensity: float) -> str:
        """Classifica tipo de textura"""
        try:
            if texture_intensity < 100:
                return "polished"
            elif texture_intensity < 500:
                return "satin"
            else:
                return "textured"
        except:
            return "unknown"
    
    def _classify_surface_finish(self, texture_intensity: float, std_dev: float) -> str:
        """Classifica acabamento da superfície"""
        try:
            if texture_intensity < 50 and std_dev < 30:
                return "mirror_polish"
            elif texture_intensity < 200:
                return "high_polish"
            elif texture_intensity < 500:
                return "satin_finish"
            else:
                return "matte_finish"
        except:
            return "unknown_finish"
    
    def _analyze_reflection_distribution(self, reflection_mask: np.ndarray) -> str:
        """Analisa distribuição dos reflexos"""
        try:
            if not np.any(reflection_mask):
                return "no_reflections"
            
            # Calcula centros dos reflexos
            contours, _ = cv2.findContours(reflection_mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            
            if len(contours) <= 1:
                return "single_reflection"
            elif len(contours) <= 3:
                return "few_reflections"
            else:
                return "multiple_reflections"
        except:
            return "unknown_distribution"
    
    def _assess_shine_quality(self, reflection_percentage: float, distribution: str) -> str:
        """Avalia qualidade do brilho"""
        try:
            if reflection_percentage > 0.1 and distribution in ["few_reflections", "multiple_reflections"]:
                return "excellent_shine"
            elif reflection_percentage > 0.05:
                return "good_shine"
            elif reflection_percentage > 0.02:
                return "moderate_shine"
            else:
                return "low_shine"
        except:
            return "unknown_shine"
    
    def _calculate_exposure_score(self, hist: np.ndarray) -> float:
        """Calcula score de exposição baseado no histograma"""
        try:
            # Verifica distribuição do histograma
            total_pixels = np.sum(hist)
            
            # Pixels muito escuros ou muito claros indicam má exposição
            dark_pixels = np.sum(hist[:50]) / total_pixels
            bright_pixels = np.sum(hist[200:]) / total_pixels
            
            # Score ideal é ter poucos pixels extremos
            exposure_score = 1.0 - (dark_pixels + bright_pixels)
            return max(0.0, min(1.0, exposure_score))
        except:
            return 0.5
    
    def _grade_quality(self, quality_score: float) -> str:
        """Classifica qualidade em grades"""
        try:
            if quality_score >= 0.8:
                return "excellent"
            elif quality_score >= 0.6:
                return "good"
            elif quality_score >= 0.4:
                return "fair"
            else:
                return "poor"
        except:
            return "unknown"