Spaces:
Sleeping
Sleeping
Teste Dir code
Browse files
api.py
CHANGED
|
@@ -1,199 +1,127 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
API
|
|
|
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
# ===== LIMPEZA E PATCHES ANTES DE QUALQUER IMPORTAÇÃO =====
|
| 7 |
import os
|
| 8 |
import sys
|
|
|
|
| 9 |
from pathlib import Path
|
| 10 |
import shutil
|
| 11 |
|
| 12 |
-
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
def
|
| 16 |
-
"""
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
# Variáveis críticas
|
| 20 |
-
env_config = {
|
| 21 |
'THUMBNAILS_PATH': '/tmp/thumbnails',
|
| 22 |
'DATA_PATH': '/tmp/data',
|
| 23 |
'TEMP_PATH': '/tmp/temp_uploads',
|
| 24 |
'MODELS_PATH': '/tmp/models',
|
| 25 |
-
'CACHE_DIR': '/tmp/cache'
|
| 26 |
-
'TMPDIR': '/tmp',
|
| 27 |
-
'TMP': '/tmp',
|
| 28 |
-
'TEMP': '/tmp',
|
| 29 |
-
'HOME': '/tmp/home',
|
| 30 |
-
'PYTORCH_CACHE_DIR': '/tmp/pytorch',
|
| 31 |
-
'HUGGINGFACE_HUB_CACHE': '/tmp/huggingface',
|
| 32 |
-
'TRANSFORMERS_CACHE': '/tmp/transformers'
|
| 33 |
}
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
os.environ[key] =
|
| 38 |
|
| 39 |
-
# Cria diretório
|
| 40 |
try:
|
| 41 |
-
Path(
|
| 42 |
-
print(f"
|
| 43 |
except Exception as e:
|
| 44 |
-
print(f"
|
| 45 |
-
|
| 46 |
-
return env_config
|
| 47 |
-
|
| 48 |
-
# 2. MONKEY PATCHES GLOBAIS
|
| 49 |
-
def apply_global_patches():
|
| 50 |
-
"""Aplica patches globais para interceptar caminhos problemáticos"""
|
| 51 |
-
print("🐒 Aplicando monkey patches globais...")
|
| 52 |
-
|
| 53 |
-
# Backup das funções originais
|
| 54 |
-
_original_makedirs = os.makedirs
|
| 55 |
-
_original_path_mkdir = Path.mkdir
|
| 56 |
-
_original_open = open
|
| 57 |
-
_original_exists = os.path.exists
|
| 58 |
-
_original_isdir = os.path.isdir
|
| 59 |
-
|
| 60 |
-
def patch_path(path_str):
|
| 61 |
-
"""Corrige qualquer caminho problemático"""
|
| 62 |
-
if isinstance(path_str, str):
|
| 63 |
-
# Substitui caminhos problemáticos
|
| 64 |
-
path_str = path_str.replace('/code/thumbnails', '/tmp/thumbnails')
|
| 65 |
-
path_str = path_str.replace('/code/data', '/tmp/data')
|
| 66 |
-
path_str = path_str.replace('/code/cache', '/tmp/cache')
|
| 67 |
-
path_str = path_str.replace('/code/models', '/tmp/models')
|
| 68 |
-
path_str = path_str.replace('/code/temp', '/tmp/temp')
|
| 69 |
-
|
| 70 |
-
# Evita outros caminhos /code/ que não sejam de código
|
| 71 |
-
if path_str.startswith('/code/') and not path_str.endswith('.py'):
|
| 72 |
-
path_str = path_str.replace('/code/', '/tmp/')
|
| 73 |
-
|
| 74 |
-
return path_str
|
| 75 |
-
|
| 76 |
-
def patched_makedirs(name, mode=0o777, exist_ok=False):
|
| 77 |
-
name = patch_path(name)
|
| 78 |
-
print(f" 📁 makedirs: {name}")
|
| 79 |
-
return _original_makedirs(name, mode, exist_ok)
|
| 80 |
-
|
| 81 |
-
def patched_path_mkdir(self, mode=0o777, parents=False, exist_ok=False):
|
| 82 |
-
new_path = patch_path(str(self))
|
| 83 |
-
print(f" 📁 Path.mkdir: {new_path}")
|
| 84 |
-
new_self = Path(new_path)
|
| 85 |
-
return _original_path_mkdir(new_self, mode, parents, exist_ok)
|
| 86 |
|
| 87 |
-
|
| 88 |
-
if hasattr(file, '__fspath__'):
|
| 89 |
-
file = file.__fspath__()
|
| 90 |
-
file = patch_path(file)
|
| 91 |
-
return _original_open(file, mode, **kwargs)
|
| 92 |
-
|
| 93 |
-
def patched_exists(path):
|
| 94 |
-
path = patch_path(path)
|
| 95 |
-
return _original_exists(path)
|
| 96 |
-
|
| 97 |
-
def patched_isdir(path):
|
| 98 |
-
path = patch_path(path)
|
| 99 |
-
return _original_isdir(path)
|
| 100 |
-
|
| 101 |
-
# Aplica os patches
|
| 102 |
-
os.makedirs = patched_makedirs
|
| 103 |
-
Path.mkdir = patched_path_mkdir
|
| 104 |
-
if hasattr(__builtins__, 'open'):
|
| 105 |
-
__builtins__['open'] = patched_open
|
| 106 |
-
else:
|
| 107 |
-
__builtins__.open = patched_open
|
| 108 |
-
os.path.exists = patched_exists
|
| 109 |
-
os.path.isdir = patched_isdir
|
| 110 |
-
|
| 111 |
-
print(" ✅ Patches aplicados!")
|
| 112 |
-
|
| 113 |
-
# 3. LIMPA CACHE DE MÓDULOS
|
| 114 |
-
def clean_module_cache():
|
| 115 |
-
"""Remove módulos problemáticos do cache"""
|
| 116 |
-
print("🧹 Limpando cache de módulos...")
|
| 117 |
-
|
| 118 |
-
modules_to_remove = []
|
| 119 |
-
for name in list(sys.modules.keys()):
|
| 120 |
-
if any(keyword in name.lower() for keyword in ['similarity', 'image', 'jewelry', 'processor']):
|
| 121 |
-
modules_to_remove.append(name)
|
| 122 |
-
|
| 123 |
-
for name in modules_to_remove:
|
| 124 |
-
if name in sys.modules:
|
| 125 |
-
del sys.modules[name]
|
| 126 |
-
print(f" ����️ Removido: {name}")
|
| 127 |
-
|
| 128 |
-
# EXECUTA LIMPEZA ANTES DE TUDO
|
| 129 |
-
print("=" * 50)
|
| 130 |
-
print("🚨 EXECUTANDO LIMPEZA FORÇADA")
|
| 131 |
-
print("=" * 50)
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
clean_module_cache()
|
| 136 |
|
| 137 |
-
|
| 138 |
-
print("✅ LIMPEZA CONCLUÍDA - Prosseguindo com importações")
|
| 139 |
-
print("=" * 50)
|
| 140 |
-
|
| 141 |
-
# ===== AGORA AS IMPORTAÇÕES NORMAIS =====
|
| 142 |
-
import uuid
|
| 143 |
from fastapi import FastAPI, File, UploadFile, HTTPException, Form
|
| 144 |
from fastapi.responses import JSONResponse
|
| 145 |
-
from typing import List
|
| 146 |
-
import shutil
|
| 147 |
|
| 148 |
-
#
|
| 149 |
-
TEMP_DIR = Path(
|
| 150 |
-
THUMBNAILS_DIR = Path(
|
| 151 |
-
DATA_DIR = Path(
|
| 152 |
|
| 153 |
-
print(f"
|
| 154 |
print(f" 🗂️ TEMP: {TEMP_DIR}")
|
| 155 |
print(f" 🖼️ THUMBNAILS: {THUMBNAILS_DIR}")
|
| 156 |
print(f" 💾 DATA: {DATA_DIR}")
|
| 157 |
|
| 158 |
-
#
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
from scripts.similarity_search import SimilaritySearcher
|
| 162 |
-
print("✅ SimilaritySearcher importado com sucesso!")
|
| 163 |
-
except Exception as e:
|
| 164 |
-
print(f"❌ Erro na importação: {e}")
|
| 165 |
-
import traceback
|
| 166 |
-
traceback.print_exc()
|
| 167 |
-
SimilaritySearcher = None
|
| 168 |
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
app = FastAPI(
|
| 171 |
title="API de Busca de Catálogo de Joias",
|
| 172 |
description="Uma API para buscar joias por texto, imagem ou áudio.",
|
| 173 |
version="1.0.0"
|
| 174 |
)
|
| 175 |
|
| 176 |
-
#
|
| 177 |
-
searcher = None
|
| 178 |
-
|
| 179 |
@app.on_event("startup")
|
| 180 |
async def startup_event():
|
| 181 |
global searcher
|
| 182 |
-
print("🚀 Inicializando
|
| 183 |
|
| 184 |
if SimilaritySearcher is None:
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
try:
|
|
|
|
| 188 |
searcher = SimilaritySearcher()
|
| 189 |
print("✅ SimilaritySearcher inicializado com sucesso!")
|
| 190 |
except Exception as e:
|
| 191 |
print(f"❌ Erro ao inicializar SimilaritySearcher: {e}")
|
| 192 |
import traceback
|
| 193 |
traceback.print_exc()
|
| 194 |
-
|
|
|
|
| 195 |
|
| 196 |
-
print("🎉 API
|
|
|
|
|
|
|
| 197 |
|
| 198 |
@app.get("/", tags=["Status"])
|
| 199 |
def read_root():
|
|
@@ -201,6 +129,7 @@ def read_root():
|
|
| 201 |
return {
|
| 202 |
"status": "online",
|
| 203 |
"message": "Bem-vindo à API de Busca de Joias!",
|
|
|
|
| 204 |
"environment": {
|
| 205 |
"temp_dir": str(TEMP_DIR),
|
| 206 |
"thumbnails_dir": str(THUMBNAILS_DIR),
|
|
@@ -208,85 +137,179 @@ def read_root():
|
|
| 208 |
}
|
| 209 |
}
|
| 210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
@app.get("/debug", tags=["Debug"])
|
| 212 |
def debug_info():
|
| 213 |
"""Informações de debug da API."""
|
| 214 |
return {
|
| 215 |
"directories": {
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
"temp": TEMP_DIR.exists(),
|
| 221 |
-
"thumbnails": THUMBNAILS_DIR.exists(),
|
| 222 |
-
"data": DATA_DIR.exists()
|
| 223 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
},
|
| 225 |
"environment_vars": {
|
| 226 |
key: value for key, value in os.environ.items()
|
| 227 |
if any(keyword in key.lower() for keyword in ['path', 'dir', 'cache', 'tmp'])
|
| 228 |
},
|
| 229 |
-
"searcher_status": "initialized" if searcher else "not_initialized"
|
|
|
|
| 230 |
}
|
| 231 |
|
| 232 |
@app.post("/search-by-text", tags=["Busca"])
|
| 233 |
async def search_by_text(query: str = Form(...)):
|
| 234 |
"""Busca joias por uma descrição de texto."""
|
| 235 |
if not searcher:
|
| 236 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
try:
|
|
|
|
| 239 |
results = searcher.search_by_text(text_query=query, top_k=3)
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
|
|
|
|
|
|
|
| 242 |
return {"results": results}
|
|
|
|
| 243 |
except Exception as e:
|
| 244 |
print(f"❌ Erro na busca por texto: {e}")
|
| 245 |
-
|
|
|
|
|
|
|
| 246 |
|
| 247 |
@app.post("/search-by-image", tags=["Busca"])
|
| 248 |
async def search_by_image(file: UploadFile = File(...)):
|
| 249 |
"""Busca joias similares a uma imagem enviada."""
|
| 250 |
if not searcher:
|
| 251 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
-
#
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
temp_file_path = TEMP_DIR / temp_filename
|
| 256 |
|
| 257 |
try:
|
| 258 |
-
print(f"📁 Salvando arquivo
|
| 259 |
|
| 260 |
-
# Salva
|
| 261 |
with temp_file_path.open("wb") as buffer:
|
| 262 |
shutil.copyfileobj(file.file, buffer)
|
| 263 |
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
-
# Realiza
|
| 267 |
results = searcher.search_by_image(image_path=temp_file_path, top_k=3)
|
| 268 |
|
| 269 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
|
| 271 |
-
if not results
|
| 272 |
return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
|
| 273 |
|
|
|
|
| 274 |
return {"results": results}
|
| 275 |
|
|
|
|
|
|
|
|
|
|
| 276 |
except Exception as e:
|
| 277 |
print(f"❌ Erro na busca por imagem: {e}")
|
| 278 |
import traceback
|
| 279 |
traceback.print_exc()
|
| 280 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 281 |
finally:
|
| 282 |
-
#
|
| 283 |
try:
|
| 284 |
if temp_file_path.exists():
|
| 285 |
temp_file_path.unlink()
|
| 286 |
-
print(f"🗑️ Arquivo temporário removido: {
|
| 287 |
except Exception as cleanup_error:
|
| 288 |
print(f"⚠️ Erro ao remover arquivo temporário: {cleanup_error}")
|
| 289 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
if __name__ == "__main__":
|
| 291 |
import uvicorn
|
| 292 |
print("🚀 Iniciando API em modo de desenvolvimento...")
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
API simplificada e robusta para busca de joias
|
| 4 |
+
Evita monkey patches complexos e foca no essencial
|
| 5 |
"""
|
| 6 |
|
|
|
|
| 7 |
import os
|
| 8 |
import sys
|
| 9 |
+
import uuid
|
| 10 |
from pathlib import Path
|
| 11 |
import shutil
|
| 12 |
|
| 13 |
+
# ===== CONFIGURAÇÃO INICIAL SIMPLES =====
|
| 14 |
+
print("🚀 Iniciando API de Busca de Joias...")
|
| 15 |
|
| 16 |
+
# Configuração de diretórios seguros
|
| 17 |
+
def setup_safe_directories():
|
| 18 |
+
"""Configura diretórios com permissão de escrita"""
|
| 19 |
+
safe_dirs = {
|
|
|
|
|
|
|
|
|
|
| 20 |
'THUMBNAILS_PATH': '/tmp/thumbnails',
|
| 21 |
'DATA_PATH': '/tmp/data',
|
| 22 |
'TEMP_PATH': '/tmp/temp_uploads',
|
| 23 |
'MODELS_PATH': '/tmp/models',
|
| 24 |
+
'CACHE_DIR': '/tmp/cache'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
}
|
| 26 |
|
| 27 |
+
for key, path in safe_dirs.items():
|
| 28 |
+
# Define variável de ambiente
|
| 29 |
+
os.environ[key] = path
|
| 30 |
|
| 31 |
+
# Cria diretório
|
| 32 |
try:
|
| 33 |
+
Path(path).mkdir(parents=True, exist_ok=True)
|
| 34 |
+
print(f"📁 {key}: {path} ✅")
|
| 35 |
except Exception as e:
|
| 36 |
+
print(f"📁 {key}: {path} ❌ - {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
return safe_dirs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
# Configuração inicial
|
| 41 |
+
safe_dirs = setup_safe_directories()
|
|
|
|
| 42 |
|
| 43 |
+
# Importações principais
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
from fastapi import FastAPI, File, UploadFile, HTTPException, Form
|
| 45 |
from fastapi.responses import JSONResponse
|
| 46 |
+
from typing import List, Optional
|
|
|
|
| 47 |
|
| 48 |
+
# Configuração de diretórios principais
|
| 49 |
+
TEMP_DIR = Path(safe_dirs['TEMP_PATH'])
|
| 50 |
+
THUMBNAILS_DIR = Path(safe_dirs['THUMBNAILS_PATH'])
|
| 51 |
+
DATA_DIR = Path(safe_dirs['DATA_PATH'])
|
| 52 |
|
| 53 |
+
print(f"📂 Diretórios configurados:")
|
| 54 |
print(f" 🗂️ TEMP: {TEMP_DIR}")
|
| 55 |
print(f" 🖼️ THUMBNAILS: {THUMBNAILS_DIR}")
|
| 56 |
print(f" 💾 DATA: {DATA_DIR}")
|
| 57 |
|
| 58 |
+
# ===== IMPORTAÇÃO SEGURA DO SEARCHER =====
|
| 59 |
+
searcher = None
|
| 60 |
+
SimilaritySearcher = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
def safe_import_searcher():
|
| 63 |
+
"""Importa o SimilaritySearcher de forma segura"""
|
| 64 |
+
global SimilaritySearcher
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
print("📦 Tentando importar SimilaritySearcher...")
|
| 68 |
+
|
| 69 |
+
# Limpa cache de módulos problemáticos primeiro
|
| 70 |
+
modules_to_clean = [name for name in sys.modules.keys()
|
| 71 |
+
if any(keyword in name.lower() for keyword in ['similarity', 'image', 'jewelry'])]
|
| 72 |
+
|
| 73 |
+
for module_name in modules_to_clean:
|
| 74 |
+
if module_name in sys.modules:
|
| 75 |
+
del sys.modules[module_name]
|
| 76 |
+
print(f"🧹 Cache limpo: {module_name}")
|
| 77 |
+
|
| 78 |
+
# Agora importa
|
| 79 |
+
from scripts.similarity_search import SimilaritySearcher
|
| 80 |
+
print("✅ SimilaritySearcher importado com sucesso!")
|
| 81 |
+
return SimilaritySearcher
|
| 82 |
+
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(f"❌ Erro na importação do SimilaritySearcher: {e}")
|
| 85 |
+
import traceback
|
| 86 |
+
traceback.print_exc()
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
# Tenta importar
|
| 90 |
+
SimilaritySearcher = safe_import_searcher()
|
| 91 |
+
|
| 92 |
+
# ===== CONFIGURAÇÃO DA API =====
|
| 93 |
app = FastAPI(
|
| 94 |
title="API de Busca de Catálogo de Joias",
|
| 95 |
description="Uma API para buscar joias por texto, imagem ou áudio.",
|
| 96 |
version="1.0.0"
|
| 97 |
)
|
| 98 |
|
| 99 |
+
# ===== INICIALIZAÇÃO =====
|
|
|
|
|
|
|
| 100 |
@app.on_event("startup")
|
| 101 |
async def startup_event():
|
| 102 |
global searcher
|
| 103 |
+
print("🚀 Inicializando API...")
|
| 104 |
|
| 105 |
if SimilaritySearcher is None:
|
| 106 |
+
print("❌ SimilaritySearcher não disponível")
|
| 107 |
+
# Não falha completamente, permite que a API funcione parcialmente
|
| 108 |
+
searcher = None
|
| 109 |
+
return
|
| 110 |
|
| 111 |
try:
|
| 112 |
+
print("🔄 Inicializando SimilaritySearcher...")
|
| 113 |
searcher = SimilaritySearcher()
|
| 114 |
print("✅ SimilaritySearcher inicializado com sucesso!")
|
| 115 |
except Exception as e:
|
| 116 |
print(f"❌ Erro ao inicializar SimilaritySearcher: {e}")
|
| 117 |
import traceback
|
| 118 |
traceback.print_exc()
|
| 119 |
+
searcher = None
|
| 120 |
+
# Não falha, permite API funcionar parcialmente
|
| 121 |
|
| 122 |
+
print("🎉 API inicializada!")
|
| 123 |
+
|
| 124 |
+
# ===== ENDPOINTS =====
|
| 125 |
|
| 126 |
@app.get("/", tags=["Status"])
|
| 127 |
def read_root():
|
|
|
|
| 129 |
return {
|
| 130 |
"status": "online",
|
| 131 |
"message": "Bem-vindo à API de Busca de Joias!",
|
| 132 |
+
"searcher_status": "ready" if searcher else "not_ready",
|
| 133 |
"environment": {
|
| 134 |
"temp_dir": str(TEMP_DIR),
|
| 135 |
"thumbnails_dir": str(THUMBNAILS_DIR),
|
|
|
|
| 137 |
}
|
| 138 |
}
|
| 139 |
|
| 140 |
+
@app.get("/health", tags=["Status"])
|
| 141 |
+
def health_check():
|
| 142 |
+
"""Health check detalhado."""
|
| 143 |
+
return {
|
| 144 |
+
"status": "healthy",
|
| 145 |
+
"components": {
|
| 146 |
+
"searcher": "ready" if searcher else "not_ready",
|
| 147 |
+
"directories": {
|
| 148 |
+
"temp": TEMP_DIR.exists(),
|
| 149 |
+
"thumbnails": THUMBNAILS_DIR.exists(),
|
| 150 |
+
"data": DATA_DIR.exists()
|
| 151 |
+
}
|
| 152 |
+
},
|
| 153 |
+
"version": "1.0.0"
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
@app.get("/debug", tags=["Debug"])
|
| 157 |
def debug_info():
|
| 158 |
"""Informações de debug da API."""
|
| 159 |
return {
|
| 160 |
"directories": {
|
| 161 |
+
dir_name: {
|
| 162 |
+
"path": str(path),
|
| 163 |
+
"exists": path.exists(),
|
| 164 |
+
"writable": os.access(path, os.W_OK) if path.exists() else False
|
|
|
|
|
|
|
|
|
|
| 165 |
}
|
| 166 |
+
for dir_name, path in [
|
| 167 |
+
("temp", TEMP_DIR),
|
| 168 |
+
("thumbnails", THUMBNAILS_DIR),
|
| 169 |
+
("data", DATA_DIR)
|
| 170 |
+
]
|
| 171 |
},
|
| 172 |
"environment_vars": {
|
| 173 |
key: value for key, value in os.environ.items()
|
| 174 |
if any(keyword in key.lower() for keyword in ['path', 'dir', 'cache', 'tmp'])
|
| 175 |
},
|
| 176 |
+
"searcher_status": "initialized" if searcher else "not_initialized",
|
| 177 |
+
"python_path": sys.path[:5] # Primeiros 5 paths
|
| 178 |
}
|
| 179 |
|
| 180 |
@app.post("/search-by-text", tags=["Busca"])
|
| 181 |
async def search_by_text(query: str = Form(...)):
|
| 182 |
"""Busca joias por uma descrição de texto."""
|
| 183 |
if not searcher:
|
| 184 |
+
raise HTTPException(
|
| 185 |
+
status_code=503,
|
| 186 |
+
detail="Serviço de busca não está disponível. Verifique os logs da API."
|
| 187 |
+
)
|
| 188 |
|
| 189 |
try:
|
| 190 |
+
print(f"🔍 Buscando por texto: '{query}'")
|
| 191 |
results = searcher.search_by_text(text_query=query, top_k=3)
|
| 192 |
+
|
| 193 |
+
# Verifica se há erro na resposta
|
| 194 |
+
if isinstance(results, dict) and results.get('error'):
|
| 195 |
+
print(f"❌ Erro no searcher: {results['error']}")
|
| 196 |
+
return JSONResponse(
|
| 197 |
+
status_code=500,
|
| 198 |
+
content={"message": "Erro na busca", "error": results['error']}
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
if not results:
|
| 202 |
return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
|
| 203 |
+
|
| 204 |
+
print(f"✅ Encontrados {len(results)} resultados")
|
| 205 |
return {"results": results}
|
| 206 |
+
|
| 207 |
except Exception as e:
|
| 208 |
print(f"❌ Erro na busca por texto: {e}")
|
| 209 |
+
import traceback
|
| 210 |
+
traceback.print_exc()
|
| 211 |
+
raise HTTPException(status_code=500, detail=f"Erro interno: {str(e)}")
|
| 212 |
|
| 213 |
@app.post("/search-by-image", tags=["Busca"])
|
| 214 |
async def search_by_image(file: UploadFile = File(...)):
|
| 215 |
"""Busca joias similares a uma imagem enviada."""
|
| 216 |
if not searcher:
|
| 217 |
+
raise HTTPException(
|
| 218 |
+
status_code=503,
|
| 219 |
+
detail="Serviço de busca não está disponível. Verifique os logs da API."
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# Validação do arquivo
|
| 223 |
+
if not file.filename:
|
| 224 |
+
raise HTTPException(status_code=400, detail="Nome do arquivo não fornecido")
|
| 225 |
|
| 226 |
+
# Verifica extensão
|
| 227 |
+
allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
|
| 228 |
+
file_extension = Path(file.filename).suffix.lower()
|
| 229 |
+
if file_extension not in allowed_extensions:
|
| 230 |
+
raise HTTPException(
|
| 231 |
+
status_code=400,
|
| 232 |
+
detail=f"Extensão {file_extension} não suportada. Use: {', '.join(allowed_extensions)}"
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
# Gera nome único
|
| 236 |
+
temp_filename = f"{uuid.uuid4()}{file_extension}"
|
| 237 |
temp_file_path = TEMP_DIR / temp_filename
|
| 238 |
|
| 239 |
try:
|
| 240 |
+
print(f"📁 Salvando arquivo: {file.filename} -> {temp_file_path}")
|
| 241 |
|
| 242 |
+
# Salva arquivo
|
| 243 |
with temp_file_path.open("wb") as buffer:
|
| 244 |
shutil.copyfileobj(file.file, buffer)
|
| 245 |
|
| 246 |
+
# Verifica se foi salvo
|
| 247 |
+
if not temp_file_path.exists():
|
| 248 |
+
raise HTTPException(status_code=500, detail="Falha ao salvar arquivo temporário")
|
| 249 |
+
|
| 250 |
+
file_size = temp_file_path.stat().st_size
|
| 251 |
+
print(f"✅ Arquivo salvo ({file_size} bytes). Iniciando busca...")
|
| 252 |
|
| 253 |
+
# Realiza busca
|
| 254 |
results = searcher.search_by_image(image_path=temp_file_path, top_k=3)
|
| 255 |
|
| 256 |
+
# Verifica erro na resposta
|
| 257 |
+
if isinstance(results, dict) and results.get('error'):
|
| 258 |
+
print(f"❌ Erro no searcher: {results['error']}")
|
| 259 |
+
return JSONResponse(
|
| 260 |
+
status_code=500,
|
| 261 |
+
content={"message": "Erro na busca", "error": results['error']}
|
| 262 |
+
)
|
| 263 |
|
| 264 |
+
if not results:
|
| 265 |
return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
|
| 266 |
|
| 267 |
+
print(f"✅ Busca concluída! Encontrados {len(results)} resultados")
|
| 268 |
return {"results": results}
|
| 269 |
|
| 270 |
+
except HTTPException:
|
| 271 |
+
# Re-raise HTTPExceptions
|
| 272 |
+
raise
|
| 273 |
except Exception as e:
|
| 274 |
print(f"❌ Erro na busca por imagem: {e}")
|
| 275 |
import traceback
|
| 276 |
traceback.print_exc()
|
| 277 |
+
raise HTTPException(status_code=500, detail=f"Erro interno: {str(e)}")
|
| 278 |
finally:
|
| 279 |
+
# Limpeza sempre executada
|
| 280 |
try:
|
| 281 |
if temp_file_path.exists():
|
| 282 |
temp_file_path.unlink()
|
| 283 |
+
print(f"🗑️ Arquivo temporário removido: {temp_filename}")
|
| 284 |
except Exception as cleanup_error:
|
| 285 |
print(f"⚠️ Erro ao remover arquivo temporário: {cleanup_error}")
|
| 286 |
|
| 287 |
+
# ===== ENDPOINT DE TESTE =====
|
| 288 |
+
@app.post("/test-upload", tags=["Teste"])
|
| 289 |
+
async def test_upload(file: UploadFile = File(...)):
|
| 290 |
+
"""Testa apenas o upload de arquivo sem busca."""
|
| 291 |
+
temp_filename = f"test_{uuid.uuid4()}{Path(file.filename).suffix}"
|
| 292 |
+
temp_file_path = TEMP_DIR / temp_filename
|
| 293 |
+
|
| 294 |
+
try:
|
| 295 |
+
with temp_file_path.open("wb") as buffer:
|
| 296 |
+
shutil.copyfileobj(file.file, buffer)
|
| 297 |
+
|
| 298 |
+
file_info = {
|
| 299 |
+
"filename": file.filename,
|
| 300 |
+
"temp_path": str(temp_file_path),
|
| 301 |
+
"size": temp_file_path.stat().st_size,
|
| 302 |
+
"exists": temp_file_path.exists()
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
return {"message": "Upload teste bem-sucedido", "file_info": file_info}
|
| 306 |
+
|
| 307 |
+
except Exception as e:
|
| 308 |
+
raise HTTPException(status_code=500, detail=f"Erro no teste de upload: {str(e)}")
|
| 309 |
+
finally:
|
| 310 |
+
if temp_file_path.exists():
|
| 311 |
+
temp_file_path.unlink()
|
| 312 |
+
|
| 313 |
if __name__ == "__main__":
|
| 314 |
import uvicorn
|
| 315 |
print("🚀 Iniciando API em modo de desenvolvimento...")
|