Spaces:
Sleeping
Sleeping
File size: 28,130 Bytes
a146cd6 | 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 | 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"}
|