Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import gradio as grimport pandas as pdimport numpy as npfrom xgboost import XGBRegressorimport joblibimport osimport logging# -----------------------------# 1️⃣ File paths# -----------------------------MODEL_PATH = "xgb_model_corn_final.json"SCALER_PATH = "minmax_scaler.pkl"EXCEL_PATH = "microalgae_pot_experiment_corrected_doses.xlsx"# Check files existfor path in [MODEL_PATH, SCALER_PATH, EXCEL_PATH]:if not os.path.exists(path):raise FileNotFoundError(f"File not found: {path}")# -----------------------------# 2️⃣ Load model, scaler, and data# -----------------------------xgb_model = XGBRegressor()xgb_model.load_model(MODEL_PATH)scaler = joblib.load(SCALER_PATH)df = pd.read_excel(EXCEL_PATH)# Only one strain existsstrain_names = df['Microalgae_Strain'].unique().tolist()single_strain_value = 0 # training used LabelEncoder -> 0# ==================== New Integration ====================# Create a list of row indices for dropdownrow_options = ["None, Enter Manually"] + [str(i) for i in range(len(df))]# Function to autofill input fields from selected rowdef autofill_fields(row_index):if row_index == "None, Enter Manually":# Reset all fields if 'None' selected UPDATEreturn (None, None, None, None, None, None, None, None, None, None, None)row = df.iloc[int(row_index)]return (row['Soil_N_ppm'], row['Soil_P_ppm'], row['Soil_K_ppm'],row['Soil_EC_dS_m'], row['Soil_Moisture_%'], row['Chlorophyll_SPAD'],row['Shoot_Length_cm'], row['Root_Length_cm'], row['Yield_g_per_pot'],row['Relative_Yield_%'], row['Dose_g_per_pot'] if 'Dose_g_per_pot' in row else None)# -----------------------------# 3️⃣ Prediction function# -----------------------------def predict_dose(crop, microalgae_strain, soil_n, soil_p, soil_k, soil_ec, soil_moisture,chlorophyll, shoot_length, root_length, yield_g, relative_yield,actual_dose):logs = [] # Capture all debug info# 1️⃣ Validate inputsrequired = [soil_n, soil_p, soil_k, soil_ec, soil_moisture,chlorophyll, shoot_length, root_length, yield_g, relative_yield]if any(v is None for v in required):logs.append("[DEBUG] Missing numeric inputs!")return "⚠️ Please fill all numeric input fields.", None, None, "\n".join(logs)logs.append("[DEBUG] All inputs received.")# 2️⃣ Encode strainstrain_encoded = single_strain_valuelogs.append(f"[DEBUG] Using Microalgae_Strain encoded value: {strain_encoded}")# 3️⃣ Create DataFramefeature_cols = ['Soil_N_ppm','Soil_P_ppm','Soil_K_ppm','Soil_EC_dS_m','Soil_Moisture_%','Chlorophyll_SPAD','Shoot_Length_cm','Root_Length_cm','Yield_g_per_pot','Relative_Yield_%','Microalgae_Strain']X_input_df = pd.DataFrame([[soil_n, soil_p, soil_k, soil_ec, soil_moisture,chlorophyll, shoot_length, root_length, yield_g,relative_yield, strain_encoded]],columns=feature_cols).astype(float)logs.append(f"[DEBUG] Input DataFrame:\n{X_input_df}")# 4️⃣ ScaleX_input_scaled = scaler.transform(X_input_df)logs.append(f"[DEBUG] Scaled Input:\n{X_input_scaled}")# 5️⃣ Predictpredicted_dose = xgb_model.predict(X_input_scaled)[0]logs.append(f"[DEBUG] Predicted dose (raw): {predicted_dose}")# # 6️⃣ Compute error# if actual_dose is not None:# abs_error = abs(predicted_dose - actual_dose)# logs.append(f"[DEBUG] Actual dose: {actual_dose}")# logs.append(f"[DEBUG] Absolute Error: {abs_error}")# return (f"**Predicted Dose:** {predicted_dose:.2f} g/pot",# f"**Actual Dose:** {actual_dose:.2f} g/pot",# f"**Absolute Error:** {abs_error:.2f} g/pot",# "\n".join(logs))# else:# logs.append("[DEBUG] Actual dose not provided.")# return (f"**Predicted Dose:** {predicted_dose:.2f} g/pot",# " Actual Dose: Not provided",# " Absolute Error: N/A",# "\n".join(logs))# 6️⃣ Compute errorif actual_dose is not None:try:actual_dose_float = float(actual_dose) # <-- convert string to floatabs_error = abs(predicted_dose - actual_dose_float)logs.append(f"[DEBUG] Actual dose: {actual_dose_float}")logs.append(f"[DEBUG] Absolute Error: {abs_error}")return (f"**Predicted Dose:** {predicted_dose:.2f} g/pot",f"**Actual Dose:** {actual_dose_float:.2f} g/pot",f"**Absolute Error:** {abs_error:.2f} g/pot","\n".join(logs))except ValueError:logs.append("[DEBUG] Actual dose could not be converted to float")return (f"**Predicted Dose:** {predicted_dose:.2f} g/pot"," Actual Dose: Invalid"," Absolute Error: N/A","\n".join(logs))else:logs.append("[DEBUG] Actual dose not provided.")return (f"**Predicted Dose:** {predicted_dose:.2f} g/pot"," Actual Dose: Not provided"," Absolute Error: N/A","\n".join(logs))# -----------------------------# 4️⃣ Gradio Interface# -----------------------------with gr.Blocks(theme=gr.themes.Soft(primary_hue="green", secondary_hue="lime", neutral_hue="gray"),title="Microalgae Dose Prediction") as demo:gr.Markdown("""<div style='text-align:center'><h1 style='color:#00b16a; margin-bottom:8px;'>Microalgae — Dose Prediction App</h1><p style='color:#555;'>Predict the optimal <b>microalgae dose (g/pot)</b> for Corn based on soil and growth parameters.</p></div><hr style='margin: 10px 0;'>""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### Crop & Microalgae Selection")crop = gr.Dropdown(["Corn"], label="Select Crop", value="Corn")strain = gr.Dropdown(strain_names, label="Microalgae Strain", value=strain_names[0])row_selector = gr.Dropdown(row_options, label="Select Row (from XLSX)", value="0")gr.Markdown("### Soil Parameters")soil_n = gr.Number(label="Soil N (ppm)")soil_p = gr.Number(label="Soil P (ppm)")soil_k = gr.Number(label="Soil K (ppm)")soil_ec = gr.Number(label="Soil EC (dS/m)")soil_moisture = gr.Number(label="Soil Moisture (%)")gr.Markdown("### Plant Growth Parameters")chlorophyll = gr.Number(label="Chlorophyll (SPAD)")shoot_length = gr.Number(label="Shoot Length (cm)")root_length = gr.Number(label="Root Length (cm)")yield_g = gr.Number(label="Yield (g/pot)")relative_yield = gr.Number(label="Relative Yield (%)")gr.Markdown("### Actual Dose (optional)")actual_dose = gr.Number(label="Actual Dose (g/pot)")predict_btn = gr.Button("Predict Dose", variant="primary")with gr.Column(scale=1):gr.Markdown("### Inference Result")pred_box = gr.Markdown("Awaiting prediction...")actual_box = gr.Markdown("")abs_box = gr.Markdown("")log_box = gr.Textbox(label="Debug Logs", lines=15)# <-- Add thisgr.Markdown("""### Input Tips:- Select Crop and the used microalgae strain.- Select rows from XLSX or Enter manually- Enter values for N, P, K, EC, and Moisture.- Fill in Chlorophyll (SPAD), Shoot/Root length, Yield, and Relative Yield.- (Optional) Add Actual Dose if you want to compare results.- Click “Predict Dose” to get results.### Output Tips:<div><p style="margin:6px 0;"><strong>Predicted Dose:</strong> Model’s suggested microalgae dose (g/pot).</p><p style="margin:6px 0;"><strong>Absolute Error:</strong> Shows how close the prediction is to your actual dose.</p><p style="margin:6px 0;"><strong>Debug Logs:</strong> Displays detailed input and model processing info.</p></div>""")# ✅ Autofill fields when row selectedrow_selector.change(fn=autofill_fields,inputs=[row_selector],outputs=[soil_n, soil_p, soil_k, soil_ec, soil_moisture,chlorophyll, shoot_length, root_length, yield_g,relative_yield, actual_dose])predict_btn.click(fn=predict_dose,inputs=[crop, strain, soil_n, soil_p, soil_k, soil_ec, soil_moisture,chlorophyll, shoot_length, root_length, yield_g, relative_yield,actual_dose],outputs=[pred_box, actual_box, abs_box, log_box])# -----------------------------# 5️⃣ Launch123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import gradio as grimport pandas as pdimport numpy as npimport joblib# -----------------------------# 1️⃣ Load model and data# -----------------------------MODEL_PATH = "linear_model.pkl"EXCEL_PATH = "excel sheet of plant 2.xlsx"linear_model = joblib.load(MODEL_PATH)df = pd.read_excel(EXCEL_PATH)df.columns = df.columns.str.strip()strain_names = df['pea plant strain'].unique().tolist()row_options = ["None, Enter Manually"] + [str(i) for i in range(len(df))]# -----------------------------# 2️⃣ Autofill function# -----------------------------def autofill_fields(row_index):if row_index == "None, Enter Manually":return [None]*11 # Dose, Soil N, P, K, pH + 6 optional yield metricsrow = df.iloc[int(row_index)]return (row['Dose (g/pot)'], row['Soil N (ppm)'], row['Soil P (ppm)'],row['Soil K (ppm)'], row['pH'], row['Chlorophyll (SPAD)'],row['Shoot Length (cm)'], row['Root Length (cm)'], row['Shoot Wt (g)'],row['Root Wt (g)'], row['Yield (g/pot)'])# -----------------------------# 3️⃣ Prediction function# -----------------------------def predict_linear(strain, dose, soil_n, soil_p, soil_k, ph,chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp,actual_yield=None):logs = []# Validate required inputsrequired = [dose, soil_n, soil_p, soil_k, ph]if any(v is None for v in required):logs.append("[DEBUG] Missing numeric inputs!")return "⚠️ Fill all inputs", "", "", "\n".join(logs)logs.append("[DEBUG] Inputs received.")# Prepare DataFrameX_input = pd.DataFrame([{'pea plant strain': strain,'Dose (g/pot)': dose,'Soil N (ppm)': soil_n,'Soil P (ppm)': soil_p,'Soil K (ppm)': soil_k,'pH': ph}])logs.append(f"[DEBUG] Input DataFrame:\n{X_input}")# Predict all 7 target metricsy_pred = linear_model.predict(X_input)[0]logs.append(f"[DEBUG] Predicted values:\n{y_pred}")# Optional actual_yield comparisonif actual_yield is not None:try:actual_val = float(actual_yield)abs_error = np.abs(actual_val - y_pred[5]) # assuming Yield (g/pot) at index 5logs.append(f"[DEBUG] Actual Yield: {actual_val}")logs.append(f"[DEBUG] Absolute Error: {abs_error}")return (f"**Predicted Metrics:** {y_pred.round(2)}",f"**Actual Yield:** {actual_val}",f"**Absolute Error:** {abs_error:.2f}","\n".join(logs))except:logs.append("[DEBUG] Actual yield invalid.")return (f"**Predicted Metrics:** {y_pred.round(2)}","Actual Yield: Not provided","Absolute Error: N/A","\n".join(logs))# -----------------------------# 4️⃣ Gradio Interface# -----------------------------with gr.Blocks(title="Linear Regression Plant Predictor") as demo:gr.Markdown("<h1 style='text-align:center'>Linear Regression — Plant Yield Predictor</h1>")with gr.Row():with gr.Column(scale=1):gr.Markdown("### Plant & Strain")strain_input = gr.Dropdown(strain_names, label="Select Strain", value=strain_names[0])row_selector = gr.Dropdown(row_options, label="Select Row", value="None, Enter Manually")gr.Markdown("### Input Parameters")dose = gr.Number(label="Dose (g/pot)")soil_n = gr.Number(label="Soil N (ppm)")soil_p = gr.Number(label="Soil P (ppm)")soil_k = gr.Number(label="Soil K (ppm)")ph = gr.Number(label="pH")gr.Markdown("### Optional Yield Metrics")chlorophyll = gr.Number(label="Chlorophyll (SPAD)")shoot_len = gr.Number(label="Shoot Length (cm)")root_len = gr.Number(label="Root Length (cm)")shoot_wt = gr.Number(label="Shoot Wt (g)")root_wt = gr.Number(label="Root Wt (g)")yield_gp = gr.Number(label="Yield (g/pot)")actual_yield = gr.Number(label="Actual Yield (g/pot)")predict_btn = gr.Button("Predict", variant="primary")with gr.Column(scale=1):gr.Markdown("### Inference Result")pred_box = gr.Markdown("Awaiting prediction...")actual_box = gr.Markdown("")abs_box = gr.Markdown("")log_box = gr.Textbox(label="Debug Logs", lines=15)# Autofill callbackrow_selector.change(fn=autofill_fields, inputs=[row_selector],outputs=[dose, soil_n, soil_p, soil_k, ph,chlorophyll, shoot_len, root_len,shoot_wt, root_wt, yield_gp])# Prediction callbackpredict_btn.click(fn=predict_linear,inputs=[strain_input, dose, soil_n, soil_p, soil_k, ph,chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp,actual_yield],outputs=[pred_box, actual_box, abs_box, log_box])# -----------------------------# 5️⃣ Launch
app.py+92-166