teste / docs /troubleshooting.md
torxyton's picture
Initial commit: Complete Fibonacci analysis application with Gradio interface
7f335a2
# 🔧 Guia de Troubleshooting
## Visão Geral
Este guia ajuda a resolver problemas comuns encontrados ao usar o Vampire Trading Bot. Os problemas estão organizados por categoria com soluções passo a passo.
## 🚨 Problemas de Instalação
### Erro: "Microsoft Visual C++ 14.0 is required"
**Sintomas**:
```
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools"
```
**Causa**: Falta de ferramentas de compilação no Windows.
**Solução**:
1. Baixe e instale o [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/)
2. Durante a instalação, selecione "C++ build tools"
3. Reinicie o terminal e tente novamente:
```bash
pip install -r requirements.txt
```
### Erro: "No module named 'pyaudioop'"
**Sintomas**:
```
ModuleNotFoundError: No module named 'pyaudioop'
```
**Causa**: Incompatibilidade com Python 3.13.
**Solução**:
```bash
# Atualizar Gradio para versão mais recente
pip install --upgrade gradio
# Verificar se audioop-lts foi instalado
pip list | grep audioop
```
### Erro: "Failed building wheel for tokenizers"
**Sintomas**:
```
Failed building wheel for tokenizers
ERROR: Could not build wheels for tokenizers
```
**Causa**: Falta do compilador Rust.
**Soluções**:
**Opção 1 - Usar versão pré-compilada**:
```bash
pip install --upgrade transformers
```
**Opção 2 - Instalar Rust**:
```bash
# Windows (PowerShell)
Invoke-WebRequest -Uri https://win.rustup.rs/ -OutFile rustup-init.exe
.\rustup-init.exe
# Linux/macOS
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env
```
### Erro: "Permission denied" (Windows)
**Sintomas**:
```
PermissionError: [WinError 5] Access is denied
```
**Solução**:
```powershell
# Alterar política de execução
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# Executar como administrador se necessário
```
## 🤖 Problemas com Modelos de IA
### Erro: "OutOfMemoryError" ao carregar modelo
**Sintomas**:
```
torch.cuda.OutOfMemoryError: CUDA out of memory
# ou
RuntimeError: [enforce fail at alloc_cpu.cpp:75]
```
**Soluções**:
**1. Usar modelo mais leve**:
```python
# Em config.py
FinancialModels.DEFAULT_MODEL = "nlptown/bert-base-multilingual-uncased-sentiment"
```
**2. Reduzir tamanho do texto**:
```python
# Em config.py
AIConfig.MAX_TEXT_LENGTH = 256 # Reduzir de 512
AIConfig.BATCH_SIZE = 4 # Reduzir de 8
```
**3. Forçar uso de CPU**:
```python
# Em config.py
AIConfig.USE_GPU = False
```
**4. Executar em modo standalone**:
```bash
python app.py --no-ai
```
### Erro: "Model not found" ou "Repository not found"
**Sintomas**:
```
OSError: Repository not found
HTTPError: 404 Client Error
```
**Soluções**:
**1. Verificar conectividade**:
```python
import requests
response = requests.get("https://huggingface.co")
print(f"Status: {response.status_code}")
```
**2. Usar modelo alternativo**:
```python
# Em config.py
FinancialModels.DEFAULT_MODEL = "cardiffnlp/twitter-roberta-base-sentiment-latest"
```
**3. Cache offline**:
```bash
# Baixar modelo manualmente
from transformers import pipeline
pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment")
```
### Modelo carrega muito lentamente
**Sintomas**: Demora excessiva no primeiro carregamento.
**Soluções**:
**1. Habilitar cache**:
```python
# Em config.py
AIConfig.ENABLE_MODEL_CACHE = True
AIConfig.CACHE_SIZE = 100
```
**2. Pré-carregar modelos**:
```python
# Adicionar ao início do app.py
from sentiment_analysis import SentimentAnalysisEngine
engine = SentimentAnalysisEngine()
engine.model_manager.load_model() # Pré-carrega
```
**3. Usar modelo local**:
```bash
# Baixar modelo para pasta local
mkdir models
# Configurar caminho local em config.py
```
## 🖥️ Problemas de Interface
### Interface não carrega (erro 500)
**Sintomas**: Página em branco ou erro 500 no navegador.
**Diagnóstico**:
```bash
# Verificar logs no terminal
python -u app.py
# Verificar porta
netstat -an | findstr 7860
```
**Soluções**:
**1. Verificar dependências**:
```python
try:
import gradio as gr
print(f"Gradio versão: {gr.__version__}")
except ImportError as e:
print(f"Erro ao importar Gradio: {e}")
```
**2. Usar porta diferente**:
```bash
python app.py --server_port=8080
```
**3. Modo debug**:
```python
# Em app.py
demo.launch(debug=True, show_error=True)
```
### Interface trava durante análise
**Sintomas**: Interface não responde após submeter análise.
**Soluções**:
**1. Verificar timeout**:
```python
# Em config.py
AIConfig.MODEL_LOAD_TIMEOUT = 120 # Aumentar timeout
```
**2. Adicionar indicador de progresso**:
```python
# Em ui.py
def analyze_with_progress(text):
yield "🔄 Iniciando análise..."
# ... análise
yield "✅ Análise concluída!"
```
**3. Processamento assíncrono**:
```python
import asyncio
async def async_analysis(text):
# Análise em background
pass
```
### Erro: "Connection refused" ou "Address already in use"
**Sintomas**:
```
OSError: [Errno 98] Address already in use
ConnectionRefusedError: [Errno 111] Connection refused
```
**Soluções**:
**1. Verificar processos na porta**:
```bash
# Windows
netstat -ano | findstr :7860
taskkill /PID <PID> /F
# Linux/macOS
lsof -ti:7860 | xargs kill -9
```
**2. Usar porta diferente**:
```bash
python app.py --server_port=8080
```
## 📊 Problemas de Performance
### Alto uso de CPU/Memória
**Sintomas**: Sistema lento, ventilador alto.
**Diagnóstico**:
```python
# Verificar uso de recursos
from performance_monitor import PerformanceMonitor
monitor = PerformanceMonitor()
monitor.start_monitoring()
print(monitor.get_current_metrics())
```
**Soluções**:
**1. Otimizar configurações**:
```python
# Em config.py
AIConfig.MAX_TEXT_LENGTH = 256
AIConfig.BATCH_SIZE = 2
AIConfig.USE_GPU = False
```
**2. Limitar histórico**:
```python
# Em performance_monitor.py
PerformanceMonitor(max_metrics_history=100)
```
**3. Desabilitar recursos**:
```python
# Desabilitar monitoramento em tempo real
real_time_integration = None
```
### Análises muito lentas
**Sintomas**: Demora excessiva para gerar resultados.
**Soluções**:
**1. Profile de performance**:
```python
import cProfile
def profile_analysis():
cProfile.run('engine.analyze_market_data(text)')
```
**2. Cache de resultados**:
```python
from functools import lru_cache
@lru_cache(maxsize=100)
def cached_analysis(text_hash):
return engine.analyze_market_data(text)
```
**3. Processamento paralelo**:
```python
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as executor:
future = executor.submit(analyze_function, text)
result = future.result(timeout=30)
```
## 📁 Problemas de Arquivos e Logs
### Erro: "File not found" para logs
**Sintomas**:
```
FileNotFoundError: [Errno 2] No such file or directory: 'trading.log'
```
**Soluções**:
**1. Verificar caminho**:
```python
from pathlib import Path
log_path = Path("d:/hugging_face_spaces/text")
print(f"Existe: {log_path.exists()}")
print(f"É arquivo: {log_path.is_file()}")
```
**2. Criar arquivo de exemplo**:
```python
# Criar log de exemplo para testes
with open("sample_log.txt", "w") as f:
f.write("""⏰ Análise #1 - 09:46:58
📊 DADOS DE MERCADO - WINV25
Preço Atual: 140135.00000 ↗
""")
```
**3. Configurar caminho correto**:
```python
# Em real_time_integration.py
LOG_FILE_PATH = "caminho/correto/para/logs.txt"
```
### Erro de permissão em arquivos
**Sintomas**:
```
PermissionError: [Errno 13] Permission denied
```
**Soluções**:
**1. Verificar permissões**:
```bash
# Linux/macOS
ls -la arquivo.log
chmod 644 arquivo.log
# Windows
icacls arquivo.log
```
**2. Executar como administrador**:
```bash
# Windows (PowerShell como Admin)
python app.py
```
## 🔄 Problemas de Integração em Tempo Real
### FileWatcher não detecta mudanças
**Sintomas**: Logs atualizados mas sistema não processa.
**Diagnóstico**:
```python
from real_time_integration import FileWatcher
def test_callback(content):
print(f"Arquivo mudou: {len(content)} caracteres")
watcher = FileWatcher("test.txt", test_callback)
watcher.start()
```
**Soluções**:
**1. Verificar intervalo**:
```python
# Em real_time_integration.py
config = RealTimeConfig(
log_file_path="logs.txt",
check_interval=0.5 # Reduzir intervalo
)
```
**2. Forçar flush do arquivo**:
```python
# No sistema que gera logs
with open("logs.txt", "a") as f:
f.write("nova linha\n")
f.flush() # Forçar escrita
```
### Eventos duplicados
**Sintomas**: Mesmo evento processado múltiplas vezes.
**Solução**:
```python
# Adicionar deduplicação
class EventDeduplicator:
def __init__(self):
self.processed_events = set()
def is_duplicate(self, event_hash):
if event_hash in self.processed_events:
return True
self.processed_events.add(event_hash)
return False
```
## 🧪 Problemas de Desenvolvimento
### Erro ao importar módulos
**Sintomas**:
```
ModuleNotFoundError: No module named 'market_analysis'
```
**Soluções**:
**1. Verificar PYTHONPATH**:
```bash
# Windows
set PYTHONPATH=%PYTHONPATH%;D:\hugging_face_spaces
# Linux/macOS
export PYTHONPATH=$PYTHONPATH:/path/to/project
```
**2. Usar imports relativos**:
```python
# Em vez de
from market_analysis import TechnicalAnalysisEngine
# Use
from .market_analysis import TechnicalAnalysisEngine
```
**3. Adicionar ao sys.path**:
```python
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
```
### Erro de encoding
**Sintomas**:
```
UnicodeDecodeError: 'utf-8' codec can't decode
```
**Soluções**:
**1. Especificar encoding**:
```python
with open("arquivo.txt", "r", encoding="utf-8") as f:
content = f.read()
```
**2. Detectar encoding automaticamente**:
```python
import chardet
with open("arquivo.txt", "rb") as f:
raw_data = f.read()
encoding = chardet.detect(raw_data)['encoding']
content = raw_data.decode(encoding)
```
## 🔍 Ferramentas de Diagnóstico
### Script de Diagnóstico Completo
```python
#!/usr/bin/env python3
# diagnostic.py
import sys
import os
import importlib
import platform
import psutil
from pathlib import Path
def run_diagnostics():
print("🔍 DIAGNÓSTICO DO VAMPIRE TRADING BOT")
print("=" * 50)
# Sistema
print(f"🖥️ Sistema: {platform.system()} {platform.release()}")
print(f"🐍 Python: {sys.version}")
print(f"📁 Diretório: {os.getcwd()}")
# Recursos
print(f"💾 RAM: {psutil.virtual_memory().total // (1024**3)} GB")
print(f"🔥 CPU: {psutil.cpu_count()} cores")
# Dependências
print("\n📦 DEPENDÊNCIAS:")
dependencies = [
'gradio', 'transformers', 'torch',
'numpy', 'pandas', 'scipy', 'psutil'
]
for dep in dependencies:
try:
module = importlib.import_module(dep)
version = getattr(module, '__version__', 'N/A')
print(f"✅ {dep}: {version}")
except ImportError:
print(f"❌ {dep}: NÃO INSTALADO")
# Arquivos
print("\n📁 ARQUIVOS:")
files = [
'app.py', 'config.py', 'market_analysis.py',
'sentiment_analysis.py', 'ui.py', 'requirements.txt'
]
for file in files:
path = Path(file)
if path.exists():
size = path.stat().st_size
print(f"✅ {file}: {size} bytes")
else:
print(f"❌ {file}: NÃO ENCONTRADO")
# Teste de importação
print("\n🧪 TESTE DE IMPORTAÇÃO:")
modules = [
'market_analysis', 'sentiment_analysis',
'fibonacci_analysis', 'ui'
]
for module in modules:
try:
importlib.import_module(module)
print(f"✅ {module}: OK")
except Exception as e:
print(f"❌ {module}: {str(e)[:50]}...")
print("\n🏁 Diagnóstico concluído!")
if __name__ == "__main__":
run_diagnostics()
```
### Script de Teste de Performance
```python
#!/usr/bin/env python3
# performance_test.py
import time
import psutil
from memory_profiler import profile
@profile
def test_analysis_performance():
"""Testa performance das análises."""
# Simular análise técnica
start_time = time.time()
# Teste de análise
sample_text = "Preço: 140135, Variação: +5, Volume: 5023"
try:
from market_analysis import TechnicalAnalysisEngine
engine = TechnicalAnalysisEngine()
result = engine.analyze_market_data(sample_text)
end_time = time.time()
analysis_time = end_time - start_time
print(f"⏱️ Tempo de análise: {analysis_time:.2f}s")
print(f"💾 Uso de memória: {psutil.Process().memory_info().rss / 1024 / 1024:.1f} MB")
print(f"🔥 Uso de CPU: {psutil.cpu_percent()}%")
return True
except Exception as e:
print(f"❌ Erro na análise: {e}")
return False
if __name__ == "__main__":
test_analysis_performance()
```
## 📞 Obtendo Ajuda
### Informações para Suporte
Ao reportar problemas, inclua:
1. **Informações do sistema**:
```bash
python diagnostic.py > diagnostic_report.txt
```
2. **Logs de erro completos**:
```bash
python app.py > app_log.txt 2>&1
```
3. **Configurações utilizadas**:
```python
# Exportar configurações
from config import *
print(f"Modelo: {FinancialModels.DEFAULT_MODEL}")
print(f"RSI: {TechnicalAnalysis.RSI_PERIOD}")
```
### Recursos Adicionais
- 📚 [Documentação da Arquitetura](architecture.md)
- ⚙️ [Guia de Configuração](configuration.md)
- 🚀 [Guia de Instalação](installation.md)
- 📖 [Referência da API](api-reference.md)
- 👨‍💻 [Guia do Desenvolvedor](developer-guide.md)
### Comunidade e Suporte
- 🐛 **Issues**: Para reportar bugs
- 💬 **Discussões**: Para dúvidas gerais
- 📧 **Email**: Para suporte direto
- 📖 **Wiki**: Para documentação adicional
---
**💡 Dica**: Mantenha sempre uma cópia de backup das suas configurações antes de fazer alterações significativas!