Spaces:
Configuration error
Configuration error
| #!/usr/bin/env python3 | |
| """ | |
| Script di setup per l'ambiente Financial Transformer | |
| """ | |
| import subprocess | |
| import sys | |
| import os | |
| import platform | |
| def run_command(command, description=""): | |
| """Esegue un comando e gestisce gli errori""" | |
| print(f"π¦ {description}") | |
| try: | |
| result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True) | |
| print(f"β {description} - Completato") | |
| return True | |
| except subprocess.CalledProcessError as e: | |
| print(f"β {description} - Errore:") | |
| print(f" {e.stderr}") | |
| return False | |
| def check_python_version(): | |
| """Verifica la versione di Python""" | |
| version = sys.version_info | |
| print(f"π Python version: {version.major}.{version.minor}.{version.micro}") | |
| if version.major < 3 or (version.major == 3 and version.minor < 8): | |
| print("β Python 3.8+ richiesto") | |
| return False | |
| print("β Versione Python compatibile") | |
| return True | |
| def detect_system(): | |
| """Rileva il sistema operativo""" | |
| system = platform.system().lower() | |
| print(f"π» Sistema operativo: {system}") | |
| return system | |
| def install_torch_optimized(): | |
| """Installa PyTorch con ottimizzazioni per il sistema""" | |
| system = detect_system() | |
| if system == "linux": | |
| # Prova CUDA se disponibile | |
| if run_command("nvidia-smi", "Verifica CUDA"): | |
| print("π CUDA rilevato, installando PyTorch con supporto GPU") | |
| return run_command( | |
| "pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118", | |
| "Installazione PyTorch con CUDA" | |
| ) | |
| else: | |
| print("π» CPU only, installando PyTorch CPU") | |
| return run_command( | |
| "pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu", | |
| "Installazione PyTorch CPU" | |
| ) | |
| elif system == "darwin": # macOS | |
| print("π macOS rilevato, installando PyTorch") | |
| return run_command( | |
| "pip install torch torchvision torchaudio", | |
| "Installazione PyTorch per macOS" | |
| ) | |
| else: # Windows e altri | |
| print("πͺ Sistema generico, installando PyTorch") | |
| return run_command( | |
| "pip install torch torchvision torchaudio", | |
| "Installazione PyTorch generico" | |
| ) | |
| def create_virtual_environment(): | |
| """Crea un ambiente virtuale""" | |
| venv_name = "financial_transformer_env" | |
| if not os.path.exists(venv_name): | |
| print(f"ποΈ Creando ambiente virtuale: {venv_name}") | |
| if run_command(f"python -m venv {venv_name}", "Creazione ambiente virtuale"): | |
| print(f"β Ambiente virtuale creato: {venv_name}") | |
| # Istruzioni per attivazione | |
| system = detect_system() | |
| if system == "windows": | |
| activate_cmd = f"{venv_name}\\Scripts\\activate" | |
| else: | |
| activate_cmd = f"source {venv_name}/bin/activate" | |
| print(f"π§ Per attivare l'ambiente virtuale:") | |
| print(f" {activate_cmd}") | |
| return True | |
| else: | |
| print(f"β Ambiente virtuale giΓ esistente: {venv_name}") | |
| return True | |
| return False | |
| def install_requirements(): | |
| """Installa i requirements""" | |
| # Aggiorna pip | |
| run_command("pip install --upgrade pip", "Aggiornamento pip") | |
| # Installa PyTorch ottimizzato | |
| if not install_torch_optimized(): | |
| print("β Errore nell'installazione di PyTorch") | |
| return False | |
| # Installa altri requirements | |
| requirements = [ | |
| ("transformers>=4.30.0", "Hugging Face Transformers"), | |
| ("numpy>=1.21.0", "NumPy"), | |
| ("pandas>=1.3.0", "Pandas"), | |
| ("yfinance>=0.2.0", "Yahoo Finance"), | |
| ("requests>=2.25.0", "Requests"), | |
| ("scipy>=1.7.0", "SciPy"), | |
| ("scikit-learn>=1.0.0", "Scikit-learn"), | |
| ("accelerate>=0.20.0", "Accelerate"), | |
| ("tokenizers>=0.13.0", "Tokenizers"), | |
| ("tqdm>=4.62.0", "Progress bars"), | |
| ("python-dateutil>=2.8.0", "Date utilities"), | |
| ("matplotlib>=3.5.0", "Matplotlib"), | |
| ("seaborn>=0.11.0", "Seaborn"), | |
| ] | |
| failed_installs = [] | |
| for package, description in requirements: | |
| if not run_command(f"pip install {package}", f"Installazione {description}"): | |
| failed_installs.append(package) | |
| if failed_installs: | |
| print(f"\nβ Pacchetti non installati:") | |
| for package in failed_installs: | |
| print(f" - {package}") | |
| return False | |
| return True | |
| def verify_installation(): | |
| """Verifica l'installazione""" | |
| print("\nπ Verifica installazione...") | |
| test_imports = [ | |
| ("torch", "PyTorch"), | |
| ("transformers", "Hugging Face Transformers"), | |
| ("numpy", "NumPy"), | |
| ("pandas", "Pandas"), | |
| ("yfinance", "Yahoo Finance"), | |
| ] | |
| failed_imports = [] | |
| for module, description in test_imports: | |
| try: | |
| __import__(module) | |
| print(f"β {description}") | |
| except ImportError as e: | |
| print(f"β {description}: {e}") | |
| failed_imports.append(module) | |
| if failed_imports: | |
| print(f"\nβ Moduli non importabili:") | |
| for module in failed_imports: | |
| print(f" - {module}") | |
| return False | |
| print("\nβ Tutti i moduli principali sono installati correttamente!") | |
| return True | |
| def create_test_script(): | |
| """Crea uno script di test""" | |
| test_script = '''#!/usr/bin/env python3 | |
| """ | |
| Script di test per verificare l'installazione | |
| """ | |
| import sys | |
| import torch | |
| import transformers | |
| import yfinance as yf | |
| import pandas as pd | |
| import numpy as np | |
| def test_torch(): | |
| """Test PyTorch""" | |
| print("π₯ Testing PyTorch...") | |
| x = torch.randn(2, 3) | |
| y = torch.randn(2, 3) | |
| z = x + y | |
| print(f" Tensor operation: {z.shape}") | |
| if torch.cuda.is_available(): | |
| print(f" CUDA available: {torch.cuda.device_count()} devices") | |
| else: | |
| print(" CUDA not available (CPU only)") | |
| print("β PyTorch OK") | |
| def test_transformers(): | |
| """Test Hugging Face""" | |
| print("π€ Testing Transformers...") | |
| from transformers import AutoTokenizer | |
| try: | |
| tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased") | |
| tokens = tokenizer("Hello, world!") | |
| print(f" Tokenized: {len(tokens['input_ids'])} tokens") | |
| print("β Transformers OK") | |
| except Exception as e: | |
| print(f"β Transformers error: {e}") | |
| def test_yfinance(): | |
| """Test Yahoo Finance""" | |
| print("π° Testing yfinance...") | |
| try: | |
| ticker = yf.Ticker("AAPL") | |
| info = ticker.info | |
| print(f" AAPL current price: ${info.get('currentPrice', 'N/A')}") | |
| print("β yfinance OK") | |
| except Exception as e: | |
| print(f"β yfinance error: {e}") | |
| def main(): | |
| print("π§ͺ Financial Transformer - Test Suite") | |
| print("=" * 40) | |
| test_torch() | |
| test_transformers() | |
| test_yfinance() | |
| print("\\nπ Test completato!") | |
| if __name__ == "__main__": | |
| main() | |
| ''' | |
| with open("test_installation.py", "w") as f: | |
| f.write(test_script) | |
| print("β Script di test creato: test_installation.py") | |
| def main(): | |
| """Funzione principale""" | |
| print("π Financial Transformer - Setup") | |
| print("=" * 40) | |
| # Verifica Python | |
| if not check_python_version(): | |
| sys.exit(1) | |
| # Rileva sistema | |
| detect_system() | |
| # Opzionale: crea ambiente virtuale | |
| print("\nπ¦ Vuoi creare un ambiente virtuale? (y/n): ", end="") | |
| if input().lower().startswith('y'): | |
| create_virtual_environment() | |
| print("\nβ οΈ Attiva l'ambiente virtuale e riavvia questo script") | |
| return | |
| # Installa requirements | |
| print("\nπ¦ Installazione dipendenze...") | |
| if not install_requirements(): | |
| print("β Errore nell'installazione") | |
| sys.exit(1) | |
| # Verifica installazione | |
| if not verify_installation(): | |
| print("β Verifica fallita") | |
| sys.exit(1) | |
| # Crea script di test | |
| create_test_script() | |
| print("\nπ Setup completato!") | |
| print("π§ͺ Esegui: python test_installation.py") | |
| print("π Esegui: python app.py") | |
| if __name__ == "__main__": | |
| main() |