Spaces:
Sleeping
Sleeping
Limpeza
Browse files- api_v0.py +0 -91
- mazzia +0 -1
- scripts/enhanced_image_processor_v0.py +0 -455
- scripts/jewelry_cataloger_v0.py +0 -228
api_v0.py
DELETED
|
@@ -1,91 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import uuid
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
from fastapi import FastAPI, File, UploadFile, HTTPException, Form
|
| 5 |
-
from fastapi.responses import JSONResponse
|
| 6 |
-
from typing import List
|
| 7 |
-
import shutil
|
| 8 |
-
|
| 9 |
-
# Importa nosso buscador
|
| 10 |
-
from scripts.similarity_search import SimilaritySearcher
|
| 11 |
-
|
| 12 |
-
# Cria a aplicação FastAPI
|
| 13 |
-
app = FastAPI(
|
| 14 |
-
title="API de Busca de Catálogo de Joias",
|
| 15 |
-
description="Uma API para buscar joias por texto, imagem ou áudio.",
|
| 16 |
-
version="1.0.0"
|
| 17 |
-
)
|
| 18 |
-
|
| 19 |
-
# Inicializa o buscador uma vez para toda a aplicação
|
| 20 |
-
# Isso evita recarregar os modelos de IA a cada requisição
|
| 21 |
-
try:
|
| 22 |
-
searcher = SimilaritySearcher()
|
| 23 |
-
except Exception as e:
|
| 24 |
-
print(f"Erro fatal ao inicializar o SimilaritySearcher: {e}")
|
| 25 |
-
searcher = None
|
| 26 |
-
|
| 27 |
-
# Cria um diretório temporário para uploads
|
| 28 |
-
# TEMP_DIR = Path("temp_uploads")
|
| 29 |
-
# TEMP_DIR.mkdir(exist_ok=True)
|
| 30 |
-
|
| 31 |
-
TEMP_DIR = Path("/tmp/temp_uploads")
|
| 32 |
-
TEMP_DIR.mkdir(parents=True, exist_ok=True)
|
| 33 |
-
|
| 34 |
-
@app.on_event("startup")
|
| 35 |
-
async def startup_event():
|
| 36 |
-
if searcher is None:
|
| 37 |
-
raise RuntimeError("Falha ao carregar o modelo de busca. A API não pode iniciar.")
|
| 38 |
-
print("API pronta para receber requisições.")
|
| 39 |
-
|
| 40 |
-
@app.get("/", tags=["Status"])
|
| 41 |
-
def read_root():
|
| 42 |
-
"""Verifica se a API está online."""
|
| 43 |
-
return {"status": "online", "message": "Bem-vindo à API de Busca de Joias!"}
|
| 44 |
-
|
| 45 |
-
@app.post("/search-by-text", tags=["Busca"])
|
| 46 |
-
async def search_by_text(query: str = Form(...)):
|
| 47 |
-
"""
|
| 48 |
-
Busca joias por uma descrição de texto.
|
| 49 |
-
"""
|
| 50 |
-
try:
|
| 51 |
-
results = searcher.search_by_text(text_query=query, top_k=3)
|
| 52 |
-
if not results:
|
| 53 |
-
return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
|
| 54 |
-
return {"results": results}
|
| 55 |
-
except Exception as e:
|
| 56 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 57 |
-
|
| 58 |
-
@app.post("/search-by-image", tags=["Busca"])
|
| 59 |
-
async def search_by_image(file: UploadFile = File(...)):
|
| 60 |
-
"""
|
| 61 |
-
Busca joias similares a uma imagem enviada.
|
| 62 |
-
"""
|
| 63 |
-
# Gera um nome de arquivo único e seguro
|
| 64 |
-
temp_filename = f"{uuid.uuid4()}{Path(file.filename).suffix}"
|
| 65 |
-
temp_file_path = TEMP_DIR / temp_filename
|
| 66 |
-
|
| 67 |
-
try:
|
| 68 |
-
# Salva o arquivo temporariamente
|
| 69 |
-
with temp_file_path.open("wb") as buffer:
|
| 70 |
-
shutil.copyfileobj(file.file, buffer)
|
| 71 |
-
|
| 72 |
-
# Realiza a busca
|
| 73 |
-
results = searcher.search_by_image(image_path=temp_file_path, top_k=3)
|
| 74 |
-
|
| 75 |
-
if not results:
|
| 76 |
-
return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
|
| 77 |
-
return {"results": results}
|
| 78 |
-
except Exception as e:
|
| 79 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 80 |
-
finally:
|
| 81 |
-
# Garante que o arquivo temporário seja deletado
|
| 82 |
-
if temp_file_path.exists():
|
| 83 |
-
temp_file_path.unlink()
|
| 84 |
-
|
| 85 |
-
# Nota: A busca por áudio será implementada na próxima fase para manter o foco.
|
| 86 |
-
# Ela exigirá a integração com a API do Whisper (OpenAI).
|
| 87 |
-
|
| 88 |
-
if __name__ == "__main__":
|
| 89 |
-
import uvicorn
|
| 90 |
-
print("Iniciando API em modo de desenvolvimento...")
|
| 91 |
-
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
mazzia
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
commit
|
|
|
|
|
|
scripts/enhanced_image_processor_v0.py
DELETED
|
@@ -1,455 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import open_clip
|
| 3 |
-
from PIL import Image, ImageEnhance, ImageFilter
|
| 4 |
-
import numpy as np
|
| 5 |
-
import cv2
|
| 6 |
-
from typing import Dict, List, Tuple, Optional
|
| 7 |
-
import json
|
| 8 |
-
import colorsys
|
| 9 |
-
from sklearn.cluster import KMeans
|
| 10 |
-
import openai
|
| 11 |
-
import os
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
|
| 14 |
-
class JewelryImageProcessor:
|
| 15 |
-
def __init__(self):
|
| 16 |
-
"""Inicializa o processador especializado em joias"""
|
| 17 |
-
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 18 |
-
|
| 19 |
-
# Carrega modelo OpenCLIP (melhor que CLIP padrão)
|
| 20 |
-
model_name = os.getenv('EMBEDDING_MODEL', 'ViT-L-14')
|
| 21 |
-
pretrained = os.getenv('EMBEDDING_PRETRAINED', 'laion2b_s32b_b82k')
|
| 22 |
-
|
| 23 |
-
self.model, _, self.preprocess = open_clip.create_model_and_transforms(
|
| 24 |
-
model_name, pretrained=pretrained, device=self.device
|
| 25 |
-
)
|
| 26 |
-
self.tokenizer = open_clip.get_tokenizer(model_name)
|
| 27 |
-
|
| 28 |
-
# Configuração OpenAI para descrições
|
| 29 |
-
openai.api_key = os.getenv('OPENAI_API_KEY')
|
| 30 |
-
|
| 31 |
-
print(f"🤖 Modelo {model_name} carregado no dispositivo: {self.device}")
|
| 32 |
-
|
| 33 |
-
def generate_embedding(self, image_path: str) -> Optional[np.ndarray]:
|
| 34 |
-
"""Gera embedding da imagem usando OpenCLIP"""
|
| 35 |
-
try:
|
| 36 |
-
image = Image.open(image_path).convert('RGB')
|
| 37 |
-
image_input = self.preprocess(image).unsqueeze(0).to(self.device)
|
| 38 |
-
|
| 39 |
-
with torch.no_grad():
|
| 40 |
-
image_features = self.model.encode_image(image_input)
|
| 41 |
-
# Normaliza o vetor
|
| 42 |
-
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
|
| 43 |
-
|
| 44 |
-
return image_features.cpu().numpy().flatten()
|
| 45 |
-
except Exception as e:
|
| 46 |
-
print(f"❌ Erro ao gerar embedding para {image_path}: {e}")
|
| 47 |
-
return None
|
| 48 |
-
|
| 49 |
-
def analyze_jewelry_technical(self, image_path: str) -> Dict:
|
| 50 |
-
"""Análise técnica especializada para joias"""
|
| 51 |
-
try:
|
| 52 |
-
# Carrega imagem
|
| 53 |
-
image = cv2.imread(image_path)
|
| 54 |
-
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 55 |
-
|
| 56 |
-
analysis = {
|
| 57 |
-
"basic_metrics": self._analyze_basic_metrics(image_rgb),
|
| 58 |
-
"color_analysis": self._analyze_jewelry_colors(image_rgb),
|
| 59 |
-
"metal_analysis": self._analyze_metal_properties(image_rgb),
|
| 60 |
-
"stone_analysis": self._analyze_stones(image_rgb),
|
| 61 |
-
"shape_analysis": self._analyze_jewelry_shapes(image_rgb),
|
| 62 |
-
"texture_analysis": self._analyze_textures(image_rgb),
|
| 63 |
-
"reflection_analysis": self._analyze_reflections(image_rgb),
|
| 64 |
-
"quality_assessment": self._assess_image_quality(image_rgb)
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
return analysis
|
| 68 |
-
except Exception as e:
|
| 69 |
-
print(f"❌ Erro na análise técnica de {image_path}: {e}")
|
| 70 |
-
return {}
|
| 71 |
-
|
| 72 |
-
def _analyze_basic_metrics(self, image: np.ndarray) -> Dict:
|
| 73 |
-
"""Métricas básicas da imagem"""
|
| 74 |
-
height, width = image.shape[:2]
|
| 75 |
-
|
| 76 |
-
# Brilho médio
|
| 77 |
-
brightness = np.mean(image)
|
| 78 |
-
|
| 79 |
-
# Contraste
|
| 80 |
-
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
| 81 |
-
contrast = np.std(gray)
|
| 82 |
-
|
| 83 |
-
# Saturação
|
| 84 |
-
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
|
| 85 |
-
saturation = np.mean(hsv[:, :, 1])
|
| 86 |
-
|
| 87 |
-
return {
|
| 88 |
-
"dimensions": {"width": width, "height": height},
|
| 89 |
-
"brightness": float(brightness),
|
| 90 |
-
"contrast": float(contrast),
|
| 91 |
-
"saturation": float(saturation),
|
| 92 |
-
"aspect_ratio": float(width / height)
|
| 93 |
-
}
|
| 94 |
-
|
| 95 |
-
def _analyze_jewelry_colors(self, image: np.ndarray) -> Dict:
|
| 96 |
-
"""Análise de cores específica para joias"""
|
| 97 |
-
# Extrai cores dominantes
|
| 98 |
-
dominant_colors = self._extract_dominant_colors(image, k=8)
|
| 99 |
-
|
| 100 |
-
# Classifica cores por categoria de joia
|
| 101 |
-
color_categories = self._classify_jewelry_colors(dominant_colors)
|
| 102 |
-
|
| 103 |
-
# Analisa temperatura de cor
|
| 104 |
-
color_temperature = self._analyze_color_temperature(image)
|
| 105 |
-
|
| 106 |
-
return {
|
| 107 |
-
"dominant_colors": dominant_colors,
|
| 108 |
-
"color_categories": color_categories,
|
| 109 |
-
"color_temperature": color_temperature,
|
| 110 |
-
"color_harmony": self._analyze_color_harmony(dominant_colors)
|
| 111 |
-
}
|
| 112 |
-
|
| 113 |
-
def _analyze_metal_properties(self, image: np.ndarray) -> Dict:
|
| 114 |
-
"""Análise específica para propriedades metálicas"""
|
| 115 |
-
# Converte para HSV para melhor análise de metais
|
| 116 |
-
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
|
| 117 |
-
|
| 118 |
-
# Detecta áreas metálicas por brilho e saturação
|
| 119 |
-
brightness_mask = hsv[:, :, 2] > 150 # Áreas brilhantes
|
| 120 |
-
low_saturation_mask = hsv[:, :, 1] < 100 # Baixa saturação (típico de metais)
|
| 121 |
-
metal_mask = brightness_mask & low_saturation_mask
|
| 122 |
-
|
| 123 |
-
metal_percentage = np.sum(metal_mask) / (image.shape[0] * image.shape[1])
|
| 124 |
-
|
| 125 |
-
# Analisa tons metálicos
|
| 126 |
-
metal_regions = image[metal_mask]
|
| 127 |
-
if len(metal_regions) > 0:
|
| 128 |
-
avg_metal_color = np.mean(metal_regions, axis=0)
|
| 129 |
-
metal_type = self._classify_metal_type(avg_metal_color)
|
| 130 |
-
else:
|
| 131 |
-
metal_type = "unknown"
|
| 132 |
-
avg_metal_color = [0, 0, 0]
|
| 133 |
-
|
| 134 |
-
return {
|
| 135 |
-
"metal_percentage": float(metal_percentage),
|
| 136 |
-
"metal_type": metal_type,
|
| 137 |
-
"average_metal_color": avg_metal_color.tolist(),
|
| 138 |
-
"metallic_shine_intensity": self._calculate_shine_intensity(image, metal_mask)
|
| 139 |
-
}
|
| 140 |
-
|
| 141 |
-
def _analyze_stones(self, image: np.ndarray) -> Dict:
|
| 142 |
-
"""Análise específica para pedras preciosas"""
|
| 143 |
-
# Detecta áreas com alta saturação (típico de pedras coloridas)
|
| 144 |
-
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
|
| 145 |
-
high_saturation_mask = hsv[:, :, 1] > 100
|
| 146 |
-
|
| 147 |
-
stone_percentage = np.sum(high_saturation_mask) / (image.shape[0] * image.shape[1])
|
| 148 |
-
|
| 149 |
-
# Analisa cores das pedras
|
| 150 |
-
stone_regions = image[high_saturation_mask]
|
| 151 |
-
stone_colors = []
|
| 152 |
-
|
| 153 |
-
if len(stone_regions) > 0:
|
| 154 |
-
# Agrupa cores das pedras
|
| 155 |
-
kmeans = KMeans(n_clusters=min(5, len(stone_regions)//100), random_state=42, n_init=10)
|
| 156 |
-
if len(stone_regions) > 100:
|
| 157 |
-
kmeans.fit(stone_regions)
|
| 158 |
-
stone_colors = [color.tolist() for color in kmeans.cluster_centers_]
|
| 159 |
-
|
| 160 |
-
return {
|
| 161 |
-
"stone_percentage": float(stone_percentage),
|
| 162 |
-
"stone_colors": stone_colors,
|
| 163 |
-
"stone_types": [self._classify_stone_type(color) for color in stone_colors],
|
| 164 |
-
"transparency_level": self._analyze_transparency(image, high_saturation_mask)
|
| 165 |
-
}
|
| 166 |
-
|
| 167 |
-
def _analyze_jewelry_shapes(self, image: np.ndarray) -> Dict:
|
| 168 |
-
"""Análise de formas geométricas típicas de joias"""
|
| 169 |
-
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
| 170 |
-
|
| 171 |
-
# Detecta bordas
|
| 172 |
-
edges = cv2.Canny(gray, 50, 150)
|
| 173 |
-
|
| 174 |
-
# Encontra contornos
|
| 175 |
-
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 176 |
-
|
| 177 |
-
shapes = []
|
| 178 |
-
for contour in contours:
|
| 179 |
-
if cv2.contourArea(contour) > 100: # Filtra contornos muito pequenos
|
| 180 |
-
shape_type = self._classify_jewelry_shape(contour)
|
| 181 |
-
shapes.append({
|
| 182 |
-
"type": shape_type,
|
| 183 |
-
"area": float(cv2.contourArea(contour)),
|
| 184 |
-
"perimeter": float(cv2.arcLength(contour, True))
|
| 185 |
-
})
|
| 186 |
-
|
| 187 |
-
return {
|
| 188 |
-
"detected_shapes": shapes,
|
| 189 |
-
"primary_shape": shapes[0]["type"] if shapes else "irregular",
|
| 190 |
-
"shape_complexity": len(shapes),
|
| 191 |
-
"edge_density": float(np.sum(edges > 0) / (edges.shape[0] * edges.shape[1]))
|
| 192 |
-
}
|
| 193 |
-
|
| 194 |
-
def _analyze_textures(self, image: np.ndarray) -> Dict:
|
| 195 |
-
"""Análise de texturas (polido, fosco, texturizado)"""
|
| 196 |
-
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
| 197 |
-
|
| 198 |
-
# Calcula variância local (indica textura)
|
| 199 |
-
kernel = np.ones((9, 9), np.float32) / 81
|
| 200 |
-
mean = cv2.filter2D(gray.astype(np.float32), -1, kernel)
|
| 201 |
-
sqr_mean = cv2.filter2D((gray.astype(np.float32))**2, -1, kernel)
|
| 202 |
-
variance = sqr_mean - mean**2
|
| 203 |
-
|
| 204 |
-
texture_intensity = np.mean(variance)
|
| 205 |
-
|
| 206 |
-
# Detecta padrões repetitivos
|
| 207 |
-
pattern_score = self._detect_patterns(gray)
|
| 208 |
-
|
| 209 |
-
return {
|
| 210 |
-
"texture_intensity": float(texture_intensity),
|
| 211 |
-
"texture_type": self._classify_texture_type(texture_intensity),
|
| 212 |
-
"pattern_score": float(pattern_score),
|
| 213 |
-
"surface_finish": self._classify_surface_finish(texture_intensity, np.std(gray))
|
| 214 |
-
}
|
| 215 |
-
|
| 216 |
-
def _analyze_reflections(self, image: np.ndarray) -> Dict:
|
| 217 |
-
"""Análise de reflexos e brilho (importante para joias)"""
|
| 218 |
-
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
| 219 |
-
|
| 220 |
-
# Detecta áreas muito brilhantes (reflexos)
|
| 221 |
-
bright_threshold = np.percentile(gray, 95)
|
| 222 |
-
reflection_mask = gray > bright_threshold
|
| 223 |
-
|
| 224 |
-
reflection_percentage = np.sum(reflection_mask) / (gray.shape[0] * gray.shape[1])
|
| 225 |
-
|
| 226 |
-
# Analisa distribuição dos reflexos
|
| 227 |
-
reflection_distribution = self._analyze_reflection_distribution(reflection_mask)
|
| 228 |
-
|
| 229 |
-
return {
|
| 230 |
-
"reflection_percentage": float(reflection_percentage),
|
| 231 |
-
"reflection_intensity": float(np.mean(gray[reflection_mask]) if np.any(reflection_mask) else 0),
|
| 232 |
-
"reflection_distribution": reflection_distribution,
|
| 233 |
-
"shine_quality": self._assess_shine_quality(reflection_percentage, reflection_distribution)
|
| 234 |
-
}
|
| 235 |
-
|
| 236 |
-
def _assess_image_quality(self, image: np.ndarray) -> Dict:
|
| 237 |
-
"""Avalia qualidade geral da imagem para joias"""
|
| 238 |
-
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
| 239 |
-
|
| 240 |
-
# Nitidez (usando variância do Laplaciano)
|
| 241 |
-
sharpness = cv2.Laplacian(gray, cv2.CV_64F).var()
|
| 242 |
-
|
| 243 |
-
# Exposição (distribuição de histograma)
|
| 244 |
-
hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
|
| 245 |
-
exposure_score = self._calculate_exposure_score(hist)
|
| 246 |
-
|
| 247 |
-
# Score geral de qualidade
|
| 248 |
-
quality_score = min(1.0, (sharpness / 1000 + exposure_score) / 2)
|
| 249 |
-
|
| 250 |
-
return {
|
| 251 |
-
"sharpness": float(sharpness),
|
| 252 |
-
"exposure_score": float(exposure_score),
|
| 253 |
-
"overall_quality": float(quality_score),
|
| 254 |
-
"quality_grade": self._grade_quality(quality_score)
|
| 255 |
-
}
|
| 256 |
-
|
| 257 |
-
def generate_ai_description(self, image_path: str, piece_metadata: Dict) -> str:
|
| 258 |
-
"""Gera descrição detalhada usando GPT-4 Vision"""
|
| 259 |
-
try:
|
| 260 |
-
# Converte imagem para base64
|
| 261 |
-
import base64
|
| 262 |
-
with open(image_path, "rb") as image_file:
|
| 263 |
-
base64_image = base64.b64encode(image_file.read()).decode('utf-8')
|
| 264 |
-
|
| 265 |
-
prompt = f"""
|
| 266 |
-
Analise esta imagem de joia e forneça uma descrição detalhada e técnica em português.
|
| 267 |
-
|
| 268 |
-
Metadados da peça:
|
| 269 |
-
- SKU: {piece_metadata.get('sku', 'N/A')}
|
| 270 |
-
- Nome: {piece_metadata.get('name', 'N/A')}
|
| 271 |
-
- Material: {piece_metadata.get('material', 'N/A')}
|
| 272 |
-
- Pedra: {piece_metadata.get('stone', 'N/A')}
|
| 273 |
-
- Coleção: {piece_metadata.get('collection', 'N/A')}
|
| 274 |
-
|
| 275 |
-
Descreva:
|
| 276 |
-
1. Tipo de joia e formato geral
|
| 277 |
-
2. Materiais visíveis (metais, pedras, acabamentos)
|
| 278 |
-
3. Cores predominantes e secundárias
|
| 279 |
-
4. Estilo e design (moderno, clássico, vintage, etc.)
|
| 280 |
-
5. Detalhes técnicos visíveis (lapidação, engastes, texturas)
|
| 281 |
-
6. Qualidade aparente e acabamento
|
| 282 |
-
7. Características que facilitariam a busca por similaridade
|
| 283 |
-
|
| 284 |
-
Seja específico e use termos técnicos de joalheria quando apropriado.
|
| 285 |
-
"""
|
| 286 |
-
|
| 287 |
-
response = openai.ChatCompletion.create(
|
| 288 |
-
model="gpt-4-vision-preview",
|
| 289 |
-
messages=[
|
| 290 |
-
{
|
| 291 |
-
"role": "user",
|
| 292 |
-
"content": [
|
| 293 |
-
{"type": "text", "text": prompt},
|
| 294 |
-
{
|
| 295 |
-
"type": "image_url",
|
| 296 |
-
"image_url": {
|
| 297 |
-
"url": f"data:image/png;base64,{base64_image}"
|
| 298 |
-
}
|
| 299 |
-
}
|
| 300 |
-
]
|
| 301 |
-
}
|
| 302 |
-
],
|
| 303 |
-
max_tokens=500
|
| 304 |
-
)
|
| 305 |
-
|
| 306 |
-
return response.choices[0].message.content
|
| 307 |
-
|
| 308 |
-
except Exception as e:
|
| 309 |
-
print(f"❌ Erro ao gerar descrição IA: {e}")
|
| 310 |
-
return f"Joia {piece_metadata.get('name', 'sem nome')} da coleção {piece_metadata.get('collection', 'N/A')}"
|
| 311 |
-
|
| 312 |
-
# Métodos auxiliares de classificação
|
| 313 |
-
def _extract_dominant_colors(self, image: np.ndarray, k: int = 8) -> List[Dict]:
|
| 314 |
-
"""Extrai cores dominantes com informações detalhadas"""
|
| 315 |
-
pixels = image.reshape(-1, 3)
|
| 316 |
-
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
|
| 317 |
-
kmeans.fit(pixels)
|
| 318 |
-
|
| 319 |
-
colors = []
|
| 320 |
-
labels = kmeans.labels_
|
| 321 |
-
unique, counts = np.unique(labels, return_counts=True)
|
| 322 |
-
|
| 323 |
-
for i, color in enumerate(kmeans.cluster_centers_):
|
| 324 |
-
percentage = counts[i] / len(labels) * 100
|
| 325 |
-
rgb = [int(c) for c in color]
|
| 326 |
-
|
| 327 |
-
colors.append({
|
| 328 |
-
"rgb": rgb,
|
| 329 |
-
"hex": "#{:02x}{:02x}{:02x}".format(*rgb),
|
| 330 |
-
"percentage": float(percentage),
|
| 331 |
-
"hsl": self._rgb_to_hsl(rgb),
|
| 332 |
-
"color_name": self._get_color_name(rgb)
|
| 333 |
-
})
|
| 334 |
-
|
| 335 |
-
return sorted(colors, key=lambda x: x['percentage'], reverse=True)
|
| 336 |
-
|
| 337 |
-
def _classify_metal_type(self, color: np.ndarray) -> str:
|
| 338 |
-
"""Classifica tipo de metal baseado na cor"""
|
| 339 |
-
r, g, b = color
|
| 340 |
-
|
| 341 |
-
# Ouro amarelo
|
| 342 |
-
if r > 200 and g > 180 and b < 150:
|
| 343 |
-
return "gold_yellow"
|
| 344 |
-
# Ouro branco/prata
|
| 345 |
-
elif abs(r - g) < 20 and abs(g - b) < 20 and r > 180:
|
| 346 |
-
return "silver_white_gold"
|
| 347 |
-
# Ouro rosé
|
| 348 |
-
elif r > 200 and g > 150 and g < 180 and b < 150:
|
| 349 |
-
return "rose_gold"
|
| 350 |
-
# Cobre
|
| 351 |
-
elif r > 180 and g > 100 and g < 150 and b < 100:
|
| 352 |
-
return "copper"
|
| 353 |
-
else:
|
| 354 |
-
return "unknown_metal"
|
| 355 |
-
|
| 356 |
-
def _classify_stone_type(self, color: List[float]) -> str:
|
| 357 |
-
"""Classifica tipo de pedra baseado na cor"""
|
| 358 |
-
r, g, b = color
|
| 359 |
-
|
| 360 |
-
if r < 100 and g < 100 and b > 150:
|
| 361 |
-
return "blue_stone" # Safira, topázio azul
|
| 362 |
-
elif r > 150 and g < 100 and b < 100:
|
| 363 |
-
return "red_stone" # Rubi, granada
|
| 364 |
-
elif r < 100 and g > 150 and b < 100:
|
| 365 |
-
return "green_stone" # Esmeralda, jade
|
| 366 |
-
elif r > 200 and g > 200 and b > 200:
|
| 367 |
-
return "clear_stone" # Diamante, cristal
|
| 368 |
-
elif r > 150 and g > 100 and b > 150:
|
| 369 |
-
return "purple_stone" # Ametista
|
| 370 |
-
else:
|
| 371 |
-
return "colored_stone"
|
| 372 |
-
|
| 373 |
-
def _rgb_to_hsl(self, rgb: List[int]) -> List[float]:
|
| 374 |
-
"""Converte RGB para HSL"""
|
| 375 |
-
r, g, b = [x/255.0 for x in rgb]
|
| 376 |
-
h, l, s = colorsys.rgb_to_hls(r, g, b)
|
| 377 |
-
return [h*360, s*100, l*100]
|
| 378 |
-
|
| 379 |
-
def _get_color_name(self, rgb: List[int]) -> str:
|
| 380 |
-
"""Retorna nome aproximado da cor"""
|
| 381 |
-
r, g, b = rgb
|
| 382 |
-
|
| 383 |
-
# Cores básicas para joias
|
| 384 |
-
if r > 200 and g > 200 and b > 200:
|
| 385 |
-
return "branco"
|
| 386 |
-
elif r < 50 and g < 50 and b < 50:
|
| 387 |
-
return "preto"
|
| 388 |
-
elif r > 200 and g > 180 and b < 100:
|
| 389 |
-
return "dourado"
|
| 390 |
-
elif r > 180 and g > 180 and b > 180:
|
| 391 |
-
return "prateado"
|
| 392 |
-
elif r > 150 and g < 100 and b < 100:
|
| 393 |
-
return "vermelho"
|
| 394 |
-
elif r < 100 and g < 100 and b > 150:
|
| 395 |
-
return "azul"
|
| 396 |
-
elif r < 100 and g > 150 and b < 100:
|
| 397 |
-
return "verde"
|
| 398 |
-
elif r > 150 and g > 100 and b > 150:
|
| 399 |
-
return "roxo"
|
| 400 |
-
elif r > 200 and g > 150 and b < 100:
|
| 401 |
-
return "laranja"
|
| 402 |
-
else:
|
| 403 |
-
return "multicolorido"
|
| 404 |
-
|
| 405 |
-
# Implementar outros métodos auxiliares...
|
| 406 |
-
def _classify_jewelry_colors(self, colors: List[Dict]) -> Dict:
|
| 407 |
-
"""Classifica cores por categorias de joias"""
|
| 408 |
-
categories = {
|
| 409 |
-
"metal_tones": [],
|
| 410 |
-
"stone_colors": [],
|
| 411 |
-
"accent_colors": []
|
| 412 |
-
}
|
| 413 |
-
|
| 414 |
-
for color in colors:
|
| 415 |
-
color_name = color["color_name"]
|
| 416 |
-
if color_name in ["dourado", "prateado", "branco"]:
|
| 417 |
-
categories["metal_tones"].append(color)
|
| 418 |
-
elif color["percentage"] > 5: # Cores significativas
|
| 419 |
-
categories["stone_colors"].append(color)
|
| 420 |
-
else:
|
| 421 |
-
categories["accent_colors"].append(color)
|
| 422 |
-
|
| 423 |
-
return categories
|
| 424 |
-
|
| 425 |
-
def _analyze_color_temperature(self, image: np.ndarray) -> str:
|
| 426 |
-
"""Analisa temperatura de cor da imagem"""
|
| 427 |
-
avg_color = np.mean(image, axis=(0, 1))
|
| 428 |
-
r, g, b = avg_color
|
| 429 |
-
|
| 430 |
-
if r > g and r > b:
|
| 431 |
-
return "warm" # Tons quentes
|
| 432 |
-
elif b > r and b > g:
|
| 433 |
-
return "cool" # Tons frios
|
| 434 |
-
else:
|
| 435 |
-
return "neutral"
|
| 436 |
-
|
| 437 |
-
def _analyze_color_harmony(self, colors: List[Dict]) -> str:
|
| 438 |
-
"""Analisa harmonia das cores"""
|
| 439 |
-
if len(colors) < 2:
|
| 440 |
-
return "monochromatic"
|
| 441 |
-
|
| 442 |
-
# Analisa diferenças de matiz
|
| 443 |
-
hues = [color["hsl"][0] for color in colors[:3]] # Top 3 cores
|
| 444 |
-
hue_differences = [abs(hues[i] - hues[i+1]) for i in range(len(hues)-1)]
|
| 445 |
-
|
| 446 |
-
avg_diff = np.mean(hue_differences)
|
| 447 |
-
|
| 448 |
-
if avg_diff < 30:
|
| 449 |
-
return "analogous"
|
| 450 |
-
elif avg_diff > 150:
|
| 451 |
-
return "complementary"
|
| 452 |
-
else:
|
| 453 |
-
return "triadic"
|
| 454 |
-
|
| 455 |
-
# Continuar implementando outros métodos auxiliares conforme necessário...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/jewelry_cataloger_v0.py
DELETED
|
@@ -1,228 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import pandas as pd
|
| 3 |
-
import requests
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
import uuid
|
| 6 |
-
from typing import Dict, List
|
| 7 |
-
from supabase import create_client, Client
|
| 8 |
-
from pinecone import Pinecone
|
| 9 |
-
from image_processor import ImageProcessor
|
| 10 |
-
import json
|
| 11 |
-
|
| 12 |
-
class JewelryCataloger:
|
| 13 |
-
def __init__(self):
|
| 14 |
-
"""Inicializa o catalogador"""
|
| 15 |
-
# Configuração Supabase
|
| 16 |
-
self.supabase: Client = create_client(
|
| 17 |
-
os.getenv('SUPABASE_URL'),
|
| 18 |
-
os.getenv('SUPABASE_KEY')
|
| 19 |
-
)
|
| 20 |
-
|
| 21 |
-
# Configuração Pinecone
|
| 22 |
-
pc = Pinecone(api_key=os.getenv('PINECONE_API_KEY'))
|
| 23 |
-
self.pinecone_index = pc.Index("jewelry-embeddings")
|
| 24 |
-
|
| 25 |
-
# Processador de imagens
|
| 26 |
-
self.image_processor = ImageProcessor()
|
| 27 |
-
|
| 28 |
-
# Diretórios
|
| 29 |
-
self.images_dir = Path("./images")
|
| 30 |
-
self.thumbnails_dir = Path("./thumbnails")
|
| 31 |
-
self.thumbnails_dir.mkdir(exist_ok=True)
|
| 32 |
-
|
| 33 |
-
print("✅ Catalogador inicializado!")
|
| 34 |
-
|
| 35 |
-
def load_metadata_from_sheets(self, csv_path: str) -> pd.DataFrame:
|
| 36 |
-
"""Carrega metadados da planilha (exportada como CSV)"""
|
| 37 |
-
try:
|
| 38 |
-
df = pd.read_csv(csv_path)
|
| 39 |
-
print(f"✅ Carregados {len(df)} registros da planilha")
|
| 40 |
-
return df
|
| 41 |
-
except Exception as e:
|
| 42 |
-
print(f"❌ Erro ao carregar planilha: {e}")
|
| 43 |
-
return pd.DataFrame()
|
| 44 |
-
|
| 45 |
-
def process_piece_metadata(self, row: pd.Series) -> Dict:
|
| 46 |
-
"""Processa metadados de uma peça"""
|
| 47 |
-
return {
|
| 48 |
-
'sku': str(row['sku']).strip(),
|
| 49 |
-
'name': str(row['peca']).strip(),
|
| 50 |
-
'collection': str(row.get('colecao', '')).strip(),
|
| 51 |
-
'material': str(row.get('material', '')).strip(),
|
| 52 |
-
'predominant_metal': str(row.get('metal_predominante', '')).strip(),
|
| 53 |
-
'stone': str(row.get('pedra', '')).strip(),
|
| 54 |
-
'size': str(row.get('tamanho', '')).strip(),
|
| 55 |
-
'description': str(row.get('descricao', '')).strip()
|
| 56 |
-
}
|
| 57 |
-
|
| 58 |
-
def find_images_for_sku(self, sku: str) -> List[Dict]:
|
| 59 |
-
"""Encontra todas as imagens relacionadas a um SKU"""
|
| 60 |
-
images = []
|
| 61 |
-
|
| 62 |
-
# Procura por arquivos que contenham o SKU no nome
|
| 63 |
-
for image_file in self.images_dir.glob("*.png"):
|
| 64 |
-
if sku.lower() in image_file.name.lower():
|
| 65 |
-
# Determina o tipo da imagem baseado no nome do arquivo
|
| 66 |
-
image_type = "lifestyle" if any(keyword in image_file.name.lower()
|
| 67 |
-
for keyword in ["modelo", "person", "wearing", "lifestyle"]) else "product"
|
| 68 |
-
|
| 69 |
-
images.append({
|
| 70 |
-
'path': str(image_file),
|
| 71 |
-
'filename': image_file.name,
|
| 72 |
-
'type': image_type
|
| 73 |
-
})
|
| 74 |
-
|
| 75 |
-
return images
|
| 76 |
-
|
| 77 |
-
def upload_to_supabase_storage(self, file_path: str, bucket_name: str, file_name: str) -> str:
|
| 78 |
-
"""Faz upload de arquivo para o storage do Supabase"""
|
| 79 |
-
try:
|
| 80 |
-
with open(file_path, 'rb') as file:
|
| 81 |
-
response = self.supabase.storage.from_(bucket_name).upload(
|
| 82 |
-
file_name, file, file_options={"content-type": "image/png"}
|
| 83 |
-
)
|
| 84 |
-
|
| 85 |
-
# Gera URL pública
|
| 86 |
-
public_url = self.supabase.storage.from_(bucket_name).get_public_url(file_name)
|
| 87 |
-
return public_url
|
| 88 |
-
except Exception as e:
|
| 89 |
-
print(f"❌ Erro no upload para Supabase: {e}")
|
| 90 |
-
return ""
|
| 91 |
-
|
| 92 |
-
def save_piece_to_database(self, piece_data: Dict) -> bool:
|
| 93 |
-
"""Salva dados da peça no banco"""
|
| 94 |
-
try:
|
| 95 |
-
response = self.supabase.table('pieces').upsert(piece_data).execute()
|
| 96 |
-
return True
|
| 97 |
-
except Exception as e:
|
| 98 |
-
print(f"❌ Erro ao salvar peça {piece_data['sku']}: {e}")
|
| 99 |
-
return False
|
| 100 |
-
|
| 101 |
-
def save_image_to_database(self, image_data: Dict) -> bool:
|
| 102 |
-
"""Salva dados da imagem no banco"""
|
| 103 |
-
try:
|
| 104 |
-
response = self.supabase.table('piece_images').insert(image_data).execute()
|
| 105 |
-
return True
|
| 106 |
-
except Exception as e:
|
| 107 |
-
print(f"❌ Erro ao salvar imagem: {e}")
|
| 108 |
-
return False
|
| 109 |
-
|
| 110 |
-
def save_embedding_to_pinecone(self, vector_id: str, embedding: List[float], metadata: Dict) -> bool:
|
| 111 |
-
"""Salva embedding no Pinecone"""
|
| 112 |
-
try:
|
| 113 |
-
self.pinecone_index.upsert([(vector_id, embedding, metadata)])
|
| 114 |
-
return True
|
| 115 |
-
except Exception as e:
|
| 116 |
-
print(f"❌ Erro ao salvar no Pinecone: {e}")
|
| 117 |
-
return False
|
| 118 |
-
|
| 119 |
-
def process_single_piece(self, piece_metadata: Dict) -> bool:
|
| 120 |
-
"""Processa uma única peça com todas suas imagens"""
|
| 121 |
-
sku = piece_metadata['sku']
|
| 122 |
-
print(f"🔄 Processando peça: {sku}")
|
| 123 |
-
|
| 124 |
-
# Salva metadados da peça
|
| 125 |
-
if not self.save_piece_to_database(piece_metadata):
|
| 126 |
-
return False
|
| 127 |
-
|
| 128 |
-
# Encontra imagens da peça
|
| 129 |
-
images = self.find_images_for_sku(sku)
|
| 130 |
-
if not images:
|
| 131 |
-
print(f"⚠️ Nenhuma imagem encontrada para SKU: {sku}")
|
| 132 |
-
return True
|
| 133 |
-
|
| 134 |
-
print(f"📸 Encontradas {len(images)} imagens para {sku}")
|
| 135 |
-
|
| 136 |
-
# Processa cada imagem
|
| 137 |
-
for img_info in images:
|
| 138 |
-
try:
|
| 139 |
-
# Gera embedding
|
| 140 |
-
embedding = self.image_processor.generate_embedding(img_info['path'])
|
| 141 |
-
if embedding is None:
|
| 142 |
-
continue
|
| 143 |
-
|
| 144 |
-
# Análise técnica
|
| 145 |
-
technical_analysis = self.image_processor.analyze_image_technical(img_info['path'])
|
| 146 |
-
|
| 147 |
-
# Cria thumbnail
|
| 148 |
-
thumbnail_filename = f"thumb_{img_info['filename']}"
|
| 149 |
-
thumbnail_path = self.thumbnails_dir / thumbnail_filename
|
| 150 |
-
|
| 151 |
-
if not self.image_processor.create_thumbnail(img_info['path'], str(thumbnail_path)):
|
| 152 |
-
continue
|
| 153 |
-
|
| 154 |
-
# Upload da imagem original
|
| 155 |
-
original_url = self.upload_to_supabase_storage(
|
| 156 |
-
img_info['path'],
|
| 157 |
-
'images',
|
| 158 |
-
f"{sku}/{img_info['filename']}"
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
# Upload do thumbnail
|
| 162 |
-
thumbnail_url = self.upload_to_supabase_storage(
|
| 163 |
-
str(thumbnail_path),
|
| 164 |
-
'images',
|
| 165 |
-
f"thumbnails/{thumbnail_filename}"
|
| 166 |
-
)
|
| 167 |
-
|
| 168 |
-
# ID único para o vetor
|
| 169 |
-
vector_id = str(uuid.uuid4())
|
| 170 |
-
|
| 171 |
-
# Salva no Pinecone
|
| 172 |
-
pinecone_metadata = {
|
| 173 |
-
'sku': sku,
|
| 174 |
-
'image_type': img_info['type'],
|
| 175 |
-
'filename': img_info['filename'],
|
| 176 |
-
'piece_name': piece_metadata['name'],
|
| 177 |
-
'collection': piece_metadata['collection']
|
| 178 |
-
}
|
| 179 |
-
|
| 180 |
-
self.save_embedding_to_pinecone(vector_id, embedding.tolist(), pinecone_metadata)
|
| 181 |
-
|
| 182 |
-
# Salva no banco
|
| 183 |
-
image_data = {
|
| 184 |
-
'sku': sku,
|
| 185 |
-
'image_type': img_info['type'],
|
| 186 |
-
'original_url': original_url,
|
| 187 |
-
'thumbnail_url': thumbnail_url,
|
| 188 |
-
'file_name': img_info['filename'],
|
| 189 |
-
'embeddings_vector_id': vector_id,
|
| 190 |
-
'technical_analysis': technical_analysis
|
| 191 |
-
}
|
| 192 |
-
|
| 193 |
-
self.save_image_to_database(image_data)
|
| 194 |
-
|
| 195 |
-
print(f"✅ Imagem processada: {img_info['filename']}")
|
| 196 |
-
|
| 197 |
-
except Exception as e:
|
| 198 |
-
print(f"❌ Erro ao processar imagem {img_info['filename']}: {e}")
|
| 199 |
-
continue
|
| 200 |
-
|
| 201 |
-
return True
|
| 202 |
-
|
| 203 |
-
def run_cataloging(self, csv_path: str):
|
| 204 |
-
"""Executa o processo completo de catalogação"""
|
| 205 |
-
print("🚀 Iniciando catalogação de joias...")
|
| 206 |
-
|
| 207 |
-
# Carrega metadados
|
| 208 |
-
df = self.load_metadata_from_sheets(csv_path)
|
| 209 |
-
if df.empty:
|
| 210 |
-
return
|
| 211 |
-
|
| 212 |
-
# Processa cada peça
|
| 213 |
-
total_pieces = len(df)
|
| 214 |
-
processed = 0
|
| 215 |
-
|
| 216 |
-
for index, row in df.iterrows():
|
| 217 |
-
piece_metadata = self.process_piece_metadata(row)
|
| 218 |
-
|
| 219 |
-
if self.process_single_piece(piece_metadata):
|
| 220 |
-
processed += 1
|
| 221 |
-
|
| 222 |
-
print(f"📊 Progresso: {processed}/{total_pieces} peças processadas")
|
| 223 |
-
|
| 224 |
-
print(f"✅ Catalogação concluída! {processed}/{total_pieces} peças processadas com sucesso.")
|
| 225 |
-
|
| 226 |
-
if __name__ == "__main__":
|
| 227 |
-
cataloger = JewelryCataloger()
|
| 228 |
-
cataloger.run_cataloging("./metadata.csv") # Planilha exportada como CSV
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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