Spaces:
Sleeping
Sleeping
Download scripts/jewelry_cataloger.py from OctusTech/cartalogo-api: direct link, hf CLI and curl.
- Browser
- Download file 9.22 kB
-
https://huggingface.co/spaces/OctusTech/cartalogo-api/resolve/main/scripts/jewelry_cataloger.py
- Command line
-
hf download hf://spaces/OctusTech/cartalogo-api/scripts/jewelry_cataloger.py
-
curl -L -o jewelry_cataloger.py https://huggingface.co/spaces/OctusTech/cartalogo-api/resolve/main/scripts/jewelry_cataloger.py
9.22 kB
| import os | |
| import pandas as pd | |
| import requests | |
| from pathlib import Path | |
| import uuid | |
| from typing import Dict, List | |
| from supabase import create_client, Client | |
| from pinecone import Pinecone | |
| from image_processor import ImageProcessor | |
| import json | |
| class JewelryCataloger: | |
| def __init__(self): | |
| """Inicializa o catalogador""" | |
| # Configuração Supabase | |
| self.supabase: Client = create_client( | |
| os.getenv('SUPABASE_URL'), | |
| os.getenv('SUPABASE_KEY') | |
| ) | |
| # Configuração Pinecone | |
| pc = Pinecone(api_key=os.getenv('PINECONE_API_KEY')) | |
| self.pinecone_index = pc.Index("jewelry-embeddings") | |
| # Processador de imagens | |
| self.image_processor = ImageProcessor() | |
| # Diretórios - CORREÇÃO PARA HUGGING FACE | |
| self.images_dir = Path("./images") | |
| # Usa variável de ambiente ou padrão para /tmp | |
| thumbnails_path = os.getenv('THUMBNAILS_PATH', '/tmp/thumbnails') | |
| self.thumbnails_dir = Path(thumbnails_path) | |
| self.thumbnails_dir.mkdir(parents=True, exist_ok=True) | |
| print(f"✅ Catalogador inicializado!") | |
| print(f"📁 Diretório de imagens: {self.images_dir}") | |
| print(f"📁 Diretório de thumbnails: {self.thumbnails_dir}") | |
| def load_metadata_from_sheets(self, csv_path: str) -> pd.DataFrame: | |
| """Carrega metadados da planilha (exportada como CSV)""" | |
| try: | |
| df = pd.read_csv(csv_path) | |
| print(f"✅ Carregados {len(df)} registros da planilha") | |
| return df | |
| except Exception as e: | |
| print(f"❌ Erro ao carregar planilha: {e}") | |
| return pd.DataFrame() | |
| def process_piece_metadata(self, row: pd.Series) -> Dict: | |
| """Processa metadados de uma peça""" | |
| return { | |
| 'sku': str(row['sku']).strip(), | |
| 'name': str(row['peca']).strip(), | |
| 'collection': str(row.get('colecao', '')).strip(), | |
| 'material': str(row.get('material', '')).strip(), | |
| 'predominant_metal': str(row.get('metal_predominante', '')).strip(), | |
| 'stone': str(row.get('pedra', '')).strip(), | |
| 'size': str(row.get('tamanho', '')).strip(), | |
| 'description': str(row.get('descricao', '')).strip() | |
| } | |
| def find_images_for_sku(self, sku: str) -> List[Dict]: | |
| """Encontra todas as imagens relacionadas a um SKU""" | |
| images = [] | |
| # Procura por arquivos que contenham o SKU no nome | |
| for image_file in self.images_dir.glob("*.png"): | |
| if sku.lower() in image_file.name.lower(): | |
| # Determina o tipo da imagem baseado no nome do arquivo | |
| image_type = "lifestyle" if any(keyword in image_file.name.lower() | |
| for keyword in ["modelo", "person", "wearing", "lifestyle"]) else "product" | |
| images.append({ | |
| 'path': str(image_file), | |
| 'filename': image_file.name, | |
| 'type': image_type | |
| }) | |
| return images | |
| def upload_to_supabase_storage(self, file_path: str, bucket_name: str, file_name: str) -> str: | |
| """Faz upload de arquivo para o storage do Supabase""" | |
| try: | |
| with open(file_path, 'rb') as file: | |
| response = self.supabase.storage.from_(bucket_name).upload( | |
| file_name, file, file_options={"content-type": "image/png"} | |
| ) | |
| # Gera URL pública | |
| public_url = self.supabase.storage.from_(bucket_name).get_public_url(file_name) | |
| return public_url | |
| except Exception as e: | |
| print(f"❌ Erro no upload para Supabase: {e}") | |
| return "" | |
| def save_piece_to_database(self, piece_data: Dict) -> bool: | |
| """Salva dados da peça no banco""" | |
| try: | |
| response = self.supabase.table('pieces').upsert(piece_data).execute() | |
| return True | |
| except Exception as e: | |
| print(f"❌ Erro ao salvar peça {piece_data['sku']}: {e}") | |
| return False | |
| def save_image_to_database(self, image_data: Dict) -> bool: | |
| """Salva dados da imagem no banco""" | |
| try: | |
| response = self.supabase.table('piece_images').insert(image_data).execute() | |
| return True | |
| except Exception as e: | |
| print(f"❌ Erro ao salvar imagem: {e}") | |
| return False | |
| def save_embedding_to_pinecone(self, vector_id: str, embedding: List[float], metadata: Dict) -> bool: | |
| """Salva embedding no Pinecone""" | |
| try: | |
| self.pinecone_index.upsert([(vector_id, embedding, metadata)]) | |
| return True | |
| except Exception as e: | |
| print(f"❌ Erro ao salvar no Pinecone: {e}") | |
| return False | |
| def process_single_piece(self, piece_metadata: Dict) -> bool: | |
| """Processa uma única peça com todas suas imagens""" | |
| sku = piece_metadata['sku'] | |
| print(f"🔄 Processando peça: {sku}") | |
| # Salva metadados da peça | |
| if not self.save_piece_to_database(piece_metadata): | |
| return False | |
| # Encontra imagens da peça | |
| images = self.find_images_for_sku(sku) | |
| if not images: | |
| print(f"⚠️ Nenhuma imagem encontrada para SKU: {sku}") | |
| return True | |
| print(f"📸 Encontradas {len(images)} imagens para {sku}") | |
| # Processa cada imagem | |
| for img_info in images: | |
| try: | |
| # Gera embedding | |
| embedding = self.image_processor.generate_embedding(img_info['path']) | |
| if embedding is None: | |
| continue | |
| # Análise técnica | |
| technical_analysis = self.image_processor.analyze_image_technical(img_info['path']) | |
| # Cria thumbnail | |
| thumbnail_filename = f"thumb_{img_info['filename']}" | |
| thumbnail_path = self.thumbnails_dir / thumbnail_filename | |
| if not self.image_processor.create_thumbnail(img_info['path'], str(thumbnail_path)): | |
| continue | |
| # Upload da imagem original | |
| original_url = self.upload_to_supabase_storage( | |
| img_info['path'], | |
| 'images', | |
| f"{sku}/{img_info['filename']}" | |
| ) | |
| # Upload do thumbnail | |
| thumbnail_url = self.upload_to_supabase_storage( | |
| str(thumbnail_path), | |
| 'images', | |
| f"thumbnails/{thumbnail_filename}" | |
| ) | |
| # ID único para o vetor | |
| vector_id = str(uuid.uuid4()) | |
| # Salva no Pinecone | |
| pinecone_metadata = { | |
| 'sku': sku, | |
| 'image_type': img_info['type'], | |
| 'filename': img_info['filename'], | |
| 'piece_name': piece_metadata['name'], | |
| 'collection': piece_metadata['collection'] | |
| } | |
| self.save_embedding_to_pinecone(vector_id, embedding.tolist(), pinecone_metadata) | |
| # Salva no banco | |
| image_data = { | |
| 'sku': sku, | |
| 'image_type': img_info['type'], | |
| 'original_url': original_url, | |
| 'thumbnail_url': thumbnail_url, | |
| 'file_name': img_info['filename'], | |
| 'embeddings_vector_id': vector_id, | |
| 'technical_analysis': technical_analysis | |
| } | |
| self.save_image_to_database(image_data) | |
| print(f"✅ Imagem processada: {img_info['filename']}") | |
| except Exception as e: | |
| print(f"❌ Erro ao processar imagem {img_info['filename']}: {e}") | |
| continue | |
| return True | |
| def run_cataloging(self, csv_path: str): | |
| """Executa o processo completo de catalogação""" | |
| print("🚀 Iniciando catalogação de joias...") | |
| # Carrega metadados | |
| df = self.load_metadata_from_sheets(csv_path) | |
| if df.empty: | |
| return | |
| # Processa cada peça | |
| total_pieces = len(df) | |
| processed = 0 | |
| for index, row in df.iterrows(): | |
| piece_metadata = self.process_piece_metadata(row) | |
| if self.process_single_piece(piece_metadata): | |
| processed += 1 | |
| print(f"📊 Progresso: {processed}/{total_pieces} peças processadas") | |
| print(f"✅ Catalogação concluída! {processed}/{total_pieces} peças processadas com sucesso.") | |
| if __name__ == "__main__": | |
| cataloger = JewelryCataloger() | |
| cataloger.run_cataloging("./metadata.csv") # Planilha exportada como CSV |