Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,201 +1,202 @@
|
|
1 |
-
from flask import Flask, render_template, request, redirect, url_for, jsonify
|
2 |
-
from tensorflow.keras.models import load_model
|
3 |
-
import numpy as np
|
4 |
-
import joblib
|
5 |
-
import pandas as pd
|
6 |
-
import io
|
7 |
-
import requests
|
8 |
-
import threading
|
9 |
-
import time
|
10 |
-
from PIL import Image # Import for image processing
|
11 |
-
|
12 |
-
app = Flask(__name__)
|
13 |
-
|
14 |
-
# Load models
|
15 |
-
pump_model = joblib.load('pump_status_dt_model.pkl')
|
16 |
-
soil_model = load_model('soil_classification_model.h5')
|
17 |
-
|
18 |
-
# Dictionaries for crop types, regions, etc.
|
19 |
-
crop_types = {'BANANA': 0, 'BEAN': 1, 'CABBAGE': 2, 'CITRUS': 3, 'COTTON': 4,
|
20 |
-
'MAIZE': 5, 'MELON': 6, 'MUSTARD': 7, 'ONION': 8, 'OTHER': 9,
|
21 |
-
'POTATO': 10, 'RICE': 11, 'SOYABEAN': 12, 'SUGARCANE': 13,
|
22 |
-
'TOMATO': 14, 'WHEAT': 15}
|
23 |
-
|
24 |
-
soil_types = {'DRY': 0, 'HUMID': 1, 'WET': 2}
|
25 |
-
regions = {'DESERT': 0, 'HUMID': 1, 'SEMI ARID': 2, 'SEMI HUMID': 3}
|
26 |
-
weather_conditions = {'SUNNY': 0, 'RAINY': 1, 'WINDY': 2, 'NORMAL': 3}
|
27 |
-
irrigation_types = {'Drip Irrigation': 0, 'Manual Irrigation': 1,
|
28 |
-
'Sprinkler Irrigation': 2, 'Subsurface Irrigation': 3,
|
29 |
-
'Surface Irrigation': 4}
|
30 |
-
|
31 |
-
soil_labels = {1: 'Black Soil', 2: 'Clay Soil', 0: 'Alluvial Soil', 3: 'Red Soil'}
|
32 |
-
|
33 |
-
# Global variables
|
34 |
-
soil_moisture_data = []
|
35 |
-
pump_status = "Off"
|
36 |
-
previous_pump_status = "Off"
|
37 |
-
graph_data = []
|
38 |
-
|
39 |
-
|
40 |
-
# Function to fetch weather data
|
41 |
-
def get_weather(city):
|
42 |
-
api_key
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
response.
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
# Function to run predictions for all soil moisture values
|
70 |
-
|
71 |
-
|
72 |
-
pump_status
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
features
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
if
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
image
|
142 |
-
image =
|
143 |
-
image =
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
|
|
|
1 |
+
from flask import Flask, render_template, request, redirect, url_for, jsonify
|
2 |
+
from tensorflow.keras.models import load_model
|
3 |
+
import numpy as np
|
4 |
+
import joblib
|
5 |
+
import pandas as pd
|
6 |
+
import io
|
7 |
+
import requests
|
8 |
+
import threading
|
9 |
+
import time
|
10 |
+
from PIL import Image # Import for image processing
|
11 |
+
|
12 |
+
app = Flask(__name__)
|
13 |
+
|
14 |
+
# Load models
|
15 |
+
pump_model = joblib.load('pump_status_dt_model.pkl')
|
16 |
+
soil_model = load_model('soil_classification_model.h5')
|
17 |
+
|
18 |
+
# Dictionaries for crop types, regions, etc.
|
19 |
+
crop_types = {'BANANA': 0, 'BEAN': 1, 'CABBAGE': 2, 'CITRUS': 3, 'COTTON': 4,
|
20 |
+
'MAIZE': 5, 'MELON': 6, 'MUSTARD': 7, 'ONION': 8, 'OTHER': 9,
|
21 |
+
'POTATO': 10, 'RICE': 11, 'SOYABEAN': 12, 'SUGARCANE': 13,
|
22 |
+
'TOMATO': 14, 'WHEAT': 15}
|
23 |
+
|
24 |
+
soil_types = {'DRY': 0, 'HUMID': 1, 'WET': 2}
|
25 |
+
regions = {'DESERT': 0, 'HUMID': 1, 'SEMI ARID': 2, 'SEMI HUMID': 3}
|
26 |
+
weather_conditions = {'SUNNY': 0, 'RAINY': 1, 'WINDY': 2, 'NORMAL': 3}
|
27 |
+
irrigation_types = {'Drip Irrigation': 0, 'Manual Irrigation': 1,
|
28 |
+
'Sprinkler Irrigation': 2, 'Subsurface Irrigation': 3,
|
29 |
+
'Surface Irrigation': 4}
|
30 |
+
|
31 |
+
soil_labels = {1: 'Black Soil', 2: 'Clay Soil', 0: 'Alluvial Soil', 3: 'Red Soil'}
|
32 |
+
|
33 |
+
# Global variables
|
34 |
+
soil_moisture_data = []
|
35 |
+
pump_status = "Off"
|
36 |
+
previous_pump_status = "Off"
|
37 |
+
graph_data = []
|
38 |
+
|
39 |
+
|
40 |
+
# Function to fetch weather data
|
41 |
+
def get_weather(city):
|
42 |
+
api_key=os.getenv('WEATHER_API')
|
43 |
+
api_key = api_key
|
44 |
+
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
|
45 |
+
try:
|
46 |
+
response = requests.get(url)
|
47 |
+
response.raise_for_status()
|
48 |
+
data = response.json()
|
49 |
+
temp = data['main']['temp']
|
50 |
+
pressure = data['main']['pressure']
|
51 |
+
humidity = data['main']['humidity']
|
52 |
+
weather_desc = data['weather'][0]['main']
|
53 |
+
return temp, pressure, humidity, weather_desc
|
54 |
+
except requests.exceptions.HTTPError:
|
55 |
+
return None, None, None, None
|
56 |
+
|
57 |
+
|
58 |
+
# Function to map soil type to pump model's expected format
|
59 |
+
def map_soil_to_pump_model(soil_label):
|
60 |
+
if soil_label in ['Black Soil', 'Red Soil']:
|
61 |
+
return 'DRY'
|
62 |
+
elif soil_label == 'Clay Soil':
|
63 |
+
return 'WET'
|
64 |
+
elif soil_label == 'Alluvial Soil':
|
65 |
+
return 'HUMID'
|
66 |
+
return None
|
67 |
+
|
68 |
+
|
69 |
+
# Function to run predictions for all soil moisture values
|
70 |
+
# Function to run predictions for all soil moisture values
|
71 |
+
def run_predictions(crop_type, soil_type_for_pump, region, temperature, pressure, humidity, crop_age, irrigation_type, auto_weather_condition):
|
72 |
+
global pump_status, graph_data, previous_pump_status
|
73 |
+
pump_status = "Off"
|
74 |
+
previous_pump_status = "Off"
|
75 |
+
graph_data = []
|
76 |
+
|
77 |
+
for soil_moisture in soil_moisture_data:
|
78 |
+
try:
|
79 |
+
soil_moisture_value = float(soil_moisture) # Ensure this is a float
|
80 |
+
except ValueError:
|
81 |
+
print(f"Skipping invalid soil moisture value: {soil_moisture}")
|
82 |
+
continue
|
83 |
+
|
84 |
+
# Prepare features for pump prediction
|
85 |
+
features = np.array([crop_types[crop_type], soil_types[soil_type_for_pump],
|
86 |
+
regions[region], temperature if temperature else 0,
|
87 |
+
weather_conditions.get(auto_weather_condition, 0),
|
88 |
+
pressure if pressure else 0, humidity if humidity else 0,
|
89 |
+
int(crop_age), irrigation_types[irrigation_type],
|
90 |
+
soil_moisture_value]).reshape(1, -1)
|
91 |
+
|
92 |
+
# Make the pump prediction
|
93 |
+
pump_prediction = pump_model.predict(features)
|
94 |
+
pump_status = 'On' if pump_prediction[0] == 1 else 'Off'
|
95 |
+
graph_data.append((soil_moisture_value, 1 if pump_status == 'On' else -1)) # Update status to -1 for Off
|
96 |
+
|
97 |
+
print(f"Predicted Pump Status: {pump_status} for Soil Moisture: {soil_moisture_value}") # Debugging output
|
98 |
+
|
99 |
+
# Play sound if pump is Off and it wasn't Off previously
|
100 |
+
if pump_status == "Off" and previous_pump_status != "Off":
|
101 |
+
play_sound()
|
102 |
+
|
103 |
+
previous_pump_status = pump_status
|
104 |
+
|
105 |
+
# Wait for 1 second before next prediction
|
106 |
+
time.sleep(2)
|
107 |
+
|
108 |
+
|
109 |
+
def play_sound():
|
110 |
+
# You can use any sound file here
|
111 |
+
print("Beep! Pump is Off.") # Placeholder for actual sound functionality
|
112 |
+
|
113 |
+
|
114 |
+
# Main route
|
115 |
+
@app.route('/', methods=['GET', 'POST'])
|
116 |
+
def index():
|
117 |
+
global soil_moisture_data
|
118 |
+
|
119 |
+
city = crop_type = region = crop_age = irrigation_type = None
|
120 |
+
temperature = pressure = humidity = weather_desc = auto_weather_condition = None
|
121 |
+
soil_image_url = None
|
122 |
+
|
123 |
+
if request.method == 'POST':
|
124 |
+
city = request.form.get('city', '')
|
125 |
+
crop_type = request.form.get('crop_type', '')
|
126 |
+
region = request.form.get('region', '')
|
127 |
+
crop_age = request.form.get('crop_age', '')
|
128 |
+
irrigation_type = request.form.get('irrigation_type', '')
|
129 |
+
|
130 |
+
# Handle CSV file upload
|
131 |
+
if 'soil_moisture' in request.files:
|
132 |
+
soil_moisture_file = request.files['soil_moisture']
|
133 |
+
if soil_moisture_file:
|
134 |
+
# Read CSV file
|
135 |
+
df = pd.read_csv(soil_moisture_file)
|
136 |
+
soil_moisture_data = df['Soil Moisture'].tolist()
|
137 |
+
|
138 |
+
# Handle soil image upload
|
139 |
+
soil_image_file = request.files.get('soil_image')
|
140 |
+
if soil_image_file:
|
141 |
+
# Load and preprocess the image for prediction
|
142 |
+
image = Image.open(io.BytesIO(soil_image_file.read()))
|
143 |
+
image = image.resize((150, 150))
|
144 |
+
image = np.array(image) / 255.0
|
145 |
+
if image.shape[-1] == 4:
|
146 |
+
image = image[..., :3]
|
147 |
+
image = np.expand_dims(image, axis=0)
|
148 |
+
|
149 |
+
# Predict the soil type
|
150 |
+
soil_pred = soil_model.predict(image)
|
151 |
+
soil_label = soil_labels[np.argmax(soil_pred)]
|
152 |
+
soil_type_for_pump = map_soil_to_pump_model(soil_label)
|
153 |
+
else:
|
154 |
+
soil_type_for_pump = request.form.get('soil_type')
|
155 |
+
|
156 |
+
if city:
|
157 |
+
temperature, pressure, humidity, weather_desc = get_weather(city)
|
158 |
+
auto_weather_condition = "NORMAL" # Default weather condition
|
159 |
+
if weather_desc:
|
160 |
+
if 'sunny' in weather_desc.lower():
|
161 |
+
auto_weather_condition = 'SUNNY'
|
162 |
+
elif 'rain' in weather_desc.lower():
|
163 |
+
auto_weather_condition = 'RAINY'
|
164 |
+
elif 'wind' in weather_desc.lower():
|
165 |
+
auto_weather_condition = 'WINDY'
|
166 |
+
|
167 |
+
if 'predict' in request.form:
|
168 |
+
# Start a thread for predictions
|
169 |
+
threading.Thread(target=run_predictions, args=(
|
170 |
+
crop_type, soil_type_for_pump, region, temperature, pressure, humidity, crop_age, irrigation_type, auto_weather_condition)).start()
|
171 |
+
return redirect(url_for('predict'))
|
172 |
+
|
173 |
+
return render_template('index.html', temperature=temperature, pressure=pressure,
|
174 |
+
humidity=humidity, weather_desc=weather_desc, crop_types=crop_types,
|
175 |
+
regions=regions, irrigation_types=irrigation_types, soil_types=soil_types,
|
176 |
+
crop_type=crop_type, region=region, crop_age=crop_age,
|
177 |
+
irrigation_type=irrigation_type, city=city, soil_image_url=soil_image_url)
|
178 |
+
|
179 |
+
|
180 |
+
# Prediction route
|
181 |
+
@app.route('/predict', methods=['GET'])
|
182 |
+
def predict():
|
183 |
+
global pump_status, graph_data
|
184 |
+
return render_template('predict.html', pump_status=pump_status, graph_data=graph_data)
|
185 |
+
|
186 |
+
|
187 |
+
# Update graph data every second
|
188 |
+
@app.route('/update_graph', methods=['GET'])
|
189 |
+
def update_graph():
|
190 |
+
global graph_data
|
191 |
+
return jsonify(graph_data)
|
192 |
+
|
193 |
+
|
194 |
+
# Update pump status every second
|
195 |
+
@app.route('/update_pump_status', methods=['GET'])
|
196 |
+
def update_pump_status():
|
197 |
+
global pump_status
|
198 |
+
return jsonify({'pump_status': pump_status})
|
199 |
+
|
200 |
+
|
201 |
+
if __name__ == '__main__':
|
202 |
+
app.run(debug=True)
|