""" Deployment script for Raspberry Pi Configures the application for optimal performance on resource-constrained devices """ import os import sys import subprocess from pathlib import Path def setup_optimized_environment(): """Set up environment variables for optimized mode""" print("Setting up optimized environment for Raspberry Pi...") # Set environment variables os.environ['FLASK_ENV'] = 'production' os.environ['OPTIMIZED_MODE'] = 'true' os.environ['FLASK_DEBUG'] = '0' os.environ['PYTHONOPTIMIZE'] = '2' # Remove docstrings and enable optimizations print("[OK] Environment variables set") def build_optimized_assets(): """Build optimized CSS assets""" print("Building optimized assets...") # Check if build script exists build_script = 'build-optimized.bat' if sys.platform == 'win32' else './build-optimized.sh' if Path(build_script).exists(): try: subprocess.run([build_script], check=True, shell=True) print("[OK] Optimized assets built successfully") except subprocess.CalledProcessError as e: print(f"[WARNING] Asset build failed: {e}") else: print("[WARNING] Build script not found, skipping asset build") def create_app_runner(): """Create optimized app runner""" runner_content = '''#!/usr/bin/env python3 """ Optimized MYP Platform runner for Raspberry Pi """ import os os.environ['OPTIMIZED_MODE'] = 'true' os.environ['FLASK_ENV'] = 'production' from app import create_app from config_optimized import OptimizedConfig # Create app with optimized config app = create_app(OptimizedConfig) if __name__ == '__main__': # Run with optimized settings app.run( host='0.0.0.0', # Allow external connections port=5000, debug=False, use_reloader=False, # Disable reloader for performance threaded=True, # Enable threading for better performance processes=1 # Single process to save memory ) ''' with open('run_optimized.py', 'w') as f: f.write(runner_content) print("[OK] Created run_optimized.py") def create_systemd_service(): """Create systemd service file for auto-start""" service_content = '''[Unit] Description=MYP Platform Optimized for Raspberry Pi After=network.target [Service] Type=simple User=pi WorkingDirectory=/home/pi/myp-platform Environment="PATH=/home/pi/.local/bin:/usr/local/bin:/usr/bin:/bin" Environment="OPTIMIZED_MODE=true" Environment="FLASK_ENV=production" ExecStart=/usr/bin/python3 /home/pi/myp-platform/run_optimized.py Restart=always RestartSec=10 [Install] WantedBy=multi-user.target ''' with open('myp-platform.service', 'w') as f: f.write(service_content) print("[OK] Created systemd service file: myp-platform.service") print(" To install: sudo cp myp-platform.service /etc/systemd/system/") print(" To enable: sudo systemctl enable myp-platform.service") print(" To start: sudo systemctl start myp-platform.service") def create_nginx_config(): """Create nginx configuration for reverse proxy""" nginx_content = '''server { listen 80; server_name _; # Gzip compression gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json; # Static file caching location /static { alias /home/pi/myp-platform/static; expires 1y; add_header Cache-Control "public, immutable"; add_header Vary "Accept-Encoding"; } # Proxy to Flask app location / { proxy_pass http://127.0.0.1:5000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # Timeouts proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; } } ''' with open('nginx-myp-platform.conf', 'w') as f: f.write(nginx_content) print("[OK] Created nginx configuration: nginx-myp-platform.conf") print(" To install: sudo cp nginx-myp-platform.conf /etc/nginx/sites-available/myp-platform") print(" To enable: sudo ln -s /etc/nginx/sites-available/myp-platform /etc/nginx/sites-enabled/") print(" To reload: sudo nginx -s reload") def create_deployment_readme(): """Create deployment instructions""" readme_content = '''# Raspberry Pi Deployment Guide ## Prerequisites - Raspberry Pi 4 (recommended) or 3B+ - Raspbian OS (latest) - Python 3.7+ - nginx (optional, for production) ## Quick Start 1. **Clone the repository** ```bash git clone /home/pi/myp-platform cd /home/pi/myp-platform ``` 2. **Install dependencies** ```bash sudo apt-get update sudo apt-get install python3-pip python3-venv nginx python3 -m venv venv source venv/bin/activate pip install -r requirements.txt ``` 3. **Run deployment script** ```bash python deploy_raspberry_pi.py ``` 4. **Start the application** ```bash python run_optimized.py ``` ## Production Deployment 1. **Install as systemd service** ```bash sudo cp myp-platform.service /etc/systemd/system/ sudo systemctl daemon-reload sudo systemctl enable myp-platform sudo systemctl start myp-platform ``` 2. **Configure nginx (optional)** ```bash sudo cp nginx-myp-platform.conf /etc/nginx/sites-available/myp-platform sudo ln -s /etc/nginx/sites-available/myp-platform /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx ``` ## Performance Tips 1. **Use a fast SD card** (Class 10 or better) 2. **Enable swap** if you have less than 4GB RAM 3. **Use nginx** for serving static files 4. **Monitor temperature** and use cooling if needed 5. **Disable unnecessary services** to free up resources ## Monitoring Check application status: ```bash sudo systemctl status myp-platform ``` View logs: ```bash sudo journalctl -u myp-platform -f ``` ## Troubleshooting - If the app doesn't start, check logs with `journalctl` - Ensure all Python dependencies are installed - Check that port 5000 is not in use - Verify file permissions in the app directory ''' with open('RASPBERRY_PI_DEPLOYMENT.md', 'w') as f: f.write(readme_content) print("[OK] Created deployment guide: RASPBERRY_PI_DEPLOYMENT.md") def main(): """Main deployment function""" print("Raspberry Pi Deployment Setup") print("================================\n") # Run all setup steps setup_optimized_environment() build_optimized_assets() create_app_runner() create_systemd_service() create_nginx_config() create_deployment_readme() print("\n[OK] Deployment setup complete!") print("\nNext steps:") print("1. Review RASPBERRY_PI_DEPLOYMENT.md for detailed instructions") print("2. Test with: python run_optimized.py") print("3. Deploy as service for production use") if __name__ == '__main__': main()