CoolFace
Apppublic

hussain2010/Optimized_Crop_Yield_Prediction

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py154 linesDownload Raw Back to root
1import os2import gradio as gr3import pandas as pd4import numpy as np5from sklearn.ensemble import RandomForestRegressor6import joblib  # To save and load the trained model7from groq import Groq8from huggingface_hub import login9from dotenv import load_dotenv10 11# Load environment variables from .env file12load_dotenv()13 14# Authenticate with Hugging Face using the token stored in .env15HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN")16 17if HUGGINGFACE_TOKEN:18    login(token=HUGGINGFACE_TOKEN)19else:20    raise ValueError("Hugging Face token not found in environment variables")21 22# Initialize Groq client with the API key from .env23GROQ_API_KEY = os.getenv("GROQ_API_KEY")24client = Groq(api_key=GROQ_API_KEY)25 26# Function to train or load the RandomForestRegressor model27def train_model(df):28    # Encode the 'Crop' column as numeric (e.g., 'Rice' = 2, 'Wheat' = 1)29    df['Crop'] = df['Crop'].map({'Wheat': 1, 'Rice': 2})30    31    # Preprocess the data (drop 'Yield' column for features)32    X = df.drop(columns=["Yield"])  # Features33    y = df["Yield"]  # Target variable34    35    # Train the Random Forest model36    model = RandomForestRegressor(n_estimators=100, random_state=42)37    model.fit(X, y)38    39    # Save the model to disk40    model_filename = '/content/crop_yield_model.pkl'41    joblib.dump(model, model_filename)42    43    return model_filename44 45# Load the trained model46def load_model():47    model_filename = '/content/crop_yield_model.pkl'48    if os.path.exists(model_filename):49        model = joblib.load(model_filename)50    else:51        raise Exception("Model not found. Please upload a valid dataset and train the model.")52    return model53 54# Function to predict crop yield based on input features55def predict_yield(N, P, K, temperature, humidity, pH, rainfall, crop):56    input_data = {57        "Nitrogen": N,58        "Phosphorus": P,59        "Potassium": K,60        "Temperature": temperature,61        "Humidity": humidity,62        "pH_Value": pH,63        "Rainfall": rainfall,64        "Crop": crop,65    }66    67    model = load_model()  # Load the trained model68    69    # Prepare input data as a DataFrame70    input_df = pd.DataFrame([input_data])71    yield_prediction = model.predict(input_df)72    73    return f"Predicted Yield: {yield_prediction[0]:.2f} kg/ha"74 75# Gradio Interface function to upload file and train the model76def upload_file(file):77    # Load the dataset from the uploaded CSV file78    try:79        df = pd.read_csv(file.name)80        81        # Check if required columns are present82        required_columns = ["Nitrogen", "Phosphorus", "Potassium", "Temperature", "Humidity", "pH_Value", "Rainfall", "Crop", "Yield"]83        missing_columns = [col for col in required_columns if col not in df.columns]84        85        if missing_columns:86            return f"Error: Missing columns: {', '.join(missing_columns)}. Please upload a file with the required columns."87        88        # Check for missing values in the required columns89        if df[required_columns].isnull().sum().sum() > 0:90            return "Error: Dataset contains missing values. Please clean the dataset before uploading."91        92        # Check data types of the columns (they should be numeric except for the 'Crop' column)93        for col in ["Nitrogen", "Phosphorus", "Potassium", "Temperature", "Humidity", "pH_Value", "Rainfall", "Yield"]:94            if not pd.api.types.is_numeric_dtype(df[col]):95                return f"Error: Column '{col}' contains non-numeric values. Please ensure all feature columns are numeric."96        97        # Encode the 'Crop' column as numeric (e.g., 'Rice' = 2, 'Wheat' = 1)98        df['Crop'] = df['Crop'].map({'Wheat': 1, 'Rice': 2})99        100        # If everything is fine, train the model101        model_filename = train_model(df)102        return f"Model trained successfully and saved as {model_filename}. You can now make predictions."103    104    except Exception as e:105        return f"Error: {str(e)}"106 107# Gradio Interface function for prediction108def interactive_interface(N, P, K, temperature, humidity, pH, rainfall, crop):109    return predict_yield(N, P, K, temperature, humidity, pH, rainfall, crop)110 111# Additional Groq API test function112def test_groq_api():113    test_response = client.chat.completions.create(114        messages=[{115            "role": "user",116            "content": "Explain the importance of fast language models",117        }],118        model="llama3-8b-8192",119    )120    return test_response.choices[0].message.content121 122# Gradio setup for prediction interface123interface = gr.Interface(124    fn=interactive_interface,125    inputs=[126        gr.Number(label="Nitrogen (N)"),127        gr.Number(label="Phosphorus (P)"),128        gr.Number(label="Potassium (K)"),129        gr.Number(label="Temperature (°C)"),130        gr.Number(label="Humidity (%)"),131        gr.Number(label="pH Value"),132        gr.Number(label="Rainfall (mm)"),133        gr.Textbox(label="Crop (1 = Wheat, 2 = Rice)"),134    ],135    outputs=[gr.Textbox(label="Predicted Yield")],136    title="Optimized Crop Yield Prediction",137    description="Input soil and weather parameters to predict crop yield.",138)139 140# Gradio setup for uploading dataset141upload_interface = gr.Interface(142    fn=upload_file,143    inputs=gr.File(label="Upload your crop yield dataset (CSV)"),144    outputs=[gr.Textbox(label="Status")],145    title="Upload and Train Model",146    description="Upload a CSV file with crop yield data to train the prediction model.",147)148 149# Test the Groq API and print the response150if __name__ == "__main__":151    print("Groq API Test Response:", test_groq_api())152    upload_interface.launch()153    interface.launch()154