Ayesha-Majeed commited on
Commit
82fef47
·
verified ·
1 Parent(s): 74fe090

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -30
app.py CHANGED
@@ -13,6 +13,7 @@ linear_model = joblib.load(MODEL_PATH)
13
  df = pd.read_excel(EXCEL_PATH)
14
  df.columns = df.columns.str.strip()
15
 
 
16
  strain_names = df['pea plant strain'].unique().tolist()
17
  row_options = ["None, Enter Manually"] + [str(i) for i in range(len(df))]
18
 
@@ -21,7 +22,7 @@ row_options = ["None, Enter Manually"] + [str(i) for i in range(len(df))]
21
  # -----------------------------
22
  def autofill_fields(row_index):
23
  if row_index == "None, Enter Manually":
24
- return [None]*11 # Dose, Soil N, P, K, pH + 6 optional yield metrics
25
  row = df.iloc[int(row_index)]
26
  return (
27
  row['Dose (g/pot)'], row['Soil N (ppm)'], row['Soil P (ppm)'],
@@ -34,18 +35,17 @@ def autofill_fields(row_index):
34
  # 3️⃣ Prediction function
35
  # -----------------------------
36
  def predict_linear(strain, dose, soil_n, soil_p, soil_k, ph,
37
- chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp,
38
- actual_yield=None):
39
  logs = []
40
 
41
  # Validate required inputs
42
  required = [dose, soil_n, soil_p, soil_k, ph]
43
  if any(v is None for v in required):
44
  logs.append("[DEBUG] Missing numeric inputs!")
45
- return "⚠️ Fill all inputs", "", "", "\n".join(logs)
46
  logs.append("[DEBUG] Inputs received.")
47
 
48
- # Prepare DataFrame
49
  X_input = pd.DataFrame([{
50
  'pea plant strain': strain,
51
  'Dose (g/pot)': dose,
@@ -56,28 +56,27 @@ def predict_linear(strain, dose, soil_n, soil_p, soil_k, ph,
56
  }])
57
  logs.append(f"[DEBUG] Input DataFrame:\n{X_input}")
58
 
59
- # Predict all 7 target metrics
60
  y_pred = linear_model.predict(X_input)[0]
61
  logs.append(f"[DEBUG] Predicted values:\n{y_pred}")
62
 
63
- # Optional actual_yield comparison
64
- if actual_yield is not None:
65
- try:
66
- actual_val = float(actual_yield)
67
- abs_error = np.abs(actual_val - y_pred[5]) # assuming Yield (g/pot) at index 5
68
- logs.append(f"[DEBUG] Actual Yield: {actual_val}")
69
- logs.append(f"[DEBUG] Absolute Error: {abs_error}")
70
- return (f"**Predicted Metrics:** {y_pred.round(2)}",
71
- f"**Actual Yield:** {actual_val}",
72
- f"**Absolute Error:** {abs_error:.2f}",
73
- "\n".join(logs))
74
- except:
75
- logs.append("[DEBUG] Actual yield invalid.")
76
-
77
- return (f"**Predicted Metrics:** {y_pred.round(2)}",
78
- "Actual Yield: Not provided",
79
- "Absolute Error: N/A",
80
- "\n".join(logs))
81
 
82
  # -----------------------------
83
  # 4️⃣ Gradio Interface
@@ -98,7 +97,7 @@ with gr.Blocks(title="Linear Regression Plant Predictor") as demo:
98
  soil_k = gr.Number(label="Soil K (ppm)")
99
  ph = gr.Number(label="pH")
100
 
101
- gr.Markdown("### Optional Yield Metrics")
102
  chlorophyll = gr.Number(label="Chlorophyll (SPAD)")
103
  shoot_len = gr.Number(label="Shoot Length (cm)")
104
  root_len = gr.Number(label="Root Length (cm)")
@@ -106,13 +105,11 @@ with gr.Blocks(title="Linear Regression Plant Predictor") as demo:
106
  root_wt = gr.Number(label="Root Wt (g)")
107
  yield_gp = gr.Number(label="Yield (g/pot)")
108
 
109
- actual_yield = gr.Number(label="Actual Yield (g/pot)")
110
  predict_btn = gr.Button("Predict", variant="primary")
111
 
112
  with gr.Column(scale=1):
113
  gr.Markdown("### Inference Result")
114
  pred_box = gr.Markdown("Awaiting prediction...")
115
- actual_box = gr.Markdown("")
116
  abs_box = gr.Markdown("")
117
  log_box = gr.Textbox(label="Debug Logs", lines=15)
118
 
@@ -125,9 +122,8 @@ with gr.Blocks(title="Linear Regression Plant Predictor") as demo:
125
  # Prediction callback
126
  predict_btn.click(fn=predict_linear,
127
  inputs=[strain_input, dose, soil_n, soil_p, soil_k, ph,
128
- chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp,
129
- actual_yield],
130
- outputs=[pred_box, actual_box, abs_box, log_box])
131
 
132
  # -----------------------------
133
  # 5️⃣ Launch
 
13
  df = pd.read_excel(EXCEL_PATH)
14
  df.columns = df.columns.str.strip()
15
 
16
+ # Strains and rows
17
  strain_names = df['pea plant strain'].unique().tolist()
18
  row_options = ["None, Enter Manually"] + [str(i) for i in range(len(df))]
19
 
 
22
  # -----------------------------
23
  def autofill_fields(row_index):
24
  if row_index == "None, Enter Manually":
25
+ return [None]*11 # Dose, Soil N, P, K, pH + 6 actual outputs
26
  row = df.iloc[int(row_index)]
27
  return (
28
  row['Dose (g/pot)'], row['Soil N (ppm)'], row['Soil P (ppm)'],
 
35
  # 3️⃣ Prediction function
36
  # -----------------------------
37
  def predict_linear(strain, dose, soil_n, soil_p, soil_k, ph,
38
+ chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp):
 
39
  logs = []
40
 
41
  # Validate required inputs
42
  required = [dose, soil_n, soil_p, soil_k, ph]
43
  if any(v is None for v in required):
44
  logs.append("[DEBUG] Missing numeric inputs!")
45
+ return "⚠️ Fill all required inputs", "", "\n".join(logs)
46
  logs.append("[DEBUG] Inputs received.")
47
 
48
+ # Prepare input DataFrame for prediction
49
  X_input = pd.DataFrame([{
50
  'pea plant strain': strain,
51
  'Dose (g/pot)': dose,
 
56
  }])
57
  logs.append(f"[DEBUG] Input DataFrame:\n{X_input}")
58
 
59
+ # Predict all 7 targets
60
  y_pred = linear_model.predict(X_input)[0]
61
  logs.append(f"[DEBUG] Predicted values:\n{y_pred}")
62
 
63
+ # Compute absolute errors using autofilled actuals
64
+ actuals = [chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp]
65
+ abs_errors = []
66
+ for pred_val, act_val in zip(y_pred[:6], actuals):
67
+ if act_val is not None:
68
+ abs_errors.append(round(abs(pred_val - act_val), 2))
69
+ else:
70
+ abs_errors.append("N/A")
71
+
72
+ # Format outputs
73
+ target_cols = ['Chlorophyll (SPAD)', 'Shoot Length (cm)', 'Root Length (cm)',
74
+ 'Shoot Wt (g)', 'Root Wt (g)', 'Yield (g/pot)', 'Relative Yield (%)']
75
+
76
+ pred_str = "\n".join([f"{c}: {round(v,2)}" for c,v in zip(target_cols, y_pred)])
77
+ abs_str = "\n".join([f"{c}: {e}" for c,e in zip(target_cols[:6], abs_errors)])
78
+
79
+ return pred_str, abs_str, "\n".join(logs)
 
80
 
81
  # -----------------------------
82
  # 4️⃣ Gradio Interface
 
97
  soil_k = gr.Number(label="Soil K (ppm)")
98
  ph = gr.Number(label="pH")
99
 
100
+ gr.Markdown("### Autofilled Actual Metrics (from CSV)")
101
  chlorophyll = gr.Number(label="Chlorophyll (SPAD)")
102
  shoot_len = gr.Number(label="Shoot Length (cm)")
103
  root_len = gr.Number(label="Root Length (cm)")
 
105
  root_wt = gr.Number(label="Root Wt (g)")
106
  yield_gp = gr.Number(label="Yield (g/pot)")
107
 
 
108
  predict_btn = gr.Button("Predict", variant="primary")
109
 
110
  with gr.Column(scale=1):
111
  gr.Markdown("### Inference Result")
112
  pred_box = gr.Markdown("Awaiting prediction...")
 
113
  abs_box = gr.Markdown("")
114
  log_box = gr.Textbox(label="Debug Logs", lines=15)
115
 
 
122
  # Prediction callback
123
  predict_btn.click(fn=predict_linear,
124
  inputs=[strain_input, dose, soil_n, soil_p, soil_k, ph,
125
+ chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp],
126
+ outputs=[pred_box, abs_box, log_box])
 
127
 
128
  # -----------------------------
129
  # 5️⃣ Launch