#!/usr/bin/env python3 import os import sys import shutil import importlib from pathlib import Path def force_clean_environment(): """Força limpeza completa do ambiente""" print("🧹 === LIMPEZA FORÇADA DO AMBIENTE ===") # 1. Remove todos os módulos Python importados print("\n🔄 LIMPANDO CACHE DE MÓDULOS:") modules_to_remove = [] for name in sys.modules.keys(): if any(keyword in name.lower() for keyword in ['similarity', 'image', 'jewelry', 'processor']): modules_to_remove.append(name) for name in modules_to_remove: if name in sys.modules: del sys.modules[name] print(f" 🗑️ Removido: {name}") # 2. Limpa cache Python print("\n🧹 LIMPANDO CACHE PYTHON:") cache_dirs = [ "./__pycache__", "./scripts/__pycache__", os.path.expanduser("~/.cache"), "/tmp/.cache", "/tmp/pip-cache" ] for cache_dir in cache_dirs: try: if os.path.exists(cache_dir): shutil.rmtree(cache_dir) print(f" 🗑️ Removido: {cache_dir}") except Exception as e: print(f" ⚠️ Erro ao remover {cache_dir}: {e}") # 3. Força variáveis de ambiente print("\n⚙️ CONFIGURANDO VARIÁVEIS (FORÇADO):") env_vars = { 'THUMBNAILS_PATH': '/tmp/thumbnails', 'DATA_PATH': '/tmp/data', 'TEMP_PATH': '/tmp/temp', 'MODELS_PATH': '/tmp/models', 'CACHE_DIR': '/tmp/cache', 'HOME': '/tmp/home', 'TMPDIR': '/tmp', 'TMP': '/tmp', 'TEMP': '/tmp', 'PYTORCH_CACHE_DIR': '/tmp/pytorch', 'HUGGINGFACE_HUB_CACHE': '/tmp/huggingface', 'TRANSFORMERS_CACHE': '/tmp/transformers' } for key, value in env_vars.items(): os.environ[key] = value # Cria diretório try: Path(value).mkdir(parents=True, exist_ok=True) print(f" ✅ {key} = {value}") except Exception as e: print(f" ❌ {key} = {value} (erro: {e})") # 4. Monkey patch global de caminhos print("\n🐒 APLICANDO MONKEY PATCHES GLOBAIS:") # Patch para os.makedirs _original_makedirs = os.makedirs def patched_makedirs(name, mode=0o777, exist_ok=False): if isinstance(name, str): name = name.replace('/code/thumbnails', '/tmp/thumbnails') name = name.replace('/code/', '/tmp/') return _original_makedirs(name, mode, exist_ok) # Patch para Path.mkdir _original_path_mkdir = Path.mkdir def patched_path_mkdir(self, mode=0o777, parents=False, exist_ok=False): new_path = str(self).replace('/code/thumbnails', '/tmp/thumbnails').replace('/code/', '/tmp/') new_self = Path(new_path) return _original_path_mkdir(new_self, mode, parents, exist_ok) # Patch para open() _original_open = open def patched_open(file, mode='r', **kwargs): if isinstance(file, str): file = file.replace('/code/thumbnails', '/tmp/thumbnails') file = file.replace('/code/', '/tmp/') return _original_open(file, mode, **kwargs) # Aplica os patches os.makedirs = patched_makedirs Path.mkdir = patched_path_mkdir __builtins__['open'] = patched_open print(" ✅ Patches aplicados globalmente!") # 5. Cria estrutura de diretórios print("\n📁 CRIANDO ESTRUTURA DE DIRETÓRIOS:") required_dirs = [ '/tmp/thumbnails', '/tmp/data', '/tmp/temp', '/tmp/models', '/tmp/cache', '/tmp/pytorch', '/tmp/huggingface', '/tmp/transformers' ] for dir_path in required_dirs: try: Path(dir_path).mkdir(parents=True, exist_ok=True) # Testa escrita test_file = Path(dir_path) / 'test.txt' test_file.write_text('test') test_file.unlink() print(f" ✅ {dir_path}") except Exception as e: print(f" ❌ {dir_path}: {e}") def restart_imports(): """Reinicia importações com ambiente limpo""" print("\n🔄 === REINICIANDO IMPORTAÇÕES ===") try: # Força reload do sys.path if '/tmp' not in sys.path: sys.path.insert(0, '/tmp') # Importa com ambiente limpo print(" 🔄 Importando SimilaritySearcher...") from scripts.similarity_search import SimilaritySearcher print(" 🔄 Inicializando SimilaritySearcher...") searcher = SimilaritySearcher() print(" ✅ Sucesso! SimilaritySearcher funcionando!") return searcher except Exception as e: print(f" ❌ Erro: {e}") import traceback traceback.print_exc() return None if __name__ == "__main__": force_clean_environment() searcher = restart_imports() if searcher: print("\n🎉 === LIMPEZA BEM-SUCEDIDA ===") else: print("\n❌ === LIMPEZA FALHOU ===") print("Execute o debug_paths.py para mais informações")