Spaces:
Sleeping
Sleeping
Download debug_paths.py from OctusTech/cartalogo-api: direct link, hf CLI and curl.
- Browser
- Download file 6.43 kB
-
https://huggingface.co/spaces/OctusTech/cartalogo-api/resolve/main/debug_paths.py
- Command line
-
hf download hf://spaces/OctusTech/cartalogo-api/debug_paths.py
-
curl -L -o debug_paths.py https://huggingface.co/spaces/OctusTech/cartalogo-api/resolve/main/debug_paths.py
6.43 kB
| #!/usr/bin/env python3 | |
| import os | |
| import sys | |
| import traceback | |
| from pathlib import Path | |
| import inspect | |
| def debug_all_paths(): | |
| """Debug completo de todos os caminhos e variáveis""" | |
| print("🔍 === DEBUG COMPLETO DE CAMINHOS ===") | |
| # 1. Variáveis de ambiente | |
| print("\n📋 VARIÁVEIS DE AMBIENTE:") | |
| for key, value in os.environ.items(): | |
| if 'path' in key.lower() or 'dir' in key.lower() or 'thumbnails' in key.lower(): | |
| print(f" {key} = {value}") | |
| # 2. Diretório atual e permissões | |
| print(f"\n📁 DIRETÓRIO ATUAL: {os.getcwd()}") | |
| print(f"📁 DIRETÓRIO HOME: {os.path.expanduser('~')}") | |
| print(f"📁 TEMP DIR: {os.path.join(os.sep, 'tmp')}") | |
| # 3. Testa criação de diretórios | |
| test_dirs = [ | |
| "/tmp/thumbnails", | |
| "/tmp/test_dir", | |
| "/code/test_write", | |
| "./test_local" | |
| ] | |
| print(f"\n🧪 TESTE DE PERMISSÕES:") | |
| for test_dir in test_dirs: | |
| try: | |
| Path(test_dir).mkdir(parents=True, exist_ok=True) | |
| # Tenta escrever um arquivo | |
| test_file = Path(test_dir) / "test.txt" | |
| test_file.write_text("test") | |
| test_file.unlink() # Remove o arquivo | |
| print(f" ✅ {test_dir} - OK (leitura/escrita)") | |
| except Exception as e: | |
| print(f" ❌ {test_dir} - ERRO: {e}") | |
| # 4. Procura por referências a /code/thumbnails | |
| print(f"\n🔍 PROCURANDO REFERÊNCIAS A '/code/thumbnails':") | |
| search_paths = [ | |
| ".", | |
| "./scripts", | |
| sys.path | |
| ] | |
| for search_path in search_paths: | |
| if isinstance(search_path, str) and os.path.exists(search_path): | |
| try: | |
| for root, dirs, files in os.walk(search_path): | |
| for file in files: | |
| if file.endswith('.py'): | |
| file_path = os.path.join(root, file) | |
| try: | |
| with open(file_path, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| if '/code/thumbnails' in content: | |
| print(f" 🎯 ENCONTRADO em: {file_path}") | |
| # Mostra as linhas que contêm a referência | |
| lines = content.split('\n') | |
| for i, line in enumerate(lines, 1): | |
| if '/code/thumbnails' in line: | |
| print(f" Linha {i}: {line.strip()}") | |
| except Exception as e: | |
| print(f" ⚠️ Erro ao ler {file_path}: {e}") | |
| except Exception as e: | |
| print(f" ⚠️ Erro ao explorar {search_path}: {e}") | |
| # 5. Força configuração de todas as variáveis | |
| print(f"\n⚙️ FORÇANDO CONFIGURAÇÕES:") | |
| forced_configs = { | |
| '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' | |
| } | |
| for key, value in forced_configs.items(): | |
| os.environ[key] = value | |
| print(f" 🔧 {key} = {value}") | |
| # Cria o diretório | |
| try: | |
| Path(value).mkdir(parents=True, exist_ok=True) | |
| print(f" ✅ Diretório criado: {value}") | |
| except Exception as e: | |
| print(f" ❌ Erro ao criar {value}: {e}") | |
| def check_imported_modules(): | |
| """Verifica módulos importados que podem estar usando caminhos hardcoded""" | |
| print(f"\n🔍 === MÓDULOS IMPORTADOS ===") | |
| problematic_modules = [] | |
| for name, module in sys.modules.items(): | |
| if module and hasattr(module, '__file__') and module.__file__: | |
| try: | |
| # Lê o código fonte se disponível | |
| source = inspect.getsource(module) | |
| if '/code/thumbnails' in source: | |
| problematic_modules.append((name, module.__file__)) | |
| print(f" 🎯 MÓDULO PROBLEMÁTICO: {name} ({module.__file__})") | |
| except: | |
| pass # Não conseguiu obter source | |
| return problematic_modules | |
| def monkey_patch_paths(): | |
| """Força patch de qualquer referência a /code/thumbnails""" | |
| print(f"\n🐒 === MONKEY PATCHING ===") | |
| # Patch em os.path e pathlib | |
| original_exists = os.path.exists | |
| original_makedirs = os.makedirs | |
| original_mkdir = Path.mkdir | |
| def patched_exists(path): | |
| if isinstance(path, str) and '/code/thumbnails' in path: | |
| new_path = path.replace('/code/thumbnails', '/tmp/thumbnails') | |
| print(f" 🔧 PATCH exists: {path} -> {new_path}") | |
| return original_exists(new_path) | |
| return original_exists(path) | |
| def patched_makedirs(name, mode=0o777, exist_ok=False): | |
| if isinstance(name, str) and '/code/thumbnails' in name: | |
| new_name = name.replace('/code/thumbnails', '/tmp/thumbnails') | |
| print(f" 🔧 PATCH makedirs: {name} -> {new_name}") | |
| return original_makedirs(new_name, mode, exist_ok) | |
| return original_makedirs(name, mode, exist_ok) | |
| # Aplica patches | |
| os.path.exists = patched_exists | |
| os.makedirs = patched_makedirs | |
| print(" ✅ Patches aplicados!") | |
| if __name__ == "__main__": | |
| try: | |
| debug_all_paths() | |
| check_imported_modules() | |
| monkey_patch_paths() | |
| print(f"\n✅ === DEBUG CONCLUÍDO ===") | |
| # Testa importação após patches | |
| print(f"\n🧪 TESTANDO IMPORTAÇÃO APÓS PATCHES:") | |
| try: | |
| from scripts.similarity_search import SimilaritySearcher | |
| print(" ✅ SimilaritySearcher importado com sucesso!") | |
| # Tenta inicializar | |
| searcher = SimilaritySearcher() | |
| print(" ✅ SimilaritySearcher inicializado com sucesso!") | |
| except Exception as e: | |
| print(f" ❌ Erro na importação/inicialização: {e}") | |
| traceback.print_exc() | |
| except Exception as e: | |
| print(f"❌ ERRO NO DEBUG: {e}") | |
| traceback.print_exc() |