File size: 5,191 Bytes
fef4203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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")