#!/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)