pmazzia commited on
Commit
fef4203
·
1 Parent(s): 75f0505

limpeza de code

Browse files
Files changed (3) hide show
  1. api.py +236 -44
  2. debug_paths.py +171 -0
  3. force_clean.py +161 -0
api.py CHANGED
@@ -1,34 +1,170 @@
 
 
 
 
 
 
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
- # ===== CONFIGURAÇÃO PARA HUGGING FACE SPACES =====
10
- # Define diretórios com permissão de escrita
11
- TEMP_DIR = Path("/tmp/temp_uploads")
12
- THUMBNAILS_DIR = Path("/tmp/thumbnails")
13
- DATA_DIR = Path("/tmp/data")
14
-
15
- # Cria os diretórios necessários
16
- TEMP_DIR.mkdir(parents=True, exist_ok=True)
17
- THUMBNAILS_DIR.mkdir(parents=True, exist_ok=True)
18
- DATA_DIR.mkdir(parents=True, exist_ok=True)
19
 
20
- # Configura variáveis de ambiente para os scripts
21
- os.environ['THUMBNAILS_PATH'] = str(THUMBNAILS_DIR)
22
- os.environ['DATA_PATH'] = str(DATA_DIR)
23
- os.environ['TEMP_PATH'] = str(TEMP_DIR)
24
 
25
- print(f"✅ Diretórios configurados:")
26
- print(f" 📁 Temp: {TEMP_DIR}")
27
- print(f" 📁 Thumbnails: {THUMBNAILS_DIR}")
28
- print(f" 📁 Data: {DATA_DIR}")
29
-
30
- # Agora importa o buscador (DEPOIS das configurações)
31
- from scripts.similarity_search import SimilaritySearcher
 
 
 
32
 
33
  # Cria a aplicação FastAPI
34
  app = FastAPI(
@@ -37,65 +173,121 @@ app = FastAPI(
37
  version="1.0.0"
38
  )
39
 
40
- # Inicializa o buscador uma vez para toda a aplicação
41
- try:
42
- searcher = SimilaritySearcher()
43
- except Exception as e:
44
- print(f"Erro fatal ao inicializar o SimilaritySearcher: {e}")
45
- searcher = None
46
 
47
  @app.on_event("startup")
48
  async def startup_event():
49
- if searcher is None:
50
- raise RuntimeError("Falha ao carregar o modelo de busca. A API não pode iniciar.")
51
- print("API pronta para receber requisições.")
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  @app.get("/", tags=["Status"])
54
  def read_root():
55
  """Verifica se a API está online."""
56
- return {"status": "online", "message": "Bem-vindo à API de Busca de Joias!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  @app.post("/search-by-text", tags=["Busca"])
59
  async def search_by_text(query: str = Form(...)):
60
- """
61
- Busca joias por uma descrição de texto.
62
- """
 
63
  try:
64
  results = searcher.search_by_text(text_query=query, top_k=3)
65
- if not results:
66
  return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
67
  return {"results": results}
68
  except Exception as e:
 
69
  raise HTTPException(status_code=500, detail=str(e))
70
 
71
  @app.post("/search-by-image", tags=["Busca"])
72
  async def search_by_image(file: UploadFile = File(...)):
73
- """
74
- Busca joias similares a uma imagem enviada.
75
- """
 
76
  # Gera um nome de arquivo único e seguro
77
  temp_filename = f"{uuid.uuid4()}{Path(file.filename).suffix}"
78
  temp_file_path = TEMP_DIR / temp_filename
79
 
80
  try:
 
 
81
  # Salva o arquivo temporariamente
82
  with temp_file_path.open("wb") as buffer:
83
  shutil.copyfileobj(file.file, buffer)
84
-
 
 
85
  # Realiza a busca
86
  results = searcher.search_by_image(image_path=temp_file_path, top_k=3)
87
 
88
- if not results:
 
 
89
  return JSONResponse(content={"message": "Nenhum resultado encontrado.", "results": []})
 
90
  return {"results": results}
 
91
  except Exception as e:
 
 
 
92
  raise HTTPException(status_code=500, detail=str(e))
93
  finally:
94
  # Garante que o arquivo temporário seja deletado
95
- if temp_file_path.exists():
96
- temp_file_path.unlink()
 
 
 
 
97
 
98
  if __name__ == "__main__":
99
  import uvicorn
100
- print("Iniciando API em modo de desenvolvimento...")
101
  uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ API com limpeza forçada e monkey patches para resolver problemas de caminhos
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
+ print("🚀 Iniciando API com limpeza forçada...")
13
+
14
+ # 1. FORÇA CONFIGURAÇÃO DE AMBIENTE
15
+ def force_environment_setup():
16
+ """Força configuração completa do ambiente"""
17
+ print("⚙️ Configurando ambiente forçadamente...")
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
+ # Aplica todas as variáveis
36
+ for key, value in env_config.items():
37
+ os.environ[key] = value
38
+
39
+ # Cria diretório imediatamente
40
+ try:
41
+ Path(value).mkdir(parents=True, exist_ok=True)
42
+ print(f" ✅ {key}: {value}")
43
+ except Exception as e:
44
+ print(f" ❌ {key}: {value} - {e}")
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
+ def patched_open(file, mode='r', **kwargs):
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
+ env_config = force_environment_setup()
134
+ apply_global_patches()
135
+ clean_module_cache()
136
+
137
+ print("=" * 50)
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
+ # Configura diretórios principais
149
+ TEMP_DIR = Path(os.environ['TEMP_PATH'])
150
+ THUMBNAILS_DIR = Path(os.environ['THUMBNAILS_PATH'])
151
+ DATA_DIR = Path(os.environ['DATA_PATH'])
 
 
 
 
 
 
152
 
153
+ print(f"📁 Diretórios configurados:")
154
+ print(f" 🗂️ TEMP: {TEMP_DIR}")
155
+ print(f" 🖼️ THUMBNAILS: {THUMBNAILS_DIR}")
156
+ print(f" 💾 DATA: {DATA_DIR}")
157
 
158
+ # Tenta importar o SimilaritySearcher
159
+ print("📦 Importando SimilaritySearcher...")
160
+ try:
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
  # Cria a aplicação FastAPI
170
  app = FastAPI(
 
173
  version="1.0.0"
174
  )
175
 
176
+ # Inicializa o buscador
177
+ searcher = None
 
 
 
 
178
 
179
  @app.on_event("startup")
180
  async def startup_event():
181
+ global searcher
182
+ print("🚀 Inicializando buscador...")
183
+
184
+ if SimilaritySearcher is None:
185
+ raise RuntimeError("SimilaritySearcher não pôde ser importado")
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
+ raise RuntimeError(f"Falha ao carregar o modelo de busca: {e}")
195
+
196
+ print("🎉 API pronta para receber requisições!")
197
 
198
  @app.get("/", tags=["Status"])
199
  def read_root():
200
  """Verifica se a API está online."""
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),
207
+ "data_dir": str(DATA_DIR)
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
+ "temp": str(TEMP_DIR),
217
+ "thumbnails": str(THUMBNAILS_DIR),
218
+ "data": str(DATA_DIR),
219
+ "exists": {
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(status_code=503, detail="Buscador não inicializado")
237
+
238
  try:
239
  results = searcher.search_by_text(text_query=query, top_k=3)
240
+ if not results or (isinstance(results, dict) and results.get('error')):
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
  raise HTTPException(status_code=500, detail=str(e))
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(status_code=503, detail="Buscador não inicializado")
252
+
253
  # Gera um nome de arquivo único e seguro
254
  temp_filename = f"{uuid.uuid4()}{Path(file.filename).suffix}"
255
  temp_file_path = TEMP_DIR / temp_filename
256
 
257
  try:
258
+ print(f"📁 Salvando arquivo em: {temp_file_path}")
259
+
260
  # Salva o arquivo temporariamente
261
  with temp_file_path.open("wb") as buffer:
262
  shutil.copyfileobj(file.file, buffer)
263
+
264
+ print(f"✅ Arquivo salvo. Iniciando busca...")
265
+
266
  # Realiza a busca
267
  results = searcher.search_by_image(image_path=temp_file_path, top_k=3)
268
 
269
+ print(f"🔍 Resultados da busca: {results}")
270
+
271
+ if not results or (isinstance(results, dict) and results.get('error')):
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
  # Garante que o arquivo temporário seja deletado
283
+ try:
284
+ if temp_file_path.exists():
285
+ temp_file_path.unlink()
286
+ print(f"🗑️ Arquivo temporário removido: {temp_file_path}")
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...")
293
  uvicorn.run(app, host="0.0.0.0", port=8000)
debug_paths.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import sys
4
+ import traceback
5
+ from pathlib import Path
6
+ import inspect
7
+
8
+ def debug_all_paths():
9
+ """Debug completo de todos os caminhos e variáveis"""
10
+ print("🔍 === DEBUG COMPLETO DE CAMINHOS ===")
11
+
12
+ # 1. Variáveis de ambiente
13
+ print("\n📋 VARIÁVEIS DE AMBIENTE:")
14
+ for key, value in os.environ.items():
15
+ if 'path' in key.lower() or 'dir' in key.lower() or 'thumbnails' in key.lower():
16
+ print(f" {key} = {value}")
17
+
18
+ # 2. Diretório atual e permissões
19
+ print(f"\n📁 DIRETÓRIO ATUAL: {os.getcwd()}")
20
+ print(f"📁 DIRETÓRIO HOME: {os.path.expanduser('~')}")
21
+ print(f"📁 TEMP DIR: {os.path.join(os.sep, 'tmp')}")
22
+
23
+ # 3. Testa criação de diretórios
24
+ test_dirs = [
25
+ "/tmp/thumbnails",
26
+ "/tmp/test_dir",
27
+ "/code/test_write",
28
+ "./test_local"
29
+ ]
30
+
31
+ print(f"\n🧪 TESTE DE PERMISSÕES:")
32
+ for test_dir in test_dirs:
33
+ try:
34
+ Path(test_dir).mkdir(parents=True, exist_ok=True)
35
+ # Tenta escrever um arquivo
36
+ test_file = Path(test_dir) / "test.txt"
37
+ test_file.write_text("test")
38
+ test_file.unlink() # Remove o arquivo
39
+ print(f" ✅ {test_dir} - OK (leitura/escrita)")
40
+ except Exception as e:
41
+ print(f" ❌ {test_dir} - ERRO: {e}")
42
+
43
+ # 4. Procura por referências a /code/thumbnails
44
+ print(f"\n🔍 PROCURANDO REFERÊNCIAS A '/code/thumbnails':")
45
+ search_paths = [
46
+ ".",
47
+ "./scripts",
48
+ sys.path
49
+ ]
50
+
51
+ for search_path in search_paths:
52
+ if isinstance(search_path, str) and os.path.exists(search_path):
53
+ try:
54
+ for root, dirs, files in os.walk(search_path):
55
+ for file in files:
56
+ if file.endswith('.py'):
57
+ file_path = os.path.join(root, file)
58
+ try:
59
+ with open(file_path, 'r', encoding='utf-8') as f:
60
+ content = f.read()
61
+ if '/code/thumbnails' in content:
62
+ print(f" 🎯 ENCONTRADO em: {file_path}")
63
+ # Mostra as linhas que contêm a referência
64
+ lines = content.split('\n')
65
+ for i, line in enumerate(lines, 1):
66
+ if '/code/thumbnails' in line:
67
+ print(f" Linha {i}: {line.strip()}")
68
+ except Exception as e:
69
+ print(f" ⚠️ Erro ao ler {file_path}: {e}")
70
+ except Exception as e:
71
+ print(f" ⚠️ Erro ao explorar {search_path}: {e}")
72
+
73
+ # 5. Força configuração de todas as variáveis
74
+ print(f"\n⚙️ FORÇANDO CONFIGURAÇÕES:")
75
+
76
+ forced_configs = {
77
+ 'THUMBNAILS_PATH': '/tmp/thumbnails',
78
+ 'DATA_PATH': '/tmp/data',
79
+ 'TEMP_PATH': '/tmp/temp',
80
+ 'MODELS_PATH': '/tmp/models',
81
+ 'CACHE_DIR': '/tmp/cache',
82
+ 'HOME': '/tmp/home',
83
+ 'TMPDIR': '/tmp',
84
+ 'TMP': '/tmp',
85
+ 'TEMP': '/tmp'
86
+ }
87
+
88
+ for key, value in forced_configs.items():
89
+ os.environ[key] = value
90
+ print(f" 🔧 {key} = {value}")
91
+
92
+ # Cria o diretório
93
+ try:
94
+ Path(value).mkdir(parents=True, exist_ok=True)
95
+ print(f" ✅ Diretório criado: {value}")
96
+ except Exception as e:
97
+ print(f" ❌ Erro ao criar {value}: {e}")
98
+
99
+ def check_imported_modules():
100
+ """Verifica módulos importados que podem estar usando caminhos hardcoded"""
101
+ print(f"\n🔍 === MÓDULOS IMPORTADOS ===")
102
+
103
+ problematic_modules = []
104
+
105
+ for name, module in sys.modules.items():
106
+ if module and hasattr(module, '__file__') and module.__file__:
107
+ try:
108
+ # Lê o código fonte se disponível
109
+ source = inspect.getsource(module)
110
+ if '/code/thumbnails' in source:
111
+ problematic_modules.append((name, module.__file__))
112
+ print(f" 🎯 MÓDULO PROBLEMÁTICO: {name} ({module.__file__})")
113
+ except:
114
+ pass # Não conseguiu obter source
115
+
116
+ return problematic_modules
117
+
118
+ def monkey_patch_paths():
119
+ """Força patch de qualquer referência a /code/thumbnails"""
120
+ print(f"\n🐒 === MONKEY PATCHING ===")
121
+
122
+ # Patch em os.path e pathlib
123
+ original_exists = os.path.exists
124
+ original_makedirs = os.makedirs
125
+ original_mkdir = Path.mkdir
126
+
127
+ def patched_exists(path):
128
+ if isinstance(path, str) and '/code/thumbnails' in path:
129
+ new_path = path.replace('/code/thumbnails', '/tmp/thumbnails')
130
+ print(f" 🔧 PATCH exists: {path} -> {new_path}")
131
+ return original_exists(new_path)
132
+ return original_exists(path)
133
+
134
+ def patched_makedirs(name, mode=0o777, exist_ok=False):
135
+ if isinstance(name, str) and '/code/thumbnails' in name:
136
+ new_name = name.replace('/code/thumbnails', '/tmp/thumbnails')
137
+ print(f" 🔧 PATCH makedirs: {name} -> {new_name}")
138
+ return original_makedirs(new_name, mode, exist_ok)
139
+ return original_makedirs(name, mode, exist_ok)
140
+
141
+ # Aplica patches
142
+ os.path.exists = patched_exists
143
+ os.makedirs = patched_makedirs
144
+
145
+ print(" ✅ Patches aplicados!")
146
+
147
+ if __name__ == "__main__":
148
+ try:
149
+ debug_all_paths()
150
+ check_imported_modules()
151
+ monkey_patch_paths()
152
+
153
+ print(f"\n✅ === DEBUG CONCLUÍDO ===")
154
+
155
+ # Testa importação após patches
156
+ print(f"\n🧪 TESTANDO IMPORTAÇÃO APÓS PATCHES:")
157
+ try:
158
+ from scripts.similarity_search import SimilaritySearcher
159
+ print(" ✅ SimilaritySearcher importado com sucesso!")
160
+
161
+ # Tenta inicializar
162
+ searcher = SimilaritySearcher()
163
+ print(" ✅ SimilaritySearcher inicializado com sucesso!")
164
+
165
+ except Exception as e:
166
+ print(f" ❌ Erro na importação/inicialização: {e}")
167
+ traceback.print_exc()
168
+
169
+ except Exception as e:
170
+ print(f"❌ ERRO NO DEBUG: {e}")
171
+ traceback.print_exc()
force_clean.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import sys
4
+ import shutil
5
+ import importlib
6
+ from pathlib import Path
7
+
8
+ def force_clean_environment():
9
+ """Força limpeza completa do ambiente"""
10
+ print("🧹 === LIMPEZA FORÇADA DO AMBIENTE ===")
11
+
12
+ # 1. Remove todos os módulos Python importados
13
+ print("\n🔄 LIMPANDO CACHE DE MÓDULOS:")
14
+ modules_to_remove = []
15
+ for name in sys.modules.keys():
16
+ if any(keyword in name.lower() for keyword in ['similarity', 'image', 'jewelry', 'processor']):
17
+ modules_to_remove.append(name)
18
+
19
+ for name in modules_to_remove:
20
+ if name in sys.modules:
21
+ del sys.modules[name]
22
+ print(f" 🗑️ Removido: {name}")
23
+
24
+ # 2. Limpa cache Python
25
+ print("\n🧹 LIMPANDO CACHE PYTHON:")
26
+ cache_dirs = [
27
+ "./__pycache__",
28
+ "./scripts/__pycache__",
29
+ os.path.expanduser("~/.cache"),
30
+ "/tmp/.cache",
31
+ "/tmp/pip-cache"
32
+ ]
33
+
34
+ for cache_dir in cache_dirs:
35
+ try:
36
+ if os.path.exists(cache_dir):
37
+ shutil.rmtree(cache_dir)
38
+ print(f" 🗑️ Removido: {cache_dir}")
39
+ except Exception as e:
40
+ print(f" ⚠️ Erro ao remover {cache_dir}: {e}")
41
+
42
+ # 3. Força variáveis de ambiente
43
+ print("\n⚙️ CONFIGURANDO VARIÁVEIS (FORÇADO):")
44
+
45
+ env_vars = {
46
+ 'THUMBNAILS_PATH': '/tmp/thumbnails',
47
+ 'DATA_PATH': '/tmp/data',
48
+ 'TEMP_PATH': '/tmp/temp',
49
+ 'MODELS_PATH': '/tmp/models',
50
+ 'CACHE_DIR': '/tmp/cache',
51
+ 'HOME': '/tmp/home',
52
+ 'TMPDIR': '/tmp',
53
+ 'TMP': '/tmp',
54
+ 'TEMP': '/tmp',
55
+ 'PYTORCH_CACHE_DIR': '/tmp/pytorch',
56
+ 'HUGGINGFACE_HUB_CACHE': '/tmp/huggingface',
57
+ 'TRANSFORMERS_CACHE': '/tmp/transformers'
58
+ }
59
+
60
+ for key, value in env_vars.items():
61
+ os.environ[key] = value
62
+
63
+ # Cria diretório
64
+ try:
65
+ Path(value).mkdir(parents=True, exist_ok=True)
66
+ print(f" ✅ {key} = {value}")
67
+ except Exception as e:
68
+ print(f" ❌ {key} = {value} (erro: {e})")
69
+
70
+ # 4. Monkey patch global de caminhos
71
+ print("\n🐒 APLICANDO MONKEY PATCHES GLOBAIS:")
72
+
73
+ # Patch para os.makedirs
74
+ _original_makedirs = os.makedirs
75
+ def patched_makedirs(name, mode=0o777, exist_ok=False):
76
+ if isinstance(name, str):
77
+ name = name.replace('/code/thumbnails', '/tmp/thumbnails')
78
+ name = name.replace('/code/', '/tmp/')
79
+ return _original_makedirs(name, mode, exist_ok)
80
+
81
+ # Patch para Path.mkdir
82
+ _original_path_mkdir = Path.mkdir
83
+ def patched_path_mkdir(self, mode=0o777, parents=False, exist_ok=False):
84
+ new_path = str(self).replace('/code/thumbnails', '/tmp/thumbnails').replace('/code/', '/tmp/')
85
+ new_self = Path(new_path)
86
+ return _original_path_mkdir(new_self, mode, parents, exist_ok)
87
+
88
+ # Patch para open()
89
+ _original_open = open
90
+ def patched_open(file, mode='r', **kwargs):
91
+ if isinstance(file, str):
92
+ file = file.replace('/code/thumbnails', '/tmp/thumbnails')
93
+ file = file.replace('/code/', '/tmp/')
94
+ return _original_open(file, mode, **kwargs)
95
+
96
+ # Aplica os patches
97
+ os.makedirs = patched_makedirs
98
+ Path.mkdir = patched_path_mkdir
99
+ __builtins__['open'] = patched_open
100
+
101
+ print(" ✅ Patches aplicados globalmente!")
102
+
103
+ # 5. Cria estrutura de diretórios
104
+ print("\n📁 CRIANDO ESTRUTURA DE DIRETÓRIOS:")
105
+
106
+ required_dirs = [
107
+ '/tmp/thumbnails',
108
+ '/tmp/data',
109
+ '/tmp/temp',
110
+ '/tmp/models',
111
+ '/tmp/cache',
112
+ '/tmp/pytorch',
113
+ '/tmp/huggingface',
114
+ '/tmp/transformers'
115
+ ]
116
+
117
+ for dir_path in required_dirs:
118
+ try:
119
+ Path(dir_path).mkdir(parents=True, exist_ok=True)
120
+ # Testa escrita
121
+ test_file = Path(dir_path) / 'test.txt'
122
+ test_file.write_text('test')
123
+ test_file.unlink()
124
+ print(f" ✅ {dir_path}")
125
+ except Exception as e:
126
+ print(f" ❌ {dir_path}: {e}")
127
+
128
+ def restart_imports():
129
+ """Reinicia importações com ambiente limpo"""
130
+ print("\n🔄 === REINICIANDO IMPORTAÇÕES ===")
131
+
132
+ try:
133
+ # Força reload do sys.path
134
+ if '/tmp' not in sys.path:
135
+ sys.path.insert(0, '/tmp')
136
+
137
+ # Importa com ambiente limpo
138
+ print(" 🔄 Importando SimilaritySearcher...")
139
+ from scripts.similarity_search import SimilaritySearcher
140
+
141
+ print(" 🔄 Inicializando SimilaritySearcher...")
142
+ searcher = SimilaritySearcher()
143
+
144
+ print(" ✅ Sucesso! SimilaritySearcher funcionando!")
145
+ return searcher
146
+
147
+ except Exception as e:
148
+ print(f" ❌ Erro: {e}")
149
+ import traceback
150
+ traceback.print_exc()
151
+ return None
152
+
153
+ if __name__ == "__main__":
154
+ force_clean_environment()
155
+ searcher = restart_imports()
156
+
157
+ if searcher:
158
+ print("\n🎉 === LIMPEZA BEM-SUCEDIDA ===")
159
+ else:
160
+ print("\n❌ === LIMPEZA FALHOU ===")
161
+ print("Execute o debug_paths.py para mais informações")