File size: 10,729 Bytes
fef4203
 
6b2eade
 
9280c68
fef4203
 
a146cd6
fef4203
6b2eade
a146cd6
fef4203
 
6b2eade
 
fef4203
6b2eade
 
 
 
fef4203
 
 
 
6b2eade
fef4203
 
6b2eade
 
 
fef4203
6b2eade
fef4203
6b2eade
 
fef4203
6b2eade
fef4203
6b2eade
fef4203
6b2eade
 
fef4203
6b2eade
a146cd6
 
6b2eade
a146cd6
6b2eade
 
 
 
1245652
6b2eade
fef4203
 
 
1245652
6b2eade
 
 
a146cd6
6b2eade
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a146cd6
 
 
 
 
 
6b2eade
a146cd6
 
fef4203
6b2eade
fef4203
 
6b2eade
 
 
 
fef4203
 
6b2eade
fef4203
 
 
 
 
 
6b2eade
 
fef4203
6b2eade
 
 
a146cd6
 
 
 
fef4203
 
 
6b2eade
fef4203
 
 
 
 
 
 
6b2eade
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fef4203
 
 
 
 
6b2eade
 
 
 
fef4203
6b2eade
 
 
 
 
fef4203
 
 
 
 
6b2eade
 
fef4203
a146cd6
 
 
fef4203
 
6b2eade
 
 
 
fef4203
a146cd6
6b2eade
a146cd6
6b2eade
 
 
 
 
 
 
 
 
 
a146cd6
6b2eade
 
a146cd6
6b2eade
a146cd6
fef4203
6b2eade
 
 
a146cd6
 
 
fef4203
 
6b2eade
 
 
 
 
 
 
 
fef4203
6b2eade
 
 
 
 
 
 
 
 
 
 
a146cd6
 
 
6b2eade
fef4203
6b2eade
a146cd6
 
fef4203
6b2eade
 
 
 
 
 
fef4203
6b2eade
a146cd6
 
6b2eade
 
 
 
 
 
 
fef4203
6b2eade
a146cd6
fef4203
6b2eade
a146cd6
fef4203
6b2eade
 
 
a146cd6
fef4203
 
 
6b2eade
a146cd6
6b2eade
fef4203
 
 
6b2eade
fef4203
 
a146cd6
6b2eade
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a146cd6
 
fef4203
1245652
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/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 =====
@app.on_event("startup")
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 =====

@app.get("/", tags=["Status"])
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)
        }
    }

@app.get("/health", tags=["Status"])
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"
    }

@app.get("/debug", tags=["Debug"])
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
    }

@app.post("/search-by-text", tags=["Busca"])
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)}")

@app.post("/search-by-image", tags=["Busca"])
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 =====
@app.post("/test-upload", tags=["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)