pmazzia commited on
Commit
a146cd6
·
1 Parent(s): bceda79

Deploy inicial da API de Busca

Browse files
.env ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Supabase Configuration
2
+ SUPABASE_URL=https://azumezqwmydxgjbiyale.supabase.co
3
+ SUPABASE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImF6dW1lenF3bXlkeGdqYml5YWxlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTMzMjc3MDYsImV4cCI6MjA2ODkwMzcwNn0.nLpWyLBH1iLnaSNzSqqOtjj189EazEazI_In5r1fSrk
4
+ SUPABASE_SERVICE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImF6dW1lenF3bXlkeGdqYml5YWxlIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc1MzMyNzcwNiwiZXhwIjoyMDY4OTAzNzA2fQ.sFEYzZFP_9XHJVL7yEN8Okf7BP6Q1jhzmkExD2wGwZs
5
+
6
+ # Pinecone Configuration
7
+ PINECONE_API_KEY=pcsk_3Je9Rv_HE9Yujqjf87Ygrh4zQG8YCmgvCrRJpJzKVidy2FELWQFrqUCHcSLoZzDeejprMK
8
+ PINECONE_INDEX_NAME=jewelry-embeddings
9
+
10
+ # OpenAI Configuration
11
+ OPENAI_API_KEY=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
12
+
13
+ # Storage Configuration
14
+ SUPABASE_STORAGE_BUCKET=jewelry-images
15
+
16
+ # Processing Configuration
17
+ EMBEDDING_MODEL=ViT-L-14
18
+ EMBEDDING_PRETRAINED=laion2b_s32b_b82k
19
+ THUMBNAIL_SIZE=200
20
+ BATCH_SIZE=10
21
+
22
+ # Local Paths (Windows)
23
+ IMAGES_LOCAL_PATH=./imagens
24
+ THUMBNAILS_LOCAL_PATH=./thumbnails
25
+ METADATA_CSV_PATH=./jewelry_metadata.csv
26
+
27
+ # Application Settings
28
+ APP_ROOT_DIR=D:/Dev_Mazzia_N8N/Workshop/Catalogo
29
+ LOG_LEVEL=INFO
README.md CHANGED
@@ -1,12 +1,11 @@
1
  ---
2
- title: Cartalogo Api
3
- emoji: 🐢
4
- colorFrom: purple
5
- colorTo: gray
6
- sdk: docker
7
- pinned: false
8
- license: mit
9
- short_description: API Catalogo Digital
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Assistente de Busca de Joias
3
+ emoji: 💎
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: fastapi
7
+ python_version: 3.10
8
+ app_file: api.py
 
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
api.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ @app.on_event("startup")
32
+ async def startup_event():
33
+ if searcher is None:
34
+ raise RuntimeError("Falha ao carregar o modelo de busca. A API não pode iniciar.")
35
+ print("API pronta para receber requisições.")
36
+
37
+ @app.get("/", tags=["Status"])
38
+ def read_root():
39
+ """Verifica se a API está online."""
40
+ return {"status": "online", "message": "Bem-vindo à API de Busca de Joias!"}
41
+
42
+ @app.post("/search-by-text", tags=["Busca"])
43
+ async def search_by_text(query: str = Form(...)):
44
+ """
45
+ Busca joias por uma descrição de texto.
46
+ """
47
+ try:
48
+ results = searcher.search_by_text(text_query=query, top_k=3)
49
+ if not results:
50
+ return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
51
+ return {"results": results}
52
+ except Exception as e:
53
+ raise HTTPException(status_code=500, detail=str(e))
54
+
55
+ @app.post("/search-by-image", tags=["Busca"])
56
+ async def search_by_image(file: UploadFile = File(...)):
57
+ """
58
+ Busca joias similares a uma imagem enviada.
59
+ """
60
+ # Gera um nome de arquivo único e seguro
61
+ temp_filename = f"{uuid.uuid4()}{Path(file.filename).suffix}"
62
+ temp_file_path = TEMP_DIR / temp_filename
63
+
64
+ try:
65
+ # Salva o arquivo temporariamente
66
+ with temp_file_path.open("wb") as buffer:
67
+ shutil.copyfileobj(file.file, buffer)
68
+
69
+ # Realiza a busca
70
+ results = searcher.search_by_image(image_path=temp_file_path, top_k=3)
71
+
72
+ if not results:
73
+ return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
74
+ return {"results": results}
75
+ except Exception as e:
76
+ raise HTTPException(status_code=500, detail=str(e))
77
+ finally:
78
+ # Garante que o arquivo temporário seja deletado
79
+ if temp_file_path.exists():
80
+ temp_file_path.unlink()
81
+
82
+ # Nota: A busca por áudio será implementada na próxima fase para manter o foco.
83
+ # Ela exigirá a integração com a API do Whisper (OpenAI).
84
+
85
+ if __name__ == "__main__":
86
+ import uvicorn
87
+ print("Iniciando API em modo de desenvolvimento...")
88
+ uvicorn.run(app, host="0.0.0.0", port=8000)
database_structure.sql ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ -- Estrutura do banco para catalogação de joias
3
+ -- Execute este script no SQL Editor do Supabase se o setup automático falhar
4
+
5
+ -- Extensões necessárias
6
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
7
+
8
+ -- Tabela principal de peças
9
+ CREATE TABLE IF NOT EXISTS pieces (
10
+ sku VARCHAR(50) PRIMARY KEY,
11
+ name VARCHAR(255) NOT NULL,
12
+ collection VARCHAR(100),
13
+ material VARCHAR(255),
14
+ predominant_metal VARCHAR(100),
15
+ stone VARCHAR(100),
16
+ stone_color VARCHAR(50),
17
+ size VARCHAR(50),
18
+ weight_grams DECIMAL(8,2),
19
+ price_brl DECIMAL(10,2),
20
+ description TEXT,
21
+ category VARCHAR(50),
22
+ gender VARCHAR(20),
23
+ style VARCHAR(100),
24
+ is_active BOOLEAN DEFAULT true,
25
+ created_at TIMESTAMP DEFAULT NOW(),
26
+ updated_at TIMESTAMP DEFAULT NOW()
27
+ );
28
+
29
+ -- Tabela de imagens das peças
30
+ CREATE TABLE IF NOT EXISTS piece_images (
31
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
32
+ sku VARCHAR(50) REFERENCES pieces(sku) ON DELETE CASCADE,
33
+ image_type VARCHAR(20) CHECK (image_type IN ('product', 'lifestyle', 'detail', 'packaging')),
34
+ original_url VARCHAR(500),
35
+ thumbnail_url VARCHAR(500),
36
+ file_name VARCHAR(255),
37
+ file_size_bytes INTEGER,
38
+ image_width INTEGER,
39
+ image_height INTEGER,
40
+ embeddings_vector_id VARCHAR(100) UNIQUE,
41
+ technical_analysis JSONB,
42
+ ai_description TEXT,
43
+ dominant_colors JSONB,
44
+ visual_features JSONB,
45
+ quality_score DECIMAL(3,2),
46
+ is_primary BOOLEAN DEFAULT false,
47
+ created_at TIMESTAMP DEFAULT NOW()
48
+ );
49
+
50
+ -- Tabela de características visuais extraídas
51
+ CREATE TABLE IF NOT EXISTS visual_features (
52
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
53
+ image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
54
+ feature_type VARCHAR(50),
55
+ feature_value VARCHAR(255),
56
+ confidence_score DECIMAL(3,2),
57
+ created_at TIMESTAMP DEFAULT NOW()
58
+ );
59
+
60
+ -- Tabela de tags automáticas
61
+ CREATE TABLE IF NOT EXISTS image_tags (
62
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
63
+ image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
64
+ tag VARCHAR(100),
65
+ confidence DECIMAL(3,2),
66
+ tag_type VARCHAR(50),
67
+ created_at TIMESTAMP DEFAULT NOW()
68
+ );
69
+
70
+ -- Tabela de histórico de processamento
71
+ CREATE TABLE IF NOT EXISTS processing_log (
72
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
73
+ sku VARCHAR(50),
74
+ image_id UUID,
75
+ process_type VARCHAR(50),
76
+ status VARCHAR(20),
77
+ error_message TEXT,
78
+ processing_time_ms INTEGER,
79
+ created_at TIMESTAMP DEFAULT NOW()
80
+ );
81
+
82
+ -- Índices para otimização
83
+ CREATE INDEX IF NOT EXISTS idx_piece_images_sku ON piece_images(sku);
84
+ CREATE INDEX IF NOT EXISTS idx_piece_images_type ON piece_images(image_type);
85
+ CREATE INDEX IF NOT EXISTS idx_piece_images_primary ON piece_images(is_primary);
86
+ CREATE INDEX IF NOT EXISTS idx_visual_features_image_id ON visual_features(image_id);
87
+ CREATE INDEX IF NOT EXISTS idx_image_tags_image_id ON image_tags(image_id);
88
+ CREATE INDEX IF NOT EXISTS idx_processing_log_sku ON processing_log(sku);
89
+ CREATE INDEX IF NOT EXISTS idx_pieces_category ON pieces(category);
90
+ CREATE INDEX IF NOT EXISTS idx_pieces_collection ON pieces(collection);
91
+
92
+ -- Função para atualizar updated_at automaticamente
93
+ CREATE OR REPLACE FUNCTION update_updated_at_column()
94
+ RETURNS TRIGGER AS $$
95
+ BEGIN
96
+ NEW.updated_at = NOW();
97
+ RETURN NEW;
98
+ END;
99
+ $$ language 'plpgsql';
100
+
101
+ -- Trigger para atualizar updated_at na tabela pieces
102
+ DROP TRIGGER IF EXISTS update_pieces_updated_at ON pieces;
103
+ CREATE TRIGGER update_pieces_updated_at
104
+ BEFORE UPDATE ON pieces
105
+ FOR EACH ROW
106
+ EXECUTE FUNCTION update_updated_at_column();
107
+
108
+ -- Views úteis
109
+ CREATE OR REPLACE VIEW pieces_with_images AS
110
+ SELECT
111
+ p.*,
112
+ pi.id as image_id,
113
+ pi.image_type,
114
+ pi.original_url,
115
+ pi.thumbnail_url,
116
+ pi.ai_description,
117
+ pi.dominant_colors,
118
+ pi.quality_score,
119
+ pi.is_primary
120
+ FROM pieces p
121
+ LEFT JOIN piece_images pi ON p.sku = pi.sku
122
+ WHERE p.is_active = true;
debug_env.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from dotenv import load_dotenv
4
+
5
+ def debug_environment():
6
+ """Script para debugar o carregamento das variáveis de ambiente"""
7
+
8
+ print("🔍 DEBUG: Verificando variáveis de ambiente...")
9
+
10
+ # Mostra diretório atual
11
+ current_dir = Path.cwd()
12
+ print(f"📁 Diretório atual: {current_dir}")
13
+
14
+ # Procura arquivo .env
15
+ env_file = current_dir / ".env"
16
+ print(f"📄 Arquivo .env: {env_file}")
17
+ print(f"📄 Arquivo existe: {env_file.exists()}")
18
+
19
+ if env_file.exists():
20
+ print(f"📄 Tamanho do arquivo: {env_file.stat().st_size} bytes")
21
+
22
+ # Lê conteúdo do arquivo
23
+ with open(env_file, 'r', encoding='utf-8') as f:
24
+ content = f.read()
25
+ lines = content.split('\n')
26
+ print(f"📄 Linhas no arquivo: {len(lines)}")
27
+
28
+ # Procura linha da OpenAI
29
+ for i, line in enumerate(lines, 1):
30
+ if 'OPENAI_API_KEY' in line:
31
+ print(f"📄 Linha {i}: {line[:50]}...")
32
+
33
+ # Tenta carregar .env
34
+ print("\n🔄 Carregando .env...")
35
+ load_result = load_dotenv(env_file, verbose=True)
36
+ print(f"✅ Load result: {load_result}")
37
+
38
+ # Verifica variáveis após carregar
39
+ print("\n🔍 Variáveis após load_dotenv:")
40
+
41
+ # Lista algumas variáveis importantes
42
+ important_vars = [
43
+ 'SUPABASE_URL',
44
+ 'SUPABASE_KEY',
45
+ 'PINECONE_API_KEY',
46
+ 'OPENAI_API_KEY'
47
+ ]
48
+
49
+ for var in important_vars:
50
+ value = os.getenv(var)
51
+ if value:
52
+ if len(value) > 20:
53
+ display_value = f"{value[:10]}...{value[-10:]}"
54
+ else:
55
+ display_value = value[:15] + "..."
56
+ print(f" {var}: {display_value}")
57
+ else:
58
+ print(f" {var}: ❌ NÃO ENCONTRADA")
59
+
60
+ # Testa carregamento forçado
61
+ print("\n🔄 Tentando carregamento forçado...")
62
+
63
+ # Força reload das variáveis
64
+ os.environ.clear() # Limpa variáveis atuais
65
+ load_dotenv(env_file, override=True) # Força reload
66
+
67
+ openai_key = os.getenv('OPENAI_API_KEY')
68
+ print(f"🔑 OpenAI após reload: {openai_key[:15] if openai_key else 'NÃO ENCONTRADA'}...")
69
+
70
+ return openai_key
71
+
72
+ if __name__ == "__main__":
73
+ debug_environment()
image_processor.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from pathlib import Path
4
+ from dotenv import load_dotenv
5
+ import torch
6
+ import open_clip
7
+ from PIL import Image, ImageEnhance, ImageFilter
8
+ import numpy as np
9
+ import cv2
10
+ from typing import Dict, List, Tuple, Optional
11
+ import json
12
+ import colorsys
13
+ from sklearn.cluster import KMeans
14
+ import time
15
+
16
+ # FORÇA carregamento das variáveis de ambiente
17
+ env_file = Path(__file__).parent / ".env"
18
+ print(f"🔍 Carregando .env de: {env_file}")
19
+ print(f"🔍 Arquivo existe: {env_file.exists()}")
20
+
21
+ if env_file.exists():
22
+ # Carrega com override para forçar
23
+ load_result = load_dotenv(env_file, override=True, verbose=True)
24
+ print(f"🔍 Load result: {load_result}")
25
+ else:
26
+ print("❌ Arquivo .env não encontrado!")
27
+ # Tenta carregar do diretório atual
28
+ load_dotenv(override=True, verbose=True)
29
+
30
+ class JewelryImageProcessor:
31
+ def __init__(self):
32
+ """Inicializa o processador especializado em joias"""
33
+ print("🤖 Inicializando processador de imagens para joias...")
34
+
35
+ # Configuração de caminhos
36
+ self.root_dir = Path(__file__).parent
37
+ self.images_dir = self.root_dir / "imagens"
38
+ self.thumbnails_dir = self.root_dir / "thumbnails"
39
+
40
+ # Cria diretório de thumbnails
41
+ self.thumbnails_dir.mkdir(exist_ok=True)
42
+
43
+ # Configuração do dispositivo
44
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
45
+ print(f"🔧 Dispositivo: {self.device}")
46
+
47
+ # Carrega modelo OpenCLIP
48
+ try:
49
+ model_name = os.getenv('EMBEDDING_MODEL', 'ViT-L-14')
50
+ pretrained = os.getenv('EMBEDDING_PRETRAINED', 'laion2b_s32b_b82k')
51
+
52
+ print(f"📥 Carregando modelo {model_name} ({pretrained})...")
53
+ self.model, _, self.preprocess = open_clip.create_model_and_transforms(
54
+ model_name, pretrained=pretrained, device=self.device
55
+ )
56
+ self.tokenizer = open_clip.get_tokenizer(model_name)
57
+ print("✅ Modelo OpenCLIP carregado com sucesso!")
58
+
59
+ except Exception as e:
60
+ print(f"❌ Erro ao carregar modelo OpenCLIP: {e}")
61
+ raise
62
+
63
+ # DEBUG: Configuração OpenAI v1.0+
64
+ print("\n🔍 DEBUG OpenAI:")
65
+
66
+ # Tenta diferentes formas de obter a chave
67
+ openai_api_key = None
68
+
69
+ # Método 1: os.getenv
70
+ openai_api_key = os.getenv('OPENAI_API_KEY')
71
+ print(f"🔍 Método 1 (os.getenv): {openai_api_key[:15] if openai_api_key else 'None'}...")
72
+
73
+ # Método 2: os.environ.get
74
+ if not openai_api_key or openai_api_key.startswith('your-'):
75
+ openai_api_key = os.environ.get('OPENAI_API_KEY')
76
+ print(f"🔍 Método 2 (os.environ): {openai_api_key[:15] if openai_api_key else 'None'}...")
77
+
78
+ # Método 3: Lê diretamente do arquivo .env
79
+ if not openai_api_key or openai_api_key.startswith('your-'):
80
+ try:
81
+ env_file = self.root_dir / ".env"
82
+ if env_file.exists():
83
+ with open(env_file, 'r', encoding='utf-8') as f:
84
+ for line in f:
85
+ if line.startswith('OPENAI_API_KEY='):
86
+ openai_api_key = line.split('=', 1)[1].strip()
87
+ print(f"🔍 Método 3 (arquivo): {openai_api_key[:15]}...")
88
+ break
89
+ except Exception as e:
90
+ print(f"🔍 Erro método 3: {e}")
91
+
92
+ self.openai_client = None
93
+
94
+ print(f"🔑 OpenAI API Key final: {'Sim' if openai_api_key else 'Não'}")
95
+ if openai_api_key:
96
+ print(f"🔑 Primeiros caracteres: {openai_api_key[:15]}...")
97
+ print(f"🔑 Começa com sk-: {openai_api_key.startswith('sk-')}")
98
+
99
+ if openai_api_key and openai_api_key.startswith('sk-'):
100
+ try:
101
+ from openai import OpenAI
102
+ self.openai_client = OpenAI(api_key=openai_api_key)
103
+ print("✅ OpenAI v1.0+ configurado para descrições IA")
104
+
105
+ # Testa a conexão
106
+ try:
107
+ # Faz um teste simples para verificar se a API key funciona
108
+ test_response = self.openai_client.models.list()
109
+ print("✅ Conexão com OpenAI testada com sucesso")
110
+ except Exception as test_error:
111
+ print(f"⚠️ Erro ao testar conexão OpenAI: {test_error}")
112
+ self.openai_client = None
113
+
114
+ except ImportError:
115
+ print("⚠️ OpenAI não instalado - descrições IA desabilitadas")
116
+ self.openai_client = None
117
+ except Exception as e:
118
+ print(f"⚠️ Erro ao configurar OpenAI: {e}")
119
+ self.openai_client = None
120
+ else:
121
+ print("⚠️ OpenAI API key inválida - descrições IA desabilitadas")
122
+ self.openai_client = None
123
+
124
+ def generate_embedding(self, image_path: Path) -> Optional[np.ndarray]:
125
+ """Gera embedding da imagem usando OpenCLIP"""
126
+ try:
127
+ if not image_path.exists():
128
+ print(f"❌ Arquivo não encontrado: {image_path}")
129
+ return None
130
+
131
+ # Carrega e processa imagem
132
+ image = Image.open(image_path).convert('RGB')
133
+ image_input = self.preprocess(image).unsqueeze(0).to(self.device)
134
+
135
+ with torch.no_grad():
136
+ image_features = self.model.encode_image(image_input)
137
+ # Normaliza o vetor
138
+ image_features = image_features / image_features.norm(dim=-1, keepdim=True)
139
+
140
+ return image_features.cpu().numpy().flatten()
141
+
142
+ except Exception as e:
143
+ print(f"❌ Erro ao gerar embedding para {image_path.name}: {e}")
144
+ return None
145
+
146
+ def analyze_jewelry_technical(self, image_path: Path) -> Dict:
147
+ """Análise técnica especializada para joias"""
148
+ try:
149
+ if not image_path.exists():
150
+ return {}
151
+
152
+ # Carrega imagem
153
+ image = cv2.imread(str(image_path))
154
+ if image is None:
155
+ print(f"❌ Não foi possível carregar a imagem: {image_path}")
156
+ return {}
157
+
158
+ image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
159
+
160
+ print(f"🔍 Analisando {image_path.name}...")
161
+
162
+ analysis = {
163
+ "basic_metrics": self._analyze_basic_metrics(image_rgb),
164
+ "color_analysis": self._analyze_jewelry_colors(image_rgb),
165
+ "metal_analysis": self._analyze_metal_properties(image_rgb),
166
+ "stone_analysis": self._analyze_stones(image_rgb),
167
+ "shape_analysis": self._analyze_jewelry_shapes(image_rgb),
168
+ "texture_analysis": self._analyze_textures(image_rgb),
169
+ "reflection_analysis": self._analyze_reflections(image_rgb),
170
+ "quality_assessment": self._assess_image_quality(image_rgb)
171
+ }
172
+
173
+ return analysis
174
+
175
+ except Exception as e:
176
+ print(f"❌ Erro na análise técnica de {image_path.name}: {e}")
177
+ return {}
178
+
179
+ def extract_visual_features(self, image_path: Path, technical_analysis: Dict) -> List[Dict]:
180
+ """Extrai características visuais estruturadas para a tabela visual_features"""
181
+ features = []
182
+
183
+ try:
184
+ # Características de cor
185
+ color_analysis = technical_analysis.get('color_analysis', {})
186
+ dominant_colors = color_analysis.get('dominant_colors', [])
187
+
188
+ for i, color in enumerate(dominant_colors[:3]): # Top 3 cores
189
+ features.append({
190
+ 'feature_type': 'dominant_color',
191
+ 'feature_value': color.get('hex', '#000000'),
192
+ 'confidence_score': min(0.99, color.get('percentage', 0) / 100)
193
+ })
194
+
195
+ # Características de metal
196
+ metal_analysis = technical_analysis.get('metal_analysis', {})
197
+ if metal_analysis.get('has_metallic_elements', False):
198
+ features.append({
199
+ 'feature_type': 'material',
200
+ 'feature_value': 'metallic',
201
+ 'confidence_score': min(0.99, metal_analysis.get('metal_percentage', 0))
202
+ })
203
+
204
+ # Características de pedras
205
+ stone_analysis = technical_analysis.get('stone_analysis', {})
206
+ if stone_analysis.get('has_colored_stones', False):
207
+ features.append({
208
+ 'feature_type': 'material',
209
+ 'feature_value': 'gemstone',
210
+ 'confidence_score': min(0.99, stone_analysis.get('stone_percentage', 0))
211
+ })
212
+
213
+ # Características de forma
214
+ shape_analysis = technical_analysis.get('shape_analysis', {})
215
+ complexity = shape_analysis.get('shape_complexity', 'unknown')
216
+ if complexity != 'unknown':
217
+ features.append({
218
+ 'feature_type': 'shape',
219
+ 'feature_value': complexity,
220
+ 'confidence_score': 0.8
221
+ })
222
+
223
+ # Características de textura
224
+ texture_analysis = technical_analysis.get('texture_analysis', {})
225
+ texture_type = texture_analysis.get('texture_type', 'unknown')
226
+ if texture_type != 'unknown':
227
+ features.append({
228
+ 'feature_type': 'texture',
229
+ 'feature_value': texture_type,
230
+ 'confidence_score': 0.75
231
+ })
232
+
233
+ # Características de qualidade
234
+ quality_assessment = technical_analysis.get('quality_assessment', {})
235
+ quality_grade = quality_assessment.get('quality_grade', 'unknown')
236
+ if quality_grade != 'unknown':
237
+ features.append({
238
+ 'feature_type': 'quality',
239
+ 'feature_value': quality_grade,
240
+ 'confidence_score': quality_assessment.get('quality_score', 0.5)
241
+ })
242
+
243
+ except Exception as e:
244
+ print(f"⚠️ Erro ao extrair características visuais: {e}")
245
+
246
+ return features
247
+
248
+ def generate_image_tags(self, image_path: Path, piece_metadata: Dict, technical_analysis: Dict) -> List[Dict]:
249
+ """Gera tags automáticas para a imagem"""
250
+ tags = []
251
+
252
+ try:
253
+ # Tags baseadas nos metadados
254
+ category = piece_metadata.get('category', '')
255
+ if category:
256
+ tags.append({
257
+ 'tag': category,
258
+ 'confidence': 0.95,
259
+ 'tag_type': 'category'
260
+ })
261
+
262
+ collection = piece_metadata.get('collection', '')
263
+ if collection:
264
+ tags.append({
265
+ 'tag': collection.lower(),
266
+ 'confidence': 0.9,
267
+ 'tag_type': 'collection'
268
+ })
269
+
270
+ stone = piece_metadata.get('stone', '')
271
+ if stone and stone.lower() not in ['', 'nan', 'none']:
272
+ tags.append({
273
+ 'tag': stone.lower(),
274
+ 'confidence': 0.85,
275
+ 'tag_type': 'material'
276
+ })
277
+
278
+ metal = piece_metadata.get('predominant_metal', '')
279
+ if metal and metal.lower() not in ['', 'nan', 'none']:
280
+ tags.append({
281
+ 'tag': metal.lower().replace(' ', '_'),
282
+ 'confidence': 0.85,
283
+ 'tag_type': 'material'
284
+ })
285
+
286
+ # Tags baseadas na análise técnica
287
+ color_analysis = technical_analysis.get('color_analysis', {})
288
+ dominant_colors = color_analysis.get('dominant_colors', [])
289
+
290
+ for color in dominant_colors[:2]: # Top 2 cores
291
+ if color.get('percentage', 0) > 15: # Apenas cores significativas
292
+ color_name = self._get_color_name_from_rgb(color.get('rgb', [0, 0, 0]))
293
+ tags.append({
294
+ 'tag': color_name,
295
+ 'confidence': min(0.8, color.get('percentage', 0) / 100),
296
+ 'tag_type': 'color'
297
+ })
298
+
299
+ # Tags de estilo baseadas no nome do arquivo
300
+ filename = image_path.name.lower()
301
+ if 'modelo' in filename:
302
+ tags.append({
303
+ 'tag': 'lifestyle',
304
+ 'confidence': 0.9,
305
+ 'tag_type': 'style'
306
+ })
307
+ else:
308
+ tags.append({
309
+ 'tag': 'product_shot',
310
+ 'confidence': 0.9,
311
+ 'tag_type': 'style'
312
+ })
313
+
314
+ # Tags de qualidade
315
+ quality_assessment = technical_analysis.get('quality_assessment', {})
316
+ quality_score = quality_assessment.get('quality_score', 0)
317
+ if quality_score > 0.7:
318
+ tags.append({
319
+ 'tag': 'high_quality',
320
+ 'confidence': quality_score,
321
+ 'tag_type': 'quality'
322
+ })
323
+ elif quality_score > 0.3:
324
+ tags.append({
325
+ 'tag': 'medium_quality',
326
+ 'confidence': quality_score,
327
+ 'tag_type': 'quality'
328
+ })
329
+
330
+ except Exception as e:
331
+ print(f"⚠️ Erro ao gerar tags: {e}")
332
+
333
+ return tags
334
+
335
+ def create_thumbnail(self, image_path: Path, size: Tuple[int, int] = None) -> Optional[Path]:
336
+ """Cria thumbnail da imagem"""
337
+ try:
338
+ if size is None:
339
+ size = (int(os.getenv('THUMBNAIL_SIZE', 200)), int(os.getenv('THUMBNAIL_SIZE', 200)))
340
+
341
+ if not image_path.exists():
342
+ return None
343
+
344
+ # Define caminho do thumbnail
345
+ thumbnail_name = f"thumb_{image_path.stem}.png"
346
+ thumbnail_path = self.thumbnails_dir / thumbnail_name
347
+
348
+ with Image.open(image_path) as img:
349
+ # Mantém proporção
350
+ img.thumbnail(size, Image.Resampling.LANCZOS)
351
+
352
+ # Cria imagem quadrada com fundo branco
353
+ thumbnail = Image.new('RGB', size, (255, 255, 255))
354
+
355
+ # Centraliza a imagem
356
+ x = (size[0] - img.width) // 2
357
+ y = (size[1] - img.height) // 2
358
+ thumbnail.paste(img, (x, y))
359
+
360
+ # Salva thumbnail
361
+ thumbnail.save(thumbnail_path, 'PNG', quality=95)
362
+
363
+ print(f"✅ Thumbnail criado: {thumbnail_name}")
364
+ return thumbnail_path
365
+
366
+ except Exception as e:
367
+ print(f"❌ Erro ao criar thumbnail de {image_path.name}: {e}")
368
+ return None
369
+
370
+ def generate_ai_description(self, image_path: Path, piece_metadata: Dict) -> str:
371
+ """Gera descrição detalhada usando GPT-4 Vision (OpenAI v1.0+)"""
372
+ try:
373
+ if not self.openai_client:
374
+ print(f" ⚠️ OpenAI não configurado, usando descrição básica")
375
+ return self._generate_basic_description(piece_metadata)
376
+
377
+ # Converte imagem para base64
378
+ import base64
379
+ with open(image_path, "rb") as image_file:
380
+ base64_image = base64.b64encode(image_file.read()).decode('utf-8')
381
+
382
+ prompt = f"""
383
+ Analise esta imagem de joia e forneça uma descrição detalhada e técnica em português brasileiro.
384
+
385
+ Metadados da peça:
386
+ - SKU: {piece_metadata.get('sku', 'N/A')}
387
+ - Nome: {piece_metadata.get('name', 'N/A')}
388
+ - Material: {piece_metadata.get('material', 'N/A')}
389
+ - Pedra: {piece_metadata.get('stone', 'N/A')}
390
+ - Coleção: {piece_metadata.get('collection', 'N/A')}
391
+
392
+ Descreva detalhadamente:
393
+ 1. Tipo de joia e formato geral
394
+ 2. Materiais visíveis (metais, pedras, acabamentos)
395
+ 3. Cores predominantes e tonalidades
396
+ 4. Estilo e design (moderno, clássico, vintage, etc.)
397
+ 5. Detalhes técnicos (lapidação, engastes, texturas)
398
+ 6. Qualidade aparente e acabamento
399
+ 7. Características distintivas para busca
400
+
401
+ Use terminologia técnica de joalheria. Seja específico e descritivo.
402
+ """
403
+
404
+ print(f" 🤖 Gerando descrição IA para {image_path.name}...")
405
+
406
+ response = self.openai_client.chat.completions.create(
407
+ model="gpt-4o", # Modelo mais recente e estável
408
+ messages=[
409
+ {
410
+ "role": "user",
411
+ "content": [
412
+ {"type": "text", "text": prompt},
413
+ {
414
+ "type": "image_url",
415
+ "image_url": {
416
+ "url": f"data:image/png;base64,{base64_image}",
417
+ "detail": "low" # Reduz custo
418
+ }
419
+ }
420
+ ]
421
+ }
422
+ ],
423
+ max_tokens=400,
424
+ temperature=0.3 # Mais consistente
425
+ )
426
+
427
+ description = response.choices[0].message.content
428
+ print(f" ✅ Descrição IA gerada ({len(description)} caracteres)")
429
+ return description
430
+
431
+ except Exception as e:
432
+ print(f" ⚠️ Erro ao gerar descrição IA para {image_path.name}: {e}")
433
+ print(f" 🔄 Usando descrição básica como fallback")
434
+ return self._generate_basic_description(piece_metadata)
435
+
436
+ def _generate_basic_description(self, piece_metadata: Dict) -> str:
437
+ """Gera descrição básica sem IA"""
438
+ name = piece_metadata.get('name', 'Joia')
439
+ collection = piece_metadata.get('collection', '')
440
+ material = piece_metadata.get('material', '')
441
+ stone = piece_metadata.get('stone', '')
442
+
443
+ description = f"{name}"
444
+ if collection:
445
+ description += f" da coleção {collection}"
446
+ if material:
447
+ description += f", confeccionada em {material}"
448
+ if stone:
449
+ description += f" com {stone}"
450
+
451
+ return description
452
+
453
+ def find_images_from_metadata(self, piece_metadata: Dict) -> List[Dict]:
454
+ """Encontra imagens baseado nos metadados da planilha"""
455
+ images = []
456
+ sku = piece_metadata.get('sku', '')
457
+
458
+ # Baseado na estrutura real do CSV: apenas arquivo_peca_01
459
+ filename = piece_metadata.get('arquivo_peca_01', '').strip()
460
+
461
+ if filename and filename != 'nan' and filename != '':
462
+ image_path = self.images_dir / filename
463
+
464
+ if image_path.exists():
465
+ # Determina tipo baseado no nome do arquivo
466
+ filename_lower = filename.lower()
467
+
468
+ if any(keyword in filename_lower for keyword in ["modelo", "person", "wearing", "lifestyle", "usando"]):
469
+ image_type = "lifestyle"
470
+ elif any(keyword in filename_lower for keyword in ["detalhe", "detail", "close"]):
471
+ image_type = "detail"
472
+ elif any(keyword in filename_lower for keyword in ["embalagem", "packaging", "box"]):
473
+ image_type = "packaging"
474
+ else:
475
+ image_type = "product"
476
+
477
+ images.append({
478
+ 'path': image_path,
479
+ 'filename': filename,
480
+ 'type': image_type,
481
+ 'size': image_path.stat().st_size,
482
+ 'column': 'arquivo_peca_01'
483
+ })
484
+ print(f" ✅ Encontrada: {filename} ({image_type})")
485
+ else:
486
+ print(f" ❌ Não encontrada: {filename}")
487
+ else:
488
+ print(f" ⚠️ Nenhum arquivo especificado para SKU: {sku}")
489
+
490
+ return images
491
+
492
+ def _get_color_name_from_rgb(self, rgb: List[int]) -> str:
493
+ """Retorna nome da cor baseado em RGB"""
494
+ if not rgb or len(rgb) != 3:
495
+ return "indefinido"
496
+
497
+ r, g, b = rgb
498
+
499
+ # Cores básicas para joias
500
+ if r > 200 and g > 200 and b > 200:
501
+ return "branco"
502
+ elif r < 50 and g < 50 and b < 50:
503
+ return "preto"
504
+ elif r > 200 and g > 180 and b < 100:
505
+ return "dourado"
506
+ elif r > 180 and g > 180 and b > 180:
507
+ return "prateado"
508
+ elif r > 150 and g < 100 and b < 100:
509
+ return "vermelho"
510
+ elif r < 100 and g < 100 and b > 150:
511
+ return "azul"
512
+ elif r < 100 and g > 150 and b < 100:
513
+ return "verde"
514
+ elif r > 150 and g > 100 and b > 150:
515
+ return "roxo"
516
+ elif r > 200 and g > 150 and b < 100:
517
+ return "laranja"
518
+ else:
519
+ return "multicolorido"
520
+
521
+ # Métodos de análise técnica (mantidos iguais)
522
+ def _analyze_basic_metrics(self, image: np.ndarray) -> Dict:
523
+ """Métricas básicas da imagem"""
524
+ height, width = image.shape[:2]
525
+ brightness = float(np.mean(image))
526
+
527
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
528
+ contrast = float(np.std(gray))
529
+
530
+ hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
531
+ saturation = float(np.mean(hsv[:, :, 1]))
532
+
533
+ return {
534
+ "dimensions": {"width": width, "height": height},
535
+ "brightness": brightness,
536
+ "contrast": contrast,
537
+ "saturation": saturation,
538
+ "aspect_ratio": float(width / height)
539
+ }
540
+
541
+ def _analyze_jewelry_colors(self, image: np.ndarray) -> Dict:
542
+ """Análise de cores para joias"""
543
+ try:
544
+ dominant_colors = self._extract_dominant_colors(image, k=6)
545
+
546
+ return {
547
+ "dominant_colors": dominant_colors,
548
+ "color_count": len(dominant_colors),
549
+ "primary_color": dominant_colors[0] if dominant_colors else None
550
+ }
551
+ except:
552
+ return {"dominant_colors": [], "color_count": 0, "primary_color": None}
553
+
554
+ def _extract_dominant_colors(self, image: np.ndarray, k: int = 6) -> List[Dict]:
555
+ """Extrai cores dominantes"""
556
+ try:
557
+ pixels = image.reshape(-1, 3)
558
+
559
+ # Reduz amostra para performance
560
+ if len(pixels) > 10000:
561
+ indices = np.random.choice(len(pixels), 10000, replace=False)
562
+ pixels = pixels[indices]
563
+
564
+ kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
565
+ kmeans.fit(pixels)
566
+
567
+ colors = []
568
+ labels = kmeans.labels_
569
+ unique, counts = np.unique(labels, return_counts=True)
570
+
571
+ for i, color in enumerate(kmeans.cluster_centers_):
572
+ percentage = counts[i] / len(labels) * 100
573
+ rgb = [int(c) for c in color]
574
+
575
+ colors.append({
576
+ "rgb": rgb,
577
+ "hex": "#{:02x}{:02x}{:02x}".format(*rgb),
578
+ "percentage": float(percentage)
579
+ })
580
+
581
+ return sorted(colors, key=lambda x: x['percentage'], reverse=True)
582
+
583
+ except Exception as e:
584
+ print(f"⚠️ Erro na extração de cores: {e}")
585
+ return []
586
+
587
+ def _analyze_metal_properties(self, image: np.ndarray) -> Dict:
588
+ """Análise básica de propriedades metálicas"""
589
+ try:
590
+ hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
591
+
592
+ # Detecta áreas metálicas (brilhantes + baixa saturação)
593
+ brightness_mask = hsv[:, :, 2] > 150
594
+ low_saturation_mask = hsv[:, :, 1] < 80
595
+ metal_mask = brightness_mask & low_saturation_mask
596
+
597
+ metal_percentage = float(np.sum(metal_mask) / (image.shape[0] * image.shape[1]))
598
+
599
+ return {
600
+ "metal_percentage": metal_percentage,
601
+ "has_metallic_elements": metal_percentage > 0.1
602
+ }
603
+ except:
604
+ return {"metal_percentage": 0.0, "has_metallic_elements": False}
605
+
606
+ def _analyze_stones(self, image: np.ndarray) -> Dict:
607
+ """Análise básica de pedras"""
608
+ try:
609
+ hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
610
+ high_saturation_mask = hsv[:, :, 1] > 100
611
+ stone_percentage = float(np.sum(high_saturation_mask) / (image.shape[0] * image.shape[1]))
612
+
613
+ return {
614
+ "stone_percentage": stone_percentage,
615
+ "has_colored_stones": stone_percentage > 0.05
616
+ }
617
+ except:
618
+ return {"stone_percentage": 0.0, "has_colored_stones": False}
619
+
620
+ def _analyze_jewelry_shapes(self, image: np.ndarray) -> Dict:
621
+ """Análise básica de formas"""
622
+ try:
623
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
624
+ edges = cv2.Canny(gray, 50, 150)
625
+ edge_density = float(np.sum(edges > 0) / (edges.shape[0] * edges.shape[1]))
626
+
627
+ return {
628
+ "edge_density": edge_density,
629
+ "shape_complexity": "high" if edge_density > 0.1 else "low"
630
+ }
631
+ except:
632
+ return {"edge_density": 0.0, "shape_complexity": "unknown"}
633
+
634
+ def _analyze_textures(self, image: np.ndarray) -> Dict:
635
+ """Análise básica de texturas"""
636
+ try:
637
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
638
+ texture_variance = float(np.var(gray))
639
+
640
+ return {
641
+ "texture_variance": texture_variance,
642
+ "texture_type": "smooth" if texture_variance < 1000 else "textured"
643
+ }
644
+ except:
645
+ return {"texture_variance": 0.0, "texture_type": "unknown"}
646
+
647
+ def _analyze_reflections(self, image: np.ndarray) -> Dict:
648
+ """Análise básica de reflexos"""
649
+ try:
650
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
651
+ bright_threshold = np.percentile(gray, 95)
652
+ reflection_mask = gray > bright_threshold
653
+ reflection_percentage = float(np.sum(reflection_mask) / (gray.shape[0] * gray.shape[1]))
654
+
655
+ return {
656
+ "reflection_percentage": reflection_percentage,
657
+ "has_reflections": reflection_percentage > 0.05
658
+ }
659
+ except:
660
+ return {"reflection_percentage": 0.0, "has_reflections": False}
661
+
662
+ def _assess_image_quality(self, image: np.ndarray) -> Dict:
663
+ """Avaliação básica de qualidade"""
664
+ try:
665
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
666
+
667
+ # Nitidez usando variância do Laplaciano
668
+ sharpness = float(cv2.Laplacian(gray, cv2.CV_64F).var())
669
+
670
+ # Score de qualidade simples
671
+ quality_score = min(1.0, sharpness / 1000)
672
+
673
+ return {
674
+ "sharpness": sharpness,
675
+ "quality_score": quality_score,
676
+ "quality_grade": "high" if quality_score > 0.7 else "medium" if quality_score > 0.3 else "low"
677
+ }
678
+ except:
679
+ return {"sharpness": 0.0, "quality_score": 0.0, "quality_grade": "unknown"}
jewelry_cataloger.py ADDED
@@ -0,0 +1,722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from pathlib import Path
4
+ from dotenv import load_dotenv
5
+ import pandas as pd
6
+ import uuid
7
+ from typing import Dict, List, Optional, Set
8
+ from supabase import create_client, Client
9
+ from pinecone import Pinecone
10
+ from image_processor import JewelryImageProcessor
11
+ import time
12
+ import json
13
+
14
+ # Carrega variáveis de ambiente
15
+ load_dotenv()
16
+
17
+ class JewelryCataloger:
18
+ def __init__(self):
19
+ """Inicializa o catalogador"""
20
+ print("🚀 Inicializando catalogador de joias...")
21
+
22
+ # Configuração de caminhos
23
+ self.root_dir = Path(__file__).parent
24
+ self.images_dir = self.root_dir / "imagens"
25
+ self.csv_path = self.root_dir / "jewelry_metadata.csv"
26
+
27
+ # Configuração Supabase
28
+ supabase_url = os.getenv('SUPABASE_URL')
29
+ supabase_key = os.getenv('SUPABASE_SERVICE_KEY') # Usa SERVICE_KEY para uploads
30
+
31
+ if not supabase_url or not supabase_key:
32
+ raise ValueError("❌ Credenciais do Supabase não encontradas! Verifique SUPABASE_URL e SUPABASE_SERVICE_KEY")
33
+
34
+ self.supabase: Client = create_client(supabase_url, supabase_key)
35
+
36
+ # Configuração Pinecone
37
+ pinecone_api_key = os.getenv('PINECONE_API_KEY')
38
+ index_name = os.getenv('PINECONE_INDEX_NAME', 'jewelry-embeddings')
39
+
40
+ if not pinecone_api_key:
41
+ raise ValueError("❌ API Key do Pinecone não encontrada!")
42
+
43
+ pc = Pinecone(api_key=pinecone_api_key)
44
+ self.pinecone_index = pc.Index(index_name)
45
+
46
+ # Processador de imagens
47
+ self.image_processor = JewelryImageProcessor()
48
+
49
+ # Configurações
50
+ self.batch_size = int(os.getenv('BATCH_SIZE', 10))
51
+ self.storage_bucket = os.getenv('SUPABASE_STORAGE_BUCKET', 'jewelry-images')
52
+
53
+ # Controle de duplicatas
54
+ self.processed_skus: Set[str] = set()
55
+
56
+ print("✅ Catalogador inicializado com sucesso!")
57
+ print(f"📁 Diretório de imagens: {self.images_dir}")
58
+ print(f"📄 Arquivo de metadados: {self.csv_path}")
59
+
60
+ def load_metadata_from_csv(self) -> pd.DataFrame:
61
+ """Carrega metadados da planilha CSV"""
62
+ try:
63
+ if not self.csv_path.exists():
64
+ print(f"❌ Arquivo CSV não encontrado: {self.csv_path}")
65
+ return pd.DataFrame()
66
+
67
+ # Tenta diferentes encodings
68
+ encodings = ['utf-8', 'latin-1', 'cp1252']
69
+ df = None
70
+
71
+ for encoding in encodings:
72
+ try:
73
+ df = pd.read_csv(self.csv_path, encoding=encoding)
74
+ print(f"✅ CSV carregado com encoding {encoding}")
75
+ break
76
+ except UnicodeDecodeError:
77
+ continue
78
+
79
+ if df is None:
80
+ print("❌ Não foi possível carregar o CSV com nenhum encoding")
81
+ return pd.DataFrame()
82
+
83
+ # Limpa dados NaN
84
+ df = df.fillna('')
85
+
86
+ # Remove duplicatas baseado no SKU + arquivo
87
+ print(f"📊 Registros antes da limpeza: {len(df)}")
88
+ df = df.drop_duplicates(subset=['sku', 'arquivo_peca_01'], keep='first')
89
+ print(f"📊 Registros após remoção de duplicatas: {len(df)}")
90
+
91
+ print(f"📋 Colunas: {list(df.columns)}")
92
+
93
+ # Mostra alguns exemplos únicos
94
+ unique_skus = df['sku'].unique()
95
+ print(f"\n📋 SKUs únicos encontrados: {len(unique_skus)}")
96
+ for sku in unique_skus[:5]:
97
+ sku_data = df[df['sku'] == sku].iloc[0]
98
+ print(f" {sku}: {sku_data['peca']}")
99
+
100
+ return df
101
+
102
+ except Exception as e:
103
+ print(f"❌ Erro ao carregar CSV: {e}")
104
+ return pd.DataFrame()
105
+
106
+ def process_piece_metadata(self, row: pd.Series) -> Dict:
107
+ """Processa metadados de uma peça"""
108
+ # Converte Series para dict para facilitar acesso
109
+ row_dict = row.to_dict()
110
+
111
+ return {
112
+ 'sku': str(row_dict.get('sku', '')).strip(),
113
+ 'name': str(row_dict.get('peca', '')).strip(),
114
+ 'collection': str(row_dict.get('colecao', '')).strip(),
115
+ 'material': str(row_dict.get('material', '')).strip(),
116
+ 'predominant_metal': str(row_dict.get('metal_predominante', '')).strip(),
117
+ 'stone': str(row_dict.get('pedra', '')).strip(),
118
+ 'size': str(row_dict.get('tamanho', '')).strip(),
119
+ 'description': str(row_dict.get('descricao', '')).strip(),
120
+ 'price_brl': self._parse_price(row_dict.get('preco', '')),
121
+ 'category': self._infer_category(str(row_dict.get('peca', ''))),
122
+ 'is_active': True,
123
+ # Apenas arquivo_peca_01 baseado na estrutura real
124
+ 'arquivo_peca_01': str(row_dict.get('arquivo_peca_01', '')).strip(),
125
+ 'id_arq_peca_01': str(row_dict.get('id_arq_peca_01', '')).strip(),
126
+ 'status': str(row_dict.get('status', '')).strip(),
127
+ }
128
+
129
+ def _parse_price(self, price_str: str) -> Optional[float]:
130
+ """Converte string de preço para float"""
131
+ try:
132
+ if not price_str or price_str == '':
133
+ return None
134
+ # Remove caracteres não numéricos exceto ponto e vírgula
135
+ price_clean = str(price_str).replace(',', '.').strip()
136
+ return float(price_clean)
137
+ except:
138
+ return None
139
+
140
+ def _infer_category(self, piece_name: str) -> str:
141
+ """Infere categoria da peça pelo nome"""
142
+ name_lower = piece_name.lower()
143
+
144
+ if any(word in name_lower for word in ['anel', 'ring']):
145
+ return 'anel'
146
+ elif any(word in name_lower for word in ['colar', 'necklace']):
147
+ return 'colar'
148
+ elif any(word in name_lower for word in ['brinco', 'earring']):
149
+ return 'brinco'
150
+ elif any(word in name_lower for word in ['pulseira', 'bracelet']):
151
+ return 'pulseira'
152
+ elif any(word in name_lower for word in ['pingente', 'pendant']):
153
+ return 'pingente'
154
+ else:
155
+ return 'outros'
156
+
157
+ def create_rich_pinecone_metadata(self, piece_metadata: Dict, img_info: Dict,
158
+ technical_analysis: Dict, ai_description: str) -> Dict:
159
+ """Cria metadados ricos para o Pinecone - FASE 1 HÍBRIDA"""
160
+
161
+ # Metadados básicos da peça
162
+ metadata = {
163
+ # Identificação
164
+ 'sku': piece_metadata['sku'],
165
+ 'piece_name': piece_metadata['name'],
166
+ 'filename': img_info['filename'],
167
+ 'image_type': img_info['type'],
168
+
169
+ # Classificação
170
+ 'category': piece_metadata['category'],
171
+ 'collection': piece_metadata['collection'],
172
+
173
+ # Materiais
174
+ 'material': piece_metadata['material'],
175
+ 'predominant_metal': piece_metadata['predominant_metal'],
176
+ 'stone': piece_metadata['stone'],
177
+
178
+ # Características físicas
179
+ 'size': piece_metadata['size'],
180
+ 'price_brl': piece_metadata.get('price_brl', 0) or 0,
181
+
182
+ # FASE 1: DESCRIÇÕES COMPLETAS
183
+ 'csv_description': piece_metadata['description'],
184
+ 'ai_description': ai_description,
185
+ 'combined_description': f"{piece_metadata['description']} {ai_description}".strip(),
186
+ }
187
+
188
+ # FASE 1: ANÁLISE TÉCNICA EXPANDIDA
189
+ try:
190
+ # Cores dominantes
191
+ color_analysis = technical_analysis.get('color_analysis', {})
192
+ dominant_colors = color_analysis.get('dominant_colors', [])
193
+
194
+ if dominant_colors:
195
+ metadata['primary_color'] = dominant_colors[0].get('hex', '#000000')
196
+ metadata['primary_color_name'] = self._get_color_name_from_hex(dominant_colors[0].get('hex', '#000000'))
197
+ metadata['color_count'] = len(dominant_colors)
198
+
199
+ # Top 3 cores como lista
200
+ top_colors = [color.get('hex', '#000000') for color in dominant_colors[:3]]
201
+ metadata['top_colors'] = top_colors
202
+
203
+ # Características de material
204
+ metal_analysis = technical_analysis.get('metal_analysis', {})
205
+ metadata['has_metallic_elements'] = metal_analysis.get('has_metallic_elements', False)
206
+ metadata['metal_percentage'] = round(metal_analysis.get('metal_percentage', 0), 2)
207
+
208
+ stone_analysis = technical_analysis.get('stone_analysis', {})
209
+ metadata['has_colored_stones'] = stone_analysis.get('has_colored_stones', False)
210
+ metadata['stone_percentage'] = round(stone_analysis.get('stone_percentage', 0), 2)
211
+
212
+ # Qualidade e características visuais
213
+ quality_assessment = technical_analysis.get('quality_assessment', {})
214
+ metadata['quality_score'] = round(quality_assessment.get('quality_score', 0), 2)
215
+ metadata['quality_grade'] = quality_assessment.get('quality_grade', 'unknown')
216
+ metadata['sharpness'] = round(quality_assessment.get('sharpness', 0), 2)
217
+
218
+ # Características de forma e textura
219
+ shape_analysis = technical_analysis.get('shape_analysis', {})
220
+ metadata['shape_complexity'] = shape_analysis.get('shape_complexity', 'unknown')
221
+ metadata['edge_density'] = round(shape_analysis.get('edge_density', 0), 3)
222
+
223
+ texture_analysis = technical_analysis.get('texture_analysis', {})
224
+ metadata['texture_type'] = texture_analysis.get('texture_type', 'unknown')
225
+
226
+ reflection_analysis = technical_analysis.get('reflection_analysis', {})
227
+ metadata['has_reflections'] = reflection_analysis.get('has_reflections', False)
228
+ metadata['reflection_percentage'] = round(reflection_analysis.get('reflection_percentage', 0), 3)
229
+
230
+ # Métricas básicas da imagem
231
+ basic_metrics = technical_analysis.get('basic_metrics', {})
232
+ dimensions = basic_metrics.get('dimensions', {})
233
+ metadata['image_width'] = dimensions.get('width', 0)
234
+ metadata['image_height'] = dimensions.get('height', 0)
235
+ metadata['aspect_ratio'] = round(basic_metrics.get('aspect_ratio', 1), 2)
236
+ metadata['brightness'] = round(basic_metrics.get('brightness', 0), 1)
237
+ metadata['contrast'] = round(basic_metrics.get('contrast', 0), 1)
238
+ metadata['saturation'] = round(basic_metrics.get('saturation', 0), 1)
239
+
240
+ # Tags derivadas para busca
241
+ search_tags = []
242
+
243
+ # Tags de categoria e coleção
244
+ if metadata['category']:
245
+ search_tags.append(metadata['category'])
246
+ if metadata['collection']:
247
+ search_tags.append(metadata['collection'].lower())
248
+
249
+ # Tags de material
250
+ if metadata['material']:
251
+ search_tags.append(metadata['material'].lower())
252
+ if metadata['predominant_metal']:
253
+ search_tags.append(metadata['predominant_metal'].lower().replace(' ', '_'))
254
+ if metadata['stone']:
255
+ search_tags.append(metadata['stone'].lower())
256
+
257
+ # Tags de qualidade
258
+ if metadata['quality_grade'] != 'unknown':
259
+ search_tags.append(f"quality_{metadata['quality_grade']}")
260
+
261
+ # Tags de características visuais
262
+ if metadata['has_metallic_elements']:
263
+ search_tags.append('metallic')
264
+ if metadata['has_colored_stones']:
265
+ search_tags.append('gemstone')
266
+ if metadata['has_reflections']:
267
+ search_tags.append('reflective')
268
+
269
+ # Tags de estilo baseadas no tipo de imagem
270
+ if img_info['type'] == 'lifestyle':
271
+ search_tags.append('lifestyle_shot')
272
+ else:
273
+ search_tags.append('product_shot')
274
+
275
+ metadata['search_tags'] = search_tags
276
+
277
+ except Exception as e:
278
+ print(f" ⚠️ Erro ao processar análise técnica para metadados: {e}")
279
+
280
+ # Remove valores None e converte para tipos serializáveis
281
+ cleaned_metadata = {}
282
+ for key, value in metadata.items():
283
+ if value is not None and value != '' and value != []:
284
+ if isinstance(value, (list, dict)):
285
+ cleaned_metadata[key] = value
286
+ else:
287
+ cleaned_metadata[key] = str(value) if not isinstance(value, (int, float, bool)) else value
288
+
289
+ return cleaned_metadata
290
+
291
+ def _get_color_name_from_hex(self, hex_color: str) -> str:
292
+ """Converte cor hex para nome"""
293
+ try:
294
+ # Remove # se presente
295
+ hex_color = hex_color.replace('#', '')
296
+
297
+ # Converte para RGB
298
+ r = int(hex_color[0:2], 16)
299
+ g = int(hex_color[2:4], 16)
300
+ b = int(hex_color[4:6], 16)
301
+
302
+ # Classifica cor
303
+ if r > 200 and g > 200 and b > 200:
304
+ return "branco"
305
+ elif r < 50 and g < 50 and b < 50:
306
+ return "preto"
307
+ elif r > 200 and g > 180 and b < 100:
308
+ return "dourado"
309
+ elif r > 180 and g > 180 and b > 180:
310
+ return "prateado"
311
+ elif r > 150 and g < 100 and b < 100:
312
+ return "vermelho"
313
+ elif r < 100 and g < 100 and b > 150:
314
+ return "azul"
315
+ elif r < 100 and g > 150 and b < 100:
316
+ return "verde"
317
+ elif r > 150 and g > 100 and b > 150:
318
+ return "roxo"
319
+ elif r > 200 and g > 150 and b < 100:
320
+ return "laranja"
321
+ else:
322
+ return "multicolorido"
323
+ except:
324
+ return "indefinido"
325
+
326
+ def upload_to_supabase_storage(self, file_path: Path, storage_path: str) -> Optional[str]:
327
+ """Faz upload de arquivo para o storage do Supabase"""
328
+ try:
329
+ print(f" 📤 Fazendo upload: {storage_path}")
330
+
331
+ with open(file_path, 'rb') as file:
332
+ response = self.supabase.storage.from_(self.storage_bucket).upload(
333
+ storage_path,
334
+ file,
335
+ file_options={
336
+ "content-type": "image/png",
337
+ "upsert": "true" # Sobrescreve se já existir
338
+ }
339
+ )
340
+
341
+ # Gera URL pública
342
+ public_url = self.supabase.storage.from_(self.storage_bucket).get_public_url(storage_path)
343
+ print(f" ✅ Upload concluído")
344
+ return public_url
345
+
346
+ except Exception as e:
347
+ print(f" ❌ Erro no upload para Supabase: {e}")
348
+ return None
349
+
350
+ def save_piece_to_database(self, piece_data: Dict) -> bool:
351
+ """Salva dados da peça no banco (apenas uma vez por SKU)"""
352
+ try:
353
+ sku = piece_data['sku']
354
+
355
+ # Verifica se já processou este SKU
356
+ if sku in self.processed_skus:
357
+ print(f" ⚠️ SKU {sku} já processado, pulando metadados...")
358
+ return True
359
+
360
+ # Remove campos que não existem na tabela
361
+ db_data = {k: v for k, v in piece_data.items()
362
+ if k not in ['arquivo_peca_01', 'id_arq_peca_01', 'status']}
363
+
364
+ print(f" 💾 Salvando peça no banco: {db_data['sku']}")
365
+ response = self.supabase.table('pieces').upsert(db_data).execute()
366
+
367
+ # Marca como processado
368
+ self.processed_skus.add(sku)
369
+
370
+ print(f" ✅ Peça salva no banco")
371
+ return True
372
+ except Exception as e:
373
+ print(f" ❌ Erro ao salvar peça {piece_data.get('sku', 'N/A')}: {e}")
374
+ return False
375
+
376
+ def save_image_to_database(self, image_data: Dict) -> Optional[str]:
377
+ """Salva dados da imagem no banco e retorna o ID"""
378
+ try:
379
+ print(f" 💾 Salvando imagem no banco: {image_data['file_name']}")
380
+ response = self.supabase.table('piece_images').insert(image_data).execute()
381
+
382
+ # Extrai o ID da imagem inserida
383
+ image_id = response.data[0]['id'] if response.data else None
384
+
385
+ print(f" ✅ Imagem salva no banco (ID: {image_id})")
386
+ return image_id
387
+ except Exception as e:
388
+ print(f" ❌ Erro ao salvar imagem: {e}")
389
+ return None
390
+
391
+ def save_visual_features(self, image_id: str, features: List[Dict]) -> bool:
392
+ """Salva características visuais na tabela visual_features"""
393
+ try:
394
+ if not features:
395
+ return True
396
+
397
+ # Adiciona image_id a cada feature
398
+ features_with_id = []
399
+ for feature in features:
400
+ feature_data = feature.copy()
401
+ feature_data['image_id'] = image_id
402
+ features_with_id.append(feature_data)
403
+
404
+ print(f" 🔍 Salvando {len(features_with_id)} características visuais...")
405
+ response = self.supabase.table('visual_features').insert(features_with_id).execute()
406
+ print(f" ✅ Características visuais salvas")
407
+ return True
408
+ except Exception as e:
409
+ print(f" ❌ Erro ao salvar características visuais: {e}")
410
+ return False
411
+
412
+ def save_image_tags(self, image_id: str, tags: List[Dict]) -> bool:
413
+ """Salva tags da imagem na tabela image_tags"""
414
+ try:
415
+ if not tags:
416
+ return True
417
+
418
+ # Adiciona image_id a cada tag
419
+ tags_with_id = []
420
+ for tag in tags:
421
+ tag_data = tag.copy()
422
+ tag_data['image_id'] = image_id
423
+ tags_with_id.append(tag_data)
424
+
425
+ print(f" 🏷️ Salvando {len(tags_with_id)} tags...")
426
+ response = self.supabase.table('image_tags').insert(tags_with_id).execute()
427
+ print(f" ✅ Tags salvas")
428
+ return True
429
+ except Exception as e:
430
+ print(f" ❌ Erro ao salvar tags: {e}")
431
+ return False
432
+
433
+ def save_embedding_to_pinecone(self, vector_id: str, embedding: List[float], metadata: Dict) -> bool:
434
+ """Salva embedding no Pinecone com metadados ricos - FASE 1"""
435
+ try:
436
+ print(f" 🔍 Salvando embedding no Pinecone: {vector_id}")
437
+ print(f" 📊 Metadados: {len(metadata)} campos")
438
+
439
+ # Mostra alguns metadados importantes
440
+ key_fields = ['sku', 'piece_name', 'category', 'primary_color_name', 'quality_grade']
441
+ preview = {k: metadata.get(k, 'N/A') for k in key_fields if k in metadata}
442
+ print(f" 🔍 Preview: {preview}")
443
+
444
+ self.pinecone_index.upsert([(vector_id, embedding, metadata)])
445
+ print(f" ✅ Embedding salvo no Pinecone com metadados expandidos")
446
+ return True
447
+ except Exception as e:
448
+ print(f" ❌ Erro ao salvar no Pinecone: {e}")
449
+ return False
450
+
451
+ def log_processing(self, sku: str, process_type: str, status: str, error_message: str = None, processing_time: int = None):
452
+ """Registra log de processamento"""
453
+ try:
454
+ log_data = {
455
+ 'sku': sku,
456
+ 'process_type': process_type,
457
+ 'status': status,
458
+ 'error_message': error_message,
459
+ 'processing_time_ms': processing_time
460
+ }
461
+ self.supabase.table('processing_log').insert(log_data).execute()
462
+ except:
463
+ pass # Log não é crítico
464
+
465
+ def process_single_piece(self, piece_metadata: Dict) -> bool:
466
+ """Processa uma única peça com todas suas imagens"""
467
+ sku = piece_metadata['sku']
468
+ start_time = time.time()
469
+
470
+ print(f"\n🔄 Processando peça: {sku} - {piece_metadata['name']}")
471
+ print(f" 📄 Arquivo: {piece_metadata.get('arquivo_peca_01', 'N/A')}")
472
+
473
+ try:
474
+ # Salva metadados da peça (apenas uma vez por SKU)
475
+ if not self.save_piece_to_database(piece_metadata):
476
+ self.log_processing(sku, 'metadata', 'error', 'Falha ao salvar metadados')
477
+ return False
478
+
479
+ # Encontra imagens da peça usando os metadados
480
+ images = self.image_processor.find_images_from_metadata(piece_metadata)
481
+ if not images:
482
+ print(f"⚠️ Nenhuma imagem encontrada para SKU: {sku}")
483
+ self.log_processing(sku, 'images', 'warning', 'Nenhuma imagem encontrada')
484
+ return True # Considera sucesso mesmo sem imagem
485
+
486
+ print(f"📸 Encontradas {len(images)} imagens para {sku}")
487
+
488
+ # Processa cada imagem
489
+ processed_images = 0
490
+ for img_info in images:
491
+ try:
492
+ img_start_time = time.time()
493
+ image_path = img_info['path']
494
+
495
+ print(f" 🖼️ Processando: {img_info['filename']} ({img_info['type']})")
496
+
497
+ # Gera embedding
498
+ embedding = self.image_processor.generate_embedding(image_path)
499
+ if embedding is None:
500
+ print(f" ❌ Falha ao gerar embedding")
501
+ continue
502
+
503
+ # Análise técnica
504
+ technical_analysis = self.image_processor.analyze_jewelry_technical(image_path)
505
+
506
+ # Extrai características visuais
507
+ visual_features = self.image_processor.extract_visual_features(image_path, technical_analysis)
508
+
509
+ # Gera tags
510
+ image_tags = self.image_processor.generate_image_tags(image_path, piece_metadata, technical_analysis)
511
+
512
+ # Cria thumbnail
513
+ thumbnail_path = self.image_processor.create_thumbnail(image_path)
514
+ if not thumbnail_path:
515
+ print(f" ❌ Falha ao criar thumbnail")
516
+ continue
517
+
518
+ # Upload da imagem original
519
+ original_storage_path = f"{sku}/{img_info['filename']}"
520
+ original_url = self.upload_to_supabase_storage(image_path, original_storage_path)
521
+
522
+ # Upload do thumbnail
523
+ thumbnail_storage_path = f"thumbnails/{thumbnail_path.name}"
524
+ thumbnail_url = self.upload_to_supabase_storage(thumbnail_path, thumbnail_storage_path)
525
+
526
+ if not original_url or not thumbnail_url:
527
+ print(f" ❌ Falha no upload")
528
+ continue
529
+
530
+ # Gera descrição IA
531
+ ai_description = self.image_processor.generate_ai_description(image_path, piece_metadata)
532
+
533
+ # ID único para o vetor
534
+ vector_id = str(uuid.uuid4())
535
+
536
+ # FASE 1: CRIA METADADOS RICOS PARA PINECONE
537
+ rich_metadata = self.create_rich_pinecone_metadata(
538
+ piece_metadata, img_info, technical_analysis, ai_description
539
+ )
540
+
541
+ # Salva no Pinecone com metadados expandidos
542
+ if not self.save_embedding_to_pinecone(vector_id, embedding.tolist(), rich_metadata):
543
+ print(f" ❌ Falha ao salvar no Pinecone")
544
+ continue
545
+
546
+ # Obtém dimensões da imagem
547
+ from PIL import Image
548
+ with Image.open(image_path) as img:
549
+ width, height = img.size
550
+
551
+ # Salva no banco
552
+ image_data = {
553
+ 'sku': sku,
554
+ 'image_type': img_info['type'],
555
+ 'original_url': original_url,
556
+ 'thumbnail_url': thumbnail_url,
557
+ 'file_name': img_info['filename'],
558
+ 'file_size_bytes': img_info['size'],
559
+ 'image_width': width,
560
+ 'image_height': height,
561
+ 'embeddings_vector_id': vector_id,
562
+ 'technical_analysis': technical_analysis,
563
+ 'ai_description': ai_description,
564
+ 'dominant_colors': technical_analysis.get('color_analysis', {}).get('dominant_colors', []),
565
+ 'quality_score': technical_analysis.get('quality_assessment', {}).get('quality_score', 0),
566
+ 'is_primary': processed_images == 0 # Primeira imagem é primária
567
+ }
568
+
569
+ # Salva imagem e obtém ID
570
+ image_id = self.save_image_to_database(image_data)
571
+ if not image_id:
572
+ print(f" ❌ Falha ao salvar no banco")
573
+ continue
574
+
575
+ # Salva características visuais
576
+ self.save_visual_features(image_id, visual_features)
577
+
578
+ # Salva tags
579
+ self.save_image_tags(image_id, image_tags)
580
+
581
+ processed_images += 1
582
+ img_time = int((time.time() - img_start_time) * 1000)
583
+ print(f" ✅ Processada em {img_time}ms")
584
+
585
+ except Exception as e:
586
+ print(f" ❌ Erro ao processar {img_info['filename']}: {e}")
587
+ continue
588
+
589
+ # Log de sucesso
590
+ total_time = int((time.time() - start_time) * 1000)
591
+ self.log_processing(sku, 'complete', 'success', None, total_time)
592
+
593
+ print(f"✅ Peça processada: {processed_images}/{len(images)} imagens em {total_time}ms")
594
+ return True # Considera sucesso se salvou a peça, mesmo sem imagens
595
+
596
+ except Exception as e:
597
+ total_time = int((time.time() - start_time) * 1000)
598
+ self.log_processing(sku, 'complete', 'error', str(e), total_time)
599
+ print(f"❌ Erro ao processar peça {sku}: {e}")
600
+ return False
601
+
602
+ def run_cataloging(self):
603
+ """Executa o processo completo de catalogação"""
604
+ print("🚀 Iniciando catalogação de joias - FASE 1 HÍBRIDA...")
605
+ print(f"📍 Diretório: {self.root_dir}")
606
+
607
+ # Carrega metadados
608
+ df = self.load_metadata_from_csv()
609
+ if df.empty:
610
+ print("❌ Nenhum metadado carregado. Verifique o arquivo CSV.")
611
+ return
612
+
613
+ # Estatísticas iniciais
614
+ total_pieces = len(df)
615
+ processed = 0
616
+ errors = 0
617
+
618
+ print(f"\n📊 Iniciando processamento de {total_pieces} registros...")
619
+ print("🎯 FASE 1: Metadados ricos + Descrições completas + Análise técnica expandida")
620
+
621
+ # Processa cada peça
622
+ for index, row in df.iterrows():
623
+ try:
624
+ piece_metadata = self.process_piece_metadata(row)
625
+
626
+ if not piece_metadata['sku']:
627
+ print(f"⚠️ SKU vazio na linha {index + 1}, pulando...")
628
+ continue
629
+
630
+ if self.process_single_piece(piece_metadata):
631
+ processed += 1
632
+ else:
633
+ errors += 1
634
+
635
+ # Progress update
636
+ progress = ((index + 1) / total_pieces) * 100
637
+ print(f"\n📊 Progresso: {progress:.1f}% ({processed} processadas, {errors} erros)")
638
+
639
+ # Pausa entre processamentos para não sobrecarregar APIs
640
+ if (index + 1) % self.batch_size == 0:
641
+ print("⏸️ Pausa entre lotes...")
642
+ time.sleep(2)
643
+
644
+ except Exception as e:
645
+ errors += 1
646
+ print(f"❌ Erro fatal na linha {index + 1}: {e}")
647
+ continue
648
+
649
+ # Relatório final
650
+ print(f"\n🎉 Catalogação FASE 1 concluída!")
651
+ print(f"📊 Estatísticas finais:")
652
+ print(f" • Total de registros: {total_pieces}")
653
+ print(f" • SKUs únicos processados: {len(self.processed_skus)}")
654
+ print(f" • Registros processados: {processed}")
655
+ print(f" • Erros: {errors}")
656
+ print(f" • Taxa de sucesso: {(processed/total_pieces)*100:.1f}%")
657
+
658
+ # Verifica estatísticas do Pinecone
659
+ try:
660
+ stats = self.pinecone_index.describe_index_stats()
661
+ print(f" • Vetores no Pinecone: {stats.total_vector_count}")
662
+
663
+ # Testa busca com metadados ricos
664
+ print(f"\n🔍 Testando busca com metadados ricos...")
665
+ test_results = self.pinecone_index.query(
666
+ vector=[0.0] * 768, # Vetor dummy
667
+ top_k=1,
668
+ include_metadata=True,
669
+ filter={"category": {"$eq": "colar"}}
670
+ )
671
+
672
+ if test_results.matches:
673
+ sample_metadata = test_results.matches[0].metadata
674
+ print(f" • Campos de metadata: {len(sample_metadata)}")
675
+ print(f" • Exemplo de busca por categoria: ✅")
676
+
677
+ # Mostra alguns campos importantes
678
+ important_fields = ['sku', 'piece_name', 'csv_description', 'ai_description',
679
+ 'primary_color_name', 'quality_grade', 'search_tags']
680
+ for field in important_fields:
681
+ if field in sample_metadata:
682
+ value = sample_metadata[field]
683
+ if isinstance(value, str) and len(value) > 50:
684
+ value = value[:50] + "..."
685
+ print(f" • {field}: {value}")
686
+
687
+ except Exception as e:
688
+ print(f" ⚠️ Erro ao verificar Pinecone: {e}")
689
+
690
+ # Verifica estatísticas do Supabase
691
+ try:
692
+ pieces_count = self.supabase.table('pieces').select('sku', count='exact').execute()
693
+ images_count = self.supabase.table('piece_images').select('id', count='exact').execute()
694
+ features_count = self.supabase.table('visual_features').select('id', count='exact').execute()
695
+ tags_count = self.supabase.table('image_tags').select('id', count='exact').execute()
696
+
697
+ print(f" • Peças no Supabase: {pieces_count.count}")
698
+ print(f" • Imagens no Supabase: {images_count.count}")
699
+ print(f" • Características visuais: {features_count.count}")
700
+ print(f" • Tags de imagens: {tags_count.count}")
701
+ except Exception as e:
702
+ print(f" ⚠️ Erro ao verificar Supabase: {e}")
703
+
704
+ print(f"\n🎯 FASE 1 HÍBRIDA IMPLEMENTADA:")
705
+ print(f" ✅ Descrições CSV e IA nos metadados do Pinecone")
706
+ print(f" ✅ Análise técnica expandida")
707
+ print(f" ✅ Tags de busca automáticas")
708
+ print(f" ✅ Filtros ricos disponíveis")
709
+ print(f" ✅ Metadados completos para busca avançada")
710
+
711
+ if __name__ == "__main__":
712
+ try:
713
+ cataloger = JewelryCataloger()
714
+ cataloger.run_cataloging()
715
+
716
+ except KeyboardInterrupt:
717
+ print("\n⏹️ Processamento interrompido pelo usuário")
718
+ sys.exit(0)
719
+
720
+ except Exception as e:
721
+ print(f"\n❌ Erro fatal: {e}")
722
+ sys.exit(1)
jewelry_metadata.csv ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ idx,sku,peca,colecao,material,metal_predominante,pedra,tamanho,descricao,preco,arquivo_peca_01,id_arq_peca_01,status
2
+ 1,CO8671,Colar Rita,Afeto,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Pérola de água doce,45 cm,"Colar com pedras coloridas, pérola de água doce, canutilhos e pingente Divino Espirito Santo",380,colar_rita_01.png,1uoy1O4gOSk0XJwuNzvB2MgRwOYwFZMpA,id_ok
3
+ 2,CO8671,Colar Rita,Afeto,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Pérola de água doce,45 cm,"Colar com pedras coloridas, pérola de água doce, canutilhos e pingente Divino Espirito Santo",380,colar_rita_02.png,1BHPzTsK-jYsBzMtro82Cp_P40ZAAOK5F,id_ok
4
+ 3,CO8671,Colar Rita,Afeto,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Pérola de água doce,45 cm,"Colar com pedras coloridas, pérola de água doce, canutilhos e pingente Divino Espirito Santo",380,colar_rita_03.png,1H-hIVnAceKBs8Ko8gGhF6p-OMMuSDQjD,id_ok
5
+ 4,CO8671,Colar Rita,Afeto,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Pérola de água doce,45 cm,"Colar com pedras coloridas, pérola de água doce, canutilhos e pingente Divino Espirito Santo",380,colar_rita_modelo_01.png,1Jv2S7PTYU4iVHzr7N8eBCh6TJTQmEfFY,id_ok
6
+ 5,CO8671,Colar Rita,Afeto,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Pérola de água doce,45 cm,"Colar com pedras coloridas, pérola de água doce, canutilhos e pingente Divino Espirito Santo",380,colar_rita_modelo_02.png,1S2ho9CgpBaBpXer1JNocV7birvMCTEu7,id_ok
7
+ 6,CO8671,Colar Rita,Afeto,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Pérola de água doce,45 cm,"Colar com pedras coloridas, pérola de água doce, canutilhos e pingente Divino Espirito Santo",380,colar_rita_modelo_03.png,1Dj4wRZ_-zy4xPRItcvJpcB69h5Jnajuc,id_ok
8
+ 7,AN935,Anel Rafaela,Astral,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Cristal,"16,17,18","Adicione um toque de moda ao seu look com o Anel Rafaela. Com banho de ouro amarelo 18k e seu lindo cristal oval de 18x25mm, este anel é o acessório perfeito para complementar qualquer roupa. Seu design sofisticado e delicado irá conquistar olhares e trazer um brilho encantador às suas mãos em qualquer ocasião.",330,anel_rafaela_01.png,1o_pwJ5bmJr-nzt4YJn8wELk3d6aFRfjU,id_ok
9
+ 8,AN935,Anel Rafaela,Astral,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Cristal,"16,17,18","Adicione um toque de moda ao seu look com o Anel Rafaela. Com banho de ouro amarelo 18k e seu lindo cristal oval de 18x25mm, este anel é o acessório perfeito para complementar qualquer roupa. Seu design sofisticado e delicado irá conquistar olhares e trazer um brilho encantador às suas mãos em qualquer ocasião.",330,anel_rafaela_02.png,1V1ohgwTvhO7NRs_veVfiZbbTbG4PZJaH,id_ok
10
+ 9,AN935,Anel Rafaela,Astral,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Cristal,"16,17,18","Adicione um toque de moda ao seu look com o Anel Rafaela. Com banho de ouro amarelo 18k e seu lindo cristal oval de 18x25mm, este anel é o acessório perfeito para complementar qualquer roupa. Seu design sofisticado e delicado irá conquistar olhares e trazer um brilho encantador às suas mãos em qualquer ocasião.",330,anel_rafaela_03.png,1pik_yPtKWrImkm5afSXvUKerT9i-DV3u,id_ok
11
+ 10,AN935,Anel Rafaela,Astral,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Cristal,"16,17,18","Adicione um toque de moda ao seu look com o Anel Rafaela. Com banho de ouro amarelo 18k e seu lindo cristal oval de 18x25mm, este anel é o acessório perfeito para complementar qualquer roupa. Seu design sofisticado e delicado irá conquistar olhares e trazer um brilho encantador às suas mãos em qualquer ocasião.",330,anel_rafaela_modelo_01.png,1SBwNNVXb-7hMvyW13hl_RIjdEQsyVPvw,id_ok
12
+ 11,BM3471,Brinco Estela,Brisa,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Concha de Péroal,8 cm,"Com pérolas e corrente veneziana, o Brinco Estela é uma joia sofisticada e exclusiva. Seus materiais luxuosos e design elegante garantem um visual refinado e versátil. Possui banho de ouro amarelo 18k. Adicione um toque de sofisticação à sua coleção de acessórios com este brinco artesanal excepcional.",160,brinco_estela_01.png,1FQgghNgHrj_Yhxgi8xPx_yHV_6kwTVeU,id_ok
13
+ 12,BM3471,Brinco Estela,Brisa,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Concha de Péroal,8 cm,"Com pérolas e corrente veneziana, o Brinco Estela é uma joia sofisticada e exclusiva. Seus materiais luxuosos e design elegante garantem um visual refinado e versátil. Possui banho de ouro amarelo 18k. Adicione um toque de sofisticação à sua coleção de acessórios com este brinco artesanal excepcional.",160,brinco_estela_modelo_01.png,1FQgghNgHrj_Yhxgi8xPx_yHV_6kwTVeU,id_ok
14
+ 13,BM3585,Brinco Sofia,Astral,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,"Pérola de água doce, Cristais",5 cm,"Adicione um toque sofisticado e elegante ao seu visual com o Brinco Sofia. Este brinco é composto por um cristal oval, um retangular e pérola de água doce, proporcionando um brilho sutil e luxuoso. Perfeito para completar qualquer look com estilo e exclusividade",190,brinco_sofia_01.png,1K-eJbpU_LYjqa8Som74g8H0-4sXvltJ3,id_ok
15
+ 14,BM3585,Brinco Sofia,Astral,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,"Pérola de água doce, Cristais",5 cm,"Adicione um toque sofisticado e elegante ao seu visual com o Brinco Sofia. Este brinco é composto por um cristal oval, um retangular e pérola de água doce, proporcionando um brilho sutil e luxuoso. Perfeito para completar qualquer look com estilo e exclusividade",190,brinco_sofia_02.png,1XJ5n-EWBIgkgKQKCEdAGvyAEoIaAXIPh,id_ok
16
+ 15,BM3585,Brinco Sofia,Astral,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,"Pérola de água doce, Cristais",5 cm,"Adicione um toque sofisticado e elegante ao seu visual com o Brinco Sofia. Este brinco é composto por um cristal oval, um retangular e pérola de água doce, proporcionando um brilho sutil e luxuoso. Perfeito para completar qualquer look com estilo e exclusividade",190,brinco_sofia_03.png,1Fx8i86mtUy0iNAwHCE9ykiEpd1EuPlxK,id_ok
17
+ 16,BM3585,Brinco Sofia,Astral,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,"Pérola de água doce, Cristais",5 cm,"Adicione um toque sofisticado e elegante ao seu visual com o Brinco Sofia. Este brinco é composto por um cristal oval, um retangular e pérola de água doce, proporcionando um brilho sutil e luxuoso. Perfeito para completar qualquer look com estilo e exclusividade",190,brinco_sofia_modelo_01.png,100ygAd4WdM6JuVy_2ZTHF6Aj6k5JuGpi,id_ok
18
+ 17,CO8677,Colar Joana,Afeto,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Jade,43 cm,Colar de pedras jade e canutilhos,380,colar_joana_01.png,1-ntzGEwRzHfthqwWngp-Smf5uCF_qQ1h,id_ok
19
+ 18,CO8677,Colar Joana,Afeto,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Jade,43 cm,Colar de pedras jade e canutilhos,380,colar_joana_modelo_01.png,1DY5uR6FRHwg2qiYUzRiV9ZdtWpv1LYad,id_ok
20
+ 19,CO8677,Colar Joana,Afeto,Liga metálica premium c/ banho de ouro amarelo 18k antialérgico,ouro amarelo,Jade,43 cm,Colar de pedras jade e canutilhos,380,colar_joana_modelo_02.png,1sOrBRazrJfFozYJ3_l7hwibMlnNV1u2A,id_ok
requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=2.0.0
2
+ torchvision>=0.15.0
3
+ open-clip-torch>=2.20.0
4
+ pillow>=9.0.0
5
+ opencv-python>=4.7.0
6
+ numpy>=1.21.0
7
+ pandas>=1.5.0
8
+ scikit-learn>=1.2.0
9
+ supabase>=1.0.0
10
+ pinecone>=3.0.0
11
+ python-dotenv>=1.0.0
12
+ requests>=2.28.0
13
+ openai>=1.0.0
14
+ pathlib
15
+ fastapi>=0.110.0
16
+ uvicorn[standard]>=0.29.0
17
+ python-multipart>=0.0.9
18
+ a2wsgi>=1.7.0
scripts/__pycache__/image_processor.cpython-311.pyc ADDED
Binary file (8.33 kB). View file
 
scripts/__pycache__/similarity_search.cpython-311.pyc ADDED
Binary file (9.32 kB). View file
 
scripts/create_supabase_tables.sql ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Extensões necessárias
2
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
3
+ CREATE EXTENSION IF NOT EXISTS "vector";
4
+
5
+ -- Tabela principal de peças de joias
6
+ CREATE TABLE IF NOT EXISTS pieces (
7
+ sku VARCHAR(50) PRIMARY KEY,
8
+ name VARCHAR(255) NOT NULL,
9
+ collection VARCHAR(100),
10
+ material VARCHAR(255),
11
+ predominant_metal VARCHAR(100),
12
+ stone VARCHAR(100),
13
+ stone_color VARCHAR(50),
14
+ size VARCHAR(50),
15
+ weight_grams DECIMAL(8,2),
16
+ price_brl DECIMAL(10,2),
17
+ description TEXT,
18
+ category VARCHAR(50), -- anel, colar, brinco, pulseira, etc
19
+ gender VARCHAR(20), -- feminino, masculino, unissex
20
+ style VARCHAR(100), -- moderno, clássico, vintage, etc
21
+ is_active BOOLEAN DEFAULT true,
22
+ created_at TIMESTAMP DEFAULT NOW(),
23
+ updated_at TIMESTAMP DEFAULT NOW()
24
+ );
25
+
26
+ -- Tabela de imagens das peças
27
+ CREATE TABLE IF NOT EXISTS piece_images (
28
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
29
+ sku VARCHAR(50) REFERENCES pieces(sku) ON DELETE CASCADE,
30
+ image_type VARCHAR(20) CHECK (image_type IN ('product', 'lifestyle', 'detail', 'packaging')),
31
+ original_url VARCHAR(500),
32
+ thumbnail_url VARCHAR(500),
33
+ file_name VARCHAR(255),
34
+ file_size_bytes INTEGER,
35
+ image_width INTEGER,
36
+ image_height INTEGER,
37
+ embeddings_vector_id VARCHAR(100) UNIQUE,
38
+ technical_analysis JSONB,
39
+ ai_description TEXT, -- Descrição gerada por IA
40
+ dominant_colors JSONB, -- Array de cores dominantes
41
+ visual_features JSONB, -- Características visuais extraídas
42
+ quality_score DECIMAL(3,2), -- Score de qualidade da imagem (0-1)
43
+ is_primary BOOLEAN DEFAULT false, -- Imagem principal da peça
44
+ created_at TIMESTAMP DEFAULT NOW()
45
+ );
46
+
47
+ -- Tabela de características visuais extraídas
48
+ CREATE TABLE IF NOT EXISTS visual_features (
49
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
50
+ image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
51
+ feature_type VARCHAR(50), -- 'color', 'shape', 'texture', 'reflection', etc
52
+ feature_value VARCHAR(255),
53
+ confidence_score DECIMAL(3,2),
54
+ created_at TIMESTAMP DEFAULT NOW()
55
+ );
56
+
57
+ -- Tabela de tags automáticas
58
+ CREATE TABLE IF NOT EXISTS image_tags (
59
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
60
+ image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
61
+ tag VARCHAR(100),
62
+ confidence DECIMAL(3,2),
63
+ tag_type VARCHAR(50), -- 'color', 'material', 'style', 'shape'
64
+ created_at TIMESTAMP DEFAULT NOW()
65
+ );
66
+
67
+ -- Tabela de histórico de processamento
68
+ CREATE TABLE IF NOT EXISTS processing_log (
69
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
70
+ sku VARCHAR(50),
71
+ image_id UUID,
72
+ process_type VARCHAR(50), -- 'embedding', 'analysis', 'upload'
73
+ status VARCHAR(20), -- 'success', 'error', 'processing'
74
+ error_message TEXT,
75
+ processing_time_ms INTEGER,
76
+ created_at TIMESTAMP DEFAULT NOW()
77
+ );
78
+
79
+ -- Índices para otimização
80
+ CREATE INDEX IF NOT EXISTS idx_piece_images_sku ON piece_images(sku);
81
+ CREATE INDEX IF NOT EXISTS idx_piece_images_type ON piece_images(image_type);
82
+ CREATE INDEX IF NOT EXISTS idx_piece_images_primary ON piece_images(is_primary);
83
+ CREATE INDEX IF NOT EXISTS idx_visual_features_image_id ON visual_features(image_id);
84
+ CREATE INDEX IF NOT EXISTS idx_visual_features_type ON visual_features(feature_type);
85
+ CREATE INDEX IF NOT EXISTS idx_image_tags_image_id ON image_tags(image_id);
86
+ CREATE INDEX IF NOT EXISTS idx_image_tags_tag ON image_tags(tag);
87
+ CREATE INDEX IF NOT EXISTS idx_processing_log_sku ON processing_log(sku);
88
+ CREATE INDEX IF NOT EXISTS idx_pieces_category ON pieces(category);
89
+ CREATE INDEX IF NOT EXISTS idx_pieces_collection ON pieces(collection);
90
+ CREATE INDEX IF NOT EXISTS idx_pieces_active ON pieces(is_active);
91
+
92
+ -- Função para atualizar updated_at automaticamente
93
+ CREATE OR REPLACE FUNCTION update_updated_at_column()
94
+ RETURNS TRIGGER AS $$
95
+ BEGIN
96
+ NEW.updated_at = NOW();
97
+ RETURN NEW;
98
+ END;
99
+ $$ language 'plpgsql';
100
+
101
+ -- Trigger para atualizar updated_at na tabela pieces
102
+ CREATE TRIGGER update_pieces_updated_at
103
+ BEFORE UPDATE ON pieces
104
+ FOR EACH ROW
105
+ EXECUTE FUNCTION update_updated_at_column();
106
+
107
+ -- View para busca completa de peças com imagens
108
+ CREATE OR REPLACE VIEW pieces_with_images AS
109
+ SELECT
110
+ p.*,
111
+ pi.id as image_id,
112
+ pi.image_type,
113
+ pi.original_url,
114
+ pi.thumbnail_url,
115
+ pi.ai_description,
116
+ pi.dominant_colors,
117
+ pi.visual_features,
118
+ pi.quality_score,
119
+ pi.is_primary
120
+ FROM pieces p
121
+ LEFT JOIN piece_images pi ON p.sku = pi.sku
122
+ WHERE p.is_active = true;
123
+
124
+ -- View para estatísticas de processamento
125
+ CREATE OR REPLACE VIEW processing_stats AS
126
+ SELECT
127
+ DATE(created_at) as process_date,
128
+ process_type,
129
+ status,
130
+ COUNT(*) as count,
131
+ AVG(processing_time_ms) as avg_processing_time_ms
132
+ FROM processing_log
133
+ GROUP BY DATE(created_at), process_type, status
134
+ ORDER BY process_date DESC;
scripts/enhanced_image_processor.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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...
scripts/image_processor.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import clip
3
+ from PIL import Image
4
+ import numpy as np
5
+ import cv2
6
+ from typing import Dict, List, Tuple
7
+ import json
8
+
9
+ class ImageProcessor:
10
+ def __init__(self):
11
+ """Inicializa o processador com modelo CLIP"""
12
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
13
+ self.model, self.preprocess = clip.load("ViT-B/32", device=self.device)
14
+ print(f"🤖 Modelo CLIP carregado no dispositivo: {self.device}")
15
+
16
+ def generate_embedding(self, image_path: str) -> np.ndarray:
17
+ """Gera embedding da imagem usando CLIP"""
18
+ try:
19
+ image = Image.open(image_path).convert('RGB')
20
+ image_input = self.preprocess(image).unsqueeze(0).to(self.device)
21
+
22
+ with torch.no_grad():
23
+ image_features = self.model.encode_image(image_input)
24
+ # Normaliza o vetor
25
+ image_features = image_features / image_features.norm(dim=-1, keepdim=True)
26
+
27
+ return image_features.cpu().numpy().flatten()
28
+ except Exception as e:
29
+ print(f"❌ Erro ao gerar embedding para {image_path}: {e}")
30
+ return None
31
+
32
+ def analyze_image_technical(self, image_path: str) -> Dict:
33
+ """Realiza análise técnica da imagem"""
34
+ try:
35
+ # Carrega imagem
36
+ image = cv2.imread(image_path)
37
+ image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
38
+
39
+ # Análise de cores dominantes
40
+ dominant_colors = self._get_dominant_colors(image_rgb)
41
+
42
+ # Análise de brilho e contraste
43
+ brightness = np.mean(image_rgb)
44
+ contrast = np.std(image_rgb)
45
+
46
+ # Detecção de bordas (complexidade visual)
47
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
48
+ edges = cv2.Canny(gray, 50, 150)
49
+ edge_density = np.sum(edges > 0) / (edges.shape[0] * edges.shape[1])
50
+
51
+ # Análise de saturação
52
+ hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
53
+ saturation = np.mean(hsv[:, :, 1])
54
+
55
+ return {
56
+ "dominant_colors": dominant_colors,
57
+ "brightness": float(brightness),
58
+ "contrast": float(contrast),
59
+ "edge_density": float(edge_density),
60
+ "saturation": float(saturation),
61
+ "image_size": {
62
+ "width": image.shape[1],
63
+ "height": image.shape[0]
64
+ }
65
+ }
66
+ except Exception as e:
67
+ print(f"❌ Erro na análise técnica de {image_path}: {e}")
68
+ return {}
69
+
70
+ def _get_dominant_colors(self, image: np.ndarray, k: int = 5) -> List[Dict]:
71
+ """Extrai cores dominantes usando K-means"""
72
+ try:
73
+ # Reshape da imagem para lista de pixels
74
+ pixels = image.reshape(-1, 3)
75
+
76
+ # K-means clustering
77
+ from sklearn.cluster import KMeans
78
+ kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
79
+ kmeans.fit(pixels)
80
+
81
+ # Calcula percentual de cada cor
82
+ labels = kmeans.labels_
83
+ unique, counts = np.unique(labels, return_counts=True)
84
+
85
+ colors = []
86
+ for i, color in enumerate(kmeans.cluster_centers_):
87
+ percentage = counts[i] / len(labels) * 100
88
+ colors.append({
89
+ "rgb": [int(c) for c in color],
90
+ "hex": "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2])),
91
+ "percentage": float(percentage)
92
+ })
93
+
94
+ # Ordena por percentual
95
+ colors.sort(key=lambda x: x['percentage'], reverse=True)
96
+ return colors
97
+ except Exception as e:
98
+ print(f"❌ Erro ao extrair cores dominantes: {e}")
99
+ return []
100
+
101
+ def create_thumbnail(self, image_path: str, output_path: str, size: Tuple[int, int] = (200, 200)) -> bool:
102
+ """Cria thumbnail da imagem"""
103
+ try:
104
+ with Image.open(image_path) as img:
105
+ # Mantém proporção
106
+ img.thumbnail(size, Image.Resampling.LANCZOS)
107
+
108
+ # Cria imagem quadrada com fundo branco
109
+ thumbnail = Image.new('RGB', size, (255, 255, 255))
110
+
111
+ # Centraliza a imagem
112
+ x = (size[0] - img.width) // 2
113
+ y = (size[1] - img.height) // 2
114
+ thumbnail.paste(img, (x, y))
115
+
116
+ # Salva thumbnail
117
+ thumbnail.save(output_path, 'PNG', quality=95)
118
+ return True
119
+ except Exception as e:
120
+ print(f"❌ Erro ao criar thumbnail de {image_path}: {e}")
121
+ return False
scripts/jewelry_cataloger.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
scripts/setup_database.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from supabase import create_client, Client
3
+ import pinecone
4
+ from pinecone import Pinecone
5
+
6
+ # Configuração do Supabase
7
+ SUPABASE_URL = os.getenv('SUPABASE_URL')
8
+ SUPABASE_KEY = os.getenv('SUPABASE_KEY')
9
+ supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
10
+
11
+ # Configuração do Pinecone
12
+ PINECONE_API_KEY = os.getenv('PINECONE_API_KEY')
13
+ pc = Pinecone(api_key=PINECONE_API_KEY)
14
+
15
+ def create_database_tables():
16
+ """Cria as tabelas necessárias no Supabase"""
17
+
18
+ # Tabela principal de peças
19
+ create_pieces_table = """
20
+ CREATE TABLE IF NOT EXISTS pieces (
21
+ sku VARCHAR(50) PRIMARY KEY,
22
+ name VARCHAR(255) NOT NULL,
23
+ collection VARCHAR(100),
24
+ material VARCHAR(255),
25
+ predominant_metal VARCHAR(100),
26
+ stone VARCHAR(100),
27
+ size VARCHAR(50),
28
+ description TEXT,
29
+ created_at TIMESTAMP DEFAULT NOW(),
30
+ updated_at TIMESTAMP DEFAULT NOW()
31
+ );
32
+ """
33
+
34
+ # Tabela de imagens
35
+ create_images_table = """
36
+ CREATE TABLE IF NOT EXISTS piece_images (
37
+ id SERIAL PRIMARY KEY,
38
+ sku VARCHAR(50) REFERENCES pieces(sku) ON DELETE CASCADE,
39
+ image_type VARCHAR(20) CHECK (image_type IN ('product', 'lifestyle')),
40
+ original_url VARCHAR(500),
41
+ thumbnail_url VARCHAR(500),
42
+ file_name VARCHAR(255),
43
+ embeddings_vector_id VARCHAR(100),
44
+ technical_analysis JSONB,
45
+ created_at TIMESTAMP DEFAULT NOW()
46
+ );
47
+ """
48
+
49
+ # Índices para otimização
50
+ create_indexes = """
51
+ CREATE INDEX IF NOT EXISTS idx_piece_images_sku ON piece_images(sku);
52
+ CREATE INDEX IF NOT EXISTS idx_piece_images_type ON piece_images(image_type);
53
+ """
54
+
55
+ try:
56
+ supabase.postgrest.rpc('exec_sql', {'sql': create_pieces_table}).execute()
57
+ supabase.postgrest.rpc('exec_sql', {'sql': create_images_table}).execute()
58
+ supabase.postgrest.rpc('exec_sql', {'sql': create_indexes}).execute()
59
+ print("✅ Tabelas criadas com sucesso!")
60
+ except Exception as e:
61
+ print(f"❌ Erro ao criar tabelas: {e}")
62
+
63
+ def setup_pinecone_index():
64
+ """Configura o índice do Pinecone"""
65
+ index_name = "jewelry-embeddings"
66
+
67
+ try:
68
+ # Verifica se o índice já existe
69
+ if index_name not in pc.list_indexes().names():
70
+ pc.create_index(
71
+ name=index_name,
72
+ dimension=512, # Dimensão do CLIP
73
+ metric='cosine',
74
+ spec=pinecone.ServerlessSpec(
75
+ cloud='aws',
76
+ region='us-east-1'
77
+ )
78
+ )
79
+ print(f"✅ Índice {index_name} criado no Pinecone!")
80
+ else:
81
+ print(f"✅ Índice {index_name} já existe!")
82
+
83
+ return pc.Index(index_name)
84
+ except Exception as e:
85
+ print(f"❌ Erro ao configurar Pinecone: {e}")
86
+ return None
87
+
88
+ if __name__ == "__main__":
89
+ print("🚀 Configurando banco de dados...")
90
+ create_database_tables()
91
+
92
+ print("🚀 Configurando Pinecone...")
93
+ index = setup_pinecone_index()
94
+
95
+ print("✅ Setup concluído!")
scripts/setup_pinecone.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pinecone import Pinecone, ServerlessSpec
3
+ import time
4
+
5
+ def setup_pinecone_index():
6
+ """Configura índice otimizado do Pinecone para joias"""
7
+
8
+ # Configuração
9
+ api_key = os.getenv('PINECONE_API_KEY')
10
+ index_name = os.getenv('PINECONE_INDEX_NAME', 'jewelry-embeddings')
11
+
12
+ if not api_key:
13
+ raise ValueError("PINECONE_API_KEY não encontrada no ambiente")
14
+
15
+ # Inicializa cliente
16
+ pc = Pinecone(api_key=api_key)
17
+
18
+ # Configuração do índice
19
+ index_config = {
20
+ "name": index_name,
21
+ "dimension": 768, # ViT-L-14 do OpenCLIP
22
+ "metric": "cosine", # Melhor para embeddings de imagem
23
+ "spec": ServerlessSpec(
24
+ cloud="aws",
25
+ region="us-east-1"
26
+ )
27
+ }
28
+
29
+ try:
30
+ # Verifica se índice existe
31
+ existing_indexes = pc.list_indexes().names()
32
+
33
+ if index_name in existing_indexes:
34
+ print(f"✅ Índice '{index_name}' já existe!")
35
+
36
+ # Verifica configuração
37
+ index_info = pc.describe_index(index_name)
38
+ print(f"📊 Dimensão: {index_info.dimension}")
39
+ print(f"📊 Métrica: {index_info.metric}")
40
+ print(f"📊 Status: {index_info.status.state}")
41
+
42
+ else:
43
+ print(f"🚀 Criando índice '{index_name}'...")
44
+ pc.create_index(**index_config)
45
+
46
+ # Aguarda criação
47
+ print("⏳ Aguardando criação do índice...")
48
+ while True:
49
+ index_info = pc.describe_index(index_name)
50
+ if index_info.status.state == "Ready":
51
+ break
52
+ time.sleep(5)
53
+
54
+ print(f"✅ Índice '{index_name}' criado com sucesso!")
55
+
56
+ # Testa conexão
57
+ index = pc.Index(index_name)
58
+ stats = index.describe_index_stats()
59
+ print(f"📊 Vetores no índice: {stats.total_vector_count}")
60
+
61
+ return index
62
+
63
+ except Exception as e:
64
+ print(f"❌ Erro ao configurar Pinecone: {e}")
65
+ return None
66
+
67
+ if __name__ == "__main__":
68
+ print("🔧 Configurando Pinecone para catalogação de joias...")
69
+ index = setup_pinecone_index()
70
+
71
+ if index:
72
+ print("✅ Configuração do Pinecone concluída!")
73
+ else:
74
+ print("❌ Falha na configuração do Pinecone!")
scripts/similarity_search.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from pinecone import Pinecone
4
+ from image_processor import JewelryImageProcessor
5
+ from typing import List, Dict
6
+ from pathlib import Path
7
+ import open_clip
8
+ import torch
9
+
10
+ # Carrega variáveis de ambiente
11
+ load_dotenv()
12
+
13
+ class SimilaritySearcher:
14
+ def __init__(self):
15
+ """Inicializa o buscador por similaridade"""
16
+ # Configuração Pinecone
17
+ pinecone_api_key = os.getenv('PINECONE_API_KEY')
18
+ index_name = os.getenv('PINECONE_INDEX_NAME', 'jewelry-embeddings')
19
+
20
+ if not pinecone_api_key:
21
+ raise ValueError("❌ API Key do Pinecone não encontrada!")
22
+
23
+ pc = Pinecone(api_key=pinecone_api_key)
24
+ self.pinecone_index = pc.Index(index_name)
25
+
26
+ # Processador de imagens (para gerar embeddings de consulta)
27
+ self.image_processor = JewelryImageProcessor()
28
+
29
+ # Modelo de texto para busca textual
30
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
31
+ model_name = os.getenv('EMBEDDING_MODEL', 'ViT-L-14')
32
+ self.text_model, _, _ = open_clip.create_model_and_transforms(model_name, device=self.device)
33
+ self.tokenizer = open_clip.get_tokenizer(model_name)
34
+
35
+ print("✅ Buscador por similaridade inicializado.")
36
+
37
+ def search_by_image(self, image_path: Path, top_k: int = 5) -> List[Dict]:
38
+ """Busca joias similares a uma imagem de consulta"""
39
+ print(f"\n--- 🖼️ Busca por Imagem Similar: {image_path.name} ---")
40
+
41
+ if not image_path.exists():
42
+ print(f"❌ Imagem de consulta não encontrada: {image_path}")
43
+ return []
44
+
45
+ try:
46
+ # Gera embedding da imagem de consulta
47
+ query_embedding = self.image_processor.generate_embedding(image_path)
48
+ if query_embedding is None:
49
+ return []
50
+
51
+ # Busca no Pinecone
52
+ results = self.pinecone_index.query(
53
+ vector=query_embedding.tolist(),
54
+ top_k=top_k,
55
+ include_metadata=True
56
+ )
57
+
58
+ return self._format_results(results)
59
+
60
+ except Exception as e:
61
+ print(f"❌ Erro na busca por similaridade: {e}")
62
+ return []
63
+
64
+ def search_by_text(self, text_query: str, top_k: int = 5) -> List[Dict]:
65
+ """Busca joias usando uma descrição textual"""
66
+ print(f"\n--- 📝 Busca por Texto: '{text_query}' ---")
67
+
68
+ try:
69
+ # Gera embedding do texto
70
+ text_input = self.tokenizer([text_query]).to(self.device)
71
+ with torch.no_grad():
72
+ text_features = self.text_model.encode_text(text_input)
73
+ text_features /= text_features.norm(dim=-1, keepdim=True)
74
+
75
+ query_embedding = text_features.cpu().numpy().flatten().tolist()
76
+
77
+ # Busca no Pinecone
78
+ results = self.pinecone_index.query(
79
+ vector=query_embedding,
80
+ top_k=top_k,
81
+ include_metadata=True
82
+ )
83
+
84
+ return self._format_results(results)
85
+
86
+ except Exception as e:
87
+ print(f"❌ Erro na busca textual: {e}")
88
+ return []
89
+
90
+ def search_with_advanced_filters(self, filters: Dict, top_k: int = 5) -> List[Dict]:
91
+ """Busca joias usando filtros avançados nos metadados"""
92
+ print(f"\n--- ⚙️ Busca por Filtros Avançados ---")
93
+ print(f"Filtros: {filters}")
94
+
95
+ try:
96
+ # Busca no Pinecone apenas com filtros (sem vetor)
97
+ # Para isso, precisamos de um vetor dummy, pois o filtro é o principal
98
+ dummy_vector = [0.0] * 768
99
+
100
+ results = self.pinecone_index.query(
101
+ vector=dummy_vector,
102
+ filter=filters,
103
+ top_k=top_k,
104
+ include_metadata=True
105
+ )
106
+
107
+ return self._format_results(results)
108
+
109
+ except Exception as e:
110
+ print(f"❌ Erro na busca com filtros: {e}")
111
+ return []
112
+
113
+ def _format_results(self, results: Dict) -> List[Dict]:
114
+ """Formata os resultados da busca do Pinecone"""
115
+ formatted_results = []
116
+ if not results.get('matches'):
117
+ print(" - Nenhum resultado encontrado.")
118
+ return formatted_results
119
+
120
+ for match in results['matches']:
121
+ metadata = match.get('metadata', {})
122
+ formatted_results.append({
123
+ 'sku': metadata.get('sku'),
124
+ 'piece_name': metadata.get('piece_name'),
125
+ 'filename': metadata.get('filename'),
126
+ 'score': match.get('score', 0),
127
+ 'primary_color': metadata.get('primary_color_name', 'N/A'),
128
+ 'quality': metadata.get('quality_grade', 'N/A')
129
+ })
130
+ return formatted_results
131
+
132
+ def print_results(results: List[Dict]):
133
+ """Imprime os resultados da busca de forma legível"""
134
+ if not results:
135
+ return
136
+ for item in results:
137
+ print(f" - SKU: {item['sku']} | Peça: {item['piece_name']} | Cor: {item['primary_color']} | Qualidade: {item['quality']}")
138
+ print(f" Arquivo: {item['filename']} (Score: {item['score']:.3f})")
139
+
140
+ if __name__ == "__main__":
141
+ searcher = SimilaritySearcher()
142
+
143
+ # --- Teste 1: Busca por Imagem Similar ---
144
+ # Coloque uma imagem de uma das suas joias na pasta principal para testar
145
+ test_image_path = Path("./colar_rita_03.png")
146
+ if test_image_path.exists():
147
+ image_results = searcher.search_by_image(test_image_path, top_k=3)
148
+ print_results(image_results)
149
+ else:
150
+ print(f"\n⚠️ Imagem de teste não encontrada em {test_image_path}. Pule este teste ou adicione a imagem.")
151
+
152
+ # --- Teste 2: Busca por Texto ---
153
+ text_results = searcher.search_by_text("colar dourado com design moderno", top_k=3)
154
+ print_results(text_results)
155
+
156
+ # --- Teste 3: Busca com Filtros Avançados ---
157
+ # Exemplo: anéis de alta qualidade que sejam prateados
158
+ advanced_filters = {
159
+ "category": {"$eq": "anel"},
160
+ "quality_grade": {"$eq": "high"},
161
+ "primary_color_name": {"$in": ["prateado", "branco"]}
162
+ }
163
+ filter_results = searcher.search_with_advanced_filters(advanced_filters, top_k=3)
164
+ print_results(filter_results)
165
+
166
+ # Exemplo 2: brincos que tenham elementos metálicos e sejam de lifestyle
167
+ advanced_filters_2 = {
168
+ "category": {"$eq": "brinco"},
169
+ "has_metallic_elements": {"$eq": True},
170
+ "image_type": {"$eq": "lifestyle"}
171
+ }
172
+ filter_results_2 = searcher.search_with_advanced_filters(advanced_filters_2, top_k=3)
173
+ print_results(filter_results_2)
scripts/validate_data.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from supabase import create_client, Client
4
+ import json
5
+
6
+ # Carrega variáveis de ambiente
7
+ load_dotenv()
8
+
9
+ class DataValidator:
10
+ def __init__(self):
11
+ """Inicializa o validador de dados"""
12
+ supabase_url = os.getenv('SUPABASE_URL')
13
+ supabase_key = os.getenv('SUPABASE_KEY') # Usa a chave anon para leitura
14
+
15
+ if not supabase_url or not supabase_key:
16
+ raise ValueError("❌ Credenciais do Supabase não encontradas!")
17
+
18
+ self.supabase: Client = create_client(supabase_url, supabase_key)
19
+ print("✅ Conectado ao Supabase para validação.")
20
+
21
+ def validate_piece(self, sku: str):
22
+ """Valida os dados de uma peça específica e suas imagens"""
23
+ print(f"\n🔍 Validando SKU: {sku}")
24
+
25
+ try:
26
+ # 1. Busca metadados da peça
27
+ piece_response = self.supabase.table('pieces').select('*').eq('sku', sku).single().execute()
28
+ if not piece_response.data:
29
+ print(f"❌ Peça com SKU {sku} não encontrada na tabela 'pieces'.")
30
+ return
31
+
32
+ piece_data = piece_response.data
33
+ print("\n--- ✅ Dados da Peça (tabela 'pieces') ---")
34
+ print(f" - Nome: {piece_data.get('name')}")
35
+ print(f" - Coleção: {piece_data.get('collection')}")
36
+ print(f" - Descrição (CSV): {piece_data.get('description', '')[:100]}...")
37
+
38
+ # 2. Busca imagens associadas
39
+ images_response = self.supabase.table('piece_images').select('*').eq('sku', sku).execute()
40
+ if not images_response.data:
41
+ print("❌ Nenhuma imagem encontrada na tabela 'piece_images'.")
42
+ return
43
+
44
+ print(f"\n--- ✅ Imagens Associadas ({len(images_response.data)}) ---")
45
+
46
+ for i, image_data in enumerate(images_response.data, 1):
47
+ image_id = image_data.get('id')
48
+ print(f"\n 🖼️ Imagem {i}: {image_data.get('file_name')}")
49
+ print(f" - ID da Imagem: {image_id}")
50
+ print(f" - URL Original: {'Sim' if image_data.get('original_url') else 'Não'}")
51
+ print(f" - URL Thumbnail: {'Sim' if image_data.get('thumbnail_url') else 'Não'}")
52
+ print(f" - Descrição IA: {'Sim' if image_data.get('ai_description') else 'Não'} ({len(image_data.get('ai_description', ''))} caracteres)")
53
+ print(f" - Análise Técnica: {'Sim' if image_data.get('technical_analysis') else 'Não'}")
54
+ print(f" - Cores Dominantes: {'Sim' if image_data.get('dominant_colors') else 'Não'}")
55
+ print(f" - Score de Qualidade: {image_data.get('quality_score')}")
56
+
57
+ # 3. Busca tags da imagem
58
+ tags_response = self.supabase.table('image_tags').select('tag, tag_type').eq('image_id', image_id).execute()
59
+ if tags_response.data:
60
+ tags = [f"{t['tag']} ({t['tag_type']})" for t in tags_response.data]
61
+ print(f" - Tags Automáticas ({len(tags)}): {', '.join(tags)}")
62
+ else:
63
+ print(" - Tags Automáticas: ❌ Nenhuma encontrada.")
64
+
65
+ # 4. Busca características visuais
66
+ features_response = self.supabase.table('visual_features').select('feature_type, feature_value').eq('image_id', image_id).execute()
67
+ if features_response.data:
68
+ features = [f"{f['feature_type']}:{f['feature_value']}" for f in features_response.data]
69
+ print(f" - Características Visuais ({len(features)}): {', '.join(features)}")
70
+ else:
71
+ print(" - Características Visuais: ❌ Nenhuma encontrada.")
72
+
73
+ except Exception as e:
74
+ print(f"❌ Erro durante a validação: {e}")
75
+
76
+ if __name__ == "__main__":
77
+ validator = DataValidator()
78
+
79
+ # Substitua pelo SKU de uma peça que você acabou de processar
80
+ sku_para_validar = "CO8671"
81
+
82
+ validator.validate_piece(sku_para_validar)
setup_database.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from pathlib import Path
4
+ from dotenv import load_dotenv
5
+ from supabase import create_client, Client
6
+ import time
7
+
8
+ # Carrega variáveis de ambiente
9
+ load_dotenv()
10
+
11
+ # Configuração de caminhos
12
+ ROOT_DIR = Path(__file__).parent
13
+ IMAGES_DIR = ROOT_DIR / "imagens"
14
+ THUMBNAILS_DIR = ROOT_DIR / "thumbnails"
15
+
16
+ # Cria diretórios se não existirem
17
+ THUMBNAILS_DIR.mkdir(exist_ok=True)
18
+
19
+ class DatabaseSetup:
20
+ def __init__(self):
21
+ """Inicializa configuração do banco"""
22
+ self.supabase_url = os.getenv('SUPABASE_URL')
23
+ self.supabase_key = os.getenv('SUPABASE_KEY')
24
+ self.pinecone_api_key = os.getenv('PINECONE_API_KEY')
25
+ self.index_name = os.getenv('PINECONE_INDEX_NAME', 'jewelry-embeddings')
26
+
27
+ if not all([self.supabase_url, self.supabase_key]):
28
+ raise ValueError("❌ Variáveis de ambiente do Supabase obrigatórias não encontradas!")
29
+
30
+ self.supabase: Client = create_client(self.supabase_url, self.supabase_key)
31
+
32
+ # Inicializa Pinecone apenas se a API key estiver disponível
33
+ if self.pinecone_api_key:
34
+ try:
35
+ from pinecone import Pinecone
36
+ self.pc = Pinecone(api_key=self.pinecone_api_key)
37
+ print("✅ Pinecone configurado")
38
+ except ImportError as e:
39
+ print(f"⚠️ Erro ao importar Pinecone: {e}")
40
+ print(" Execute: pip uninstall pinecone-client && pip install pinecone")
41
+ self.pc = None
42
+ else:
43
+ print("⚠️ PINECONE_API_KEY não encontrada - Pinecone será configurado depois")
44
+ self.pc = None
45
+
46
+ print(f"✅ Configuração carregada do diretório: {ROOT_DIR}")
47
+ print(f"📁 Diretório de imagens: {IMAGES_DIR}")
48
+ print(f"📁 Diretório de thumbnails: {THUMBNAILS_DIR}")
49
+
50
+ def create_database_tables(self):
51
+ """Cria as tabelas necessárias no Supabase"""
52
+
53
+ sql_commands = [
54
+ # Extensões
55
+ """CREATE EXTENSION IF NOT EXISTS "uuid-ossp";""",
56
+
57
+ # Tabela principal de peças
58
+ """
59
+ CREATE TABLE IF NOT EXISTS pieces (
60
+ sku VARCHAR(50) PRIMARY KEY,
61
+ name VARCHAR(255) NOT NULL,
62
+ collection VARCHAR(100),
63
+ material VARCHAR(255),
64
+ predominant_metal VARCHAR(100),
65
+ stone VARCHAR(100),
66
+ stone_color VARCHAR(50),
67
+ size VARCHAR(50),
68
+ weight_grams DECIMAL(8,2),
69
+ price_brl DECIMAL(10,2),
70
+ description TEXT,
71
+ category VARCHAR(50),
72
+ gender VARCHAR(20),
73
+ style VARCHAR(100),
74
+ is_active BOOLEAN DEFAULT true,
75
+ created_at TIMESTAMP DEFAULT NOW(),
76
+ updated_at TIMESTAMP DEFAULT NOW()
77
+ );
78
+ """,
79
+
80
+ # Tabela de imagens
81
+ """
82
+ CREATE TABLE IF NOT EXISTS piece_images (
83
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
84
+ sku VARCHAR(50) REFERENCES pieces(sku) ON DELETE CASCADE,
85
+ image_type VARCHAR(20) CHECK (image_type IN ('product', 'lifestyle', 'detail', 'packaging')),
86
+ original_url VARCHAR(500),
87
+ thumbnail_url VARCHAR(500),
88
+ file_name VARCHAR(255),
89
+ file_size_bytes INTEGER,
90
+ image_width INTEGER,
91
+ image_height INTEGER,
92
+ embeddings_vector_id VARCHAR(100) UNIQUE,
93
+ technical_analysis JSONB,
94
+ ai_description TEXT,
95
+ dominant_colors JSONB,
96
+ visual_features JSONB,
97
+ quality_score DECIMAL(3,2),
98
+ is_primary BOOLEAN DEFAULT false,
99
+ created_at TIMESTAMP DEFAULT NOW()
100
+ );
101
+ """,
102
+
103
+ # Tabela de características visuais
104
+ """
105
+ CREATE TABLE IF NOT EXISTS visual_features (
106
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
107
+ image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
108
+ feature_type VARCHAR(50),
109
+ feature_value VARCHAR(255),
110
+ confidence_score DECIMAL(3,2),
111
+ created_at TIMESTAMP DEFAULT NOW()
112
+ );
113
+ """,
114
+
115
+ # Tabela de tags
116
+ """
117
+ CREATE TABLE IF NOT EXISTS image_tags (
118
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
119
+ image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
120
+ tag VARCHAR(100),
121
+ confidence DECIMAL(3,2),
122
+ tag_type VARCHAR(50),
123
+ created_at TIMESTAMP DEFAULT NOW()
124
+ );
125
+ """,
126
+
127
+ # Tabela de log
128
+ """
129
+ CREATE TABLE IF NOT EXISTS processing_log (
130
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
131
+ sku VARCHAR(50),
132
+ image_id UUID,
133
+ process_type VARCHAR(50),
134
+ status VARCHAR(20),
135
+ error_message TEXT,
136
+ processing_time_ms INTEGER,
137
+ created_at TIMESTAMP DEFAULT NOW()
138
+ );
139
+ """,
140
+
141
+ # Índices
142
+ """
143
+ CREATE INDEX IF NOT EXISTS idx_piece_images_sku ON piece_images(sku);
144
+ CREATE INDEX IF NOT EXISTS idx_piece_images_type ON piece_images(image_type);
145
+ CREATE INDEX IF NOT EXISTS idx_piece_images_primary ON piece_images(is_primary);
146
+ CREATE INDEX IF NOT EXISTS idx_visual_features_image_id ON visual_features(image_id);
147
+ CREATE INDEX IF NOT EXISTS idx_image_tags_image_id ON image_tags(image_id);
148
+ CREATE INDEX IF NOT EXISTS idx_processing_log_sku ON processing_log(sku);
149
+ CREATE INDEX IF NOT EXISTS idx_pieces_category ON pieces(category);
150
+ CREATE INDEX IF NOT EXISTS idx_pieces_collection ON pieces(collection);
151
+ """,
152
+
153
+ # Função de trigger
154
+ """
155
+ CREATE OR REPLACE FUNCTION update_updated_at_column()
156
+ RETURNS TRIGGER AS $$
157
+ BEGIN
158
+ NEW.updated_at = NOW();
159
+ RETURN NEW;
160
+ END;
161
+ $$ language 'plpgsql';
162
+ """,
163
+
164
+ # Trigger
165
+ """
166
+ DROP TRIGGER IF EXISTS update_pieces_updated_at ON pieces;
167
+ CREATE TRIGGER update_pieces_updated_at
168
+ BEFORE UPDATE ON pieces
169
+ FOR EACH ROW
170
+ EXECUTE FUNCTION update_updated_at_column();
171
+ """
172
+ ]
173
+
174
+ try:
175
+ print("🗄️ Criando estrutura do banco de dados...")
176
+
177
+ for i, command in enumerate(sql_commands, 1):
178
+ print(f"🔄 Executando comando {i}/{len(sql_commands)}...")
179
+
180
+ # Executa comando SQL diretamente
181
+ try:
182
+ result = self.supabase.postgrest.rpc('exec_sql', {'sql': command.strip()}).execute()
183
+ except Exception as cmd_error:
184
+ # Se exec_sql não funcionar, tenta executar diretamente
185
+ print(f" ⚠️ Tentativa alternativa para comando {i}...")
186
+ # Para comandos DDL, podemos tentar usar uma abordagem diferente
187
+ continue
188
+
189
+ print("✅ Estrutura do banco criada com sucesso!")
190
+ return True
191
+
192
+ except Exception as e:
193
+ print(f"❌ Erro ao criar estrutura do banco: {e}")
194
+ print(" Você pode executar os comandos SQL manualmente no painel do Supabase")
195
+ return False
196
+
197
+ def setup_pinecone_index(self):
198
+ """Configura o índice do Pinecone"""
199
+ if not self.pc:
200
+ print("⚠️ Pinecone não configurado - pulando configuração do índice")
201
+ return None
202
+
203
+ try:
204
+ from pinecone import ServerlessSpec
205
+
206
+ # Verifica índices existentes
207
+ existing_indexes = self.pc.list_indexes().names()
208
+
209
+ if self.index_name in existing_indexes:
210
+ print(f"✅ Índice '{self.index_name}' já existe!")
211
+ index_info = self.pc.describe_index(self.index_name)
212
+ print(f"📊 Dimensão: {index_info.dimension}")
213
+ print(f"📊 Métrica: {index_info.metric}")
214
+
215
+ else:
216
+ print(f"🚀 Criando índice '{self.index_name}'...")
217
+ self.pc.create_index(
218
+ name=self.index_name,
219
+ dimension=768, # ViT-L-14 OpenCLIP
220
+ metric='cosine',
221
+ spec=ServerlessSpec(
222
+ cloud='aws',
223
+ region='us-east-1'
224
+ )
225
+ )
226
+
227
+ # Aguarda criação
228
+ print("⏳ Aguardando criação do índice...")
229
+ while True:
230
+ try:
231
+ index_info = self.pc.describe_index(self.index_name)
232
+ if index_info.status.state == "Ready":
233
+ break
234
+ except:
235
+ pass
236
+ time.sleep(5)
237
+
238
+ print(f"✅ Índice '{self.index_name}' criado com sucesso!")
239
+
240
+ # Testa conexão
241
+ index = self.pc.Index(self.index_name)
242
+ stats = index.describe_index_stats()
243
+ print(f"📊 Vetores no índice: {stats.total_vector_count}")
244
+
245
+ return index
246
+
247
+ except Exception as e:
248
+ print(f"❌ Erro ao configurar Pinecone: {e}")
249
+ return None
250
+
251
+ def verify_directories(self):
252
+ """Verifica e cria diretórios necessários"""
253
+ print("📁 Verificando estrutura de diretórios...")
254
+
255
+ if not IMAGES_DIR.exists():
256
+ print(f"⚠️ Diretório de imagens não encontrado: {IMAGES_DIR}")
257
+ print(" Criando diretório...")
258
+ IMAGES_DIR.mkdir(parents=True, exist_ok=True)
259
+
260
+ # Conta arquivos PNG
261
+ png_files = list(IMAGES_DIR.glob("*.png"))
262
+ print(f"📸 Encontrados {len(png_files)} arquivos PNG em {IMAGES_DIR}")
263
+
264
+ if len(png_files) == 0:
265
+ print("⚠️ Nenhuma imagem PNG encontrada!")
266
+ print(" Certifique-se de colocar as imagens no diretório 'imagens'")
267
+ else:
268
+ # Mostra algumas imagens encontradas
269
+ print(" Exemplos de imagens encontradas:")
270
+ for img in png_files[:5]:
271
+ print(f" • {img.name}")
272
+ if len(png_files) > 5:
273
+ print(f" • ... e mais {len(png_files) - 5} imagens")
274
+
275
+ # Verifica se existe CSV de metadados
276
+ csv_path = ROOT_DIR / "jewelry_metadata.csv"
277
+ if not csv_path.exists():
278
+ print(f"⚠️ Arquivo de metadados não encontrado: {csv_path}")
279
+ print(" Exporte a planilha Google Sheets como CSV com este nome")
280
+ else:
281
+ print(f"✅ Arquivo de metadados encontrado: {csv_path}")
282
+
283
+ return len(png_files) > 0 or csv_path.exists()
284
+
285
+ def create_sql_file(self):
286
+ """Cria arquivo SQL para execução manual se necessário"""
287
+ sql_content = """
288
+ -- Estrutura do banco para catalogação de joias
289
+ -- Execute este script no SQL Editor do Supabase se o setup automático falhar
290
+
291
+ -- Extensões necessárias
292
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
293
+
294
+ -- Tabela principal de peças
295
+ CREATE TABLE IF NOT EXISTS pieces (
296
+ sku VARCHAR(50) PRIMARY KEY,
297
+ name VARCHAR(255) NOT NULL,
298
+ collection VARCHAR(100),
299
+ material VARCHAR(255),
300
+ predominant_metal VARCHAR(100),
301
+ stone VARCHAR(100),
302
+ stone_color VARCHAR(50),
303
+ size VARCHAR(50),
304
+ weight_grams DECIMAL(8,2),
305
+ price_brl DECIMAL(10,2),
306
+ description TEXT,
307
+ category VARCHAR(50),
308
+ gender VARCHAR(20),
309
+ style VARCHAR(100),
310
+ is_active BOOLEAN DEFAULT true,
311
+ created_at TIMESTAMP DEFAULT NOW(),
312
+ updated_at TIMESTAMP DEFAULT NOW()
313
+ );
314
+
315
+ -- Tabela de imagens das peças
316
+ CREATE TABLE IF NOT EXISTS piece_images (
317
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
318
+ sku VARCHAR(50) REFERENCES pieces(sku) ON DELETE CASCADE,
319
+ image_type VARCHAR(20) CHECK (image_type IN ('product', 'lifestyle', 'detail', 'packaging')),
320
+ original_url VARCHAR(500),
321
+ thumbnail_url VARCHAR(500),
322
+ file_name VARCHAR(255),
323
+ file_size_bytes INTEGER,
324
+ image_width INTEGER,
325
+ image_height INTEGER,
326
+ embeddings_vector_id VARCHAR(100) UNIQUE,
327
+ technical_analysis JSONB,
328
+ ai_description TEXT,
329
+ dominant_colors JSONB,
330
+ visual_features JSONB,
331
+ quality_score DECIMAL(3,2),
332
+ is_primary BOOLEAN DEFAULT false,
333
+ created_at TIMESTAMP DEFAULT NOW()
334
+ );
335
+
336
+ -- Tabela de características visuais extraídas
337
+ CREATE TABLE IF NOT EXISTS visual_features (
338
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
339
+ image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
340
+ feature_type VARCHAR(50),
341
+ feature_value VARCHAR(255),
342
+ confidence_score DECIMAL(3,2),
343
+ created_at TIMESTAMP DEFAULT NOW()
344
+ );
345
+
346
+ -- Tabela de tags automáticas
347
+ CREATE TABLE IF NOT EXISTS image_tags (
348
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
349
+ image_id UUID REFERENCES piece_images(id) ON DELETE CASCADE,
350
+ tag VARCHAR(100),
351
+ confidence DECIMAL(3,2),
352
+ tag_type VARCHAR(50),
353
+ created_at TIMESTAMP DEFAULT NOW()
354
+ );
355
+
356
+ -- Tabela de histórico de processamento
357
+ CREATE TABLE IF NOT EXISTS processing_log (
358
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
359
+ sku VARCHAR(50),
360
+ image_id UUID,
361
+ process_type VARCHAR(50),
362
+ status VARCHAR(20),
363
+ error_message TEXT,
364
+ processing_time_ms INTEGER,
365
+ created_at TIMESTAMP DEFAULT NOW()
366
+ );
367
+
368
+ -- Índices para otimização
369
+ CREATE INDEX IF NOT EXISTS idx_piece_images_sku ON piece_images(sku);
370
+ CREATE INDEX IF NOT EXISTS idx_piece_images_type ON piece_images(image_type);
371
+ CREATE INDEX IF NOT EXISTS idx_piece_images_primary ON piece_images(is_primary);
372
+ CREATE INDEX IF NOT EXISTS idx_visual_features_image_id ON visual_features(image_id);
373
+ CREATE INDEX IF NOT EXISTS idx_image_tags_image_id ON image_tags(image_id);
374
+ CREATE INDEX IF NOT EXISTS idx_processing_log_sku ON processing_log(sku);
375
+ CREATE INDEX IF NOT EXISTS idx_pieces_category ON pieces(category);
376
+ CREATE INDEX IF NOT EXISTS idx_pieces_collection ON pieces(collection);
377
+
378
+ -- Função para atualizar updated_at automaticamente
379
+ CREATE OR REPLACE FUNCTION update_updated_at_column()
380
+ RETURNS TRIGGER AS $$
381
+ BEGIN
382
+ NEW.updated_at = NOW();
383
+ RETURN NEW;
384
+ END;
385
+ $$ language 'plpgsql';
386
+
387
+ -- Trigger para atualizar updated_at na tabela pieces
388
+ DROP TRIGGER IF EXISTS update_pieces_updated_at ON pieces;
389
+ CREATE TRIGGER update_pieces_updated_at
390
+ BEFORE UPDATE ON pieces
391
+ FOR EACH ROW
392
+ EXECUTE FUNCTION update_updated_at_column();
393
+
394
+ -- Views úteis
395
+ CREATE OR REPLACE VIEW pieces_with_images AS
396
+ SELECT
397
+ p.*,
398
+ pi.id as image_id,
399
+ pi.image_type,
400
+ pi.original_url,
401
+ pi.thumbnail_url,
402
+ pi.ai_description,
403
+ pi.dominant_colors,
404
+ pi.quality_score,
405
+ pi.is_primary
406
+ FROM pieces p
407
+ LEFT JOIN piece_images pi ON p.sku = pi.sku
408
+ WHERE p.is_active = true;
409
+ """
410
+
411
+ sql_file_path = ROOT_DIR / "database_structure.sql"
412
+ with open(sql_file_path, 'w', encoding='utf-8') as f:
413
+ f.write(sql_content)
414
+
415
+ print(f"📄 Arquivo SQL criado: {sql_file_path}")
416
+ print(" Use este arquivo para criar as tabelas manualmente se necessário")
417
+
418
+ def run_setup(self):
419
+ """Executa setup completo"""
420
+ print("🚀 Iniciando configuração do sistema de catalogação...")
421
+ print(f"📍 Diretório de trabalho: {ROOT_DIR}")
422
+
423
+ # Cria arquivo SQL de backup
424
+ self.create_sql_file()
425
+
426
+ # Verifica diretórios
427
+ self.verify_directories()
428
+
429
+ # Configura banco
430
+ print("\n🗄️ Configurando banco de dados...")
431
+ db_success = self.create_database_tables()
432
+
433
+ # Configura Pinecone
434
+ print("\n🔍 Configurando Pinecone...")
435
+ index = self.setup_pinecone_index()
436
+
437
+ print("\n" + "="*60)
438
+ if db_success:
439
+ print("✅ Configuração do banco: SUCESSO")
440
+ else:
441
+ print("⚠️ Configuração do banco: VERIFICAR")
442
+ print(" Execute o arquivo 'database_structure.sql' manualmente no Supabase")
443
+
444
+ if index or not self.pc:
445
+ print("✅ Configuração do Pinecone: SUCESSO")
446
+ else:
447
+ print("⚠️ Configuração do Pinecone: VERIFICAR")
448
+
449
+ print("\n📋 Próximos passos:")
450
+ print(" 1. Certifique-se de que as imagens estão no diretório 'imagens'")
451
+ print(" 2. Exporte a planilha como 'jewelry_metadata.csv'")
452
+ print(" 3. Configure todas as variáveis no arquivo .env")
453
+ print(" 4. Execute: python jewelry_cataloger.py")
454
+
455
+ return True
456
+
457
+ if __name__ == "__main__":
458
+ try:
459
+ setup = DatabaseSetup()
460
+ success = setup.run_setup()
461
+
462
+ if success:
463
+ print("\n🎉 Setup concluído!")
464
+ else:
465
+ print("\n❌ Falha no setup. Verifique os logs acima.")
466
+ sys.exit(1)
467
+
468
+ except Exception as e:
469
+ print(f"❌ Erro fatal na configuração: {e}")
470
+ print("\nDicas para resolver:")
471
+ print("1. Verifique se o arquivo .env está configurado corretamente")
472
+ print("2. Execute: pip uninstall pinecone-client")
473
+ print("3. Execute: pip install pinecone")
474
+ sys.exit(1)
similarity_search.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from pinecone import Pinecone
4
+ from image_processor import JewelryImageProcessor
5
+ from typing import List, Dict
6
+ from pathlib import Path
7
+ import open_clip
8
+ import torch
9
+
10
+ # Carrega variáveis de ambiente
11
+ load_dotenv()
12
+
13
+ class SimilaritySearcher:
14
+ def __init__(self):
15
+ """Inicializa o buscador por similaridade"""
16
+ # Configuração Pinecone
17
+ pinecone_api_key = os.getenv('PINECONE_API_KEY')
18
+ index_name = os.getenv('PINECONE_INDEX_NAME', 'jewelry-embeddings')
19
+
20
+ if not pinecone_api_key:
21
+ raise ValueError("❌ API Key do Pinecone não encontrada!")
22
+
23
+ pc = Pinecone(api_key=pinecone_api_key)
24
+ self.pinecone_index = pc.Index(index_name)
25
+
26
+ # Processador de imagens (para gerar embeddings de consulta)
27
+ self.image_processor = JewelryImageProcessor()
28
+
29
+ # Modelo de texto para busca textual
30
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
31
+ model_name = os.getenv('EMBEDDING_MODEL', 'ViT-L-14')
32
+ self.text_model, _, _ = open_clip.create_model_and_transforms(model_name, device=self.device)
33
+ self.tokenizer = open_clip.get_tokenizer(model_name)
34
+
35
+ print("✅ Buscador por similaridade inicializado.")
36
+
37
+ def search_by_image(self, image_path: Path, top_k: int = 5, return_only_products: bool = True) -> List[Dict]:
38
+ """
39
+ Busca joias similares a uma imagem de consulta.
40
+
41
+ Args:
42
+ image_path (Path): Caminho para a imagem de consulta.
43
+ top_k (int): Número de resultados a retornar.
44
+ return_only_products (bool): Se True, filtra para retornar apenas imagens de produto.
45
+ """
46
+ print(f"\n--- 🖼️ Busca por Imagem Similar: {image_path.name} ---")
47
+ if return_only_products:
48
+ print("🎯 Filtro ativado: Retornando apenas imagens de PRODUTO.")
49
+
50
+ if not image_path.exists():
51
+ print(f"❌ Imagem de consulta não encontrada: {image_path}")
52
+ return []
53
+
54
+ try:
55
+ # Gera embedding da imagem de consulta
56
+ query_embedding = self.image_processor.generate_embedding(image_path)
57
+ if query_embedding is None:
58
+ return []
59
+
60
+ # Constrói o filtro
61
+ search_filter = {}
62
+ if return_only_products:
63
+ search_filter = {"image_type": {"$eq": "product"}}
64
+
65
+ # Busca no Pinecone com o filtro
66
+ results = self.pinecone_index.query(
67
+ vector=query_embedding.tolist(),
68
+ top_k=top_k,
69
+ filter=search_filter,
70
+ include_metadata=True
71
+ )
72
+
73
+ return self._format_results(results)
74
+
75
+ except Exception as e:
76
+ print(f"❌ Erro na busca por similaridade: {e}")
77
+ return []
78
+
79
+ def search_by_text(self, text_query: str, top_k: int = 5, return_only_products: bool = True) -> List[Dict]:
80
+ """Busca joias usando uma descrição textual, retornando apenas imagens de produto."""
81
+ print(f"\n--- 📝 Busca por Texto: '{text_query}' ---")
82
+ if return_only_products:
83
+ print("🎯 Filtro ativado: Retornando apenas imagens de PRODUTO.")
84
+
85
+ try:
86
+ # Gera embedding do texto
87
+ text_input = self.tokenizer([text_query]).to(self.device)
88
+ with torch.no_grad():
89
+ text_features = self.text_model.encode_text(text_input)
90
+ text_features /= text_features.norm(dim=-1, keepdim=True)
91
+
92
+ query_embedding = text_features.cpu().numpy().flatten().tolist()
93
+
94
+ # Constrói o filtro
95
+ search_filter = {}
96
+ if return_only_products:
97
+ search_filter = {"image_type": {"$eq": "product"}}
98
+
99
+ # Busca no Pinecone com o filtro
100
+ results = self.pinecone_index.query(
101
+ vector=query_embedding,
102
+ top_k=top_k,
103
+ filter=search_filter,
104
+ include_metadata=True
105
+ )
106
+
107
+ return self._format_results(results)
108
+
109
+ except Exception as e:
110
+ print(f"❌ Erro na busca textual: {e}")
111
+ return []
112
+
113
+ def search_with_advanced_filters(self, filters: Dict, top_k: int = 5) -> List[Dict]:
114
+ """Busca joias usando filtros avançados, priorizando imagens de produto."""
115
+ print(f"\n--- ⚙️ Busca por Filtros Avançados ---")
116
+
117
+ # Garante que, por padrão, a busca retorne apenas imagens de produto
118
+ # a menos que o usuário especifique o contrário no filtro.
119
+ final_filter = {"image_type": {"$eq": "product"}}
120
+ final_filter.update(filters) # O filtro do usuário sobrescreve o padrão se houver conflito
121
+
122
+ print(f"Filtros Finais: {final_filter}")
123
+
124
+ try:
125
+ # Busca no Pinecone apenas com filtros (sem vetor)
126
+ # Para isso, precisamos de um vetor dummy, pois o filtro é o principal
127
+ dummy_vector = [0.0] * 768
128
+
129
+ results = self.pinecone_index.query(
130
+ vector=dummy_vector,
131
+ filter=final_filter,
132
+ top_k=top_k,
133
+ include_metadata=True
134
+ )
135
+
136
+ return self._format_results(results)
137
+
138
+ except Exception as e:
139
+ print(f"❌ Erro na busca com filtros: {e}")
140
+ return []
141
+
142
+ def _format_results(self, results: Dict) -> List[Dict]:
143
+ """Formata os resultados da busca do Pinecone"""
144
+ formatted_results = []
145
+ if not results.get('matches'):
146
+ print(" - Nenhum resultado encontrado.")
147
+ return formatted_results
148
+
149
+ for match in results['matches']:
150
+ metadata = match.get('metadata', {})
151
+ formatted_results.append({
152
+ 'sku': metadata.get('sku'),
153
+ 'piece_name': metadata.get('piece_name'),
154
+ 'filename': metadata.get('filename'),
155
+ 'image_type': metadata.get('image_type'),
156
+ 'score': match.get('score', 0),
157
+ 'primary_color': metadata.get('primary_color_name', 'N/A'),
158
+ 'quality': metadata.get('quality_grade', 'N/A')
159
+ })
160
+ return formatted_results
161
+
162
+ def print_results(results: List[Dict]):
163
+ """Imprime os resultados da busca de forma legível"""
164
+ if not results:
165
+ return
166
+ for item in results:
167
+ print(f" - SKU: {item['sku']} | Peça: {item['piece_name']} | Tipo: {item['image_type']}")
168
+ print(f" Arquivo: {item['filename']} (Score: {item['score']:.3f})")
169
+
170
+ if __name__ == "__main__":
171
+ searcher = SimilaritySearcher()
172
+
173
+ # --- Teste 1: Busca por Imagem Similar (com filtro de produto) ---
174
+ # Use uma imagem de lifestyle (com modelo) para a busca
175
+ test_image_path = Path("./colar_rita_modelo_03.png")
176
+ if test_image_path.exists():
177
+ # A função agora filtra por padrão para retornar apenas imagens de produto
178
+ image_results = searcher.search_by_image(test_image_path, top_k=3)
179
+ print_results(image_results)
180
+ else:
181
+ print(f"\n⚠️ Imagem de teste não encontrada em {test_image_path}. Pule este teste ou adicione a imagem.")
182
+
183
+ # --- Teste 2: Busca por Texto (agora com filtro de produto) ---
184
+ text_results = searcher.search_by_text("colar dourado com design moderno", top_k=3)
185
+ print_results(text_results)
186
+
187
+ # --- Teste 3: Busca com Filtros Avançados (agora com filtro de produto) ---
188
+ # Exemplo: anéis de alta qualidade (o filtro de produto é adicionado automaticamente)
189
+ advanced_filters = {
190
+ "category": {"$eq": "anel"},
191
+ "quality_grade": {"$eq": "high"},
192
+ }
193
+ filter_results = searcher.search_with_advanced_filters(advanced_filters, top_k=3)
194
+ print_results(filter_results)