3v324v23's picture
🌾 Deploy SIH Crop Yield Prediction API to Hugging Face Spaces
a4348ce
Raw
History Blame Contribute Delete
2.83 kB
#!/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)