Zsirak's picture
Create app.py
153d335 verified
# app.py
# Gradio app for coffee yield prediction on Hugging Face Spaces
import gradio as gr
import pandas as pd
import joblib
# Load the model, scaler, and feature names
lasso_model = joblib.load('lasso_model.joblib')
scaler = joblib.load('scaler.joblib')
features = joblib.load('feature_names.joblib')
# Define the prediction function
def predict_yield(hectares, *feature_inputs):
try:
# Create a dictionary of inputs
input_dict = {feature: value for feature, value in zip(features, feature_inputs)}
# Convert to DataFrame
input_df = pd.DataFrame([input_dict], columns=features)
# Scale the input data
input_scaled = scaler.transform(input_df)
input_scaled = pd.DataFrame(input_scaled, columns=features)
# Predict yield per hectare (kg/ha)
yield_kg_ha = lasso_model.predict(input_scaled)[0]
# Scale by hectares to get total yield (kg)
total_yield_kg = yield_kg_ha * hectares
return f"Predicted Total Yield: {total_yield_kg:.2f} kg for {hectares} hectares (Yield per hectare: {yield_kg_ha:.2f} kg/ha)"
except Exception as e:
return f"Error: {str(e)}"
# Create feature input fields dynamically based on feature names
inputs = [
gr.Number(label="Total Hectares of Farmland", value=1.0, minimum=0.1, step=0.1)
] + [gr.Number(label=feature, value=0.0, step=0.01) for feature in features]
# Create the Gradio interface
demo = gr.Interface(
fn=predict_yield,
inputs=inputs,
outputs=gr.Textbox(label="Prediction Result"),
title="Coffee Yield Predictor for Sidama",
description="Enter the total hectares of farmland and environmental/vegetation features to predict coffee yield. Features are based on annual means for Sidama, Ethiopia (2019–2023).",
allow_flagging="never"
)
# Launch the app (Hugging Face will handle this automatically)
demo.launch(share=False)