import gradio as gr
import pandas as pd
import lightgbm as lgb
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
# Load dataset
url = "https://raw.githubusercontent.com/sehajpreet22/data/refs/heads/main/cleaned_crop_data_with_pbi_labels.csv"
data = pd.read_csv(url)
# Define the crops in Punjabi
crops = [
'ਚੌਲ',
'ਮੱਕੀ',
'ਛੋਲੇ',
'ਰਾਜ਼ਮਾ',
'ਅਰਹਰ ਦੀ ਦਾਲ',
'ਮੋਠ ਦੀ ਦਾਲ',
'ਮੂੰਗ ਦੀ ਦਾਲ',
'ਮਾਂਹ ਦੀ ਦਾਲ',
'ਮਸਰ ਦੀ ਦਾਲ',
'ਅਨਾਰ',
'ਕੇਲਾ',
'ਅੰਬ',
'ਤਰਬੂਜ਼',
'ਖਰਬੂਜ਼ਾ',
'ਸੰਤਰਾ',
'ਪਪੀਤਾ',
'ਨਾਰੀਅਲ',
'ਕਪਾਹ',
'ਜੂਟ',
'ਕੌਫ਼ੀ'
]
# Fit the label encoder
le = LabelEncoder()
le.fit(data['label']) # ✅ Fit first
data['crop_encoded'] = le.transform(data['label']) # ✅ Then transform
# Prepare for reverse prediction
reverse_X = data[['crop_encoded']]
y_cols = [
'ਨਾਈਟ੍ਰੋਜਨ (kg/ha)',
'ਫਾਸਫੋਰਸ (kg/ha)',
'ਪੋਟਾਸ਼ੀਅਮ (kg/ha)',
'ਤਾਪਮਾਨ (°C)',
'ਨਮੀ (%)',
'ਮਿੱਟੀ ਦਾ pH',
'ਵਰਖਾ (mm)'
]
# Train reverse models
reverse_models = {}
for col in y_cols:
y = data[col]
X_train, X_test, y_train, y_test = train_test_split(reverse_X, y, test_size=0.2, random_state=42)
model_r = lgb.LGBMRegressor()
model_r.fit(X_train, y_train)
reverse_models[col] = model_r
# Mapping from crop name to encoded value
label_to_encoded = {label: le.transform([label])[0] for label in le.classes_}
# Reverse prediction function
def predict_crop_parameters(crop_name):
crop_name = crop_name.strip()
if crop_name not in label_to_encoded:
return f"❌ '{crop_name}' ਲਈ ਡਾਟਾ ਨਹੀਂ ਮਿਲਿਆ।"
encoded_value = label_to_encoded[crop_name]
input_data = [[encoded_value]]
predictions = {}
for param, model_r in reverse_models.items():
predicted_value = model_r.predict(input_data)[0]
predictions[param] = round(predicted_value, 2)
formatted_output = ""
for k, v in predictions.items():
formatted_output += f"{k}: {v}
"
return formatted_output
with gr.Blocks() as demo:
gr.Markdown("# 🌾 **AgroVision: ਫਸਲ ਤੋਂ ਪੈਰਾਮੀਟਰ**")
crop_input = gr.Dropdown(choices=crops, label="🌿 ਫਸਲ ਦਾ ਨਾਂ ਲਿਖੋ")
result_output = gr.Markdown(label="🧪 ਅਨੁਕੂਲ ਪੈਰਾਮੀਟਰ")
run_btn = gr.Button("➡️ ਭਵਿੱਖਬਾਣੀ ਲਵੋ")
run_btn.click(fn=predict_crop_parameters, inputs=[crop_input], outputs=[result_output])
demo.launch()