nischal5490 commited on
Commit
77ccb87
Β·
verified Β·
1 Parent(s): db819c5

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +179 -0
app.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import gradio as gr
3
+ from datetime import datetime, date
4
+ from PIL import Image
5
+ import matplotlib.pyplot as plt
6
+ import matplotlib
7
+ matplotlib.use('Agg')
8
+ import torch
9
+ import torchvision.transforms as transforms
10
+ from torchvision.models import resnet18
11
+ import torch.nn as nn
12
+ import io
13
+ import os
14
+ from huggingface_hub import hf_hub_download
15
+
16
+ # Constants
17
+ GROWTH_STAGES = {
18
+ "Planting": (0, 30),
19
+ "Vegetative": (31, 120),
20
+ "Rhizome Bulking": (121, 200),
21
+ "Maturity": (201, 240)
22
+ }
23
+ STAGE_DETAILS = {
24
+ "Planting": "Initial planting and establishment of turmeric rhizomes.",
25
+ "Vegetative": "Rapid leaf and shoot growth. High water and light needs.",
26
+ "Rhizome Bulking": "Main rhizome expansion phase. Needs stable soil moisture.",
27
+ "Maturity": "Leaves yellow and die back. Rhizomes mature underground."
28
+ }
29
+ BASE_CONDITIONS = {
30
+ "Planting": {"temp": (25, 32), "humidity": (70, 90), "soil": (65, 105), "light": (200, 300), "ph": (6.0, 6.8)},
31
+ "Vegetative": {"temp": (20, 30), "humidity": (60, 80), "soil": (45, 75), "light": (300, 500), "ph": (6.0, 6.8)},
32
+ "Rhizome Bulking": {"temp": (22, 28), "humidity": (60, 70), "soil": (45, 65), "light": (400, 600), "ph": (6.0, 6.8)},
33
+ "Maturity": {"temp": (18, 30), "humidity": (50, 60), "soil": (25, 45), "light": (200, 300), "ph": (6.0, 6.8)}
34
+ }
35
+
36
+ DISEASE_CLASSES = ['Dry_Leaf', 'Healthy_Leaf', 'Leaf_Blotch', 'Rhizome_Disease', 'Rhizome_Healthy']
37
+ transform_img = transforms.Compose([
38
+ transforms.Resize((224, 224)),
39
+ transforms.ToTensor()
40
+ ])
41
+
42
+ model_path = hf_hub_download(
43
+ repo_id="your-username/your-private-model-repo",
44
+ filename="turmeric_model.pth",
45
+ repo_type="model",
46
+ token=os.getenv("HUGGINGFACEHUB_API_TOKEN")
47
+ )
48
+
49
+ model = resnet18(weights=None)
50
+ model.fc = nn.Linear(model.fc.in_features, len(DISEASE_CLASSES))
51
+ model.load_state_dict(torch.load(model_path, map_location=torch.device("cpu")))
52
+ model.eval()
53
+
54
+ action_log = []
55
+
56
+ def highlight_text(text):
57
+ if text.startswith("βœ…"):
58
+ return f"<span style='color:green; font-weight:bold; animation: blink-green 1s infinite;'>{text}</span>"
59
+ else:
60
+ return f"<span style='color:red; font-weight:bold; animation: blink-red 1s infinite;'>{text}</span>"
61
+
62
+ def turmeric_advisor(planting_date, temp, humidity, soil_moisture, light_intensity, ph):
63
+ try:
64
+ planting_date = datetime.strptime(planting_date, "%Y-%m-%d").date()
65
+ except:
66
+ return ["❌ Invalid planting date format.", "", "", "", "", "", "", "", None]
67
+
68
+ days_since = (date.today() - planting_date).days
69
+ current_stage = "Unknown"
70
+ for stage, (start, end) in GROWTH_STAGES.items():
71
+ if start <= days_since <= end:
72
+ current_stage = stage
73
+ break
74
+
75
+ if current_stage == "Unknown":
76
+ return ["⚠️ Could not estimate stage. Check date.", "", "", "", "", "", "", "", None]
77
+
78
+ stage_description = STAGE_DETAILS[current_stage]
79
+ stage_ideal = BASE_CONDITIONS[current_stage]
80
+
81
+ def feedback(val, low, high, ok_text, low_text, high_text):
82
+ if val < low:
83
+ return f"πŸ”» {low_text}"
84
+ elif val > high:
85
+ return f"πŸ”Ί {high_text}"
86
+ else:
87
+ return f"βœ… {ok_text}"
88
+
89
+ temp_msg = feedback(temp, *stage_ideal['temp'], "Temperature OK", "Too Cold – Consider warming", "Too Hot – Consider shading")
90
+ hum_msg = feedback(humidity, *stage_ideal['humidity'], "Humidity OK", "Too Dry – Mist/spray", "Too Humid – Ventilate")
91
+ soil_msg = feedback(soil_moisture, *stage_ideal['soil'], "Soil Moisture OK", "Too Dry – Water required", "Too Wet – Drain excess")
92
+ light_msg = feedback(light_intensity, *stage_ideal['light'], "Light Intensity OK", "Too Low – Increase light", "Too High – Reduce light")
93
+ ph_msg = feedback(ph, *stage_ideal['ph'], "pH OK", "Too Low – Add base", "Too High – Add acid")
94
+
95
+ stages = list(GROWTH_STAGES.keys())
96
+ days = [GROWTH_STAGES[s][1] for s in stages]
97
+ colors = ["green" if d >= days_since else "lightgray" for d in days]
98
+ fig, ax = plt.subplots()
99
+ ax.bar(stages, days, color=colors)
100
+ ax.axhline(days_since, color="red", linestyle="--")
101
+ ax.set_ylabel("Days")
102
+ ax.set_title("Estimated Growth Progress")
103
+ buf = io.BytesIO()
104
+ plt.savefig(buf, format='png')
105
+ buf.seek(0)
106
+ chart_img = Image.open(buf)
107
+
108
+ return [f"🌱 Stage: {current_stage} ({days_since} days since planting)",
109
+ stage_description,
110
+ highlight_text(temp_msg),
111
+ highlight_text(hum_msg),
112
+ highlight_text(soil_msg),
113
+ highlight_text(light_msg),
114
+ highlight_text(ph_msg),
115
+ chart_img]
116
+
117
+ def detect_disease(image):
118
+ image = image.convert("RGB")
119
+ img_tensor = transform_img(image).unsqueeze(0)
120
+ with torch.no_grad():
121
+ outputs = model(img_tensor)
122
+ _, predicted = torch.max(outputs, 1)
123
+ return f"🩺 Prediction: {DISEASE_CLASSES[predicted.item()]}"
124
+
125
+ def simulate_action(action):
126
+ log = f"βœ… Simulated: {action} activated."
127
+ action_log.append(log)
128
+ return "\n".join(action_log[-10:])
129
+
130
+ with gr.Blocks(title="🌿 Smart Turmeric Farming Advisor") as demo:
131
+ with gr.Tab("🌱 Growth Advisor"):
132
+ gr.Markdown("## 🌿 Turmeric Growth Advisor")
133
+ with gr.Row():
134
+ planting_date = gr.Textbox(label="πŸ“… Planting Date (YYYY-MM-DD)")
135
+ soil_moisture = gr.Slider(0, 100, value=60, label="🌱 Soil Moisture (%)")
136
+ with gr.Row():
137
+ temp = gr.Slider(10, 45, value=28, label="🌑️ Temperature (°C)")
138
+ humidity = gr.Slider(30, 100, value=70, label="πŸ’§ Humidity (%)")
139
+ light_intensity = gr.Slider(100, 700, value=300, label="πŸ’‘ Light Intensity (Β΅mol/mΒ²/s)")
140
+ ph = gr.Slider(4.0, 8.0, value=6.5, step=0.1, label="πŸ§ͺ Soil pH")
141
+ submit_btn = gr.Button("πŸ” Get Recommendations")
142
+ with gr.Column():
143
+ stage_out = gr.HTML()
144
+ stage_desc = gr.HTML()
145
+ temp_out = gr.HTML()
146
+ hum_out = gr.HTML()
147
+ soil_out = gr.HTML()
148
+ light_out = gr.HTML()
149
+ ph_out = gr.HTML()
150
+ chart_out = gr.Image(type="pil")
151
+
152
+ gr.Markdown("### βš™οΈ Simulated Adjustments")
153
+ fan_btn = gr.Button("πŸŒ€ Activate Fan")
154
+ humidifier_btn = gr.Button("πŸ’¨ Turn On Humidifier")
155
+ light_btn = gr.Button("πŸ’‘ Adjust Light")
156
+ pump_btn = gr.Button("πŸ’§ Water Pump")
157
+ ph_btn = gr.Button("πŸ§ͺ Apply pH Solution")
158
+ action_result = gr.Textbox(label="πŸ“ Simulated Action Log", lines=8)
159
+
160
+ submit_btn.click(
161
+ turmeric_advisor,
162
+ inputs=[planting_date, temp, humidity, soil_moisture, light_intensity, ph],
163
+ outputs=[stage_out, stage_desc, temp_out, hum_out, soil_out, light_out, ph_out, chart_out]
164
+ )
165
+
166
+ fan_btn.click(lambda: simulate_action("Fan"), inputs=[], outputs=action_result)
167
+ humidifier_btn.click(lambda: simulate_action("Humidifier"), inputs=[], outputs=action_result)
168
+ light_btn.click(lambda: simulate_action("Light Adjustment"), inputs=[], outputs=action_result)
169
+ pump_btn.click(lambda: simulate_action("Water Pump"), inputs=[], outputs=action_result)
170
+ ph_btn.click(lambda: simulate_action("pH Balancer"), inputs=[], outputs=action_result)
171
+
172
+ with gr.Tab("🩺 Disease Detection"):
173
+ gr.Markdown("## 🩺 Turmeric Disease Detection")
174
+ image_input = gr.Image(type="pil", label="πŸ“· Upload Leaf or Rhizome Image")
175
+ prediction_output = gr.Textbox(label="Prediction")
176
+ detect_btn = gr.Button("🧠 Analyze Disease")
177
+ detect_btn.click(fn=detect_disease, inputs=image_input, outputs=prediction_output)
178
+
179
+ demo.launch()