Spaces:
Sleeping
Sleeping
Download image_processor.py from OctusTech/cartalogo-api: direct link, hf CLI and curl.
- Browser
- Download file 28.1 kB
-
https://huggingface.co/spaces/OctusTech/cartalogo-api/resolve/fef4203a8e525970ba9ea85cd6f4d8d406402c23/image_processor.py
- Command line
-
hf download hf://spaces/OctusTech/cartalogo-api@fef4203a8e525970ba9ea85cd6f4d8d406402c23/image_processor.py
-
curl -L -o image_processor.py https://huggingface.co/spaces/OctusTech/cartalogo-api/resolve/fef4203a8e525970ba9ea85cd6f4d8d406402c23/image_processor.py
28.1 kB
| import os | |
| import sys | |
| from pathlib import Path | |
| from dotenv import load_dotenv | |
| 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 time | |
| # FORÇA carregamento das variáveis de ambiente | |
| env_file = Path(__file__).parent / ".env" | |
| print(f"🔍 Carregando .env de: {env_file}") | |
| print(f"🔍 Arquivo existe: {env_file.exists()}") | |
| if env_file.exists(): | |
| # Carrega com override para forçar | |
| load_result = load_dotenv(env_file, override=True, verbose=True) | |
| print(f"🔍 Load result: {load_result}") | |
| else: | |
| print("❌ Arquivo .env não encontrado!") | |
| # Tenta carregar do diretório atual | |
| load_dotenv(override=True, verbose=True) | |
| class JewelryImageProcessor: | |
| def __init__(self): | |
| """Inicializa o processador especializado em joias""" | |
| print("🤖 Inicializando processador de imagens para joias...") | |
| # Configuração de caminhos | |
| self.root_dir = Path(__file__).parent | |
| self.images_dir = self.root_dir / "imagens" | |
| self.thumbnails_dir = self.root_dir / "thumbnails" | |
| # Cria diretório de thumbnails | |
| self.thumbnails_dir.mkdir(exist_ok=True) | |
| # Configuração do dispositivo | |
| self.device = "cuda" if torch.cuda.is_available() else "cpu" | |
| print(f"🔧 Dispositivo: {self.device}") | |
| # Carrega modelo OpenCLIP | |
| try: | |
| model_name = os.getenv('EMBEDDING_MODEL', 'ViT-L-14') | |
| pretrained = os.getenv('EMBEDDING_PRETRAINED', 'laion2b_s32b_b82k') | |
| print(f"📥 Carregando modelo {model_name} ({pretrained})...") | |
| 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("✅ Modelo OpenCLIP carregado com sucesso!") | |
| except Exception as e: | |
| print(f"❌ Erro ao carregar modelo OpenCLIP: {e}") | |
| raise | |
| # DEBUG: Configuração OpenAI v1.0+ | |
| print("\n🔍 DEBUG OpenAI:") | |
| # Tenta diferentes formas de obter a chave | |
| openai_api_key = None | |
| # Método 1: os.getenv | |
| openai_api_key = os.getenv('OPENAI_API_KEY') | |
| print(f"🔍 Método 1 (os.getenv): {openai_api_key[:15] if openai_api_key else 'None'}...") | |
| # Método 2: os.environ.get | |
| if not openai_api_key or openai_api_key.startswith('your-'): | |
| openai_api_key = os.environ.get('OPENAI_API_KEY') | |
| print(f"🔍 Método 2 (os.environ): {openai_api_key[:15] if openai_api_key else 'None'}...") | |
| # Método 3: Lê diretamente do arquivo .env | |
| if not openai_api_key or openai_api_key.startswith('your-'): | |
| try: | |
| env_file = self.root_dir / ".env" | |
| if env_file.exists(): | |
| with open(env_file, 'r', encoding='utf-8') as f: | |
| for line in f: | |
| if line.startswith('OPENAI_API_KEY='): | |
| openai_api_key = line.split('=', 1)[1].strip() | |
| print(f"🔍 Método 3 (arquivo): {openai_api_key[:15]}...") | |
| break | |
| except Exception as e: | |
| print(f"🔍 Erro método 3: {e}") | |
| self.openai_client = None | |
| print(f"🔑 OpenAI API Key final: {'Sim' if openai_api_key else 'Não'}") | |
| if openai_api_key: | |
| print(f"🔑 Primeiros caracteres: {openai_api_key[:15]}...") | |
| print(f"🔑 Começa com sk-: {openai_api_key.startswith('sk-')}") | |
| if openai_api_key and openai_api_key.startswith('sk-'): | |
| try: | |
| from openai import OpenAI | |
| self.openai_client = OpenAI(api_key=openai_api_key) | |
| print("✅ OpenAI v1.0+ configurado para descrições IA") | |
| # Testa a conexão | |
| try: | |
| # Faz um teste simples para verificar se a API key funciona | |
| test_response = self.openai_client.models.list() | |
| print("✅ Conexão com OpenAI testada com sucesso") | |
| except Exception as test_error: | |
| print(f"⚠️ Erro ao testar conexão OpenAI: {test_error}") | |
| self.openai_client = None | |
| except ImportError: | |
| print("⚠️ OpenAI não instalado - descrições IA desabilitadas") | |
| self.openai_client = None | |
| except Exception as e: | |
| print(f"⚠️ Erro ao configurar OpenAI: {e}") | |
| self.openai_client = None | |
| else: | |
| print("⚠️ OpenAI API key inválida - descrições IA desabilitadas") | |
| self.openai_client = None | |
| def generate_embedding(self, image_path: Path) -> Optional[np.ndarray]: | |
| """Gera embedding da imagem usando OpenCLIP""" | |
| try: | |
| if not image_path.exists(): | |
| print(f"❌ Arquivo não encontrado: {image_path}") | |
| return None | |
| # Carrega e processa imagem | |
| 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.name}: {e}") | |
| return None | |
| def analyze_jewelry_technical(self, image_path: Path) -> Dict: | |
| """Análise técnica especializada para joias""" | |
| try: | |
| if not image_path.exists(): | |
| return {} | |
| # Carrega imagem | |
| image = cv2.imread(str(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) | |
| print(f"🔍 Analisando {image_path.name}...") | |
| 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.name}: {e}") | |
| return {} | |
| def extract_visual_features(self, image_path: Path, technical_analysis: Dict) -> List[Dict]: | |
| """Extrai características visuais estruturadas para a tabela visual_features""" | |
| features = [] | |
| try: | |
| # Características de cor | |
| color_analysis = technical_analysis.get('color_analysis', {}) | |
| dominant_colors = color_analysis.get('dominant_colors', []) | |
| for i, color in enumerate(dominant_colors[:3]): # Top 3 cores | |
| features.append({ | |
| 'feature_type': 'dominant_color', | |
| 'feature_value': color.get('hex', '#000000'), | |
| 'confidence_score': min(0.99, color.get('percentage', 0) / 100) | |
| }) | |
| # Características de metal | |
| metal_analysis = technical_analysis.get('metal_analysis', {}) | |
| if metal_analysis.get('has_metallic_elements', False): | |
| features.append({ | |
| 'feature_type': 'material', | |
| 'feature_value': 'metallic', | |
| 'confidence_score': min(0.99, metal_analysis.get('metal_percentage', 0)) | |
| }) | |
| # Características de pedras | |
| stone_analysis = technical_analysis.get('stone_analysis', {}) | |
| if stone_analysis.get('has_colored_stones', False): | |
| features.append({ | |
| 'feature_type': 'material', | |
| 'feature_value': 'gemstone', | |
| 'confidence_score': min(0.99, stone_analysis.get('stone_percentage', 0)) | |
| }) | |
| # Características de forma | |
| shape_analysis = technical_analysis.get('shape_analysis', {}) | |
| complexity = shape_analysis.get('shape_complexity', 'unknown') | |
| if complexity != 'unknown': | |
| features.append({ | |
| 'feature_type': 'shape', | |
| 'feature_value': complexity, | |
| 'confidence_score': 0.8 | |
| }) | |
| # Características de textura | |
| texture_analysis = technical_analysis.get('texture_analysis', {}) | |
| texture_type = texture_analysis.get('texture_type', 'unknown') | |
| if texture_type != 'unknown': | |
| features.append({ | |
| 'feature_type': 'texture', | |
| 'feature_value': texture_type, | |
| 'confidence_score': 0.75 | |
| }) | |
| # Características de qualidade | |
| quality_assessment = technical_analysis.get('quality_assessment', {}) | |
| quality_grade = quality_assessment.get('quality_grade', 'unknown') | |
| if quality_grade != 'unknown': | |
| features.append({ | |
| 'feature_type': 'quality', | |
| 'feature_value': quality_grade, | |
| 'confidence_score': quality_assessment.get('quality_score', 0.5) | |
| }) | |
| except Exception as e: | |
| print(f"⚠️ Erro ao extrair características visuais: {e}") | |
| return features | |
| def generate_image_tags(self, image_path: Path, piece_metadata: Dict, technical_analysis: Dict) -> List[Dict]: | |
| """Gera tags automáticas para a imagem""" | |
| tags = [] | |
| try: | |
| # Tags baseadas nos metadados | |
| category = piece_metadata.get('category', '') | |
| if category: | |
| tags.append({ | |
| 'tag': category, | |
| 'confidence': 0.95, | |
| 'tag_type': 'category' | |
| }) | |
| collection = piece_metadata.get('collection', '') | |
| if collection: | |
| tags.append({ | |
| 'tag': collection.lower(), | |
| 'confidence': 0.9, | |
| 'tag_type': 'collection' | |
| }) | |
| stone = piece_metadata.get('stone', '') | |
| if stone and stone.lower() not in ['', 'nan', 'none']: | |
| tags.append({ | |
| 'tag': stone.lower(), | |
| 'confidence': 0.85, | |
| 'tag_type': 'material' | |
| }) | |
| metal = piece_metadata.get('predominant_metal', '') | |
| if metal and metal.lower() not in ['', 'nan', 'none']: | |
| tags.append({ | |
| 'tag': metal.lower().replace(' ', '_'), | |
| 'confidence': 0.85, | |
| 'tag_type': 'material' | |
| }) | |
| # Tags baseadas na análise técnica | |
| color_analysis = technical_analysis.get('color_analysis', {}) | |
| dominant_colors = color_analysis.get('dominant_colors', []) | |
| for color in dominant_colors[:2]: # Top 2 cores | |
| if color.get('percentage', 0) > 15: # Apenas cores significativas | |
| color_name = self._get_color_name_from_rgb(color.get('rgb', [0, 0, 0])) | |
| tags.append({ | |
| 'tag': color_name, | |
| 'confidence': min(0.8, color.get('percentage', 0) / 100), | |
| 'tag_type': 'color' | |
| }) | |
| # Tags de estilo baseadas no nome do arquivo | |
| filename = image_path.name.lower() | |
| if 'modelo' in filename: | |
| tags.append({ | |
| 'tag': 'lifestyle', | |
| 'confidence': 0.9, | |
| 'tag_type': 'style' | |
| }) | |
| else: | |
| tags.append({ | |
| 'tag': 'product_shot', | |
| 'confidence': 0.9, | |
| 'tag_type': 'style' | |
| }) | |
| # Tags de qualidade | |
| quality_assessment = technical_analysis.get('quality_assessment', {}) | |
| quality_score = quality_assessment.get('quality_score', 0) | |
| if quality_score > 0.7: | |
| tags.append({ | |
| 'tag': 'high_quality', | |
| 'confidence': quality_score, | |
| 'tag_type': 'quality' | |
| }) | |
| elif quality_score > 0.3: | |
| tags.append({ | |
| 'tag': 'medium_quality', | |
| 'confidence': quality_score, | |
| 'tag_type': 'quality' | |
| }) | |
| except Exception as e: | |
| print(f"⚠️ Erro ao gerar tags: {e}") | |
| return tags | |
| def create_thumbnail(self, image_path: Path, size: Tuple[int, int] = None) -> Optional[Path]: | |
| """Cria thumbnail da imagem""" | |
| try: | |
| if size is None: | |
| size = (int(os.getenv('THUMBNAIL_SIZE', 200)), int(os.getenv('THUMBNAIL_SIZE', 200))) | |
| if not image_path.exists(): | |
| return None | |
| # Define caminho do thumbnail | |
| thumbnail_name = f"thumb_{image_path.stem}.png" | |
| thumbnail_path = self.thumbnails_dir / thumbnail_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(thumbnail_path, 'PNG', quality=95) | |
| print(f"✅ Thumbnail criado: {thumbnail_name}") | |
| return thumbnail_path | |
| except Exception as e: | |
| print(f"❌ Erro ao criar thumbnail de {image_path.name}: {e}") | |
| return None | |
| def generate_ai_description(self, image_path: Path, piece_metadata: Dict) -> str: | |
| """Gera descrição detalhada usando GPT-4 Vision (OpenAI v1.0+)""" | |
| try: | |
| if not self.openai_client: | |
| print(f" ⚠️ OpenAI não configurado, usando descrição básica") | |
| return self._generate_basic_description(piece_metadata) | |
| # Converte imagem para base64 | |
| import 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 brasileiro. | |
| 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 detalhadamente: | |
| 1. Tipo de joia e formato geral | |
| 2. Materiais visíveis (metais, pedras, acabamentos) | |
| 3. Cores predominantes e tonalidades | |
| 4. Estilo e design (moderno, clássico, vintage, etc.) | |
| 5. Detalhes técnicos (lapidação, engastes, texturas) | |
| 6. Qualidade aparente e acabamento | |
| 7. Características distintivas para busca | |
| Use terminologia técnica de joalheria. Seja específico e descritivo. | |
| """ | |
| print(f" 🤖 Gerando descrição IA para {image_path.name}...") | |
| response = self.openai_client.chat.completions.create( | |
| model="gpt-4o", # Modelo mais recente e estável | |
| messages=[ | |
| { | |
| "role": "user", | |
| "content": [ | |
| {"type": "text", "text": prompt}, | |
| { | |
| "type": "image_url", | |
| "image_url": { | |
| "url": f"data:image/png;base64,{base64_image}", | |
| "detail": "low" # Reduz custo | |
| } | |
| } | |
| ] | |
| } | |
| ], | |
| max_tokens=400, | |
| temperature=0.3 # Mais consistente | |
| ) | |
| description = response.choices[0].message.content | |
| print(f" ✅ Descrição IA gerada ({len(description)} caracteres)") | |
| return description | |
| except Exception as e: | |
| print(f" ⚠️ Erro ao gerar descrição IA para {image_path.name}: {e}") | |
| print(f" 🔄 Usando descrição básica como fallback") | |
| return self._generate_basic_description(piece_metadata) | |
| def _generate_basic_description(self, piece_metadata: Dict) -> str: | |
| """Gera descrição básica sem IA""" | |
| name = piece_metadata.get('name', 'Joia') | |
| collection = piece_metadata.get('collection', '') | |
| material = piece_metadata.get('material', '') | |
| stone = piece_metadata.get('stone', '') | |
| description = f"{name}" | |
| if collection: | |
| description += f" da coleção {collection}" | |
| if material: | |
| description += f", confeccionada em {material}" | |
| if stone: | |
| description += f" com {stone}" | |
| return description | |
| def find_images_from_metadata(self, piece_metadata: Dict) -> List[Dict]: | |
| """Encontra imagens baseado nos metadados da planilha""" | |
| images = [] | |
| sku = piece_metadata.get('sku', '') | |
| # Baseado na estrutura real do CSV: apenas arquivo_peca_01 | |
| filename = piece_metadata.get('arquivo_peca_01', '').strip() | |
| if filename and filename != 'nan' and filename != '': | |
| image_path = self.images_dir / filename | |
| if image_path.exists(): | |
| # Determina tipo baseado no nome do arquivo | |
| filename_lower = filename.lower() | |
| if any(keyword in filename_lower for keyword in ["modelo", "person", "wearing", "lifestyle", "usando"]): | |
| image_type = "lifestyle" | |
| elif any(keyword in filename_lower for keyword in ["detalhe", "detail", "close"]): | |
| image_type = "detail" | |
| elif any(keyword in filename_lower for keyword in ["embalagem", "packaging", "box"]): | |
| image_type = "packaging" | |
| else: | |
| image_type = "product" | |
| images.append({ | |
| 'path': image_path, | |
| 'filename': filename, | |
| 'type': image_type, | |
| 'size': image_path.stat().st_size, | |
| 'column': 'arquivo_peca_01' | |
| }) | |
| print(f" ✅ Encontrada: {filename} ({image_type})") | |
| else: | |
| print(f" ❌ Não encontrada: {filename}") | |
| else: | |
| print(f" ⚠️ Nenhum arquivo especificado para SKU: {sku}") | |
| return images | |
| def _get_color_name_from_rgb(self, rgb: List[int]) -> str: | |
| """Retorna nome da cor baseado em RGB""" | |
| if not rgb or len(rgb) != 3: | |
| return "indefinido" | |
| 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" | |
| # Métodos de análise técnica (mantidos iguais) | |
| def _analyze_basic_metrics(self, image: np.ndarray) -> Dict: | |
| """Métricas básicas da imagem""" | |
| height, width = image.shape[:2] | |
| brightness = float(np.mean(image)) | |
| gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
| contrast = float(np.std(gray)) | |
| hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) | |
| saturation = float(np.mean(hsv[:, :, 1])) | |
| return { | |
| "dimensions": {"width": width, "height": height}, | |
| "brightness": brightness, | |
| "contrast": contrast, | |
| "saturation": saturation, | |
| "aspect_ratio": float(width / height) | |
| } | |
| def _analyze_jewelry_colors(self, image: np.ndarray) -> Dict: | |
| """Análise de cores para joias""" | |
| try: | |
| dominant_colors = self._extract_dominant_colors(image, k=6) | |
| return { | |
| "dominant_colors": dominant_colors, | |
| "color_count": len(dominant_colors), | |
| "primary_color": dominant_colors[0] if dominant_colors else None | |
| } | |
| except: | |
| return {"dominant_colors": [], "color_count": 0, "primary_color": None} | |
| def _extract_dominant_colors(self, image: np.ndarray, k: int = 6) -> List[Dict]: | |
| """Extrai cores dominantes""" | |
| try: | |
| pixels = image.reshape(-1, 3) | |
| # Reduz amostra para performance | |
| if len(pixels) > 10000: | |
| indices = np.random.choice(len(pixels), 10000, replace=False) | |
| pixels = pixels[indices] | |
| 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) | |
| }) | |
| return sorted(colors, key=lambda x: x['percentage'], reverse=True) | |
| except Exception as e: | |
| print(f"⚠️ Erro na extração de cores: {e}") | |
| return [] | |
| def _analyze_metal_properties(self, image: np.ndarray) -> Dict: | |
| """Análise básica de propriedades metálicas""" | |
| try: | |
| hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) | |
| # Detecta áreas metálicas (brilhantes + baixa saturação) | |
| brightness_mask = hsv[:, :, 2] > 150 | |
| low_saturation_mask = hsv[:, :, 1] < 80 | |
| metal_mask = brightness_mask & low_saturation_mask | |
| metal_percentage = float(np.sum(metal_mask) / (image.shape[0] * image.shape[1])) | |
| return { | |
| "metal_percentage": metal_percentage, | |
| "has_metallic_elements": metal_percentage > 0.1 | |
| } | |
| except: | |
| return {"metal_percentage": 0.0, "has_metallic_elements": False} | |
| def _analyze_stones(self, image: np.ndarray) -> Dict: | |
| """Análise básica de pedras""" | |
| try: | |
| hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) | |
| high_saturation_mask = hsv[:, :, 1] > 100 | |
| stone_percentage = float(np.sum(high_saturation_mask) / (image.shape[0] * image.shape[1])) | |
| return { | |
| "stone_percentage": stone_percentage, | |
| "has_colored_stones": stone_percentage > 0.05 | |
| } | |
| except: | |
| return {"stone_percentage": 0.0, "has_colored_stones": False} | |
| def _analyze_jewelry_shapes(self, image: np.ndarray) -> Dict: | |
| """Análise básica de formas""" | |
| try: | |
| gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
| edges = cv2.Canny(gray, 50, 150) | |
| edge_density = float(np.sum(edges > 0) / (edges.shape[0] * edges.shape[1])) | |
| return { | |
| "edge_density": edge_density, | |
| "shape_complexity": "high" if edge_density > 0.1 else "low" | |
| } | |
| except: | |
| return {"edge_density": 0.0, "shape_complexity": "unknown"} | |
| def _analyze_textures(self, image: np.ndarray) -> Dict: | |
| """Análise básica de texturas""" | |
| try: | |
| gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
| texture_variance = float(np.var(gray)) | |
| return { | |
| "texture_variance": texture_variance, | |
| "texture_type": "smooth" if texture_variance < 1000 else "textured" | |
| } | |
| except: | |
| return {"texture_variance": 0.0, "texture_type": "unknown"} | |
| def _analyze_reflections(self, image: np.ndarray) -> Dict: | |
| """Análise básica de reflexos""" | |
| try: | |
| gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
| bright_threshold = np.percentile(gray, 95) | |
| reflection_mask = gray > bright_threshold | |
| reflection_percentage = float(np.sum(reflection_mask) / (gray.shape[0] * gray.shape[1])) | |
| return { | |
| "reflection_percentage": reflection_percentage, | |
| "has_reflections": reflection_percentage > 0.05 | |
| } | |
| except: | |
| return {"reflection_percentage": 0.0, "has_reflections": False} | |
| def _assess_image_quality(self, image: np.ndarray) -> Dict: | |
| """Avaliação básica de qualidade""" | |
| try: | |
| gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
| # Nitidez usando variância do Laplaciano | |
| sharpness = float(cv2.Laplacian(gray, cv2.CV_64F).var()) | |
| # Score de qualidade simples | |
| quality_score = min(1.0, sharpness / 1000) | |
| return { | |
| "sharpness": sharpness, | |
| "quality_score": quality_score, | |
| "quality_grade": "high" if quality_score > 0.7 else "medium" if quality_score > 0.3 else "low" | |
| } | |
| except: | |
| return {"sharpness": 0.0, "quality_score": 0.0, "quality_grade": "unknown"} | |