Spaces:
Sleeping
Sleeping
File size: 13,673 Bytes
a4348ce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | #!/usr/bin/env python3
"""
Simplified FastAPI Crop Yield Prediction API
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import Optional
import pandas as pd
import numpy as np
import joblib
import warnings
import os
from datetime import datetime
# Import model classes - joblib setup is handled in start.py
try:
from models import DataPreprocessor
except ImportError as e:
print(f"Warning: Could not import DataPreprocessor: {e}")
DataPreprocessor = None
warnings.filterwarnings('ignore')
# Simple predictor class to avoid import conflicts
class CropYieldPredictor:
"""Simplified prediction class that loads Random Forest model."""
def __init__(self, models_dir='models', quiet=False):
self.models_dir = models_dir
self.model = None
self.preprocessor = None
self.quiet = quiet
self.fallback_mode = False
if not quiet:
print(f"π Initializing Random Forest Crop Yield Predictor...")
self.load_models()
def load_models(self):
"""Load Random Forest model and preprocessor."""
if not self.quiet:
print("π₯ Loading trained model...")
try:
# Try using the model_loader
from model_loader import load_models_safely
model, preprocessor = load_models_safely(self.models_dir)
if model is not None and preprocessor is not None:
self.model = model
self.preprocessor = preprocessor
if not self.quiet:
print(" β
Models loaded successfully using model_loader")
return
else:
raise Exception("Model loader failed")
except Exception as e:
if not self.quiet:
print(f"β οΈ Primary model loading failed: {e}")
print("β οΈ Switching to fallback mode - limited functionality")
# Fallback: create a simple mock predictor
self.fallback_mode = True
self.model = None
self.preprocessor = self._create_fallback_preprocessor()
if not self.quiet:
print("β
Fallback mode initialized")
def _create_fallback_preprocessor(self):
"""Create a simple fallback preprocessor for basic functionality"""
class FallbackPreprocessor:
def __init__(self):
self.label_encoders = {
'State': type('MockEncoder', (), {'classes_': ['Punjab', 'Maharashtra', 'Karnataka', 'Gujarat', 'Rajasthan']}),
'Crop': type('MockEncoder', (), {'classes_': ['Rice', 'Wheat', 'Cotton', 'Sugarcane', 'Maize']}),
'District': type('MockEncoder', (), {'classes_': ['Default District']})
}
return FallbackPreprocessor()
def predict_yield(self, input_data):
"""Make yield prediction using Random Forest model or fallback."""
if self.fallback_mode:
# Simple fallback prediction based on basic rules
try:
if isinstance(input_data, dict):
area = input_data.get('Area', 10)
production = input_data.get('Production', 25)
rainfall = input_data.get('Annual_Rainfall', 1000)
crop = input_data.get('Crop', 'Rice')
# Simple formula based on typical crop yields
base_yield = {
'Rice': 2500, 'Wheat': 3000, 'Cotton': 1200,
'Sugarcane': 60000, 'Maize': 2800
}.get(crop.title(), 2000)
# Adjust for rainfall
rainfall_factor = min(1.2, max(0.8, rainfall / 1000))
# Simple prediction
prediction = base_yield * rainfall_factor
return prediction, None
else:
return "Error: Invalid input format", None
except Exception as e:
return f"Fallback Error: {str(e)}", None
try:
# Convert input to DataFrame
if isinstance(input_data, dict):
df = pd.DataFrame([input_data])
else:
df = input_data.copy()
# Prepare features
X, processed_data = self.preprocessor.prepare_features(df)
# Transform data
X_processed = self.preprocessor.transform(X)
# Make prediction with Random Forest
try:
prediction = self.model.predict(X_processed)[0]
prediction = max(0, prediction) # Ensure non-negative yield
return prediction, processed_data
except Exception as e:
return f"Error: {str(e)}", None
except Exception as e:
return f"Error: {str(e)}", None
def get_crop_options(self):
"""Get available crop options from the preprocessor."""
if hasattr(self.preprocessor, 'label_encoders') and 'Crop' in self.preprocessor.label_encoders:
return list(self.preprocessor.label_encoders['Crop'].classes_)
return []
def get_state_options(self):
"""Get available state options from the preprocessor."""
if hasattr(self.preprocessor, 'label_encoders') and 'State' in self.preprocessor.label_encoders:
return list(self.preprocessor.label_encoders['State'].classes_)
return []
def get_season_options(self):
"""Get available season options."""
return ['Kharif', 'Rabi', 'Summer', 'Whole Year', 'Autumn', 'Winter', 'Total']
# Initialize FastAPI app
app = FastAPI(
title="πΎ SIH Crop Yield Prediction API",
description="""**Smart India Hackathon Project**
Predict crop yields using advanced Machine Learning models including Random Forest, XGBoost, and PyTorch neural networks.
**Features:**
- π€ Multiple ML models (Random Forest, XGBoost, PyTorch)
- π± Supports major Indian crops (Rice, Wheat, Cotton, etc.)
- ποΈ State-wise predictions across India
- π Intelligent fallback system for reliability
- β‘ Fast predictions (~100-500ms)
**Perfect for:**
- Farmers planning crop yields
- Agricultural consultants
- Government agricultural departments
- Research and academic studies
""",
version="2.0.0",
docs_url="/docs",
redoc_url="/redoc",
contact={
"name": "SIH Team - Crop Yield Prediction",
"url": "https://github.com/AshrafGalibShaik/SIH-2",
},
license_info={
"name": "MIT License",
"url": "https://opensource.org/licenses/MIT",
},
)
# Pydantic models for request and response
class CropPredictionRequest(BaseModel):
year: int = Field(..., description="Crop year (e.g., 2024)", example=2024)
state: str = Field(..., description="State name", example="Punjab")
crop: str = Field(..., description="Crop name", example="Rice")
season: str = Field(..., description="Season", example="Kharif")
area: float = Field(..., description="Area in hectares", example=10.0)
production: float = Field(..., description="Production in tons", example=25.0)
rainfall: Optional[float] = Field(1000.0, description="Annual rainfall in mm", example=1200)
fertilizer: Optional[float] = Field(50.0, description="Fertilizer usage in kg", example=75)
pesticide: Optional[float] = Field(5.0, description="Pesticide usage in kg", example=8)
class CropPredictionResponse(BaseModel):
model: str = Field(..., description="Model used for prediction", example="Random Forest")
predicted_yield: str = Field(..., description="Predicted yield with units", example="2017.7 kg/hectare")
total_expected_production: str = Field(..., description="Total expected production with units", example="20.18 tons")
assessment: str = Field(..., description="Yield assessment", example="Good yield expected")
class ErrorResponse(BaseModel):
error: str = Field(..., description="Error message")
# Global predictor instance - initialize on startup
predictor = None
@app.on_event("startup")
async def startup_event():
"""Initialize ML models on startup for better performance"""
global predictor
print("π Initializing ML models on startup...")
try:
predictor = CropYieldPredictor(quiet=False)
print("β
Startup initialization completed successfully")
except Exception as e:
print(f"β οΈ Startup initialization failed: {e}")
print("π API will use fallback mode for predictions")
predictor = "failed"
def get_predictor():
"""Get the pre-initialized predictor"""
global predictor
if predictor is None:
# This shouldn't happen with startup event, but fallback just in case
try:
predictor = CropYieldPredictor(quiet=True)
print("β
Crop Yield Predictor initialized (fallback)")
except Exception as e:
print(f"β Failed to initialize predictor: {e}")
predictor = "failed"
return predictor if predictor != "failed" else None
@app.get("/")
async def root():
"""Root endpoint"""
return {
"message": "Crop Yield Prediction API. Use /docs for interactive API documentation.",
"version": "1.0.0",
"endpoints": {
"predict": "/predict",
"health": "/health",
"docs": "/docs",
"available_options": "/available-options"
}
}
@app.get("/health")
async def health_check():
"""Health check endpoint"""
predictor_instance = get_predictor()
return {
"status": "healthy",
"timestamp": datetime.now().isoformat(),
"model_loaded": predictor_instance is not None
}
@app.post("/predict", response_model=CropPredictionResponse, responses={400: {"model": ErrorResponse}})
async def predict_yield(request: CropPredictionRequest):
"""
Predict crop yield based on input parameters
Input format:
{
"year": 2024,
"state": "Punjab",
"crop": "Rice",
"season": "Kharif",
"area": 10.0,
"production": 25.0,
"rainfall": 1200,
"fertilizer": 75,
"pesticide": 8
}
Returns prediction with model type, predicted yield, total production, and assessment.
"""
try:
predictor_instance = get_predictor()
if predictor_instance is None:
raise HTTPException(status_code=500, detail="Predictor not initialized. Please check if trained models are available.")
# Convert request to internal format
input_data = {
'Crop_Year': request.year,
'State': request.state,
'District': "Unknown", # Default district
'Crop': request.crop,
'Season': request.season,
'Area': request.area,
'Production': request.production,
'Annual_Rainfall': request.rainfall,
'Fertilizer': request.fertilizer,
'Pesticide': request.pesticide
}
# Make prediction
prediction, _ = predictor_instance.predict_yield(input_data)
if isinstance(prediction, str) and 'Error' in prediction:
raise HTTPException(status_code=400, detail=prediction)
# Calculate total production
total_production = (prediction * request.area) / 1000.0 # Convert to tons
# Determine assessment
if prediction > 3000:
assessment = "Excellent yield expected"
elif prediction > 2000:
assessment = "Good yield expected"
elif prediction > 1000:
assessment = "Moderate yield expected"
else:
assessment = "Low yield expected"
# Format response
model_type = "Random Forest" if not predictor_instance.fallback_mode else "Fallback Model (Rule-based)"
response = CropPredictionResponse(
model=model_type,
predicted_yield=f"{round(prediction, 2)} kg/hectare",
total_expected_production=f"{round(total_production, 2)} tons",
assessment=assessment
)
return response
except HTTPException:
raise # Re-raise HTTP exceptions
except Exception as e:
raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")
@app.get("/available-options")
async def get_available_options():
"""Get available crops, states, and seasons"""
try:
predictor_instance = get_predictor()
if predictor_instance is None:
raise HTTPException(status_code=500, detail="Predictor not initialized")
return {
"states": predictor_instance.get_state_options()[:10], # Limit to first 10 for readability
"crops": predictor_instance.get_crop_options()[:10], # Limit to first 10 for readability
"seasons": predictor_instance.get_season_options(),
"note": "This shows first 10 states and crops. All are supported in predictions."
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Note: Server startup is handled by start.py for Railway deployment
# This prevents conflicts between different startup methods
|