Spaces:
Running
Running
| #!/usr/bin/env python3 | |
| """ | |
| Startup script for Hugging Face Spaces deployment. | |
| This script sets the appropriate environment variables and starts the application. | |
| """ | |
| import os | |
| import sys | |
| import subprocess | |
| def setup_environment(): | |
| """Setup environment variables for Hugging Face Spaces""" | |
| # Set port from environment or default to 7860 for Hugging Face Spaces | |
| port = int(os.environ.get('PORT', 7860)) | |
| os.environ['PORT'] = str(port) | |
| # Set host to 0.0.0.0 for containerized environments | |
| os.environ['HOST'] = '0.0.0.0' | |
| # Set environment to production | |
| os.environ['FLASK_ENV'] = 'production' | |
| # Set log directory to /tmp which is writable in Hugging Face Spaces | |
| os.environ['LOG_DIR'] = '/tmp/logs' | |
| # Set matplotlib config directory to writable location | |
| os.environ['MPLCONFIGDIR'] = '/tmp/matplotlib' | |
| # Create directories if they don't exist | |
| for directory in ['/tmp/logs', '/tmp/matplotlib']: | |
| try: | |
| if not os.path.exists(directory): | |
| os.makedirs(directory) | |
| except Exception as e: | |
| print(f"Warning: Could not create directory {directory}: {e}") | |
| print(f"Environment configured for Hugging Face Spaces on port {port}") | |
| def start_application(): | |
| """Start the Flask application using gunicorn""" | |
| port = os.environ.get('PORT', '7860') | |
| # Use gunicorn to serve the Flask app | |
| cmd = [ | |
| 'gunicorn', | |
| '--bind', f'0.0.0.0:{port}', | |
| '--worker-class', 'eventlet', | |
| '--workers', '1', | |
| '--timeout', '120', | |
| '--log-level', 'info', | |
| 'app:app' | |
| ] | |
| print(f"Starting application with command: {' '.join(cmd)}") | |
| subprocess.run(cmd) | |
| if __name__ == '__main__': | |
| setup_environment() | |
| start_application() |