Spaces:
Sleeping
Sleeping
File size: 14,292 Bytes
7f335a2 | 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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | # 🔧 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! |