Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python3 | |
| """ | |
| πΎ Hugging Face Spaces Entry Point | |
| SIH Crop Yield Prediction API - Optimized for HF Spaces | |
| """ | |
| import sys | |
| import os | |
| import time | |
| from pathlib import Path | |
| # Add src to Python path | |
| sys.path.insert(0, 'src') | |
| print("πΎ Initializing SIH Crop Yield Prediction API...") | |
| print("π Hugging Face Spaces Deployment") | |
| # Set up proper module structure for joblib loading | |
| try: | |
| from models import DataPreprocessor | |
| import types | |
| # Make it available in multiple namespaces for joblib compatibility | |
| globals()['DataPreprocessor'] = DataPreprocessor | |
| # Ensure __main__ module has the class | |
| if '__main__' in sys.modules: | |
| sys.modules['__main__'].DataPreprocessor = DataPreprocessor | |
| # Create models module if not exists | |
| if 'models' not in sys.modules: | |
| models_module = types.ModuleType('models') | |
| models_module.DataPreprocessor = DataPreprocessor | |
| sys.modules['models'] = models_module | |
| print("β DataPreprocessor class prepared for joblib loading") | |
| except ImportError as e: | |
| print(f"β οΈ Warning: Could not import DataPreprocessor: {e}") | |
| print("π The API will still work with basic functionality") | |
| # Verify model files exist | |
| model_dir = Path("models") | |
| if model_dir.exists(): | |
| model_files = list(model_dir.glob("*.pkl")) + list(model_dir.glob("*.json")) + list(model_dir.glob("*.pth")) | |
| print(f"π€ Found {len(model_files)} model files") | |
| for model_file in model_files: | |
| print(f" π {model_file.name} ({model_file.stat().st_size // 1024 // 1024}MB)") | |
| else: | |
| print("β οΈ Models directory not found") | |
| # Import the FastAPI app | |
| try: | |
| from app import app | |
| print("β FastAPI application loaded successfully") | |
| except ImportError as e: | |
| print(f"β Failed to import FastAPI app: {e}") | |
| sys.exit(1) | |
| # This is the entry point for Hugging Face Spaces | |
| if __name__ == "__main__": | |
| import uvicorn | |
| # Get port from environment (Hugging Face Spaces uses 7860) | |
| port = int(os.environ.get("PORT", 7860)) | |
| print("\n" + "="*60) | |
| print("π STARTING SIH CROP YIELD PREDICTION API") | |
| print("="*60) | |
| print(f"π Platform: Hugging Face Spaces") | |
| print(f"π Port: {port}") | |
| print(f"π Local URL: http://localhost:{port}") | |
| print(f"π API Docs: http://localhost:{port}/docs") | |
| print(f"β€οΈ Health Check: http://localhost:{port}/health") | |
| print("="*60) | |
| print("\nπ― Ready for ML predictions!") | |
| # Small delay to ensure everything is initialized | |
| time.sleep(1) | |
| try: | |
| uvicorn.run( | |
| app, | |
| host="0.0.0.0", | |
| port=port, | |
| log_level="info", | |
| access_log=True | |
| ) | |
| except Exception as e: | |
| print(f"β Failed to start server: {e}") | |
| sys.exit(1) | |