""" predictor.py Loads the saved model and provides the predict() function used by app.py. """ import joblib import numpy as np import os _model = None _encoders = None _features = None DISEASE_BAND = { "None": 0.08, "Mild": 0.15, "Moderate": 0.20, "Severe": 0.30, } def _load(): global _model, _encoders, _features if _model is None: if not os.path.exists("model/yield_model.pkl"): from model_train import train print("Model not found — training now...") train() _model = joblib.load("model/yield_model.pkl") _encoders = joblib.load("model/encoders.pkl") _features = joblib.load("model/features.pkl") def predict(crop, soil, season, disease, irrigation, rainfall, temperature, fertilizer, area): """ Returns a dict: mid – central yield estimate (kg/acre) low – lower bound (kg/acre) high – upper bound (kg/acre) total – mid × area (kg) band – ± % used for confidence band """ _load() cat_map = { "crop": crop, "soil": soil, "season": season, "disease": disease, "irrigation": irrigation, } row = {} for col, val in cat_map.items(): le = _encoders[col] if val not in le.classes_: val = le.classes_[0] # fallback to first class row[col + "_enc"] = le.transform([val])[0] row["rainfall"] = float(rainfall) row["temperature"] = float(temperature) row["fertilizer"] = float(fertilizer) row["area"] = float(area) X = np.array([[row[f] for f in _features]]) mid = float(_model.predict(X)[0]) mid = max(50.0, mid) band = DISEASE_BAND.get(disease, 0.15) low = round(mid * (1 - band)) high = round(mid * (1 + band)) mid = round(mid) total = round(mid * float(area)) return { "mid": mid, "low": low, "high": high, "total": total, "band": round(band * 100), }