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"