Spaces:
Sleeping
Sleeping
Download api.py from OctusTech/cartalogo-api: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/spaces/OctusTech/cartalogo-api/resolve/main/api.py
- Command line
-
hf download hf://spaces/OctusTech/cartalogo-api/api.py
-
curl -L -o api.py https://huggingface.co/spaces/OctusTech/cartalogo-api/resolve/main/api.py
10.7 kB
| #!/usr/bin/env python3 | |
| """ | |
| API simplificada e robusta para busca de joias | |
| Evita monkey patches complexos e foca no essencial | |
| -- Marcador de arquivo | |
| """ | |
| import os | |
| import sys | |
| import uuid | |
| from pathlib import Path | |
| import shutil | |
| # ===== CONFIGURAÇÃO INICIAL SIMPLES ===== | |
| print("🚀 Iniciando API de Busca de Joias...") | |
| # Configuração de diretórios seguros | |
| def setup_safe_directories(): | |
| """Configura diretórios com permissão de escrita""" | |
| safe_dirs = { | |
| 'THUMBNAILS_PATH': '/tmp/thumbnails', | |
| 'DATA_PATH': '/tmp/data', | |
| 'TEMP_PATH': '/tmp/temp_uploads', | |
| 'MODELS_PATH': '/tmp/models', | |
| 'CACHE_DIR': '/tmp/cache' | |
| } | |
| for key, path in safe_dirs.items(): | |
| # Define variável de ambiente | |
| os.environ[key] = path | |
| # Cria diretório | |
| try: | |
| Path(path).mkdir(parents=True, exist_ok=True) | |
| print(f"📁 {key}: {path} ✅") | |
| except Exception as e: | |
| print(f"📁 {key}: {path} ❌ - {e}") | |
| return safe_dirs | |
| # Configuração inicial | |
| safe_dirs = setup_safe_directories() | |
| # Importações principais | |
| from fastapi import FastAPI, File, UploadFile, HTTPException, Form | |
| from fastapi.responses import JSONResponse | |
| from typing import List, Optional | |
| # Configuração de diretórios principais | |
| TEMP_DIR = Path(safe_dirs['TEMP_PATH']) | |
| THUMBNAILS_DIR = Path(safe_dirs['THUMBNAILS_PATH']) | |
| DATA_DIR = Path(safe_dirs['DATA_PATH']) | |
| print(f"📂 Diretórios configurados:") | |
| print(f" 🗂️ TEMP: {TEMP_DIR}") | |
| print(f" 🖼️ THUMBNAILS: {THUMBNAILS_DIR}") | |
| print(f" 💾 DATA: {DATA_DIR}") | |
| # ===== IMPORTAÇÃO SEGURA DO SEARCHER ===== | |
| searcher = None | |
| SimilaritySearcher = None | |
| def safe_import_searcher(): | |
| """Importa o SimilaritySearcher de forma segura""" | |
| global SimilaritySearcher | |
| try: | |
| print("📦 Tentando importar SimilaritySearcher...") | |
| # Limpa cache de módulos problemáticos primeiro | |
| modules_to_clean = [name for name in sys.modules.keys() | |
| if any(keyword in name.lower() for keyword in ['similarity', 'image', 'jewelry'])] | |
| for module_name in modules_to_clean: | |
| if module_name in sys.modules: | |
| del sys.modules[module_name] | |
| print(f"🧹 Cache limpo: {module_name}") | |
| # Agora importa | |
| from scripts.similarity_search import SimilaritySearcher | |
| print("✅ SimilaritySearcher importado com sucesso!") | |
| return SimilaritySearcher | |
| except Exception as e: | |
| print(f"❌ Erro na importação do SimilaritySearcher: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return None | |
| # Tenta importar | |
| SimilaritySearcher = safe_import_searcher() | |
| # ===== CONFIGURAÇÃO DA API ===== | |
| app = FastAPI( | |
| title="API de Busca de Catálogo de Joias", | |
| description="Uma API para buscar joias por texto, imagem ou áudio.", | |
| version="1.0.0" | |
| ) | |
| # ===== INICIALIZAÇÃO ===== | |
| async def startup_event(): | |
| global searcher | |
| print("🚀 Inicializando API...") | |
| if SimilaritySearcher is None: | |
| print("❌ SimilaritySearcher não disponível") | |
| # Não falha completamente, permite que a API funcione parcialmente | |
| searcher = None | |
| return | |
| try: | |
| print("🔄 Inicializando SimilaritySearcher...") | |
| searcher = SimilaritySearcher() | |
| print("✅ SimilaritySearcher inicializado com sucesso!") | |
| except Exception as e: | |
| print(f"❌ Erro ao inicializar SimilaritySearcher: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| searcher = None | |
| # Não falha, permite API funcionar parcialmente | |
| print("🎉 API inicializada!") | |
| # ===== ENDPOINTS ===== | |
| def read_root(): | |
| """Verifica se a API está online.""" | |
| return { | |
| "status": "online", | |
| "message": "Bem-vindo à API de Busca de Joias!", | |
| "searcher_status": "ready" if searcher else "not_ready", | |
| "environment": { | |
| "temp_dir": str(TEMP_DIR), | |
| "thumbnails_dir": str(THUMBNAILS_DIR), | |
| "data_dir": str(DATA_DIR) | |
| } | |
| } | |
| def health_check(): | |
| """Health check detalhado.""" | |
| return { | |
| "status": "healthy", | |
| "components": { | |
| "searcher": "ready" if searcher else "not_ready", | |
| "directories": { | |
| "temp": TEMP_DIR.exists(), | |
| "thumbnails": THUMBNAILS_DIR.exists(), | |
| "data": DATA_DIR.exists() | |
| } | |
| }, | |
| "version": "1.0.0" | |
| } | |
| def debug_info(): | |
| """Informações de debug da API.""" | |
| return { | |
| "directories": { | |
| dir_name: { | |
| "path": str(path), | |
| "exists": path.exists(), | |
| "writable": os.access(path, os.W_OK) if path.exists() else False | |
| } | |
| for dir_name, path in [ | |
| ("temp", TEMP_DIR), | |
| ("thumbnails", THUMBNAILS_DIR), | |
| ("data", DATA_DIR) | |
| ] | |
| }, | |
| "environment_vars": { | |
| key: value for key, value in os.environ.items() | |
| if any(keyword in key.lower() for keyword in ['path', 'dir', 'cache', 'tmp']) | |
| }, | |
| "searcher_status": "initialized" if searcher else "not_initialized", | |
| "python_path": sys.path[:5] # Primeiros 5 paths | |
| } | |
| async def search_by_text(query: str = Form(...)): | |
| """Busca joias por uma descrição de texto.""" | |
| if not searcher: | |
| raise HTTPException( | |
| status_code=503, | |
| detail="Serviço de busca não está disponível. Verifique os logs da API." | |
| ) | |
| try: | |
| print(f"🔍 Buscando por texto: '{query}'") | |
| results = searcher.search_by_text(text_query=query, top_k=3) | |
| # Verifica se há erro na resposta | |
| if isinstance(results, dict) and results.get('error'): | |
| print(f"❌ Erro no searcher: {results['error']}") | |
| return JSONResponse( | |
| status_code=500, | |
| content={"message": "Erro na busca", "error": results['error']} | |
| ) | |
| if not results: | |
| return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []}) | |
| print(f"✅ Encontrados {len(results)} resultados") | |
| return {"results": results} | |
| except Exception as e: | |
| print(f"❌ Erro na busca por texto: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| raise HTTPException(status_code=500, detail=f"Erro interno: {str(e)}") | |
| async def search_by_image(file: UploadFile = File(...)): | |
| """Busca joias similares a uma imagem enviada.""" | |
| if not searcher: | |
| raise HTTPException( | |
| status_code=503, | |
| detail="Serviço de busca não está disponível. Verifique os logs da API." | |
| ) | |
| # Validação do arquivo | |
| if not file.filename: | |
| raise HTTPException(status_code=400, detail="Nome do arquivo não fornecido") | |
| # Verifica extensão | |
| allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'} | |
| file_extension = Path(file.filename).suffix.lower() | |
| if file_extension not in allowed_extensions: | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Extensão {file_extension} não suportada. Use: {', '.join(allowed_extensions)}" | |
| ) | |
| # Gera nome único | |
| temp_filename = f"{uuid.uuid4()}{file_extension}" | |
| temp_file_path = TEMP_DIR / temp_filename | |
| try: | |
| print(f"📁 Salvando arquivo: {file.filename} -> {temp_file_path}") | |
| # Salva arquivo | |
| with temp_file_path.open("wb") as buffer: | |
| shutil.copyfileobj(file.file, buffer) | |
| # Verifica se foi salvo | |
| if not temp_file_path.exists(): | |
| raise HTTPException(status_code=500, detail="Falha ao salvar arquivo temporário") | |
| file_size = temp_file_path.stat().st_size | |
| print(f"✅ Arquivo salvo ({file_size} bytes). Iniciando busca...") | |
| # Realiza busca | |
| results = searcher.search_by_image(image_path=temp_file_path, top_k=3) | |
| # Verifica erro na resposta | |
| if isinstance(results, dict) and results.get('error'): | |
| print(f"❌ Erro no searcher: {results['error']}") | |
| return JSONResponse( | |
| status_code=500, | |
| content={"message": "Erro na busca", "error": results['error']} | |
| ) | |
| if not results: | |
| return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []}) | |
| print(f"✅ Busca concluída! Encontrados {len(results)} resultados") | |
| return {"results": results} | |
| except HTTPException: | |
| # Re-raise HTTPExceptions | |
| raise | |
| except Exception as e: | |
| print(f"❌ Erro na busca por imagem: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| raise HTTPException(status_code=500, detail=f"Erro interno: {str(e)}") | |
| finally: | |
| # Limpeza sempre executada | |
| try: | |
| if temp_file_path.exists(): | |
| temp_file_path.unlink() | |
| print(f"🗑️ Arquivo temporário removido: {temp_filename}") | |
| except Exception as cleanup_error: | |
| print(f"⚠️ Erro ao remover arquivo temporário: {cleanup_error}") | |
| # ===== ENDPOINT DE TESTE ===== | |
| async def test_upload(file: UploadFile = File(...)): | |
| """Testa apenas o upload de arquivo sem busca.""" | |
| temp_filename = f"test_{uuid.uuid4()}{Path(file.filename).suffix}" | |
| temp_file_path = TEMP_DIR / temp_filename | |
| try: | |
| with temp_file_path.open("wb") as buffer: | |
| shutil.copyfileobj(file.file, buffer) | |
| file_info = { | |
| "filename": file.filename, | |
| "temp_path": str(temp_file_path), | |
| "size": temp_file_path.stat().st_size, | |
| "exists": temp_file_path.exists() | |
| } | |
| return {"message": "Upload teste bem-sucedido", "file_info": file_info} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Erro no teste de upload: {str(e)}") | |
| finally: | |
| if temp_file_path.exists(): | |
| temp_file_path.unlink() | |
| if __name__ == "__main__": | |
| import uvicorn | |
| print("🚀 Iniciando API em modo de desenvolvimento...") | |
| uvicorn.run(app, host="0.0.0.0", port=8000) |