CoolFace
Apppublic

OctusTech/cartalogo-api

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
debug_paths.py171 linesDownload Raw Back to root
1#!/usr/bin/env python32import os3import sys4import traceback5from pathlib import Path6import inspect7 8def 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 ambiente13    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ões19    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órios24    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 arquivo36            test_file = Path(test_dir) / "test.txt"37            test_file.write_text("test")38            test_file.unlink()  # Remove o arquivo39            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/thumbnails44    print(f"\n🔍 PROCURANDO REFERÊNCIAS A '/code/thumbnails':")45    search_paths = [46        ".",47        "./scripts",48        sys.path49    ]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ência64                                        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áveis74    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] = value90        print(f"  🔧 {key} = {value}")91        92        # Cria o diretório93        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 99def 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ível109                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 source115    116    return problematic_modules117 118def 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 pathlib123    original_exists = os.path.exists124    original_makedirs = os.makedirs125    original_mkdir = Path.mkdir126    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 patches142    os.path.exists = patched_exists143    os.makedirs = patched_makedirs144    145    print("  ✅ Patches aplicados!")146 147if __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 patches156        print(f"\n🧪 TESTANDO IMPORTAÇÃO APÓS PATCHES:")157        try:158            from scripts.similarity_search import SimilaritySearcher159            print("  ✅ SimilaritySearcher importado com sucesso!")160            161            # Tenta inicializar162            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()