Ayesha-Majeed commited on
Commit
945c40c
·
verified ·
1 Parent(s): c61f4a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -38
app.py CHANGED
@@ -22,7 +22,7 @@ row_options = ["None, Enter Manually"] + [str(i) for i in range(len(df))]
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)'],
@@ -38,14 +38,13 @@ 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,58 +55,67 @@ 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 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
83
  # -----------------------------
84
  invalid_strains = ["Strains", "strain1", "strain2", ""]
85
  valid_strain = next(
86
- (s for s in strain_names if pd.notna(s) and s not in invalid_strains),
87
- strain_names[0] # fallback if none found
88
  )
89
 
90
- with gr.Blocks(title="Linear Regression Plant Predictor") as demo:
91
- gr.Markdown("<h1 style='text-align:center'>Linear Regression Plant Yield Predictor</h1>")
 
 
 
 
 
 
 
92
 
93
  with gr.Row():
94
  with gr.Column(scale=1):
95
- gr.Markdown("### Plant & Strain")
96
  strain_input = gr.Dropdown(
97
  strain_names,
98
  label="Select Strain",
99
- value=valid_strain # first valid, non-NaN, non-invalid strain
100
  )
101
  row_selector = gr.Dropdown(row_options, label="Select Row", value="None, Enter Manually")
102
 
103
- gr.Markdown("### Input Parameters")
104
  dose = gr.Number(label="Dose (g/pot)")
105
  soil_n = gr.Number(label="Soil N (ppm)")
106
  soil_p = gr.Number(label="Soil P (ppm)")
107
  soil_k = gr.Number(label="Soil K (ppm)")
108
  ph = gr.Number(label="pH")
109
 
110
- gr.Markdown("### Autofilled Actual Metrics (from CSV)")
111
  chlorophyll = gr.Number(label="Chlorophyll (SPAD)")
112
  shoot_len = gr.Number(label="Shoot Length (cm)")
113
  root_len = gr.Number(label="Root Length (cm)")
@@ -115,25 +123,34 @@ with gr.Blocks(title="Linear Regression Plant Predictor") as demo:
115
  root_wt = gr.Number(label="Root Wt (g)")
116
  yield_gp = gr.Number(label="Yield (g/pot)")
117
 
118
- predict_btn = gr.Button("Predict", variant="primary")
119
 
120
  with gr.Column(scale=1):
121
- gr.Markdown("### Inference Result")
122
- pred_box = gr.Markdown("Awaiting prediction...")
123
- abs_box = gr.Markdown("")
 
 
 
 
124
  log_box = gr.Textbox(label="Debug Logs", lines=15)
125
 
126
  # Autofill callback
127
- row_selector.change(fn=autofill_fields, inputs=[row_selector],
128
- outputs=[dose, soil_n, soil_p, soil_k, ph,
129
- chlorophyll, shoot_len, root_len,
130
- shoot_wt, root_wt, yield_gp])
 
 
 
131
 
132
  # Prediction callback
133
- predict_btn.click(fn=predict_linear,
134
- inputs=[strain_input, dose, soil_n, soil_p, soil_k, ph,
135
- chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp],
136
- outputs=[pred_box, abs_box, log_box])
 
 
137
 
138
  # -----------------------------
139
  # 5️⃣ Launch
 
22
  # -----------------------------
23
  def autofill_fields(row_index):
24
  if row_index == "None, Enter Manually":
25
+ return [None]*11
26
  row = df.iloc[int(row_index)]
27
  return (
28
  row['Dose (g/pot)'], row['Soil N (ppm)'], row['Soil P (ppm)'],
 
38
  chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp):
39
  logs = []
40
 
 
41
  required = [dose, soil_n, soil_p, soil_k, ph]
42
  if any(v is None for v in required):
43
  logs.append("[DEBUG] Missing numeric inputs!")
44
+ return pd.DataFrame(), "\n⚠️ Fill all required inputs", "\n".join(logs)
45
  logs.append("[DEBUG] Inputs received.")
46
 
47
+ # Prepare DataFrame for model
48
  X_input = pd.DataFrame([{
49
  'pea plant strain': strain,
50
  'Dose (g/pot)': dose,
 
55
  }])
56
  logs.append(f"[DEBUG] Input DataFrame:\n{X_input}")
57
 
 
58
  y_pred = linear_model.predict(X_input)[0]
59
  logs.append(f"[DEBUG] Predicted values:\n{y_pred}")
60
 
61
+ # Actuals and errors
62
  actuals = [chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp]
63
+ abs_errors = [
64
+ round(abs(p - a), 2) if a is not None else "N/A"
65
+ for p, a in zip(y_pred[:6], actuals)
66
+ ]
67
+
 
 
 
68
  target_cols = ['Chlorophyll (SPAD)', 'Shoot Length (cm)', 'Root Length (cm)',
69
  'Shoot Wt (g)', 'Root Wt (g)', 'Yield (g/pot)', 'Relative Yield (%)']
70
 
71
+ # Build table DataFrame
72
+ data = {
73
+ "Output Metric": target_cols,
74
+ "Actual Value": actuals + ["N/A"],
75
+ "Predicted Value": [round(v, 2) for v in y_pred],
76
+ "Absolute Error": abs_errors + ["N/A"]
77
+ }
78
+ result_df = pd.DataFrame(data)
79
 
80
+ return result_df, "✅ Prediction complete!", "\n".join(logs)
81
 
82
  # -----------------------------
83
+ # 4️⃣ Gradio Interface (Green Theme)
84
  # -----------------------------
85
  invalid_strains = ["Strains", "strain1", "strain2", ""]
86
  valid_strain = next(
87
+ (s for s in strain_names if pd.notna(s) and s not in invalid_strains),
88
+ strain_names[0]
89
  )
90
 
91
+ with gr.Blocks(
92
+ title="Linear Regression Plant Predictor",
93
+ theme=gr.themes.Soft(
94
+ primary_hue="green",
95
+ secondary_hue="green",
96
+ neutral_hue="green"
97
+ )
98
+ ) as demo:
99
+ gr.Markdown("<h1 style='text-align:center; color:#2E8B57;'>🌿 Linear Regression — Plant Yield Predictor 🌿</h1>")
100
 
101
  with gr.Row():
102
  with gr.Column(scale=1):
103
+ gr.Markdown("### 🌱 Plant & Strain")
104
  strain_input = gr.Dropdown(
105
  strain_names,
106
  label="Select Strain",
107
+ value=valid_strain
108
  )
109
  row_selector = gr.Dropdown(row_options, label="Select Row", value="None, Enter Manually")
110
 
111
+ gr.Markdown("### 🌾 Input Parameters")
112
  dose = gr.Number(label="Dose (g/pot)")
113
  soil_n = gr.Number(label="Soil N (ppm)")
114
  soil_p = gr.Number(label="Soil P (ppm)")
115
  soil_k = gr.Number(label="Soil K (ppm)")
116
  ph = gr.Number(label="pH")
117
 
118
+ gr.Markdown("### 📊 Autofilled Actual Metrics (from Excel)")
119
  chlorophyll = gr.Number(label="Chlorophyll (SPAD)")
120
  shoot_len = gr.Number(label="Shoot Length (cm)")
121
  root_len = gr.Number(label="Root Length (cm)")
 
123
  root_wt = gr.Number(label="Root Wt (g)")
124
  yield_gp = gr.Number(label="Yield (g/pot)")
125
 
126
+ predict_btn = gr.Button("🌿 Predict", variant="primary")
127
 
128
  with gr.Column(scale=1):
129
+ gr.Markdown("### 🌼 Prediction Results Table")
130
+ result_table = gr.DataFrame(
131
+ headers=["Output Metric", "Actual Value", "Predicted Value", "Absolute Error"],
132
+ label="Results Comparison",
133
+ interactive=False
134
+ )
135
+ status_box = gr.Markdown("")
136
  log_box = gr.Textbox(label="Debug Logs", lines=15)
137
 
138
  # Autofill callback
139
+ row_selector.change(
140
+ fn=autofill_fields,
141
+ inputs=[row_selector],
142
+ outputs=[dose, soil_n, soil_p, soil_k, ph,
143
+ chlorophyll, shoot_len, root_len,
144
+ shoot_wt, root_wt, yield_gp]
145
+ )
146
 
147
  # Prediction callback
148
+ predict_btn.click(
149
+ fn=predict_linear,
150
+ inputs=[strain_input, dose, soil_n, soil_p, soil_k, ph,
151
+ chlorophyll, shoot_len, root_len, shoot_wt, root_wt, yield_gp],
152
+ outputs=[result_table, status_box, log_box]
153
+ )
154
 
155
  # -----------------------------
156
  # 5️⃣ Launch